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