]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/crypto.c
Update copyrights
[bacula/bacula] / bacula / src / lib / crypto.c
1 /*
2  * crypto.c Encryption support functions
3  *
4  * Author: Landon Fuller <landonf@opendarwin.org>
5  *
6  * Version $Id$
7  *
8  * This file was contributed to the Bacula project by Landon Fuller.
9  *
10  * Landon Fuller has been granted a perpetual, worldwide, non-exclusive,
11  * no-charge, royalty-free, irrevocable copyright license to reproduce,
12  * prepare derivative works of, publicly display, publicly perform,
13  * sublicense, and distribute the original work contributed by Landon Fuller
14  * to the Bacula project in source or object form.
15  *
16  * If you wish to license these contributions under an alternate open source
17  * license please contact Landon Fuller <landonf@opendarwin.org>.
18  */
19 /*
20    Bacula® - The Network Backup Solution
21
22    Copyright (C) 2005-2006 Free Software Foundation Europe e.V.
23
24    The main author of Bacula is Kern Sibbald, with contributions from
25    many others, a complete list can be found in the file AUTHORS.
26    This program is Free Software; you can redistribute it and/or
27    modify it under the terms of version two of the GNU General Public
28    License as published by the Free Software Foundation plus additions
29    that are listed in the file LICENSE.
30
31    This program is distributed in the hope that it will be useful, but
32    WITHOUT ANY WARRANTY; without even the implied warranty of
33    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
34    General Public License for more details.
35
36    You should have received a copy of the GNU General Public License
37    along with this program; if not, write to the Free Software
38    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
39    02110-1301, USA.
40
41    Bacula® is a registered trademark of John Walker.
42    The licensor of Bacula is the Free Software Foundation Europe
43    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
44    Switzerland, email:ftf@fsfeurope.org.
45 */
46
47
48 #include "bacula.h"
49 #include <assert.h>
50
51 /*
52  * Bacula ASN.1 Syntax
53  *
54  * OID Allocation:
55  * Prefix: iso.org.dod.internet.private.enterprise.threerings.external.bacula (1.3.6.1.4.1.22054.500.2)
56  * Organization: Bacula Project
57  * Contact Name: Kern Sibbald
58  * Contact E-mail: kern@sibbald.com
59  *
60  * Top Level Allocations - 500.2
61  * 1 - Published Allocations
62  *   1.1 - Bacula Encryption
63  *
64  * Bacula Encryption - 500.2.1.1
65  * 1 - ASN.1 Modules
66  *    1.1 - BaculaCrypto
67  * 2 - ASN.1 Object Identifiers
68  *    2.1 - SignatureData
69  *    2.2 - SignerInfo
70  *    2.3 - CryptoData
71  *    2.4 - RecipientInfo
72  *
73  * BaculaCrypto { iso(1) identified-organization(3) usdod(6)
74  *                internet(1) private(4) enterprises(1) three-rings(22054)
75  *                external(500) bacula(2) published(1) bacula-encryption(1)
76  *                asn1-modules(1) bacula-crypto(1) }
77  *
78  * DEFINITIONS AUTOMATIC TAGS ::=
79  * BEGIN
80  *
81  * SignatureData ::= SEQUENCE {
82  *    version         Version DEFAULT v0,
83  *    signerInfo      SignerInfo }
84  *
85  * CryptoData ::= SEQUENCE {
86  *    version                     Version DEFAULT v0,
87  *    contentEncryptionAlgorithm  ContentEncryptionAlgorithmIdentifier,
88  *    iv                          InitializationVector,
89  *    recipientInfo               RecipientInfo
90  * }
91  *
92  * SignerInfo ::= SET OF SignerInfo
93  * RecipientInfo ::= SET OF RecipientInfo
94  *
95  * Version ::= INTEGER { v0(0) }
96  *
97  * SignerInfo ::= SEQUENCE {
98  *    version                 Version,
99  *    subjectKeyIdentifier    SubjectKeyIdentifier,
100  *    digestAlgorithm         DigestAlgorithmIdentifier,
101  *    signatureAlgorithm      SignatureAlgorithmIdentifier,
102  *    signature               SignatureValue }
103  *
104  * RecipientInfo ::= SEQUENCE {
105  *    version                 Version
106  *    subjectKeyIdentifier    SubjectKeyIdentifier
107  *    keyEncryptionAlgorithm  KeyEncryptionAlgorithmIdentifier
108  *    encryptedKey            EncryptedKey
109  * }
110  *
111  * SubjectKeyIdentifier ::= OCTET STRING
112  *
113  * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
114  *
115  * SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
116  *
117  * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
118  *
119  * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
120  *
121  * InitializationVector ::= OCTET STRING
122  *
123  * SignatureValue ::= OCTET STRING
124  *
125  * EncryptedKey ::= OCTET STRING
126  *
127  * AlgorithmIdentifier ::= OBJECT IDENTIFIER
128  *
129  * END
130  */
131
132 #ifdef HAVE_CRYPTO /* Is encryption enabled? */
133 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
134
135 /* Are we initialized? */
136 static int crypto_initialized = false;
137
138 /* ASN.1 Declarations */
139 #define BACULA_ASN1_VERSION 0
140
141 typedef struct {
142    ASN1_INTEGER *version;
143    ASN1_OCTET_STRING *subjectKeyIdentifier;
144    ASN1_OBJECT *digestAlgorithm;
145    ASN1_OBJECT *signatureAlgorithm;
146    ASN1_OCTET_STRING *signature;
147 } SignerInfo;
148
149 typedef struct {
150    ASN1_INTEGER *version;
151    ASN1_OCTET_STRING *subjectKeyIdentifier;
152    ASN1_OBJECT *keyEncryptionAlgorithm;
153    ASN1_OCTET_STRING *encryptedKey;
154 } RecipientInfo;
155
156 ASN1_SEQUENCE(SignerInfo) = {
157    ASN1_SIMPLE(SignerInfo, version, ASN1_INTEGER),
158    ASN1_SIMPLE(SignerInfo, subjectKeyIdentifier, ASN1_OCTET_STRING),
159    ASN1_SIMPLE(SignerInfo, digestAlgorithm, ASN1_OBJECT),
160    ASN1_SIMPLE(SignerInfo, signatureAlgorithm, ASN1_OBJECT),
161    ASN1_SIMPLE(SignerInfo, signature, ASN1_OCTET_STRING)
162 } ASN1_SEQUENCE_END(SignerInfo);
163
164 ASN1_SEQUENCE(RecipientInfo) = {
165    ASN1_SIMPLE(RecipientInfo, version, ASN1_INTEGER),
166    ASN1_SIMPLE(RecipientInfo, subjectKeyIdentifier, ASN1_OCTET_STRING),
167    ASN1_SIMPLE(RecipientInfo, keyEncryptionAlgorithm, ASN1_OBJECT),
168    ASN1_SIMPLE(RecipientInfo, encryptedKey, ASN1_OCTET_STRING),
169 } ASN1_SEQUENCE_END(RecipientInfo);
170
171 typedef struct {
172    ASN1_INTEGER *version;
173    STACK_OF(SignerInfo) *signerInfo;
174 } SignatureData;
175
176 typedef struct {
177    ASN1_INTEGER *version;
178    ASN1_OBJECT *contentEncryptionAlgorithm;
179    ASN1_OCTET_STRING *iv;
180    STACK_OF(RecipientInfo) *recipientInfo;
181 } CryptoData;
182
183 ASN1_SEQUENCE(SignatureData) = {
184    ASN1_SIMPLE(SignatureData, version, ASN1_INTEGER),
185    ASN1_SET_OF(SignatureData, signerInfo, SignerInfo),
186 } ASN1_SEQUENCE_END(SignatureData);
187
188 ASN1_SEQUENCE(CryptoData) = {
189    ASN1_SIMPLE(CryptoData, version, ASN1_INTEGER),
190    ASN1_SIMPLE(CryptoData, contentEncryptionAlgorithm, ASN1_OBJECT),
191    ASN1_SIMPLE(CryptoData, iv, ASN1_OCTET_STRING),
192    ASN1_SET_OF(CryptoData, recipientInfo, RecipientInfo)
193 } ASN1_SEQUENCE_END(CryptoData);
194
195 IMPLEMENT_ASN1_FUNCTIONS(SignerInfo)
196 IMPLEMENT_ASN1_FUNCTIONS(RecipientInfo)
197 IMPLEMENT_ASN1_FUNCTIONS(SignatureData)
198 IMPLEMENT_ASN1_FUNCTIONS(CryptoData)
199 IMPLEMENT_STACK_OF(SignerInfo)
200 IMPLEMENT_STACK_OF(RecipientInfo)
201
202 /*
203  * SignerInfo and RecipientInfo stack macros, generated by OpenSSL's util/mkstack.pl.
204  */
205 #define sk_SignerInfo_new(st) SKM_sk_new(SignerInfo, (st))
206 #define sk_SignerInfo_new_null() SKM_sk_new_null(SignerInfo)
207 #define sk_SignerInfo_free(st) SKM_sk_free(SignerInfo, (st))
208 #define sk_SignerInfo_num(st) SKM_sk_num(SignerInfo, (st))
209 #define sk_SignerInfo_value(st, i) SKM_sk_value(SignerInfo, (st), (i))
210 #define sk_SignerInfo_set(st, i, val) SKM_sk_set(SignerInfo, (st), (i), (val))
211 #define sk_SignerInfo_zero(st) SKM_sk_zero(SignerInfo, (st))
212 #define sk_SignerInfo_push(st, val) SKM_sk_push(SignerInfo, (st), (val))
213 #define sk_SignerInfo_unshift(st, val) SKM_sk_unshift(SignerInfo, (st), (val))
214 #define sk_SignerInfo_find(st, val) SKM_sk_find(SignerInfo, (st), (val))
215 #define sk_SignerInfo_delete(st, i) SKM_sk_delete(SignerInfo, (st), (i))
216 #define sk_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(SignerInfo, (st), (ptr))
217 #define sk_SignerInfo_insert(st, val, i) SKM_sk_insert(SignerInfo, (st), (val), (i))
218 #define sk_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(SignerInfo, (st), (cmp))
219 #define sk_SignerInfo_dup(st) SKM_sk_dup(SignerInfo, st)
220 #define sk_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(SignerInfo, (st), (free_func))
221 #define sk_SignerInfo_shift(st) SKM_sk_shift(SignerInfo, (st))
222 #define sk_SignerInfo_pop(st) SKM_sk_pop(SignerInfo, (st))
223 #define sk_SignerInfo_sort(st) SKM_sk_sort(SignerInfo, (st))
224 #define sk_SignerInfo_is_sorted(st) SKM_sk_is_sorted(SignerInfo, (st))
225
226 #define d2i_ASN1_SET_OF_SignerInfo(st, pp, length, d2i_func, free_func, ex_tag, ex_class) \
227         SKM_ASN1_SET_OF_d2i(SignerInfo, (st), (pp), (length), (d2i_func), (free_func), (ex_tag), (ex_class)) 
228 #define i2d_ASN1_SET_OF_SignerInfo(st, pp, i2d_func, ex_tag, ex_class, is_set) \
229         SKM_ASN1_SET_OF_i2d(SignerInfo, (st), (pp), (i2d_func), (ex_tag), (ex_class), (is_set))
230 #define ASN1_seq_pack_SignerInfo(st, i2d_func, buf, len) \
231         SKM_ASN1_seq_pack(SignerInfo, (st), (i2d_func), (buf), (len))
232 #define ASN1_seq_unpack_SignerInfo(buf, len, d2i_func, free_func) \
233         SKM_ASN1_seq_unpack(SignerInfo, (buf), (len), (d2i_func), (free_func))
234
235 #define sk_RecipientInfo_new(st) SKM_sk_new(RecipientInfo, (st))
236 #define sk_RecipientInfo_new_null() SKM_sk_new_null(RecipientInfo)
237 #define sk_RecipientInfo_free(st) SKM_sk_free(RecipientInfo, (st))
238 #define sk_RecipientInfo_num(st) SKM_sk_num(RecipientInfo, (st))
239 #define sk_RecipientInfo_value(st, i) SKM_sk_value(RecipientInfo, (st), (i))
240 #define sk_RecipientInfo_set(st, i, val) SKM_sk_set(RecipientInfo, (st), (i), (val))
241 #define sk_RecipientInfo_zero(st) SKM_sk_zero(RecipientInfo, (st))
242 #define sk_RecipientInfo_push(st, val) SKM_sk_push(RecipientInfo, (st), (val))
243 #define sk_RecipientInfo_unshift(st, val) SKM_sk_unshift(RecipientInfo, (st), (val))
244 #define sk_RecipientInfo_find(st, val) SKM_sk_find(RecipientInfo, (st), (val))
245 #define sk_RecipientInfo_delete(st, i) SKM_sk_delete(RecipientInfo, (st), (i))
246 #define sk_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(RecipientInfo, (st), (ptr))
247 #define sk_RecipientInfo_insert(st, val, i) SKM_sk_insert(RecipientInfo, (st), (val), (i))
248 #define sk_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(RecipientInfo, (st), (cmp))
249 #define sk_RecipientInfo_dup(st) SKM_sk_dup(RecipientInfo, st)
250 #define sk_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(RecipientInfo, (st), (free_func))
251 #define sk_RecipientInfo_shift(st) SKM_sk_shift(RecipientInfo, (st))
252 #define sk_RecipientInfo_pop(st) SKM_sk_pop(RecipientInfo, (st))
253 #define sk_RecipientInfo_sort(st) SKM_sk_sort(RecipientInfo, (st))
254 #define sk_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(RecipientInfo, (st))
255
256 #define d2i_ASN1_SET_OF_RecipientInfo(st, pp, length, d2i_func, free_func, ex_tag, ex_class) \
257         SKM_ASN1_SET_OF_d2i(RecipientInfo, (st), (pp), (length), (d2i_func), (free_func), (ex_tag), (ex_class)) 
258 #define i2d_ASN1_SET_OF_RecipientInfo(st, pp, i2d_func, ex_tag, ex_class, is_set) \
259         SKM_ASN1_SET_OF_i2d(RecipientInfo, (st), (pp), (i2d_func), (ex_tag), (ex_class), (is_set))
260 #define ASN1_seq_pack_RecipientInfo(st, i2d_func, buf, len) \
261         SKM_ASN1_seq_pack(RecipientInfo, (st), (i2d_func), (buf), (len))
262 #define ASN1_seq_unpack_RecipientInfo(buf, len, d2i_func, free_func) \
263         SKM_ASN1_seq_unpack(RecipientInfo, (buf), (len), (d2i_func), (free_func))
264 /* End of util/mkstack.pl block */
265
266 /* X509 Public/Private Key Pair Structure */
267 struct X509_Keypair {
268    ASN1_OCTET_STRING *keyid;
269    EVP_PKEY *pubkey;
270    EVP_PKEY *privkey;
271 };
272
273 /* Message Digest Structure */
274 struct Digest {
275    crypto_digest_t type;
276    EVP_MD_CTX ctx;
277 };
278
279 /* Message Signature Structure */
280 struct Signature {
281    SignatureData *sigData;
282 };
283
284 /* Encryption Session Data */
285 struct Crypto_Session {
286    CryptoData *cryptoData;                        /* ASN.1 Structure */
287    unsigned char *session_key;                    /* Private symmetric session key */
288    size_t session_key_len;                        /* Symmetric session key length */
289 };
290
291 /* Symmetric Cipher Context */
292 struct Cipher_Context {
293    EVP_CIPHER_CTX ctx;
294 };
295
296 /* PEM Password Dispatch Context */
297 typedef struct PEM_CB_Context {
298    CRYPTO_PEM_PASSWD_CB *pem_callback;
299    const void *pem_userdata;
300 } PEM_CB_CONTEXT;
301
302 /*
303  * Extract subjectKeyIdentifier from x509 certificate.
304  * Returns: On success, an ASN1_OCTET_STRING that must be freed via M_ASN1_OCTET_STRING_free().
305  *          NULL on failure.
306  */
307 static ASN1_OCTET_STRING *openssl_cert_keyid(X509 *cert){
308    X509_EXTENSION *ext;
309    X509V3_EXT_METHOD *method;
310    ASN1_OCTET_STRING *keyid;
311    int i;
312 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
313    const unsigned char *ext_value_data;
314 #else
315    unsigned char *ext_value_data;
316 #endif
317
318
319    /* Find the index to the subjectKeyIdentifier extension */
320    i = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
321    if (i < 0) {
322       /* Not found */
323       return NULL;
324    }
325
326    /* Grab the extension */
327    ext = X509_get_ext(cert, i);
328
329    /* Get x509 extension method structure */
330    if (!(method = X509V3_EXT_get(ext))) {
331       return NULL;
332    }
333
334    ext_value_data = ext->value->data;
335
336 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
337    if (method->it) {
338       /* New style ASN1 */
339
340       /* Decode ASN1 item in data */
341       keyid = (ASN1_OCTET_STRING *) ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
342                                                   ASN1_ITEM_ptr(method->it));
343    } else {
344       /* Old style ASN1 */
345
346       /* Decode ASN1 item in data */
347       keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
348    }
349
350 #else
351    keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
352 #endif
353
354    return keyid;
355 }
356
357 /*
358  * Create a new keypair object.
359  *  Returns: A pointer to a X509 KEYPAIR object on success.
360  *           NULL on failure.
361  */
362 X509_KEYPAIR *crypto_keypair_new (void) {
363    X509_KEYPAIR *keypair;
364
365    /* Allocate our keypair structure */
366    keypair = (X509_KEYPAIR *) malloc(sizeof(X509_KEYPAIR));
367    if (!keypair) {
368       return NULL;
369    }
370
371    /* Initialize our keypair structure */
372    keypair->keyid = NULL;
373    keypair->pubkey = NULL;
374    keypair->privkey = NULL;
375
376    return keypair;
377 }
378
379 /*
380  * Create a copy of a keypair object. The underlying
381  * EVP objects are not duplicated, as no EVP_PKEY_dup()
382  * API is available. Instead, the reference count is
383  * incremented.
384  */
385 X509_KEYPAIR *crypto_keypair_dup (X509_KEYPAIR *keypair)
386 {
387    X509_KEYPAIR *newpair;
388
389    newpair = crypto_keypair_new();
390
391    if (!newpair) {
392       /* Allocation failed */
393       return NULL;
394    }
395
396    /* Increment the public key ref count */
397    if (keypair->pubkey) {
398       CRYPTO_add(&(keypair->pubkey->references), 1, CRYPTO_LOCK_EVP_PKEY);
399       newpair->pubkey = keypair->pubkey;
400    }
401
402    /* Increment the private key ref count */
403    if (keypair->privkey) {
404       CRYPTO_add(&(keypair->privkey->references), 1, CRYPTO_LOCK_EVP_PKEY);
405       newpair->privkey = keypair->privkey;
406    }
407
408    /* Duplicate the keyid */
409    if (keypair->keyid) {
410       newpair->keyid = M_ASN1_OCTET_STRING_dup(keypair->keyid);
411       if (!newpair->keyid) {
412          /* Allocation failed */
413          crypto_keypair_free(newpair);
414          return NULL;
415       }
416    }
417
418    return newpair;
419 }
420
421
422 /*
423  * Load a public key from a PEM-encoded x509 certificate.
424  *  Returns: true on success
425  *           false on failure
426  */
427 int crypto_keypair_load_cert (X509_KEYPAIR *keypair, const char *file)
428 {
429    BIO *bio;
430    X509 *cert;
431
432    /* Open the file */
433    if (!(bio = BIO_new_file(file, "r"))) {
434       openssl_post_errors(M_ERROR, _("Unable to open certificate file"));
435       return false;
436    }
437
438    cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
439    BIO_free(bio);
440    if (!cert) {
441       openssl_post_errors(M_ERROR, _("Unable to read certificate from file"));
442       return false;
443    }
444
445    /* Extract the public key */
446    if (!(keypair->pubkey = X509_get_pubkey(cert))) {
447       openssl_post_errors(M_ERROR, _("Unable to extract public key from certificate"));
448       goto err;
449    }
450
451    /* Extract the subjectKeyIdentifier extension field */
452    if ((keypair->keyid = openssl_cert_keyid(cert)) == NULL) {
453       Emsg0(M_ERROR, 0, _("Provided certificate does not include the required subjectKeyIdentifier extension."));
454       goto err;
455    }
456
457    /* Validate the public key type (only RSA is supported) */
458    if (EVP_PKEY_type(keypair->pubkey->type) != EVP_PKEY_RSA) {
459        Emsg1(M_ERROR, 0, _("Unsupported key type provided: %d\n"), EVP_PKEY_type(keypair->pubkey->type));
460        goto err;
461    }
462
463    X509_free(cert);
464    return true;
465
466 err:
467    X509_free(cert);
468    if (keypair->pubkey) {
469       EVP_PKEY_free(keypair->pubkey);
470    }
471    return false;
472 }
473
474 /* Dispatch user PEM encryption callbacks */
475 static int crypto_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
476 {
477    PEM_CB_CONTEXT *ctx = (PEM_CB_CONTEXT *) userdata;
478    return (ctx->pem_callback(buf, size, ctx->pem_userdata));
479 }
480
481 /*
482  * Check a PEM-encoded file
483  * for the existence of a private key.
484  * Returns: true if a private key is found
485  *          false otherwise
486  */
487 bool crypto_keypair_has_key (const char *file) {
488    BIO *bio;
489    char *name = NULL;
490    char *header = NULL;
491    unsigned char *data = NULL;
492    bool retval = false;
493    long len;
494
495    if (!(bio = BIO_new_file(file, "r"))) {
496       openssl_post_errors(M_ERROR, _("Unable to open private key file"));
497       return false;
498    }
499
500    while (PEM_read_bio(bio, &name, &header, &data, &len)) {
501       /* We don't care what the data is, just that it's there */
502       OPENSSL_free(header);
503       OPENSSL_free(data);
504
505       /*
506        * PEM Header Found, check for a private key
507        * Due to OpenSSL limitations, we must specifically
508        * list supported PEM private key encodings.
509        */
510       if (strcmp(name, PEM_STRING_RSA) == 0
511             || strcmp(name, PEM_STRING_DSA) == 0
512             || strcmp(name, PEM_STRING_PKCS8) == 0
513             || strcmp(name, PEM_STRING_PKCS8INF) == 0) {
514          retval = true;
515          OPENSSL_free(name);
516          break;
517       } else {
518          OPENSSL_free(name);
519       }
520    }
521
522    /* Free our bio */
523    BIO_free(bio);
524
525    /* Post PEM-decoding error messages, if any */
526    openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
527    return retval;
528 }
529
530 /*
531  * Load a PEM-encoded private key.
532  *  Returns: true on success
533  *           false on failure
534  */
535 int crypto_keypair_load_key (X509_KEYPAIR *keypair, const char *file,
536                              CRYPTO_PEM_PASSWD_CB *pem_callback,
537                              const void *pem_userdata)
538 {
539    BIO *bio;
540    PEM_CB_CONTEXT ctx;
541
542    /* Open the file */
543    if (!(bio = BIO_new_file(file, "r"))) {
544       openssl_post_errors(M_ERROR, _("Unable to open private key file"));
545       return false;
546    }
547
548    /* Set up PEM encryption callback */
549    if (pem_callback) {
550       ctx.pem_callback = pem_callback;
551       ctx.pem_userdata = pem_userdata;
552    } else {
553       ctx.pem_callback = crypto_default_pem_callback;
554       ctx.pem_userdata = NULL;
555    }
556
557    keypair->privkey = PEM_read_bio_PrivateKey(bio, NULL, crypto_pem_callback_dispatch, &ctx);
558    BIO_free(bio);
559    if (!keypair->privkey) {
560       openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
561       return false;
562    }
563
564    return true;
565 }
566
567 /*
568  * Free memory associated with a keypair object.
569  */
570 void crypto_keypair_free (X509_KEYPAIR *keypair)
571 {
572    if (keypair->pubkey) {
573       EVP_PKEY_free(keypair->pubkey);
574    }
575    if (keypair->privkey) {
576       EVP_PKEY_free(keypair->privkey);
577    }
578    if (keypair->keyid) {
579       M_ASN1_OCTET_STRING_free(keypair->keyid);
580    }
581    free(keypair);
582 }
583
584 /*
585  * Create a new message digest context of the specified type
586  *  Returns: A pointer to a DIGEST object on success.
587  *           NULL on failure.
588  */
589 DIGEST *crypto_digest_new (crypto_digest_t type)
590 {
591    DIGEST *digest;
592    const EVP_MD *md = NULL; /* Quell invalid uninitialized warnings */
593
594    digest = (DIGEST *)malloc(sizeof(DIGEST));
595    digest->type = type;
596
597    /* Initialize the OpenSSL message digest context */
598    EVP_MD_CTX_init(&digest->ctx);
599
600    /* Determine the correct OpenSSL message digest type */
601    switch (type) {
602    case CRYPTO_DIGEST_MD5:
603       md = EVP_md5();
604       break;
605    case CRYPTO_DIGEST_SHA1:
606       md = EVP_sha1();
607       break;
608 #ifdef HAVE_SHA2
609    case CRYPTO_DIGEST_SHA256:
610       md = EVP_sha256();
611       break;
612    case CRYPTO_DIGEST_SHA512:
613       md = EVP_sha512();
614       break;
615 #endif
616    default:
617       Emsg1(M_ERROR, 0, _("Unsupported digest type: %d\n"), type);
618       goto err;
619    }
620
621    /* Initialize the backing OpenSSL context */
622    if (EVP_DigestInit_ex(&digest->ctx, md, NULL) == 0) {
623       goto err;
624    }
625
626    return digest;
627
628 err:
629    /* This should not happen, but never say never ... */
630    openssl_post_errors(M_ERROR, _("OpenSSL digest initialization failed"));
631    crypto_digest_free(digest);
632    return NULL;
633 }
634
635 /*
636  * Hash length bytes of data into the provided digest context.
637  * Returns: true on success
638  *          false on failure
639  */
640 bool crypto_digest_update(DIGEST *digest, const uint8_t *data, uint32_t length)
641 {
642    if (EVP_DigestUpdate(&digest->ctx, data, length) == 0) {
643       return true;
644    } else { 
645       return false;
646    }
647 }
648
649 /*
650  * Finalize the data in digest, storing the result in dest and the result size
651  * in length. The result size can be determined with crypto_digest_size().
652  *
653  * Returns: true on success
654  *          false on failure
655  */
656 bool crypto_digest_finalize (DIGEST *digest, uint8_t *dest, uint32_t *length) {
657    if (!EVP_DigestFinal(&digest->ctx, dest, (unsigned int *)length)) {
658       return false;
659    } else {
660       return true;
661    }
662 }
663
664 /*
665  * Free memory associated with a digest object.
666  */
667 void crypto_digest_free (DIGEST *digest)
668 {
669   EVP_MD_CTX_cleanup(&digest->ctx);
670   free (digest);
671 }
672
673 /*
674  * Create a new message signature context.
675  *  Returns: A pointer to a SIGNATURE object on success.
676  *           NULL on failure.
677  */
678 SIGNATURE *crypto_sign_new (void)
679 {
680    SIGNATURE *sig;
681
682    sig = (SIGNATURE *) malloc(sizeof(SIGNATURE));
683    if (!sig) {
684       return NULL;
685    }
686
687    sig->sigData = SignatureData_new();
688
689    if (!sig->sigData) {
690       /* Allocation failed in OpenSSL */
691       free(sig);
692       return NULL;
693    }
694
695    /* Set the ASN.1 structure version number */
696    ASN1_INTEGER_set(sig->sigData->version, BACULA_ASN1_VERSION);
697
698    return sig;
699 }
700
701 /*
702  * For a given public key, find the associated SignatureInfo record
703  * and create a digest context for signature validation
704  * Returns: CRYPTO_ERROR_NONE on success, with the newly allocated DIGEST in digest.
705  *          A crypto_error_t value on failure.
706  */
707 crypto_error_t crypto_sign_get_digest(SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST **digest)
708 {
709    STACK_OF(SignerInfo) *signers;
710    SignerInfo *si;
711    int i;
712
713    signers = sig->sigData->signerInfo;
714
715    for (i = 0; i < sk_SignerInfo_num(signers); i++) {
716       si = sk_SignerInfo_value(signers, i);
717       if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
718          /* Get the digest algorithm and allocate a digest context */
719          switch (OBJ_obj2nid(si->digestAlgorithm)) {
720          case NID_md5:
721             *digest = crypto_digest_new(CRYPTO_DIGEST_MD5);
722             break;
723          case NID_sha1:
724             *digest = crypto_digest_new(CRYPTO_DIGEST_SHA1);
725             break;
726 #ifdef HAVE_SHA2
727          case NID_sha256:
728             *digest = crypto_digest_new(CRYPTO_DIGEST_SHA256);
729             break;
730          case NID_sha512:
731             *digest = crypto_digest_new(CRYPTO_DIGEST_SHA512);
732             break;
733 #endif
734          default:
735             *digest = NULL;
736             return CRYPTO_ERROR_INVALID_DIGEST;
737          }
738
739          /* Shouldn't happen */
740          if (*digest == NULL) {
741             return CRYPTO_ERROR_INVALID_DIGEST;
742          } else {
743             return CRYPTO_ERROR_NONE;
744          }
745       }
746    }
747
748    return CRYPTO_ERROR_NOSIGNER;
749 }
750
751 /*
752  * For a given signature, public key, and digest, verify the SIGNATURE.
753  * Returns: CRYPTO_ERROR_NONE on success.
754  *          A crypto_error_t value on failure.
755  */
756 crypto_error_t crypto_sign_verify(SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest)
757 {
758    STACK_OF(SignerInfo) *signers;
759    SignerInfo *si;
760    int ok, i;
761    unsigned int sigLen;
762 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
763    const unsigned char *sigData;
764 #else
765    unsigned char *sigData;
766 #endif
767
768    signers = sig->sigData->signerInfo;
769
770    /* Find the signer */
771    for (i = 0; i < sk_SignerInfo_num(signers); i++) {
772       si = sk_SignerInfo_value(signers, i);
773       if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
774          /* Extract the signature data */
775          sigLen = M_ASN1_STRING_length(si->signature);
776          sigData = M_ASN1_STRING_data(si->signature);
777
778          ok = EVP_VerifyFinal(&digest->ctx, sigData, sigLen, keypair->pubkey);
779          if (ok >= 1) {
780             return CRYPTO_ERROR_NONE;
781          } else if (ok == 0) {
782             return CRYPTO_ERROR_BAD_SIGNATURE;
783          } else if (ok < 0) {
784             /* Shouldn't happen */
785             openssl_post_errors(M_ERROR, _("OpenSSL error occured"));
786             return CRYPTO_ERROR_INTERNAL;
787          }
788       }
789    }
790
791    /* Signer wasn't found. */
792    return CRYPTO_ERROR_NOSIGNER;
793 }
794
795
796 /*
797  * Add a new signer
798  *  Returns: true on success
799  *           false on failure
800  */
801 int crypto_sign_add_signer(SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair)
802 {
803    SignerInfo *si = NULL;
804    unsigned char *buf = NULL;
805    unsigned int len;
806
807    si = SignerInfo_new();
808
809    if (!si) {
810       /* Allocation failed in OpenSSL */
811       return false;
812    }
813
814    /* Set the ASN.1 structure version number */
815    ASN1_INTEGER_set(si->version, BACULA_ASN1_VERSION);
816
817    /* Set the digest algorithm identifier */
818    switch (digest->type) {
819    case CRYPTO_DIGEST_MD5:
820       si->digestAlgorithm = OBJ_nid2obj(NID_md5);
821       break;
822    case CRYPTO_DIGEST_SHA1:
823       si->digestAlgorithm = OBJ_nid2obj(NID_sha1);
824       break;
825 #ifdef HAVE_SHA2
826    case CRYPTO_DIGEST_SHA256:
827       si->digestAlgorithm = OBJ_nid2obj(NID_sha256);
828       break;
829    case CRYPTO_DIGEST_SHA512:
830       si->digestAlgorithm = OBJ_nid2obj(NID_sha512);
831       break;
832 #endif
833    default:
834       /* This should never happen */
835       goto err;
836    }
837
838    /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
839    M_ASN1_OCTET_STRING_free(si->subjectKeyIdentifier);
840    si->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
841
842    /* Set our signature algorithm. We currently require RSA */
843    assert(EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
844    /* This is slightly evil. Reach into the MD structure and grab the key type */
845    si->signatureAlgorithm = OBJ_nid2obj(digest->ctx.digest->pkey_type);
846
847    /* Finalize/Sign our Digest */
848    len = EVP_PKEY_size(keypair->privkey);
849    buf = (unsigned char *) malloc(len);
850    if (!EVP_SignFinal(&digest->ctx, buf, &len, keypair->privkey)) {
851       openssl_post_errors(M_ERROR, _("Signature creation failed"));
852       goto err;
853    }
854
855    /* Add the signature to the SignerInfo structure */
856    if (!M_ASN1_OCTET_STRING_set(si->signature, buf, len)) {
857       /* Allocation failed in OpenSSL */
858       goto err;
859    }
860
861    /* No longer needed */
862    free(buf);
863
864    /* Push the new SignerInfo structure onto the stack */
865    sk_SignerInfo_push(sig->sigData->signerInfo, si);
866
867    return true;
868
869 err:
870    if (si) {
871       SignerInfo_free(si);
872    }
873    if (buf) {
874       free(buf);
875    }
876
877    return false;
878 }
879
880 /*
881  * Encodes the SignatureData structure. The length argument is used to specify the
882  * size of dest. A length of 0 will cause no data to be written to dest, and the
883  * required length to be written to length. The caller can then allocate sufficient
884  * space for the output.
885  *
886  * Returns: true on success, stores the encoded data in dest, and the size in length.
887  *          false on failure.
888  */
889 int crypto_sign_encode(SIGNATURE *sig, uint8_t *dest, uint32_t *length)
890 {
891    if (*length == 0) {
892       *length = i2d_SignatureData(sig->sigData, NULL);
893       return true;
894    }
895
896    *length = i2d_SignatureData(sig->sigData, (unsigned char **)&dest);
897    return true;
898 }
899
900 /*
901  * Decodes the SignatureData structure. The length argument is used to specify the
902  * size of sigData.
903  *
904  * Returns: SIGNATURE instance on success.
905  *          NULL on failure.
906
907  */
908
909 SIGNATURE *crypto_sign_decode(const uint8_t *sigData, uint32_t length)
910 {
911    SIGNATURE *sig;
912 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
913    const unsigned char *p = (const unsigned char *) sigData;
914 #else
915    unsigned char *p = (unsigned char *)sigData;
916 #endif
917
918    sig = (SIGNATURE *)malloc(sizeof(SIGNATURE));
919    if (!sig) {
920       return NULL;
921    }
922
923    /* d2i_SignatureData modifies the supplied pointer */
924    sig->sigData  = d2i_SignatureData(NULL, &p, length);
925
926    if (!sig->sigData) {
927       /* Allocation / Decoding failed in OpenSSL */
928       openssl_post_errors(M_ERROR, _("Signature decoding failed"));
929       free(sig);
930       return NULL;
931    }
932
933    return sig;
934 }
935
936 /*
937  * Free memory associated with a signature object.
938  */
939 void crypto_sign_free(SIGNATURE *sig)
940 {
941    SignatureData_free(sig->sigData);
942    free (sig);
943 }
944
945 /*
946  * Create a new encryption session.
947  *  Returns: A pointer to a CRYPTO_SESSION object on success.
948  *           NULL on failure.
949  */
950 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys)
951 {
952    CRYPTO_SESSION *cs;
953    X509_KEYPAIR *keypair;
954    const EVP_CIPHER *ec;
955    unsigned char *iv;
956    int iv_len;
957
958    /* Allocate our session description structures */
959    cs = (CRYPTO_SESSION *) malloc(sizeof(CRYPTO_SESSION));
960    if (!cs) {
961       return NULL;
962    }
963
964    /* Initialize required fields */
965    cs->session_key = NULL;
966
967    /* Allocate a CryptoData structure */
968    cs->cryptoData = CryptoData_new();
969
970    if (!cs->cryptoData) {
971       /* Allocation failed in OpenSSL */
972       free(cs);
973       return NULL;
974    }
975
976    /* Set the ASN.1 structure version number */
977    ASN1_INTEGER_set(cs->cryptoData->version, BACULA_ASN1_VERSION);
978
979    /*
980     * Acquire a cipher instance and set the ASN.1 cipher NID
981     */
982    switch (cipher) {
983    case CRYPTO_CIPHER_AES_128_CBC:
984       /* AES 128 bit CBC */
985       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_128_cbc);
986       ec = EVP_aes_128_cbc();
987       break;
988    case CRYPTO_CIPHER_AES_192_CBC:
989       /* AES 192 bit CBC */
990       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_192_cbc);
991       ec = EVP_aes_192_cbc();
992       break;
993    case CRYPTO_CIPHER_AES_256_CBC:
994       /* AES 256 bit CBC */
995       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_256_cbc);
996       ec = EVP_aes_256_cbc();
997       break;
998    case CRYPTO_CIPHER_BLOWFISH_CBC:
999       /* Blowfish CBC */
1000       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_bf_cbc);
1001       ec = EVP_bf_cbc();
1002       break;
1003    default:
1004       Emsg0(M_ERROR, 0, _("Unsupported cipher type specified\n"));
1005       crypto_session_free(cs);
1006       return NULL;
1007    }
1008
1009    /* Generate a symmetric session key */
1010    cs->session_key_len = EVP_CIPHER_key_length(ec);
1011    cs->session_key = (unsigned char *) malloc(cs->session_key_len);
1012    if (RAND_bytes(cs->session_key, cs->session_key_len) <= 0) {
1013       /* OpenSSL failure */
1014       crypto_session_free(cs);
1015       return NULL;
1016    }
1017
1018    /* Generate an IV if possible */
1019    if ((iv_len = EVP_CIPHER_iv_length(ec))) {
1020       iv = (unsigned char *) malloc(iv_len);
1021       if (!iv) {
1022          /* Malloc failure */
1023          crypto_session_free(cs);
1024          return NULL;
1025       }
1026
1027       /* Generate random IV */
1028       if (RAND_bytes(iv, iv_len) <= 0) {
1029          /* OpenSSL failure */
1030          crypto_session_free(cs);
1031          free(iv);
1032          return NULL;
1033       }
1034
1035       /* Store it in our ASN.1 structure */
1036       if (!M_ASN1_OCTET_STRING_set(cs->cryptoData->iv, iv, iv_len)) {
1037          /* Allocation failed in OpenSSL */
1038          crypto_session_free(cs);
1039          free(iv);
1040          return NULL;
1041       }
1042       free(iv);
1043    }
1044
1045    /*
1046     * Create RecipientInfo structures for supplied
1047     * public keys.
1048     */
1049    foreach_alist(keypair, pubkeys) {
1050       RecipientInfo *ri;
1051       unsigned char *ekey;
1052       int ekey_len;
1053
1054       ri = RecipientInfo_new();
1055       if (!ri) {
1056          /* Allocation failed in OpenSSL */
1057          crypto_session_free(cs);
1058          return NULL;
1059       }
1060
1061       /* Set the ASN.1 structure version number */
1062       ASN1_INTEGER_set(ri->version, BACULA_ASN1_VERSION);
1063
1064       /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
1065       M_ASN1_OCTET_STRING_free(ri->subjectKeyIdentifier);
1066       ri->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
1067
1068       /* Set our key encryption algorithm. We currently require RSA */
1069       assert(keypair->pubkey && EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
1070       ri->keyEncryptionAlgorithm = OBJ_nid2obj(NID_rsaEncryption);
1071
1072       /* Encrypt the session key */
1073       ekey = (unsigned char *) malloc(EVP_PKEY_size(keypair->pubkey));
1074       if (!ekey) {
1075          RecipientInfo_free(ri);
1076          crypto_session_free(cs);
1077          return NULL;
1078       }
1079
1080       if ((ekey_len = EVP_PKEY_encrypt(ekey, cs->session_key, cs->session_key_len, keypair->pubkey)) <= 0) {
1081          /* OpenSSL failure */
1082          RecipientInfo_free(ri);
1083          crypto_session_free(cs);
1084          free(ekey);
1085          return NULL;
1086       }
1087
1088       /* Store it in our ASN.1 structure */
1089       if (!M_ASN1_OCTET_STRING_set(ri->encryptedKey, ekey, ekey_len)) {
1090          /* Allocation failed in OpenSSL */
1091          RecipientInfo_free(ri);
1092          crypto_session_free(cs);
1093          free(ekey);
1094          return NULL;
1095       }
1096
1097       /* Free the encrypted key buffer */
1098       free(ekey);
1099
1100       /* Push the new RecipientInfo structure onto the stack */
1101       sk_RecipientInfo_push(cs->cryptoData->recipientInfo, ri);
1102    }
1103
1104    return cs;
1105 }
1106
1107 /*
1108  * Encodes the CryptoData structure. The length argument is used to specify the
1109  * size of dest. A length of 0 will cause no data to be written to dest, and the
1110  * required length to be written to length. The caller can then allocate sufficient
1111  * space for the output.
1112  *
1113  * Returns: true on success, stores the encoded data in dest, and the size in length.
1114  *          false on failure.
1115  */
1116 bool crypto_session_encode(CRYPTO_SESSION *cs, uint8_t *dest, uint32_t *length)
1117 {
1118    if (*length == 0) {
1119       *length = i2d_CryptoData(cs->cryptoData, NULL);
1120       return true;
1121    }
1122
1123    *length = i2d_CryptoData(cs->cryptoData, &dest);
1124    return true;
1125 }
1126
1127 /*
1128  * Decodes the CryptoData structure. The length argument is
1129  * used to specify the size of data.
1130  *
1131  * Returns: CRYPTO_SESSION instance on success.
1132  *          NULL on failure.
1133  * Returns: CRYPTO_ERROR_NONE and a pointer to a newly allocated CRYPTO_SESSION structure in *session on success.
1134  *          A crypto_error_t value on failure.
1135  */
1136 crypto_error_t crypto_session_decode(const uint8_t *data, uint32_t length, alist *keypairs, CRYPTO_SESSION **session)
1137 {
1138    CRYPTO_SESSION *cs;
1139    X509_KEYPAIR *keypair;
1140    STACK_OF(RecipientInfo) *recipients;
1141    crypto_error_t retval = CRYPTO_ERROR_NONE;
1142 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
1143    const unsigned char *p = (const unsigned char *)data;
1144 #else
1145    unsigned char *p = (unsigned char *)data;
1146 #endif
1147
1148    /* bacula-fd.conf doesn't contains any key */
1149    if (!keypairs) {
1150       return CRYPTO_ERROR_NORECIPIENT;
1151    }
1152
1153    cs = (CRYPTO_SESSION *) malloc(sizeof(CRYPTO_SESSION));
1154    if (!cs) {
1155       return CRYPTO_ERROR_INTERNAL;
1156    }
1157
1158    /* Initialize required fields */
1159    cs->session_key = NULL;
1160
1161    /* d2i_CryptoData modifies the supplied pointer */
1162    cs->cryptoData = d2i_CryptoData(NULL, &p, length);
1163
1164    if (!cs->cryptoData) {
1165       /* Allocation / Decoding failed in OpenSSL */
1166       openssl_post_errors(M_ERROR, _("CryptoData decoding failed"));
1167       retval = CRYPTO_ERROR_INTERNAL;
1168       goto err;
1169    }
1170
1171    recipients = cs->cryptoData->recipientInfo;
1172
1173    /*
1174     * Find a matching RecipientInfo structure for a supplied
1175     * public key
1176     */
1177    foreach_alist(keypair, keypairs) {
1178       RecipientInfo *ri;
1179       int i;
1180
1181       /* Private key available? */
1182       if (keypair->privkey == NULL) {
1183          continue;
1184       }
1185
1186       for (i = 0; i < sk_RecipientInfo_num(recipients); i++) {
1187          ri = sk_RecipientInfo_value(recipients, i);
1188
1189          /* Match against the subjectKeyIdentifier */
1190          if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, ri->subjectKeyIdentifier) == 0) {
1191             /* Match found, extract symmetric encryption session data */
1192             
1193             /* RSA is required. */
1194             assert(EVP_PKEY_type(keypair->privkey->type) == EVP_PKEY_RSA);
1195
1196             /* If we recieve a RecipientInfo structure that does not use
1197              * RSA, return an error */
1198             if (OBJ_obj2nid(ri->keyEncryptionAlgorithm) != NID_rsaEncryption) {
1199                retval = CRYPTO_ERROR_INVALID_CRYPTO;
1200                goto err;
1201             }
1202
1203             /* Decrypt the session key */
1204             /* Allocate sufficient space for the largest possible decrypted data */
1205             cs->session_key = (unsigned char *) malloc(EVP_PKEY_size(keypair->privkey));
1206             cs->session_key_len = EVP_PKEY_decrypt(cs->session_key, M_ASN1_STRING_data(ri->encryptedKey),
1207                                   M_ASN1_STRING_length(ri->encryptedKey), keypair->privkey);
1208
1209             if (cs->session_key_len <= 0) {
1210                openssl_post_errors(M_ERROR, _("Failure decrypting the session key"));
1211                retval = CRYPTO_ERROR_DECRYPTION;
1212                goto err;
1213             }
1214
1215             /* Session key successfully extracted, return the CRYPTO_SESSION structure */
1216             *session = cs;
1217             return CRYPTO_ERROR_NONE;
1218          }
1219       }
1220    }
1221
1222    /* No matching recipient found */
1223    return CRYPTO_ERROR_NORECIPIENT;
1224
1225 err:
1226    crypto_session_free(cs);
1227    return retval;
1228 }
1229
1230 /*
1231  * Free memory associated with a crypto session object.
1232  */
1233 void crypto_session_free (CRYPTO_SESSION *cs)
1234 {
1235    if (cs->cryptoData) {
1236       CryptoData_free(cs->cryptoData);
1237    }
1238    if (cs->session_key){
1239       free(cs->session_key);
1240    }
1241    free(cs);
1242 }
1243
1244 /*
1245  * Create a new crypto cipher context with the specified session object
1246  *  Returns: A pointer to a CIPHER_CONTEXT object on success. The cipher block size is returned in blocksize.
1247  *           NULL on failure.
1248  */
1249 CIPHER_CONTEXT *crypto_cipher_new (CRYPTO_SESSION *cs, bool encrypt, uint32_t *blocksize)
1250 {
1251    CIPHER_CONTEXT *cipher_ctx;
1252    const EVP_CIPHER *ec;
1253
1254    cipher_ctx = (CIPHER_CONTEXT *) malloc(sizeof(CIPHER_CONTEXT));
1255    if (!cipher_ctx) {
1256       return NULL;
1257    }
1258
1259    /*
1260     * Acquire a cipher instance for the given ASN.1 cipher NID
1261     */
1262    if ((ec = EVP_get_cipherbyobj(cs->cryptoData->contentEncryptionAlgorithm)) == NULL) {
1263       Emsg1(M_ERROR, 0, _("Unsupported contentEncryptionAlgorithm: %d\n"), OBJ_obj2nid(cs->cryptoData->contentEncryptionAlgorithm));
1264       free(cipher_ctx);
1265       return NULL;
1266    }
1267
1268    /* Initialize the OpenSSL cipher context */
1269    EVP_CIPHER_CTX_init(&cipher_ctx->ctx);
1270    if (encrypt) {
1271       /* Initialize for encryption */
1272       if (!EVP_CipherInit_ex(&cipher_ctx->ctx, ec, NULL, NULL, NULL, 1)) {
1273          openssl_post_errors(M_ERROR, _("OpenSSL cipher context initialization failed"));
1274          goto err;
1275       }
1276    } else {
1277       /* Initialize for decryption */
1278       if (!EVP_CipherInit_ex(&cipher_ctx->ctx, ec, NULL, NULL, NULL, 0)) {
1279          openssl_post_errors(M_ERROR, _("OpenSSL cipher context initialization failed"));
1280          goto err;
1281       }
1282    }
1283
1284    /* Set the key size */
1285    if (!EVP_CIPHER_CTX_set_key_length(&cipher_ctx->ctx, cs->session_key_len)) {
1286       openssl_post_errors(M_ERROR, _("Encryption session provided an invalid symmetric key"));
1287       goto err;
1288    }
1289
1290    /* Validate the IV length */
1291    if (EVP_CIPHER_iv_length(ec) != M_ASN1_STRING_length(cs->cryptoData->iv)) {
1292       openssl_post_errors(M_ERROR, _("Encryption session provided an invalid IV"));
1293       goto err;
1294    }
1295    
1296    /* Add the key and IV to the cipher context */
1297    if (!EVP_CipherInit_ex(&cipher_ctx->ctx, NULL, NULL, cs->session_key, M_ASN1_STRING_data(cs->cryptoData->iv), -1)) {
1298       openssl_post_errors(M_ERROR, _("OpenSSL cipher context key/IV initialization failed"));
1299       goto err;
1300    }
1301
1302    *blocksize = EVP_CIPHER_CTX_block_size(&cipher_ctx->ctx);
1303    return cipher_ctx;
1304
1305 err:
1306    crypto_cipher_free(cipher_ctx);
1307    return NULL;
1308 }
1309
1310
1311 /*
1312  * Encrypt/Decrypt length bytes of data using the provided cipher context
1313  * Returns: true on success, number of bytes output in written
1314  *          false on failure
1315  */
1316 bool crypto_cipher_update(CIPHER_CONTEXT *cipher_ctx, const uint8_t *data, uint32_t length, const uint8_t *dest, uint32_t *written)
1317 {
1318    if (!EVP_CipherUpdate(&cipher_ctx->ctx, (unsigned char *)dest, (int *)written, (const unsigned char *)data, length)) {
1319       /* This really shouldn't fail */
1320       return false;
1321    } else {
1322       return true;
1323    }
1324 }
1325
1326 /*
1327  * Finalize the cipher context, writing any remaining data and necessary padding
1328  * to dest, and the size in written.
1329  * The result size will either be one block of data or zero.
1330  *
1331  * Returns: true on success
1332  *          false on failure
1333  */
1334 bool crypto_cipher_finalize (CIPHER_CONTEXT *cipher_ctx, uint8_t *dest, uint32_t *written)
1335 {
1336    if (!EVP_CipherFinal_ex(&cipher_ctx->ctx, (unsigned char *)dest, (int *) written)) {
1337       /* This really shouldn't fail */
1338       return false;
1339    } else {
1340       return true;
1341    }
1342 }
1343
1344
1345 /*
1346  * Free memory associated with a cipher context.
1347  */
1348 void crypto_cipher_free (CIPHER_CONTEXT *cipher_ctx)
1349 {
1350    EVP_CIPHER_CTX_cleanup(&cipher_ctx->ctx);
1351    free (cipher_ctx);
1352 }
1353
1354
1355 /*
1356  * Perform global initialization of OpenSSL
1357  * This function is not thread safe.
1358  *  Returns: 0 on success
1359  *           errno on failure
1360  */
1361 int init_crypto (void)
1362 {
1363    int stat;
1364
1365    if ((stat = openssl_init_threads()) != 0) {
1366       Emsg1(M_ABORT, 0, _("Unable to init OpenSSL threading: ERR=%s\n"), strerror(stat));
1367    }
1368
1369    /* Load libssl and libcrypto human-readable error strings */
1370    SSL_load_error_strings();
1371
1372    /* Initialize OpenSSL SSL  library */
1373    SSL_library_init();
1374
1375    /* Register OpenSSL ciphers and digests */
1376    OpenSSL_add_all_algorithms();
1377
1378    if (!openssl_seed_prng()) {
1379       Emsg0(M_ERROR_TERM, 0, _("Failed to seed OpenSSL PRNG\n"));
1380    }
1381
1382    crypto_initialized = true;
1383
1384    return stat;
1385 }
1386
1387 /*
1388  * Perform global cleanup of OpenSSL
1389  * All cryptographic operations must be completed before calling this function.
1390  * This function is not thread safe.
1391  *  Returns: 0 on success
1392  *           errno on failure
1393  */
1394 int cleanup_crypto (void)
1395 {
1396    /*
1397     * Ensure that we've actually been initialized; Doing this here decreases the
1398     * complexity of client's termination/cleanup code.
1399     */
1400    if (!crypto_initialized) {
1401       return 0;
1402    }
1403
1404    if (!openssl_save_prng()) {
1405       Emsg0(M_ERROR, 0, _("Failed to save OpenSSL PRNG\n"));
1406    }
1407
1408    openssl_cleanup_threads();
1409
1410    /* Free libssl and libcrypto error strings */
1411    ERR_free_strings();
1412
1413    /* Free all ciphers and digests */
1414    EVP_cleanup();
1415
1416    /* Free memory used by PRNG */
1417    RAND_cleanup();
1418
1419    crypto_initialized = false;
1420
1421    return 0;
1422 }
1423
1424
1425 #else /* HAVE_OPENSSL */
1426 # error No encryption library available
1427 #endif /* HAVE_OPENSSL */
1428
1429 #else /* HAVE_CRYPTO */
1430
1431 /*
1432  * Cryptography Support Disabled
1433  */
1434
1435 /* Message Digest Structure */
1436 struct Digest {
1437    crypto_digest_t type;
1438    union {
1439       SHA1Context sha1;
1440       MD5Context md5;
1441    };
1442 };
1443
1444 /* Dummy Signature Structure */
1445 struct Signature {
1446 };
1447
1448 DIGEST *crypto_digest_new (crypto_digest_t type)
1449 {
1450    DIGEST *digest;
1451
1452    digest = (DIGEST *)malloc(sizeof(DIGEST));
1453    digest->type = type;
1454
1455    switch (type) {
1456    case CRYPTO_DIGEST_MD5:
1457       MD5Init(&digest->md5);
1458       break;
1459    case CRYPTO_DIGEST_SHA1:
1460       SHA1Init(&digest->sha1);
1461       break;
1462    default:
1463       Emsg0(M_ERROR, 0, _("Unsupported digest type specified\n"));
1464       free(digest);
1465       return NULL;
1466    }
1467
1468    return (digest);
1469 }
1470
1471 bool crypto_digest_update(DIGEST *digest, const uint8_t *data, uint32_t length)
1472 {
1473    switch (digest->type) {
1474    case CRYPTO_DIGEST_MD5:
1475       /* Doesn't return anything ... */
1476       MD5Update(&digest->md5, (unsigned char *) data, length);
1477       return true;
1478    case CRYPTO_DIGEST_SHA1:
1479       int ret;
1480       if ((ret = SHA1Update(&digest->sha1, (const u_int8_t *) data, length)) == shaSuccess) {
1481          return true;
1482       } else {
1483          Emsg1(M_ERROR, 0, _("SHA1Update() returned an error: %d\n"), ret);
1484          return false;
1485       }
1486       break;
1487    default:
1488       return false;
1489    }
1490 }
1491
1492 bool crypto_digest_finalize(DIGEST *digest, uint8_t *dest, uint32_t *length) 
1493 {
1494    switch (digest->type) {
1495    case CRYPTO_DIGEST_MD5:
1496       /* Guard against programmer error by either the API client or
1497        * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1498       assert(*length >= CRYPTO_DIGEST_MD5_SIZE);
1499       *length = CRYPTO_DIGEST_MD5_SIZE;
1500       /* Doesn't return anything ... */
1501       MD5Final((unsigned char *)dest, &digest->md5);
1502       return true;
1503    case CRYPTO_DIGEST_SHA1:
1504       /* Guard against programmer error by either the API client or
1505        * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1506       assert(*length >= CRYPTO_DIGEST_SHA1_SIZE);
1507       *length = CRYPTO_DIGEST_SHA1_SIZE;
1508       if (SHA1Final(&digest->sha1, (u_int8_t *) dest) == shaSuccess) {
1509          return true;
1510       } else {
1511          return false;
1512       }
1513       break;
1514    default:
1515       return false;
1516    }
1517
1518    return false;
1519 }
1520
1521 void crypto_digest_free(DIGEST *digest)
1522 {
1523    free (digest);
1524 }
1525
1526 /* Dummy routines */
1527 int init_crypto (void) { return 0; }
1528 int cleanup_crypto (void) { return 0; }
1529
1530 SIGNATURE *crypto_sign_new (void) { return NULL; }
1531
1532 crypto_error_t crypto_sign_get_digest (SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST **digest) { return CRYPTO_ERROR_INTERNAL; }
1533 crypto_error_t crypto_sign_verify (SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest) { return CRYPTO_ERROR_INTERNAL; }
1534
1535 int crypto_sign_add_signer (SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair) { return false; }
1536 int crypto_sign_encode (SIGNATURE *sig, uint8_t *dest, uint32_t *length) { return false; }
1537
1538 SIGNATURE *crypto_sign_decode (const uint8_t *sigData, uint32_t length) { return NULL; }
1539 void crypto_sign_free (SIGNATURE *sig) { }
1540
1541
1542 X509_KEYPAIR *crypto_keypair_new (void) { return NULL; }
1543 X509_KEYPAIR *crypto_keypair_dup (X509_KEYPAIR *keypair) { return NULL; }
1544 int crypto_keypair_load_cert (X509_KEYPAIR *keypair, const char *file) { return false; }
1545 bool crypto_keypair_has_key (const char *file) { return false; }
1546 int crypto_keypair_load_key (X509_KEYPAIR *keypair, const char *file, CRYPTO_PEM_PASSWD_CB *pem_callback, const void *pem_userdata) { return false; }
1547 void crypto_keypair_free (X509_KEYPAIR *keypair) { }
1548
1549 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys) { return NULL; }
1550 void crypto_session_free (CRYPTO_SESSION *cs) { }
1551 bool crypto_session_encode (CRYPTO_SESSION *cs, uint8_t *dest, uint32_t *length) { return false; }
1552 crypto_error_t crypto_session_decode(const uint8_t *data, uint32_t length, alist *keypairs, CRYPTO_SESSION **session) { return CRYPTO_ERROR_INTERNAL; }
1553
1554 CIPHER_CONTEXT *crypto_cipher_new (CRYPTO_SESSION *cs, bool encrypt, uint32_t *blocksize) { return NULL; }
1555 bool crypto_cipher_update (CIPHER_CONTEXT *cipher_ctx, const uint8_t *data, uint32_t length, const uint8_t *dest, uint32_t *written) { return false; }
1556 bool crypto_cipher_finalize (CIPHER_CONTEXT *cipher_ctx, uint8_t *dest, uint32_t *written) { return false; }
1557 void crypto_cipher_free (CIPHER_CONTEXT *cipher_ctx) { }
1558
1559 #endif /* HAVE_CRYPTO */
1560
1561 /* Shared Code */
1562
1563 /*
1564  * Default PEM encryption passphrase callback.
1565  * Returns an empty password.
1566  */
1567 int crypto_default_pem_callback(char *buf, int size, const void *userdata)
1568 {
1569    bstrncpy(buf, "", size);
1570    return (strlen(buf));
1571 }
1572
1573 /*
1574  * Returns the ASCII name of the digest type.
1575  * Returns: ASCII name of digest type.
1576  */
1577 const char *crypto_digest_name (DIGEST *digest) {
1578    switch (digest->type) {
1579    case CRYPTO_DIGEST_MD5:
1580       return "MD5";
1581    case CRYPTO_DIGEST_SHA1:
1582       return "SHA1";
1583    case CRYPTO_DIGEST_SHA256:
1584       return "SHA256";
1585    case CRYPTO_DIGEST_SHA512:
1586       return "SHA512";
1587    case CRYPTO_DIGEST_NONE:
1588       return "None";
1589    default:
1590       return "Invalid Digest Type";
1591    }
1592
1593 }
1594
1595 /*
1596  * Given a stream type, returns the associated
1597  * crypto_digest_t value.
1598  */
1599 crypto_digest_t crypto_digest_stream_type (int stream) {
1600    switch (stream) {
1601    case STREAM_MD5_DIGEST:
1602       return CRYPTO_DIGEST_MD5;
1603    case STREAM_SHA1_DIGEST:
1604       return CRYPTO_DIGEST_SHA1;
1605    case STREAM_SHA256_DIGEST:
1606       return CRYPTO_DIGEST_SHA256;
1607    case STREAM_SHA512_DIGEST:
1608       return CRYPTO_DIGEST_SHA512;
1609    default:
1610       return CRYPTO_DIGEST_NONE;
1611    }
1612 }
1613
1614 /*
1615  *  * Given a crypto_error_t value, return the associated
1616  *   * error string
1617  *    */
1618 const char *crypto_strerror(crypto_error_t error) {
1619    switch (error) {
1620    case CRYPTO_ERROR_NONE:
1621       return "No error";
1622    case CRYPTO_ERROR_NOSIGNER:
1623       return "Signer not found";
1624    case CRYPTO_ERROR_NORECIPIENT:
1625       return "Recipient not found";
1626    case CRYPTO_ERROR_INVALID_DIGEST:
1627       return "Unsupported digest algorithm";
1628    case CRYPTO_ERROR_INVALID_CRYPTO:
1629       return "Unsupported encryption algorithm";
1630    case CRYPTO_ERROR_BAD_SIGNATURE:
1631       return "Signature is invalid";
1632    case CRYPTO_ERROR_DECRYPTION:
1633       return "Decryption error";
1634    case CRYPTO_ERROR_INTERNAL:
1635       /* This shouldn't happen */
1636       return "Internal error";
1637    default:
1638       return "Unknown error";
1639    }
1640 }