]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/crypto.c
4b9f0f2a2f3a9a4a8b2087f20131be1f9bf274e8
[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 #include "openssl-compat.h"
135
136 /* ASN.1 Declarations */
137 #define BACULA_ASN1_VERSION 0
138
139 typedef struct {
140    ASN1_INTEGER *version;
141    ASN1_OCTET_STRING *subjectKeyIdentifier;
142    ASN1_OBJECT *digestAlgorithm;
143    ASN1_OBJECT *signatureAlgorithm;
144    ASN1_OCTET_STRING *signature;
145 } SignerInfo;
146
147 typedef struct {
148    ASN1_INTEGER *version;
149    ASN1_OCTET_STRING *subjectKeyIdentifier;
150    ASN1_OBJECT *keyEncryptionAlgorithm;
151    ASN1_OCTET_STRING *encryptedKey;
152 } RecipientInfo;
153
154 ASN1_SEQUENCE(SignerInfo) = {
155    ASN1_SIMPLE(SignerInfo, version, ASN1_INTEGER),
156    ASN1_SIMPLE(SignerInfo, subjectKeyIdentifier, ASN1_OCTET_STRING),
157    ASN1_SIMPLE(SignerInfo, digestAlgorithm, ASN1_OBJECT),
158    ASN1_SIMPLE(SignerInfo, signatureAlgorithm, ASN1_OBJECT),
159    ASN1_SIMPLE(SignerInfo, signature, ASN1_OCTET_STRING)
160 } ASN1_SEQUENCE_END(SignerInfo);
161
162 ASN1_SEQUENCE(RecipientInfo) = {
163    ASN1_SIMPLE(RecipientInfo, version, ASN1_INTEGER),
164    ASN1_SIMPLE(RecipientInfo, subjectKeyIdentifier, ASN1_OCTET_STRING),
165    ASN1_SIMPLE(RecipientInfo, keyEncryptionAlgorithm, ASN1_OBJECT),
166    ASN1_SIMPLE(RecipientInfo, encryptedKey, ASN1_OCTET_STRING),
167 } ASN1_SEQUENCE_END(RecipientInfo);
168
169 typedef struct {
170    ASN1_INTEGER *version;
171    STACK_OF(SignerInfo) *signerInfo;
172 } SignatureData;
173
174 typedef struct {
175    ASN1_INTEGER *version;
176    ASN1_OBJECT *contentEncryptionAlgorithm;
177    ASN1_OCTET_STRING *iv;
178    STACK_OF(RecipientInfo) *recipientInfo;
179 } CryptoData;
180
181 ASN1_SEQUENCE(SignatureData) = {
182    ASN1_SIMPLE(SignatureData, version, ASN1_INTEGER),
183    ASN1_SET_OF(SignatureData, signerInfo, SignerInfo),
184 } ASN1_SEQUENCE_END(SignatureData);
185
186 ASN1_SEQUENCE(CryptoData) = {
187    ASN1_SIMPLE(CryptoData, version, ASN1_INTEGER),
188    ASN1_SIMPLE(CryptoData, contentEncryptionAlgorithm, ASN1_OBJECT),
189    ASN1_SIMPLE(CryptoData, iv, ASN1_OCTET_STRING),
190    ASN1_SET_OF(CryptoData, recipientInfo, RecipientInfo)
191 } ASN1_SEQUENCE_END(CryptoData);
192
193 IMPLEMENT_ASN1_FUNCTIONS(SignerInfo)
194 IMPLEMENT_ASN1_FUNCTIONS(RecipientInfo)
195 IMPLEMENT_ASN1_FUNCTIONS(SignatureData)
196 IMPLEMENT_ASN1_FUNCTIONS(CryptoData)
197
198 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
199 DEFINE_STACK_OF(SignerInfo);
200 DEFINE_STACK_OF(RecipientInfo);
201 #else
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 #endif
266
267 /* X509 Public/Private Key Pair Structure */
268 struct X509_Keypair {
269    ASN1_OCTET_STRING *keyid;
270    EVP_PKEY *pubkey;
271    EVP_PKEY *privkey;
272 };
273
274 /* Message Digest Structure */
275 struct Digest {
276    crypto_digest_t type;
277    JCR *jcr;
278    EVP_MD_CTX ctx;
279 };
280
281 /* Message Signature Structure */
282 struct Signature {
283    SignatureData *sigData;
284    JCR *jcr;
285 };
286
287 /* Encryption Session Data */
288 struct Crypto_Session {
289    CryptoData *cryptoData;                        /* ASN.1 Structure */
290    unsigned char *session_key;                    /* Private symmetric session key */
291    size_t session_key_len;                        /* Symmetric session key length */
292 };
293
294 /* Symmetric Cipher Context */
295 struct Cipher_Context {
296    EVP_CIPHER_CTX ctx;
297 };
298
299 /* PEM Password Dispatch Context */
300 typedef struct PEM_CB_Context {
301    CRYPTO_PEM_PASSWD_CB *pem_callback;
302    const void *pem_userdata;
303 } PEM_CB_CONTEXT;
304
305 /*
306  * Extract subjectKeyIdentifier from x509 certificate.
307  * Returns: On success, an ASN1_OCTET_STRING that must be freed via M_ASN1_OCTET_STRING_free().
308  *          NULL on failure.
309  */
310 static ASN1_OCTET_STRING *openssl_cert_keyid(X509 *cert) {
311    X509_EXTENSION *ext;
312    const X509V3_EXT_METHOD *method;
313    ASN1_OCTET_STRING *keyid;
314    int i;
315    const unsigned char *ext_value_data;
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 (method->it) {
335       /* New style ASN1 */
336
337       /* Decode ASN1 item in data */
338       keyid = (ASN1_OCTET_STRING *) ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
339                                                   ASN1_ITEM_ptr(method->it));
340    } else {
341       /* Old style ASN1 */
342
343       /* Decode ASN1 item in data */
344       keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
345    }
346
347    return keyid;
348 }
349
350 /*
351  * Create a new keypair object.
352  *  Returns: A pointer to a X509 KEYPAIR object on success.
353  *           NULL on failure.
354  */
355 X509_KEYPAIR *crypto_keypair_new(void)
356 {
357    X509_KEYPAIR *keypair;
358
359    /* Allocate our keypair structure */
360    keypair = (X509_KEYPAIR *)malloc(sizeof(X509_KEYPAIR));
361
362    /* Initialize our keypair structure */
363    keypair->keyid = NULL;
364    keypair->pubkey = NULL;
365    keypair->privkey = NULL;
366
367    return keypair;
368 }
369
370 /*
371  * Create a copy of a keypair object. The underlying
372  * EVP objects are not duplicated, as no EVP_PKEY_dup()
373  * API is available. Instead, the reference count is
374  * incremented.
375  */
376 X509_KEYPAIR *crypto_keypair_dup(X509_KEYPAIR *keypair)
377 {
378    X509_KEYPAIR *newpair;
379
380    newpair = crypto_keypair_new();
381
382    if (!newpair) {
383       /* Allocation failed */
384       return NULL;
385    }
386
387    /* Increment the public key ref count */
388    if (keypair->pubkey) {
389       CRYPTO_add(&(keypair->pubkey->references), 1, CRYPTO_LOCK_EVP_PKEY);
390       newpair->pubkey = keypair->pubkey;
391    }
392
393    /* Increment the private key ref count */
394    if (keypair->privkey) {
395       CRYPTO_add(&(keypair->privkey->references), 1, CRYPTO_LOCK_EVP_PKEY);
396       newpair->privkey = keypair->privkey;
397    }
398
399    /* Duplicate the keyid */
400    if (keypair->keyid) {
401       newpair->keyid = M_ASN1_OCTET_STRING_dup(keypair->keyid);
402       if (!newpair->keyid) {
403          /* Allocation failed */
404          crypto_keypair_free(newpair);
405          return NULL;
406       }
407    }
408
409    return newpair;
410 }
411
412
413 /*
414  * Load a public key from a PEM-encoded x509 certificate.
415  *  Returns: true on success
416  *           false on failure
417  */
418 int crypto_keypair_load_cert(X509_KEYPAIR *keypair, const char *file)
419 {
420    BIO *bio;
421    X509 *cert;
422
423    /* Open the file */
424    if (!(bio = BIO_new_file(file, "r"))) {
425       openssl_post_errors(M_ERROR, _("Unable to open certificate file"));
426       return false;
427    }
428
429    cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
430    BIO_free(bio);
431    if (!cert) {
432       openssl_post_errors(M_ERROR, _("Unable to read certificate from file"));
433       return false;
434    }
435
436    /* Extract the public key */
437    if (!(keypair->pubkey = X509_get_pubkey(cert))) {
438       openssl_post_errors(M_ERROR, _("Unable to extract public key from certificate"));
439       goto err;
440    }
441
442    /* Extract the subjectKeyIdentifier extension field */
443    if ((keypair->keyid = openssl_cert_keyid(cert)) == NULL) {
444       Jmsg0(NULL, M_ERROR, 0,
445          _("Provided certificate does not include the required subjectKeyIdentifier extension."));
446       goto err;
447    }
448
449    /* Validate the public key type (only RSA is supported) */
450    if (EVP_PKEY_type(keypair->pubkey->type) != EVP_PKEY_RSA) {
451        Jmsg1(NULL, M_ERROR, 0,
452              _("Unsupported key type provided: %d\n"), EVP_PKEY_type(keypair->pubkey->type));
453        goto err;
454    }
455
456    X509_free(cert);
457    return true;
458
459 err:
460    X509_free(cert);
461    if (keypair->pubkey) {
462       EVP_PKEY_free(keypair->pubkey);
463    }
464    return false;
465 }
466
467 /* Dispatch user PEM encryption callbacks */
468 static int crypto_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
469 {
470    PEM_CB_CONTEXT *ctx = (PEM_CB_CONTEXT *) userdata;
471    return (ctx->pem_callback(buf, size, ctx->pem_userdata));
472 }
473
474 /*
475  * Check a PEM-encoded file
476  * for the existence of a private key.
477  * Returns: true if a private key is found
478  *          false otherwise
479  */
480 bool crypto_keypair_has_key(const char *file) {
481    BIO *bio;
482    char *name = NULL;
483    char *header = NULL;
484    unsigned char *data = NULL;
485    bool retval = false;
486    long len;
487
488    if (!(bio = BIO_new_file(file, "r"))) {
489       openssl_post_errors(M_ERROR, _("Unable to open private key file"));
490       return false;
491    }
492
493    while (PEM_read_bio(bio, &name, &header, &data, &len)) {
494       /* We don't care what the data is, just that it's there */
495       OPENSSL_free(header);
496       OPENSSL_free(data);
497
498       /*
499        * PEM Header Found, check for a private key
500        * Due to OpenSSL limitations, we must specifically
501        * list supported PEM private key encodings.
502        */
503       if (strcmp(name, PEM_STRING_RSA) == 0
504             || strcmp(name, PEM_STRING_DSA) == 0
505             || strcmp(name, PEM_STRING_PKCS8) == 0
506             || strcmp(name, PEM_STRING_PKCS8INF) == 0) {
507          retval = true;
508          OPENSSL_free(name);
509          break;
510       } else {
511          OPENSSL_free(name);
512       }
513    }
514
515    /* Free our bio */
516    BIO_free(bio);
517
518    /* Post PEM-decoding error messages, if any */
519    openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
520    return retval;
521 }
522
523 /*
524  * Load a PEM-encoded private key.
525  *  Returns: true on success
526  *           false on failure
527  */
528 int crypto_keypair_load_key(X509_KEYPAIR *keypair, const char *file,
529                              CRYPTO_PEM_PASSWD_CB *pem_callback,
530                              const void *pem_userdata)
531 {
532    BIO *bio;
533    PEM_CB_CONTEXT ctx;
534
535    /* Open the file */
536    if (!(bio = BIO_new_file(file, "r"))) {
537       openssl_post_errors(M_ERROR, _("Unable to open private key file"));
538       return false;
539    }
540
541    /* Set up PEM encryption callback */
542    if (pem_callback) {
543       ctx.pem_callback = pem_callback;
544       ctx.pem_userdata = pem_userdata;
545    } else {
546       ctx.pem_callback = crypto_default_pem_callback;
547       ctx.pem_userdata = NULL;
548    }
549
550    keypair->privkey = PEM_read_bio_PrivateKey(bio, NULL, crypto_pem_callback_dispatch, &ctx);
551    BIO_free(bio);
552    if (!keypair->privkey) {
553       openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
554       return false;
555    }
556
557    return true;
558 }
559
560 /*
561  * Free memory associated with a keypair object.
562  */
563 void crypto_keypair_free(X509_KEYPAIR *keypair)
564 {
565    if (keypair->pubkey) {
566       EVP_PKEY_free(keypair->pubkey);
567    }
568    if (keypair->privkey) {
569       EVP_PKEY_free(keypair->privkey);
570    }
571    if (keypair->keyid) {
572       M_ASN1_OCTET_STRING_free(keypair->keyid);
573    }
574    free(keypair);
575 }
576
577 /*
578  * Create a new message digest context of the specified type
579  *  Returns: A pointer to a DIGEST object on success.
580  *           NULL on failure.
581  */
582 DIGEST *crypto_digest_new(JCR *jcr, crypto_digest_t type)
583 {
584    DIGEST *digest;
585    const EVP_MD *md = NULL; /* Quell invalid uninitialized warnings */
586
587    digest = (DIGEST *)malloc(sizeof(DIGEST));
588    digest->type = type;
589    digest->jcr = jcr;
590    Dmsg1(150, "crypto_digest_new jcr=%p\n", jcr);
591
592    /* Initialize the OpenSSL message digest context */
593    EVP_MD_CTX_init(&digest->ctx);
594
595    /* Determine the correct OpenSSL message digest type */
596    switch (type) {
597    case CRYPTO_DIGEST_MD5:
598       md = EVP_md5();
599       break;
600    case CRYPTO_DIGEST_SHA1:
601       md = EVP_sha1();
602       break;
603 #ifdef HAVE_SHA2
604    case CRYPTO_DIGEST_SHA256:
605       md = EVP_sha256();
606       break;
607    case CRYPTO_DIGEST_SHA512:
608       md = EVP_sha512();
609       break;
610 #endif
611    default:
612       Jmsg1(jcr, M_ERROR, 0, _("Unsupported digest type: %d\n"), type);
613       goto err;
614    }
615
616    /* Initialize the backing OpenSSL context */
617    if (EVP_DigestInit_ex(&digest->ctx, md, NULL) == 0) {
618       goto err;
619    }
620
621    return digest;
622
623 err:
624    /* This should not happen, but never say never ... */
625    Dmsg0(150, "Digest init failed.\n");
626    openssl_post_errors(jcr, M_ERROR, _("OpenSSL digest initialization failed"));
627    crypto_digest_free(digest);
628    return NULL;
629 }
630
631 /*
632  * Hash length bytes of data into the provided digest context.
633  * Returns: true on success
634  *          false on failure
635  */
636 bool crypto_digest_update(DIGEST *digest, const uint8_t *data, uint32_t length)
637 {
638    if (EVP_DigestUpdate(&digest->ctx, data, length) == 0) {
639       Dmsg0(150, "digest update failed\n");
640       openssl_post_errors(digest->jcr, M_ERROR, _("OpenSSL digest update failed"));
641       return false;
642    } else {
643       return true;
644    }
645 }
646
647 /*
648  * Finalize the data in digest, storing the result in dest and the result size
649  * in length. The result size can be determined with crypto_digest_size().
650  *
651  * Returns: true on success
652  *          false on failure
653  */
654 bool crypto_digest_finalize(DIGEST *digest, uint8_t *dest, uint32_t *length)
655 {
656    if (!EVP_DigestFinal(&digest->ctx, dest, (unsigned int *)length)) {
657       Dmsg0(150, "digest finalize failed\n");
658       openssl_post_errors(digest->jcr, M_ERROR, _("OpenSSL digest finalize failed"));
659       return false;
660    } else {
661       return true;
662    }
663 }
664
665 /*
666  * Free memory associated with a digest object.
667  */
668 void crypto_digest_free(DIGEST *digest)
669 {
670   EVP_MD_CTX_cleanup(&digest->ctx);
671   free(digest);
672 }
673
674 /*
675  * Create a new message signature context.
676  *  Returns: A pointer to a SIGNATURE object on success.
677  *           NULL on failure.
678  */
679 SIGNATURE *crypto_sign_new(JCR *jcr)
680 {
681    SIGNATURE *sig;
682
683    sig = (SIGNATURE *)malloc(sizeof(SIGNATURE));
684    if (!sig) {
685       return NULL;
686    }
687
688    sig->sigData = SignatureData_new();
689    sig->jcr = jcr;
690    Dmsg1(150, "crypto_sign_new jcr=%p\n", jcr);
691
692    if (!sig->sigData) {
693       /* Allocation failed in OpenSSL */
694       free(sig);
695       return NULL;
696    }
697
698    /* Set the ASN.1 structure version number */
699    ASN1_INTEGER_set(sig->sigData->version, BACULA_ASN1_VERSION);
700
701    return sig;
702 }
703
704 /*
705  * For a given public key, find the associated SignatureInfo record
706  *   and create a digest context for signature validation
707  *
708  * Returns: CRYPTO_ERROR_NONE on success, with the newly allocated DIGEST in digest.
709  *          A crypto_error_t value on failure.
710  */
711 crypto_error_t crypto_sign_get_digest(SIGNATURE *sig, X509_KEYPAIR *keypair,
712                                       crypto_digest_t &type, DIGEST **digest)
713 {
714    STACK_OF(SignerInfo) *signers;
715    SignerInfo *si;
716    int i;
717
718    signers = sig->sigData->signerInfo;
719
720    for (i = 0; i < sk_SignerInfo_num(signers); i++) {
721       si = sk_SignerInfo_value(signers, i);
722       if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
723          /* Get the digest algorithm and allocate a digest context */
724          Dmsg1(150, "crypto_sign_get_digest jcr=%p\n", sig->jcr);
725          switch (OBJ_obj2nid(si->digestAlgorithm)) {
726          case NID_md5:
727             Dmsg0(100, "sign digest algorithm is MD5\n");
728             type = CRYPTO_DIGEST_MD5;
729             *digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_MD5);
730             break;
731          case NID_sha1:
732             Dmsg0(100, "sign digest algorithm is SHA1\n");
733             type = CRYPTO_DIGEST_SHA1;
734             *digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA1);
735             break;
736 #ifdef HAVE_SHA2
737          case NID_sha256:
738             Dmsg0(100, "sign digest algorithm is SHA256\n");
739             type = CRYPTO_DIGEST_SHA256;
740             *digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA256);
741             break;
742          case NID_sha512:
743             Dmsg0(100, "sign digest algorithm is SHA512\n");
744             type = CRYPTO_DIGEST_SHA512;
745             *digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA512);
746             break;
747 #endif
748          default:
749             type = CRYPTO_DIGEST_NONE;
750             *digest = NULL;
751             return CRYPTO_ERROR_INVALID_DIGEST;
752          }
753
754          /* Shouldn't happen */
755          if (*digest == NULL) {
756             openssl_post_errors(sig->jcr, M_ERROR, _("OpenSSL digest_new failed"));
757             return CRYPTO_ERROR_INVALID_DIGEST;
758          } else {
759             return CRYPTO_ERROR_NONE;
760          }
761       } else {
762          openssl_post_errors(sig->jcr, M_ERROR, _("OpenSSL sign get digest failed"));
763       }
764
765    }
766
767    return CRYPTO_ERROR_NOSIGNER;
768 }
769
770 /*
771  * For a given signature, public key, and digest, verify the SIGNATURE.
772  * Returns: CRYPTO_ERROR_NONE on success.
773  *          A crypto_error_t value on failure.
774  */
775 crypto_error_t crypto_sign_verify(SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest)
776 {
777    STACK_OF(SignerInfo) *signers;
778    SignerInfo *si;
779    int ok, i;
780    unsigned int sigLen;
781    const unsigned char *sigData;
782
783    signers = sig->sigData->signerInfo;
784
785    /* Find the signer */
786    for (i = 0; i < sk_SignerInfo_num(signers); i++) {
787       si = sk_SignerInfo_value(signers, i);
788       if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
789          /* Extract the signature data */
790          sigLen = M_ASN1_STRING_length(si->signature);
791          sigData = M_ASN1_STRING_data(si->signature);
792
793          ok = EVP_VerifyFinal(&digest->ctx, sigData, sigLen, keypair->pubkey);
794          if (ok >= 1) {
795             return CRYPTO_ERROR_NONE;
796          } else if (ok == 0) {
797             openssl_post_errors(sig->jcr, M_ERROR, _("OpenSSL digest Verify final failed"));
798             return CRYPTO_ERROR_BAD_SIGNATURE;
799          } else if (ok < 0) {
800             /* Shouldn't happen */
801             openssl_post_errors(sig->jcr, M_ERROR, _("OpenSSL digest Verify final failed"));
802             return CRYPTO_ERROR_INTERNAL;
803          }
804       }
805    }
806    Jmsg(sig->jcr, M_ERROR, 0, _("No signers found for crypto verify.\n"));
807    /* Signer wasn't found. */
808    return CRYPTO_ERROR_NOSIGNER;
809 }
810
811
812 /*
813  * Add a new signer
814  *  Returns: true on success
815  *           false on failure
816  */
817 int crypto_sign_add_signer(SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair)
818 {
819    SignerInfo *si = NULL;
820    unsigned char *buf = NULL;
821    unsigned int len;
822
823    si = SignerInfo_new();
824
825    if (!si) {
826       /* Allocation failed in OpenSSL */
827       return false;
828    }
829
830    /* Set the ASN.1 structure version number */
831    ASN1_INTEGER_set(si->version, BACULA_ASN1_VERSION);
832
833    /* Set the digest algorithm identifier */
834    switch (digest->type) {
835    case CRYPTO_DIGEST_MD5:
836       si->digestAlgorithm = OBJ_nid2obj(NID_md5);
837       break;
838    case CRYPTO_DIGEST_SHA1:
839       si->digestAlgorithm = OBJ_nid2obj(NID_sha1);
840       break;
841 #ifdef HAVE_SHA2
842    case CRYPTO_DIGEST_SHA256:
843       si->digestAlgorithm = OBJ_nid2obj(NID_sha256);
844       break;
845    case CRYPTO_DIGEST_SHA512:
846       si->digestAlgorithm = OBJ_nid2obj(NID_sha512);
847       break;
848 #endif
849    default:
850       /* This should never happen */
851       goto err;
852    }
853
854    /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
855    M_ASN1_OCTET_STRING_free(si->subjectKeyIdentifier);
856    si->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
857
858    /* Set our signature algorithm. We currently require RSA */
859    assert(EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
860    /* This is slightly evil. Reach into the MD structure and grab the key type */
861    si->signatureAlgorithm = OBJ_nid2obj(digest->ctx.digest->pkey_type);
862
863    /* Finalize/Sign our Digest */
864    len = EVP_PKEY_size(keypair->privkey);
865    buf = (unsigned char *) malloc(len);
866    if (!EVP_SignFinal(&digest->ctx, buf, &len, keypair->privkey)) {
867       openssl_post_errors(M_ERROR, _("Signature creation failed"));
868       goto err;
869    }
870
871    /* Add the signature to the SignerInfo structure */
872    if (!M_ASN1_OCTET_STRING_set(si->signature, buf, len)) {
873       /* Allocation failed in OpenSSL */
874       goto err;
875    }
876
877    /* No longer needed */
878    free(buf);
879
880    /* Push the new SignerInfo structure onto the stack */
881    sk_SignerInfo_push(sig->sigData->signerInfo, si);
882
883    return true;
884
885 err:
886    if (si) {
887       SignerInfo_free(si);
888    }
889    if (buf) {
890       free(buf);
891    }
892
893    return false;
894 }
895
896 /*
897  * Encodes the SignatureData structure. The length argument is used to specify the
898  * size of dest. A length of 0 will cause no data to be written to dest, and the
899  * required length to be written to length. The caller can then allocate sufficient
900  * space for the output.
901  *
902  * Returns: true on success, stores the encoded data in dest, and the size in length.
903  *          false on failure.
904  */
905 int crypto_sign_encode(SIGNATURE *sig, uint8_t *dest, uint32_t *length)
906 {
907    if (*length == 0) {
908       *length = i2d_SignatureData(sig->sigData, NULL);
909       return true;
910    }
911
912    *length = i2d_SignatureData(sig->sigData, (unsigned char **)&dest);
913    return true;
914 }
915
916 /*
917  * Decodes the SignatureData structure. The length argument is used to specify the
918  * size of sigData.
919  *
920  * Returns: SIGNATURE instance on success.
921  *          NULL on failure.
922
923  */
924
925 SIGNATURE *crypto_sign_decode(JCR *jcr, const uint8_t *sigData, uint32_t length)
926 {
927    SIGNATURE *sig;
928    const unsigned char *p = (const unsigned char *) sigData;
929
930    sig = (SIGNATURE *)malloc(sizeof(SIGNATURE));
931    if (!sig) {
932       return NULL;
933    }
934    sig->jcr = jcr;
935
936    /* d2i_SignatureData modifies the supplied pointer */
937    sig->sigData  = d2i_SignatureData(NULL, &p, length);
938
939    if (!sig->sigData) {
940       /* Allocation / Decoding failed in OpenSSL */
941       openssl_post_errors(jcr, M_ERROR, _("Signature decoding failed"));
942       free(sig);
943       return NULL;
944    }
945
946    return sig;
947 }
948
949 /*
950  * Free memory associated with a signature object.
951  */
952 void crypto_sign_free(SIGNATURE *sig)
953 {
954    SignatureData_free(sig->sigData);
955    free (sig);
956 }
957
958 /*
959  * Create a new encryption session.
960  *  Returns: A pointer to a CRYPTO_SESSION object on success.
961  *           NULL on failure.
962  *
963  *  Note! Bacula malloc() fails if out of memory.
964  */
965 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys)
966 {
967    CRYPTO_SESSION *cs;
968    X509_KEYPAIR *keypair;
969    const EVP_CIPHER *ec;
970    unsigned char *iv;
971    int iv_len;
972
973    /* Allocate our session description structures */
974    cs = (CRYPTO_SESSION *)malloc(sizeof(CRYPTO_SESSION));
975
976    /* Initialize required fields */
977    cs->session_key = NULL;
978
979    /* Allocate a CryptoData structure */
980    cs->cryptoData = CryptoData_new();
981
982    if (!cs->cryptoData) {
983       /* Allocation failed in OpenSSL */
984       free(cs);
985       return NULL;
986    }
987
988    /* Set the ASN.1 structure version number */
989    ASN1_INTEGER_set(cs->cryptoData->version, BACULA_ASN1_VERSION);
990
991    /*
992     * Acquire a cipher instance and set the ASN.1 cipher NID
993     */
994    switch (cipher) {
995    case CRYPTO_CIPHER_AES_128_CBC:
996       /* AES 128 bit CBC */
997       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_128_cbc);
998       ec = EVP_aes_128_cbc();
999       break;
1000 #ifndef HAVE_OPENSSL_EXPORT_LIBRARY
1001    case CRYPTO_CIPHER_AES_192_CBC:
1002       /* AES 192 bit CBC */
1003       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_192_cbc);
1004       ec = EVP_aes_192_cbc();
1005       break;
1006    case CRYPTO_CIPHER_AES_256_CBC:
1007       /* AES 256 bit CBC */
1008       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_256_cbc);
1009       ec = EVP_aes_256_cbc();
1010       break;
1011 #endif
1012    case CRYPTO_CIPHER_BLOWFISH_CBC:
1013       /* Blowfish CBC */
1014       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_bf_cbc);
1015       ec = EVP_bf_cbc();
1016       break;
1017    default:
1018       Jmsg0(NULL, M_ERROR, 0, _("Unsupported cipher type specified\n"));
1019       crypto_session_free(cs);
1020       return NULL;
1021    }
1022
1023    /* Generate a symmetric session key */
1024    cs->session_key_len = EVP_CIPHER_key_length(ec);
1025    cs->session_key = (unsigned char *) malloc(cs->session_key_len);
1026    if (RAND_bytes(cs->session_key, cs->session_key_len) <= 0) {
1027       /* OpenSSL failure */
1028       crypto_session_free(cs);
1029       return NULL;
1030    }
1031
1032    /* Generate an IV if possible */
1033    if ((iv_len = EVP_CIPHER_iv_length(ec))) {
1034       iv = (unsigned char *)malloc(iv_len);
1035
1036       /* Generate random IV */
1037       if (RAND_bytes(iv, iv_len) <= 0) {
1038          /* OpenSSL failure */
1039          crypto_session_free(cs);
1040          free(iv);
1041          return NULL;
1042       }
1043
1044       /* Store it in our ASN.1 structure */
1045       if (!M_ASN1_OCTET_STRING_set(cs->cryptoData->iv, iv, iv_len)) {
1046          /* Allocation failed in OpenSSL */
1047          crypto_session_free(cs);
1048          free(iv);
1049          return NULL;
1050       }
1051       free(iv);
1052    }
1053
1054    /*
1055     * Create RecipientInfo structures for supplied
1056     * public keys.
1057     */
1058    foreach_alist(keypair, pubkeys) {
1059       RecipientInfo *ri;
1060       unsigned char *ekey;
1061       int ekey_len;
1062
1063       ri = RecipientInfo_new();
1064       if (!ri) {
1065          /* Allocation failed in OpenSSL */
1066          crypto_session_free(cs);
1067          return NULL;
1068       }
1069
1070       /* Set the ASN.1 structure version number */
1071       ASN1_INTEGER_set(ri->version, BACULA_ASN1_VERSION);
1072
1073       /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
1074       M_ASN1_OCTET_STRING_free(ri->subjectKeyIdentifier);
1075       ri->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
1076
1077       /* Set our key encryption algorithm. We currently require RSA */
1078       assert(keypair->pubkey && EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
1079       ri->keyEncryptionAlgorithm = OBJ_nid2obj(NID_rsaEncryption);
1080
1081       /* Encrypt the session key */
1082       ekey = (unsigned char *)malloc(EVP_PKEY_size(keypair->pubkey));
1083
1084       if ((ekey_len = EVP_PKEY_encrypt(ekey, cs->session_key, cs->session_key_len, keypair->pubkey)) <= 0) {
1085          /* OpenSSL failure */
1086          RecipientInfo_free(ri);
1087          crypto_session_free(cs);
1088          free(ekey);
1089          return NULL;
1090       }
1091
1092       /* Store it in our ASN.1 structure */
1093       if (!M_ASN1_OCTET_STRING_set(ri->encryptedKey, ekey, ekey_len)) {
1094          /* Allocation failed in OpenSSL */
1095          RecipientInfo_free(ri);
1096          crypto_session_free(cs);
1097          free(ekey);
1098          return NULL;
1099       }
1100
1101       /* Free the encrypted key buffer */
1102       free(ekey);
1103
1104       /* Push the new RecipientInfo structure onto the stack */
1105       sk_RecipientInfo_push(cs->cryptoData->recipientInfo, ri);
1106    }
1107
1108    return cs;
1109 }
1110
1111 /*
1112  * Encodes the CryptoData structure. The length argument is used to specify the
1113  * size of dest. A length of 0 will cause no data to be written to dest, and the
1114  * required length to be written to length. The caller can then allocate sufficient
1115  * space for the output.
1116  *
1117  * Returns: true on success, stores the encoded data in dest, and the size in length.
1118  *          false on failure.
1119  */
1120 bool crypto_session_encode(CRYPTO_SESSION *cs, uint8_t *dest, uint32_t *length)
1121 {
1122    if (*length == 0) {
1123       *length = i2d_CryptoData(cs->cryptoData, NULL);
1124       return true;
1125    }
1126
1127    *length = i2d_CryptoData(cs->cryptoData, &dest);
1128    return true;
1129 }
1130
1131 /*
1132  * Decodes the CryptoData structure. The length argument is
1133  * used to specify the size of data.
1134  *
1135  * Returns: CRYPTO_SESSION instance on success.
1136  *          NULL on failure.
1137  * Returns: CRYPTO_ERROR_NONE and a pointer to a newly allocated CRYPTO_SESSION structure in *session on success.
1138  *          A crypto_error_t value on failure.
1139  */
1140 crypto_error_t crypto_session_decode(const uint8_t *data, uint32_t length, alist *keypairs, CRYPTO_SESSION **session)
1141 {
1142    CRYPTO_SESSION *cs;
1143    X509_KEYPAIR *keypair;
1144    STACK_OF(RecipientInfo) *recipients;
1145    crypto_error_t retval = CRYPTO_ERROR_NONE;
1146    const unsigned char *p = (const unsigned char *)data;
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
1155    /* Initialize required fields */
1156    cs->session_key = NULL;
1157
1158    /* d2i_CryptoData modifies the supplied pointer */
1159    cs->cryptoData = d2i_CryptoData(NULL, &p, length);
1160
1161    if (!cs->cryptoData) {
1162       /* Allocation / Decoding failed in OpenSSL */
1163       openssl_post_errors(M_ERROR, _("CryptoData decoding failed"));
1164       retval = CRYPTO_ERROR_INTERNAL;
1165       goto err;
1166    }
1167
1168    recipients = cs->cryptoData->recipientInfo;
1169
1170    /*
1171     * Find a matching RecipientInfo structure for a supplied
1172     * public key
1173     */
1174    foreach_alist(keypair, keypairs) {
1175       RecipientInfo *ri;
1176       int i;
1177
1178       /* Private key available? */
1179       if (keypair->privkey == NULL) {
1180          continue;
1181       }
1182
1183       for (i = 0; i < sk_RecipientInfo_num(recipients); i++) {
1184          ri = sk_RecipientInfo_value(recipients, i);
1185
1186          /* Match against the subjectKeyIdentifier */
1187          if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, ri->subjectKeyIdentifier) == 0) {
1188             /* Match found, extract symmetric encryption session data */
1189
1190             /* RSA is required. */
1191             assert(EVP_PKEY_type(keypair->privkey->type) == EVP_PKEY_RSA);
1192
1193             /* If we recieve a RecipientInfo structure that does not use
1194              * RSA, return an error */
1195             if (OBJ_obj2nid(ri->keyEncryptionAlgorithm) != NID_rsaEncryption) {
1196                retval = CRYPTO_ERROR_INVALID_CRYPTO;
1197                goto err;
1198             }
1199
1200             /* Decrypt the session key */
1201             /* Allocate sufficient space for the largest possible decrypted data */
1202             cs->session_key = (unsigned char *)malloc(EVP_PKEY_size(keypair->privkey));
1203             cs->session_key_len = EVP_PKEY_decrypt(cs->session_key, M_ASN1_STRING_data(ri->encryptedKey),
1204                                   M_ASN1_STRING_length(ri->encryptedKey), keypair->privkey);
1205
1206             if (cs->session_key_len <= 0) {
1207                openssl_post_errors(M_ERROR, _("Failure decrypting the session key"));
1208                retval = CRYPTO_ERROR_DECRYPTION;
1209                goto err;
1210             }
1211
1212             /* Session key successfully extracted, return the CRYPTO_SESSION structure */
1213             *session = cs;
1214             return CRYPTO_ERROR_NONE;
1215          }
1216       }
1217    }
1218
1219    /* No matching recipient found */
1220    return CRYPTO_ERROR_NORECIPIENT;
1221
1222 err:
1223    crypto_session_free(cs);
1224    return retval;
1225 }
1226
1227 /*
1228  * Free memory associated with a crypto session object.
1229  */
1230 void crypto_session_free(CRYPTO_SESSION *cs)
1231 {
1232    if (cs->cryptoData) {
1233       CryptoData_free(cs->cryptoData);
1234    }
1235    if (cs->session_key){
1236       free(cs->session_key);
1237    }
1238    free(cs);
1239 }
1240
1241 /*
1242  * Create a new crypto cipher context with the specified session object
1243  *  Returns: A pointer to a CIPHER_CONTEXT object on success. The cipher block size is returned in blocksize.
1244  *           NULL on failure.
1245  */
1246 CIPHER_CONTEXT *crypto_cipher_new(CRYPTO_SESSION *cs, bool encrypt, uint32_t *blocksize)
1247 {
1248    CIPHER_CONTEXT *cipher_ctx;
1249    const EVP_CIPHER *ec;
1250
1251    cipher_ctx = (CIPHER_CONTEXT *)malloc(sizeof(CIPHER_CONTEXT));
1252
1253    /*
1254     * Acquire a cipher instance for the given ASN.1 cipher NID
1255     */
1256    if ((ec = EVP_get_cipherbyobj(cs->cryptoData->contentEncryptionAlgorithm)) == NULL) {
1257       Jmsg1(NULL, M_ERROR, 0,
1258          _("Unsupported contentEncryptionAlgorithm: %d\n"), OBJ_obj2nid(cs->cryptoData->contentEncryptionAlgorithm));
1259       free(cipher_ctx);
1260       return NULL;
1261    }
1262
1263    /* Initialize the OpenSSL cipher context */
1264    EVP_CIPHER_CTX_init(&cipher_ctx->ctx);
1265    if (encrypt) {
1266       /* Initialize for encryption */
1267       if (!EVP_CipherInit_ex(&cipher_ctx->ctx, ec, NULL, NULL, NULL, 1)) {
1268          openssl_post_errors(M_ERROR, _("OpenSSL cipher context initialization failed"));
1269          goto err;
1270       }
1271    } else {
1272       /* Initialize for decryption */
1273       if (!EVP_CipherInit_ex(&cipher_ctx->ctx, ec, NULL, NULL, NULL, 0)) {
1274          openssl_post_errors(M_ERROR, _("OpenSSL cipher context initialization failed"));
1275          goto err;
1276       }
1277    }
1278
1279    /* Set the key size */
1280    if (!EVP_CIPHER_CTX_set_key_length(&cipher_ctx->ctx, cs->session_key_len)) {
1281       openssl_post_errors(M_ERROR, _("Encryption session provided an invalid symmetric key"));
1282       goto err;
1283    }
1284
1285    /* Validate the IV length */
1286    if (EVP_CIPHER_iv_length(ec) != M_ASN1_STRING_length(cs->cryptoData->iv)) {
1287       openssl_post_errors(M_ERROR, _("Encryption session provided an invalid IV"));
1288       goto err;
1289    }
1290
1291    /* Add the key and IV to the cipher context */
1292    if (!EVP_CipherInit_ex(&cipher_ctx->ctx, NULL, NULL, cs->session_key, M_ASN1_STRING_data(cs->cryptoData->iv), -1)) {
1293       openssl_post_errors(M_ERROR, _("OpenSSL cipher context key/IV initialization failed"));
1294       goto err;
1295    }
1296
1297    *blocksize = EVP_CIPHER_CTX_block_size(&cipher_ctx->ctx);
1298    return cipher_ctx;
1299
1300 err:
1301    crypto_cipher_free(cipher_ctx);
1302    return NULL;
1303 }
1304
1305
1306 /*
1307  * Encrypt/Decrypt length bytes of data using the provided cipher context
1308  * Returns: true on success, number of bytes output in written
1309  *          false on failure
1310  */
1311 bool crypto_cipher_update(CIPHER_CONTEXT *cipher_ctx, const uint8_t *data, uint32_t length, const uint8_t *dest, uint32_t *written)
1312 {
1313    if (!EVP_CipherUpdate(&cipher_ctx->ctx, (unsigned char *)dest, (int *)written, (const unsigned char *)data, length)) {
1314       /* This really shouldn't fail */
1315       return false;
1316    } else {
1317       return true;
1318    }
1319 }
1320
1321 /*
1322  * Finalize the cipher context, writing any remaining data and necessary padding
1323  * to dest, and the size in written.
1324  * The result size will either be one block of data or zero.
1325  *
1326  * Returns: true on success
1327  *          false on failure
1328  */
1329 bool crypto_cipher_finalize (CIPHER_CONTEXT *cipher_ctx, uint8_t *dest, uint32_t *written)
1330 {
1331    if (!EVP_CipherFinal_ex(&cipher_ctx->ctx, (unsigned char *)dest, (int *) written)) {
1332       /* This really shouldn't fail */
1333       return false;
1334    } else {
1335       return true;
1336    }
1337 }
1338
1339
1340 /*
1341  * Free memory associated with a cipher context.
1342  */
1343 void crypto_cipher_free (CIPHER_CONTEXT *cipher_ctx)
1344 {
1345    EVP_CIPHER_CTX_cleanup(&cipher_ctx->ctx);
1346    free (cipher_ctx);
1347 }
1348
1349
1350
1351 #else /* HAVE_OPENSSL */
1352 # error No encryption library available
1353 #endif /* HAVE_OPENSSL */
1354
1355 #else /* HAVE_CRYPTO */
1356
1357 /*
1358  * Cryptography Support Disabled
1359  */
1360
1361 /* Message Digest Structure */
1362 struct Digest {
1363    crypto_digest_t type;
1364    JCR *jcr;
1365    union {
1366       SHA1Context sha1;
1367       MD5Context md5;
1368    };
1369 };
1370
1371 /* Dummy Signature Structure */
1372 struct Signature {
1373    JCR *jcr;
1374 };
1375
1376 DIGEST *crypto_digest_new(JCR *jcr, crypto_digest_t type)
1377 {
1378    DIGEST *digest;
1379
1380    digest = (DIGEST *)malloc(sizeof(DIGEST));
1381    digest->type = type;
1382    digest->jcr = jcr;
1383
1384    switch (type) {
1385    case CRYPTO_DIGEST_MD5:
1386       MD5Init(&digest->md5);
1387       break;
1388    case CRYPTO_DIGEST_SHA1:
1389       SHA1Init(&digest->sha1);
1390       break;
1391    default:
1392       Jmsg1(jcr, M_ERROR, 0, _("Unsupported digest type=%d specified\n"), type);
1393       free(digest);
1394       return NULL;
1395    }
1396
1397    return (digest);
1398 }
1399
1400 bool crypto_digest_update(DIGEST *digest, const uint8_t *data, uint32_t length)
1401 {
1402    switch (digest->type) {
1403    case CRYPTO_DIGEST_MD5:
1404       /* Doesn't return anything ... */
1405       MD5Update(&digest->md5, (unsigned char *) data, length);
1406       return true;
1407    case CRYPTO_DIGEST_SHA1:
1408       int ret;
1409       if ((ret = SHA1Update(&digest->sha1, (const u_int8_t *) data, length)) == shaSuccess) {
1410          return true;
1411       } else {
1412          Jmsg1(NULL, M_ERROR, 0, _("SHA1Update() returned an error: %d\n"), ret);
1413          return false;
1414       }
1415       break;
1416    default:
1417       return false;
1418    }
1419 }
1420
1421 bool crypto_digest_finalize(DIGEST *digest, uint8_t *dest, uint32_t *length)
1422 {
1423    switch (digest->type) {
1424    case CRYPTO_DIGEST_MD5:
1425       /* Guard against programmer error by either the API client or
1426        * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1427       assert(*length >= CRYPTO_DIGEST_MD5_SIZE);
1428       *length = CRYPTO_DIGEST_MD5_SIZE;
1429       /* Doesn't return anything ... */
1430       MD5Final((unsigned char *)dest, &digest->md5);
1431       return true;
1432    case CRYPTO_DIGEST_SHA1:
1433       /* Guard against programmer error by either the API client or
1434        * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1435       assert(*length >= CRYPTO_DIGEST_SHA1_SIZE);
1436       *length = CRYPTO_DIGEST_SHA1_SIZE;
1437       if (SHA1Final(&digest->sha1, (u_int8_t *) dest) == shaSuccess) {
1438          return true;
1439       } else {
1440          return false;
1441       }
1442       break;
1443    default:
1444       return false;
1445    }
1446
1447    return false;
1448 }
1449
1450 void crypto_digest_free(DIGEST *digest)
1451 {
1452    free(digest);
1453 }
1454
1455 SIGNATURE *crypto_sign_new(JCR *jcr) { return NULL; }
1456
1457 crypto_error_t crypto_sign_get_digest (SIGNATURE *sig, X509_KEYPAIR *keypair,
1458                                        crypto_digest_t &type, DIGEST **digest)
1459    { return CRYPTO_ERROR_INTERNAL; }
1460
1461 crypto_error_t crypto_sign_verify (SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest) { return CRYPTO_ERROR_INTERNAL; }
1462
1463 int crypto_sign_add_signer (SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair) { return false; }
1464 int crypto_sign_encode (SIGNATURE *sig, uint8_t *dest, uint32_t *length) { return false; }
1465
1466 SIGNATURE *crypto_sign_decode (JCR *jcr, const uint8_t *sigData, uint32_t length) { return NULL; }
1467 void crypto_sign_free (SIGNATURE *sig) { }
1468
1469
1470 X509_KEYPAIR *crypto_keypair_new(void) { return NULL; }
1471 X509_KEYPAIR *crypto_keypair_dup (X509_KEYPAIR *keypair) { return NULL; }
1472 int crypto_keypair_load_cert (X509_KEYPAIR *keypair, const char *file) { return false; }
1473 bool crypto_keypair_has_key (const char *file) { return false; }
1474 int crypto_keypair_load_key (X509_KEYPAIR *keypair, const char *file, CRYPTO_PEM_PASSWD_CB *pem_callback, const void *pem_userdata) { return false; }
1475 void crypto_keypair_free (X509_KEYPAIR *keypair) { }
1476
1477 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys) { return NULL; }
1478 void crypto_session_free (CRYPTO_SESSION *cs) { }
1479 bool crypto_session_encode (CRYPTO_SESSION *cs, uint8_t *dest, uint32_t *length) { return false; }
1480 crypto_error_t crypto_session_decode(const uint8_t *data, uint32_t length, alist *keypairs, CRYPTO_SESSION **session) { return CRYPTO_ERROR_INTERNAL; }
1481
1482 CIPHER_CONTEXT *crypto_cipher_new (CRYPTO_SESSION *cs, bool encrypt, uint32_t *blocksize) { return NULL; }
1483 bool crypto_cipher_update (CIPHER_CONTEXT *cipher_ctx, const uint8_t *data, uint32_t length, const uint8_t *dest, uint32_t *written) { return false; }
1484 bool crypto_cipher_finalize (CIPHER_CONTEXT *cipher_ctx, uint8_t *dest, uint32_t *written) { return false; }
1485 void crypto_cipher_free (CIPHER_CONTEXT *cipher_ctx) { }
1486
1487 #endif /* HAVE_CRYPTO */
1488
1489 /* Shared Code */
1490
1491 /*
1492  * Default PEM encryption passphrase callback.
1493  * Returns an empty password.
1494  */
1495 int crypto_default_pem_callback(char *buf, int size, const void *userdata)
1496 {
1497    bstrncpy(buf, "", size);
1498    return (strlen(buf));
1499 }
1500
1501 /*
1502  * Returns the ASCII name of the digest type.
1503  * Returns: ASCII name of digest type.
1504  */
1505 const char *crypto_digest_name(DIGEST *digest)
1506 {
1507    switch (digest->type) {
1508    case CRYPTO_DIGEST_MD5:
1509       return "MD5";
1510    case CRYPTO_DIGEST_SHA1:
1511       return "SHA1";
1512    case CRYPTO_DIGEST_SHA256:
1513       return "SHA256";
1514    case CRYPTO_DIGEST_SHA512:
1515       return "SHA512";
1516    case CRYPTO_DIGEST_NONE:
1517       return "None";
1518    default:
1519       return "Invalid Digest Type";
1520    }
1521
1522 }
1523
1524 /*
1525  * Given a stream type, returns the associated
1526  * crypto_digest_t value.
1527  */
1528 crypto_digest_t crypto_digest_stream_type(int stream)
1529 {
1530    switch (stream) {
1531    case STREAM_MD5_DIGEST:
1532       return CRYPTO_DIGEST_MD5;
1533    case STREAM_SHA1_DIGEST:
1534       return CRYPTO_DIGEST_SHA1;
1535    case STREAM_SHA256_DIGEST:
1536       return CRYPTO_DIGEST_SHA256;
1537    case STREAM_SHA512_DIGEST:
1538       return CRYPTO_DIGEST_SHA512;
1539    default:
1540       return CRYPTO_DIGEST_NONE;
1541    }
1542 }
1543
1544 /*
1545  *  * Given a crypto_error_t value, return the associated
1546  *   * error string
1547  *    */
1548 const char *crypto_strerror(crypto_error_t error) {
1549    switch (error) {
1550    case CRYPTO_ERROR_NONE:
1551       return _("No error");
1552    case CRYPTO_ERROR_NOSIGNER:
1553       return _("Signer not found");
1554    case CRYPTO_ERROR_NORECIPIENT:
1555       return _("Recipient not found");
1556    case CRYPTO_ERROR_INVALID_DIGEST:
1557       return _("Unsupported digest algorithm");
1558    case CRYPTO_ERROR_INVALID_CRYPTO:
1559       return _("Unsupported encryption algorithm");
1560    case CRYPTO_ERROR_BAD_SIGNATURE:
1561       return _("Signature is invalid");
1562    case CRYPTO_ERROR_DECRYPTION:
1563       return _("Decryption error");
1564    case CRYPTO_ERROR_INTERNAL:
1565       /* This shouldn't happen */
1566       return _("Internal error");
1567    default:
1568       return _("Unknown error");
1569    }
1570 }