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