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