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