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