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