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