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