]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/crypto.c
9ce98184570bb22711929cb3f4d07e348e0b5d8e
[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 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, iv, ASN1_OCTET_STRING),
180    ASN1_SET_OF(CryptoData, recipientInfo, RecipientInfo)
181 } ASN1_SEQUENCE_END(CryptoData);
182
183 IMPLEMENT_ASN1_FUNCTIONS(SignerInfo)
184 IMPLEMENT_ASN1_FUNCTIONS(RecipientInfo)
185 IMPLEMENT_ASN1_FUNCTIONS(SignatureData)
186 IMPLEMENT_ASN1_FUNCTIONS(CryptoData)
187 IMPLEMENT_STACK_OF(SignerInfo)
188 IMPLEMENT_STACK_OF(RecipientInfo)
189
190 /*
191  * SignerInfo and RecipientInfo stack macros, generated by OpenSSL's util/mkstack.pl.
192  */
193 #define sk_SignerInfo_new(st) SKM_sk_new(SignerInfo, (st))
194 #define sk_SignerInfo_new_null() SKM_sk_new_null(SignerInfo)
195 #define sk_SignerInfo_free(st) SKM_sk_free(SignerInfo, (st))
196 #define sk_SignerInfo_num(st) SKM_sk_num(SignerInfo, (st))
197 #define sk_SignerInfo_value(st, i) SKM_sk_value(SignerInfo, (st), (i))
198 #define sk_SignerInfo_set(st, i, val) SKM_sk_set(SignerInfo, (st), (i), (val))
199 #define sk_SignerInfo_zero(st) SKM_sk_zero(SignerInfo, (st))
200 #define sk_SignerInfo_push(st, val) SKM_sk_push(SignerInfo, (st), (val))
201 #define sk_SignerInfo_unshift(st, val) SKM_sk_unshift(SignerInfo, (st), (val))
202 #define sk_SignerInfo_find(st, val) SKM_sk_find(SignerInfo, (st), (val))
203 #define sk_SignerInfo_delete(st, i) SKM_sk_delete(SignerInfo, (st), (i))
204 #define sk_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(SignerInfo, (st), (ptr))
205 #define sk_SignerInfo_insert(st, val, i) SKM_sk_insert(SignerInfo, (st), (val), (i))
206 #define sk_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(SignerInfo, (st), (cmp))
207 #define sk_SignerInfo_dup(st) SKM_sk_dup(SignerInfo, st)
208 #define sk_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(SignerInfo, (st), (free_func))
209 #define sk_SignerInfo_shift(st) SKM_sk_shift(SignerInfo, (st))
210 #define sk_SignerInfo_pop(st) SKM_sk_pop(SignerInfo, (st))
211 #define sk_SignerInfo_sort(st) SKM_sk_sort(SignerInfo, (st))
212 #define sk_SignerInfo_is_sorted(st) SKM_sk_is_sorted(SignerInfo, (st))
213
214 #define d2i_ASN1_SET_OF_SignerInfo(st, pp, length, d2i_func, free_func, ex_tag, ex_class) \
215         SKM_ASN1_SET_OF_d2i(SignerInfo, (st), (pp), (length), (d2i_func), (free_func), (ex_tag), (ex_class)) 
216 #define i2d_ASN1_SET_OF_SignerInfo(st, pp, i2d_func, ex_tag, ex_class, is_set) \
217         SKM_ASN1_SET_OF_i2d(SignerInfo, (st), (pp), (i2d_func), (ex_tag), (ex_class), (is_set))
218 #define ASN1_seq_pack_SignerInfo(st, i2d_func, buf, len) \
219         SKM_ASN1_seq_pack(SignerInfo, (st), (i2d_func), (buf), (len))
220 #define ASN1_seq_unpack_SignerInfo(buf, len, d2i_func, free_func) \
221         SKM_ASN1_seq_unpack(SignerInfo, (buf), (len), (d2i_func), (free_func))
222
223 #define sk_RecipientInfo_new(st) SKM_sk_new(RecipientInfo, (st))
224 #define sk_RecipientInfo_new_null() SKM_sk_new_null(RecipientInfo)
225 #define sk_RecipientInfo_free(st) SKM_sk_free(RecipientInfo, (st))
226 #define sk_RecipientInfo_num(st) SKM_sk_num(RecipientInfo, (st))
227 #define sk_RecipientInfo_value(st, i) SKM_sk_value(RecipientInfo, (st), (i))
228 #define sk_RecipientInfo_set(st, i, val) SKM_sk_set(RecipientInfo, (st), (i), (val))
229 #define sk_RecipientInfo_zero(st) SKM_sk_zero(RecipientInfo, (st))
230 #define sk_RecipientInfo_push(st, val) SKM_sk_push(RecipientInfo, (st), (val))
231 #define sk_RecipientInfo_unshift(st, val) SKM_sk_unshift(RecipientInfo, (st), (val))
232 #define sk_RecipientInfo_find(st, val) SKM_sk_find(RecipientInfo, (st), (val))
233 #define sk_RecipientInfo_delete(st, i) SKM_sk_delete(RecipientInfo, (st), (i))
234 #define sk_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(RecipientInfo, (st), (ptr))
235 #define sk_RecipientInfo_insert(st, val, i) SKM_sk_insert(RecipientInfo, (st), (val), (i))
236 #define sk_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(RecipientInfo, (st), (cmp))
237 #define sk_RecipientInfo_dup(st) SKM_sk_dup(RecipientInfo, st)
238 #define sk_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(RecipientInfo, (st), (free_func))
239 #define sk_RecipientInfo_shift(st) SKM_sk_shift(RecipientInfo, (st))
240 #define sk_RecipientInfo_pop(st) SKM_sk_pop(RecipientInfo, (st))
241 #define sk_RecipientInfo_sort(st) SKM_sk_sort(RecipientInfo, (st))
242 #define sk_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(RecipientInfo, (st))
243
244 #define d2i_ASN1_SET_OF_RecipientInfo(st, pp, length, d2i_func, free_func, ex_tag, ex_class) \
245         SKM_ASN1_SET_OF_d2i(RecipientInfo, (st), (pp), (length), (d2i_func), (free_func), (ex_tag), (ex_class)) 
246 #define i2d_ASN1_SET_OF_RecipientInfo(st, pp, i2d_func, ex_tag, ex_class, is_set) \
247         SKM_ASN1_SET_OF_i2d(RecipientInfo, (st), (pp), (i2d_func), (ex_tag), (ex_class), (is_set))
248 #define ASN1_seq_pack_RecipientInfo(st, i2d_func, buf, len) \
249         SKM_ASN1_seq_pack(RecipientInfo, (st), (i2d_func), (buf), (len))
250 #define ASN1_seq_unpack_RecipientInfo(buf, len, d2i_func, free_func) \
251         SKM_ASN1_seq_unpack(RecipientInfo, (buf), (len), (d2i_func), (free_func))
252 /* End of util/mkstack.pl block */
253
254 /* X509 Public/Private Key Pair Structure */
255 struct X509_Keypair {
256    ASN1_OCTET_STRING *keyid;
257    EVP_PKEY *pubkey;
258    EVP_PKEY *privkey;
259 };
260
261 /* Message Digest Structure */
262 struct Digest {
263    crypto_digest_t type;
264    EVP_MD_CTX ctx;
265 };
266
267 /* Message Signature Structure */
268 struct Signature {
269    SignatureData *sigData;
270 };
271
272 /* Encryption Session Data */
273 struct Crypto_Session {
274    CryptoData *cryptoData;                        /* ASN.1 Structure */
275    unsigned char *session_key;                    /* Private symmetric session key */
276    size_t session_key_len;                        /* Symmetric session key length */
277 };
278
279 /* PEM Password Dispatch Context */
280 typedef struct PEM_CB_Context {
281    CRYPTO_PEM_PASSWD_CB *pem_callback;
282    const void *pem_userdata;
283 } PEM_CB_CONTEXT;
284
285 /*
286  * Extract subjectKeyIdentifier from x509 certificate.
287  * Returns: On success, an ASN1_OCTET_STRING that must be freed via M_ASN1_OCTET_STRING_free().
288  *          NULL on failure.
289  */
290 static ASN1_OCTET_STRING *openssl_cert_keyid(X509 *cert){
291    X509_EXTENSION *ext;
292    X509V3_EXT_METHOD *method;
293    ASN1_OCTET_STRING *keyid;
294    int i;
295 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
296    const unsigned char *ext_value_data;
297 #else
298    unsigned char *ext_value_data;
299 #endif
300
301
302    /* Find the index to the subjectKeyIdentifier extension */
303    i = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
304    if (i < 0) {
305       /* Not found */
306       return NULL;
307    }
308
309    /* Grab the extension */
310    ext = X509_get_ext(cert, i);
311
312    /* Get x509 extension method structure */
313    if (!(method = X509V3_EXT_get(ext))) {
314       return NULL;
315    }
316
317    ext_value_data = ext->value->data;
318
319 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
320    if (method->it) {
321       /* New style ASN1 */
322
323       /* Decode ASN1 item in data */
324       keyid = (ASN1_OCTET_STRING *) ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
325                                                   ASN1_ITEM_ptr(method->it));
326    } else {
327       /* Old style ASN1 */
328
329       /* Decode ASN1 item in data */
330       keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
331    }
332
333 #else
334    keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
335 #endif
336
337    return keyid;
338 }
339
340 /*
341  * Create a new keypair object.
342  *  Returns: A pointer to a X509 KEYPAIR object on success.
343  *           NULL on failure.
344  */
345 X509_KEYPAIR *crypto_keypair_new (void) {
346    X509_KEYPAIR *keypair;
347
348    /* Allocate our keypair structure */
349    keypair = (X509_KEYPAIR *) malloc(sizeof(X509_KEYPAIR));
350    if (!keypair) {
351       return NULL;
352    }
353
354    /* Initialize our keypair structure */
355    keypair->keyid = NULL;
356    keypair->pubkey = NULL;
357    keypair->privkey = NULL;
358
359    return keypair;
360 }
361
362 /*
363  * Create a copy of a keypair object. The underlying
364  * EVP objects are not duplicated, as no EVP_PKEY_dup()
365  * API is available. Instead, the reference count is
366  * incremented.
367  */
368 X509_KEYPAIR *crypto_keypair_dup (X509_KEYPAIR *keypair)
369 {
370    X509_KEYPAIR *newpair;
371
372    newpair = crypto_keypair_new();
373
374    if (!newpair) {
375       /* Allocation failed */
376       return NULL;
377    }
378
379    /* Increment the public key ref count */
380    if (keypair->pubkey) {
381       CRYPTO_add(&(keypair->pubkey->references), 1, CRYPTO_LOCK_EVP_PKEY);
382       newpair->pubkey = keypair->pubkey;
383    }
384
385    /* Increment the private key ref count */
386    if (keypair->privkey) {
387       CRYPTO_add(&(keypair->privkey->references), 1, CRYPTO_LOCK_EVP_PKEY);
388       newpair->privkey = keypair->privkey;
389    }
390
391    /* Duplicate the keyid */
392    if (keypair->keyid) {
393       newpair->keyid = M_ASN1_OCTET_STRING_dup(keypair->keyid);
394       if (!newpair->keyid) {
395          /* Allocation failed */
396          crypto_keypair_free(newpair);
397          return NULL;
398       }
399    }
400
401    return newpair;
402 }
403
404
405 /*
406  * Load a public key from a PEM-encoded x509 certificate.
407  *  Returns: true on success
408  *           false on failure
409  */
410 int crypto_keypair_load_cert (X509_KEYPAIR *keypair, const char *file)
411 {
412    BIO *bio;
413    X509 *cert;
414
415    /* Open the file */
416    if (!(bio = BIO_new_file(file, "r"))) {
417       openssl_post_errors(M_ERROR, _("Unable to open certificate file"));
418       return false;
419    }
420
421    cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
422    BIO_free(bio);
423    if (!cert) {
424       openssl_post_errors(M_ERROR, _("Unable to read certificate from file"));
425       return false;
426    }
427
428    /* Extract the public key */
429    if (!(keypair->pubkey = X509_get_pubkey(cert))) {
430       openssl_post_errors(M_ERROR, _("Unable to extract public key from certificate"));
431       goto err;
432    }
433
434    /* Extract the subjectKeyIdentifier extension field */
435    if ((keypair->keyid = openssl_cert_keyid(cert)) == NULL) {
436       Emsg0(M_ERROR, 0, _("Provided certificate does not include the required subjectKeyIdentifier extension."));
437       goto err;
438    }
439
440    /* Validate the public key type (only RSA is supported) */
441    if (EVP_PKEY_type(keypair->pubkey->type) != EVP_PKEY_RSA) {
442        Emsg1(M_ERROR, 0, _("Unsupported key type provided: %d\n"), EVP_PKEY_type(keypair->pubkey->type));
443        goto err;
444    }
445
446    return true;
447
448 err:
449    X509_free(cert);
450    if (keypair->pubkey) {
451       EVP_PKEY_free(keypair->pubkey);
452    }
453    return false;
454 }
455
456 /* Dispatch user PEM encryption callbacks */
457 static int crypto_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
458 {
459    PEM_CB_CONTEXT *ctx = (PEM_CB_CONTEXT *) userdata;
460    return (ctx->pem_callback(buf, size, ctx->pem_userdata));
461 }
462
463 /*
464  * Check a PEM-encoded file
465  * for the existence of a private key.
466  * Returns: true if a private key is found
467  *          false otherwise
468  */
469 bool crypto_keypair_has_key (const char *file) {
470    BIO *bio;
471    char *name = NULL;
472    char *header = NULL;
473    unsigned char *data = NULL;
474    bool retval = false;
475    long len;
476
477    if (!(bio = BIO_new_file(file, "r"))) {
478       openssl_post_errors(M_ERROR, _("Unable to open private key file"));
479       return false;
480    }
481
482    while (PEM_read_bio(bio, &name, &header, &data, &len)) {
483       /* We don't care what the data is, just that it's there */
484       OPENSSL_free(header);
485       OPENSSL_free(data);
486
487       /*
488        * PEM Header Found, check for a private key
489        * Due to OpenSSL limitations, we must specifically
490        * list supported PEM private key encodings.
491        */
492       if (strcmp(name, PEM_STRING_RSA) == 0
493             || strcmp(name, PEM_STRING_DSA) == 0
494             || strcmp(name, PEM_STRING_PKCS8) == 0
495             || strcmp(name, PEM_STRING_PKCS8INF) == 0) {
496          retval = true;
497          OPENSSL_free(name);
498          break;
499       } else {
500          OPENSSL_free(name);
501       }
502    }
503
504    /* Free our bio */
505    BIO_free(bio);
506
507    /* Post PEM-decoding error messages, if any */
508    openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
509    return retval;
510 }
511
512 /*
513  * Load a PEM-encoded private key.
514  *  Returns: true on success
515  *           false on failure
516  */
517 int crypto_keypair_load_key (X509_KEYPAIR *keypair, const char *file,
518                              CRYPTO_PEM_PASSWD_CB *pem_callback,
519                              const void *pem_userdata)
520 {
521    BIO *bio;
522    PEM_CB_CONTEXT ctx;
523
524    /* Open the file */
525    if (!(bio = BIO_new_file(file, "r"))) {
526       openssl_post_errors(M_ERROR, _("Unable to open private key file"));
527       return false;
528    }
529
530    /* Set up PEM encryption callback */
531    if (pem_callback) {
532       ctx.pem_callback = pem_callback;
533       ctx.pem_userdata = pem_userdata;
534    } else {
535       ctx.pem_callback = crypto_default_pem_callback;
536       ctx.pem_userdata = NULL;
537    }
538
539    keypair->privkey = PEM_read_bio_PrivateKey(bio, NULL, crypto_pem_callback_dispatch, &ctx);
540    BIO_free(bio);
541    if (!keypair->privkey) {
542       openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
543       return false;
544    }
545
546    return true;
547 }
548
549 /*
550  * Free memory associated with a keypair object.
551  */
552 void crypto_keypair_free (X509_KEYPAIR *keypair)
553 {
554    if (keypair->pubkey) {
555       EVP_PKEY_free(keypair->pubkey);
556    }
557    if (keypair->privkey) {
558       EVP_PKEY_free(keypair->privkey);
559    }
560    if (keypair->keyid) {
561       M_ASN1_OCTET_STRING_free(keypair->keyid);
562    }
563    free(keypair);
564 }
565
566 /*
567  * Create a new message digest context of the specified type
568  *  Returns: A pointer to a DIGEST object on success.
569  *           NULL on failure.
570  */
571 DIGEST *crypto_digest_new (crypto_digest_t type)
572 {
573    DIGEST *digest;
574    const EVP_MD *md = NULL; /* Quell invalid uninitialized warnings */
575
576    digest = (DIGEST *) malloc(sizeof(DIGEST));
577    digest->type = type;
578
579    /* Initialize the OpenSSL message digest context */
580    EVP_MD_CTX_init(&digest->ctx);
581
582    /* Determine the correct OpenSSL message digest type */
583    switch (type) {
584    case CRYPTO_DIGEST_MD5:
585       md = EVP_md5();
586       break;
587    case CRYPTO_DIGEST_SHA1:
588       md = EVP_sha1();
589       break;
590 #ifdef HAVE_SHA2
591    case CRYPTO_DIGEST_SHA256:
592       md = EVP_sha256();
593       break;
594    case CRYPTO_DIGEST_SHA512:
595       md = EVP_sha512();
596       break;
597 #endif
598    default:
599       Emsg1(M_ERROR, 0, _("Unsupported digest type: %d\n"), type);
600       goto err;
601    }
602
603    /* Initialize the backing OpenSSL context */
604    if (EVP_DigestInit_ex(&digest->ctx, md, NULL) == 0) {
605       goto err;
606    }
607
608    return digest;
609
610 err:
611    /* This should not happen, but never say never ... */
612    openssl_post_errors(M_ERROR, _("OpenSSL digest initialization failed"));
613    crypto_digest_free(digest);
614    return NULL;
615 }
616
617 /*
618  * Hash length bytes of data into the provided digest context.
619  * Returns: true on success
620  *          false on failure
621  */
622 bool crypto_digest_update (DIGEST *digest, const void *data, size_t length) {
623    if (EVP_DigestUpdate(&digest->ctx, data, length) == 0) {
624       return true;
625    } else { 
626       return false;
627    }
628 }
629
630 /*
631  * Finalize the data in digest, storing the result in dest and the result size
632  * in length. The result size can be determined with crypto_digest_size().
633  *
634  * Returns: true on success
635  *          false on failure
636  */
637 bool crypto_digest_finalize (DIGEST *digest, void *dest, size_t *length) {
638    if (!EVP_DigestFinal(&digest->ctx, (unsigned char *) dest, (unsigned int *) length)) {
639       return false;
640    } else {
641       return true;
642    }
643 }
644
645 /*
646  * Free memory associated with a digest object.
647  */
648 void crypto_digest_free (DIGEST *digest)
649 {
650   EVP_MD_CTX_cleanup(&digest->ctx);
651   free (digest);
652 }
653
654 /*
655  * Create a new message signature context.
656  *  Returns: A pointer to a SIGNATURE object on success.
657  *           NULL on failure.
658  */
659 SIGNATURE *crypto_sign_new (void)
660 {
661    SIGNATURE *sig;
662
663    sig = (SIGNATURE *) malloc(sizeof(SIGNATURE));
664    if (!sig) {
665       return NULL;
666    }
667
668    sig->sigData = SignatureData_new();
669
670    if (!sig->sigData) {
671       /* Allocation failed in OpenSSL */
672       free(sig);
673       return NULL;
674    }
675
676    /* Set the ASN.1 structure version number */
677    ASN1_INTEGER_set(sig->sigData->version, BACULA_ASN1_VERSION);
678
679    return sig;
680 }
681
682 /*
683  * For a given public key, find the associated SignatureInfo record
684  * and create a digest context for signature validation
685  * Returns: CRYPTO_ERROR_NONE on success, with the newly allocated DIGEST in digest.
686  *          A crypto_error_t value on failure.
687  */
688 crypto_error_t crypto_sign_get_digest(SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST **digest)
689 {
690    STACK_OF(SignerInfo) *signers;
691    SignerInfo *si;
692    int i;
693
694    signers = sig->sigData->signerInfo;
695
696    for (i = 0; i < sk_SignerInfo_num(signers); i++) {
697       si = sk_SignerInfo_value(signers, i);
698       if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
699          /* Get the digest algorithm and allocate a digest context */
700          switch (OBJ_obj2nid(si->digestAlgorithm)) {
701          case NID_md5:
702             *digest = crypto_digest_new(CRYPTO_DIGEST_MD5);
703             break;
704          case NID_sha1:
705             *digest = crypto_digest_new(CRYPTO_DIGEST_SHA1);
706             break;
707 #ifdef HAVE_SHA2
708          case NID_sha256:
709             *digest = crypto_digest_new(CRYPTO_DIGEST_SHA256);
710             break;
711          case NID_sha512:
712             *digest = crypto_digest_new(CRYPTO_DIGEST_SHA512);
713             break;
714 #endif
715          default:
716             *digest = NULL;
717             return CRYPTO_ERROR_INVALID_DIGEST;
718          }
719
720          /* Shouldn't happen */
721          if (*digest == NULL) {
722             return CRYPTO_ERROR_INVALID_DIGEST;
723          } else {
724             return CRYPTO_ERROR_NONE;
725          }
726       }
727    }
728
729    return CRYPTO_ERROR_NOSIGNER;
730 }
731
732 /*
733  * For a given signature, public key, and digest, verify the SIGNATURE.
734  * Returns: CRYPTO_ERROR_NONE on success.
735  *          A crypto_error_t value on failure.
736  */
737 crypto_error_t crypto_sign_verify(SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest)
738 {
739    STACK_OF(SignerInfo) *signers;
740    SignerInfo *si;
741    int ok, i;
742    unsigned int sigLen;
743 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
744    const unsigned char *sigData;
745 #else
746    unsigned char *sigData;
747 #endif
748
749    signers = sig->sigData->signerInfo;
750
751    /* Find the signer */
752    for (i = 0; i < sk_SignerInfo_num(signers); i++) {
753       si = sk_SignerInfo_value(signers, i);
754       if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
755          /* Extract the signature data */
756          sigLen = M_ASN1_STRING_length(si->signature);
757          sigData = M_ASN1_STRING_data(si->signature);
758
759          ok = EVP_VerifyFinal(&digest->ctx, sigData, sigLen, keypair->pubkey);
760          if (ok >= 1) {
761             return CRYPTO_ERROR_NONE;
762          } else if (ok == 0) {
763             return CRYPTO_ERROR_BAD_SIGNATURE;
764          } else if (ok < 0) {
765             /* Shouldn't happen */
766             openssl_post_errors(M_ERROR, _("OpenSSL error occured"));
767             return CRYPTO_ERROR_INTERNAL;
768          }
769       }
770    }
771
772    /* Signer wasn't found. */
773    return CRYPTO_ERROR_NOSIGNER;
774 }
775
776
777 /*
778  * Add a new signer
779  *  Returns: true on success
780  *           false on failure
781  */
782 int crypto_sign_add_signer(SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair)
783 {
784    SignerInfo *si = NULL;
785    unsigned char *buf = NULL;
786    unsigned int len;
787
788    si = SignerInfo_new();
789
790    if (!si) {
791       /* Allocation failed in OpenSSL */
792       return false;
793    }
794
795    /* Set the ASN.1 structure version number */
796    ASN1_INTEGER_set(si->version, BACULA_ASN1_VERSION);
797
798    /* Set the digest algorithm identifier */
799    switch (digest->type) {
800    case CRYPTO_DIGEST_MD5:
801       si->digestAlgorithm = OBJ_nid2obj(NID_md5);
802       break;
803    case CRYPTO_DIGEST_SHA1:
804       si->digestAlgorithm = OBJ_nid2obj(NID_sha1);
805       break;
806 #ifdef HAVE_SHA2
807    case CRYPTO_DIGEST_SHA256:
808       si->digestAlgorithm = OBJ_nid2obj(NID_sha256);
809       break;
810    case CRYPTO_DIGEST_SHA512:
811       si->digestAlgorithm = OBJ_nid2obj(NID_sha512);
812       break;
813 #endif
814    default:
815       /* This should never happen */
816       goto err;
817    }
818
819    /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
820    M_ASN1_OCTET_STRING_free(si->subjectKeyIdentifier);
821    si->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
822
823    /* Set our signature algorithm. We currently require RSA */
824    assert(EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
825    /* This is slightly evil. Reach into the MD structure and grab the key type */
826    si->signatureAlgorithm = OBJ_nid2obj(digest->ctx.digest->pkey_type);
827
828    /* Finalize/Sign our Digest */
829    len = EVP_PKEY_size(keypair->privkey);
830    buf = (unsigned char *) malloc(len);
831    if (!EVP_SignFinal(&digest->ctx, buf, &len, keypair->privkey)) {
832       openssl_post_errors(M_ERROR, _("Signature creation failed"));
833       goto err;
834    }
835
836    /* Add the signature to the SignerInfo structure */
837    if (!M_ASN1_OCTET_STRING_set(si->signature, buf, len)) {
838       /* Allocation failed in OpenSSL */
839       goto err;
840    }
841
842    /* No longer needed */
843    free(buf);
844
845    /* Push the new SignerInfo structure onto the stack */
846    sk_SignerInfo_push(sig->sigData->signerInfo, si);
847
848    return true;
849
850 err:
851    if (si) {
852       SignerInfo_free(si);
853    }
854    if (buf) {
855       free(buf);
856    }
857
858    return false;
859 }
860
861 /*
862  * Encodes the SignatureData structure. The length argument is used to specify the
863  * size of dest. A length of 0 will cause no data to be written to dest, and the
864  * required length to be written to length. The caller can then allocate sufficient
865  * space for the output.
866  *
867  * Returns: true on success, stores the encoded data in dest, and the size in length.
868  *          false on failure.
869  */
870 int crypto_sign_encode(SIGNATURE *sig, void *dest, size_t *length)
871 {
872    if (*length == 0) {
873       *length = i2d_SignatureData(sig->sigData, NULL);
874       return true;
875    }
876
877    *length = i2d_SignatureData(sig->sigData, (unsigned char **) &dest);
878    return true;
879 }
880
881 /*
882  * Decodes the SignatureData structure. The length argument is used to specify the
883  * size of sigData.
884  *
885  * Returns: SIGNATURE instance on success.
886  *          NULL on failure.
887
888  */
889
890 SIGNATURE *crypto_sign_decode(const void *sigData, size_t length)
891 {
892    SIGNATURE *sig;
893 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
894    const unsigned char *p = (const unsigned char *) sigData;
895 #else
896    unsigned char *p = (unsigned char *) sigData;
897 #endif
898
899    sig = (SIGNATURE *) malloc(sizeof(SIGNATURE));
900    if (!sig) {
901       return NULL;
902    }
903
904    /* d2i_SignatureData modifies the supplied pointer */
905    sig->sigData  = d2i_SignatureData(NULL, &p, length);
906
907    if (!sig->sigData) {
908       /* Allocation / Decoding failed in OpenSSL */
909       openssl_post_errors(M_ERROR, _("Signature decoding failed"));
910       return NULL;
911    }
912
913    return sig;
914 }
915
916 /*
917  * Free memory associated with a signature object.
918  */
919 void crypto_sign_free(SIGNATURE *sig)
920 {
921    SignatureData_free(sig->sigData);
922    free (sig);
923 }
924
925 /*
926  * Create a new encryption session.
927  *  Returns: A pointer to a CRYPTO_SESSION object on success.
928  *           NULL on failure.
929  */
930 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys)
931 {
932    CRYPTO_SESSION *cs;
933    X509_KEYPAIR *keypair;
934    const EVP_CIPHER *ec;
935    unsigned char *iv;
936    int iv_len;
937
938    /* Allocate our session description structures */
939    cs = (CRYPTO_SESSION *) malloc(sizeof(CRYPTO_SESSION));
940    if (!cs) {
941       return NULL;
942    }
943
944    /* Initialize required fields */
945    cs->session_key = NULL;
946
947    /* Allocate a CryptoData structure */
948    cs->cryptoData = CryptoData_new();
949
950    if (!cs->cryptoData) {
951       /* Allocation failed in OpenSSL */
952       free(cs);
953       return NULL;
954    }
955
956    /* Set the ASN.1 structure version number */
957    ASN1_INTEGER_set(cs->cryptoData->version, BACULA_ASN1_VERSION);
958
959    /*
960     * Acquire a cipher instance and set the ASN.1 cipher NID
961     */
962    switch (cipher) {
963    case CRYPTO_CIPHER_AES_128_CBC:
964       /* AES 128 bit CBC */
965       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_128_cbc);
966       ec = EVP_aes_128_cbc();
967       break;
968    case CRYPTO_CIPHER_AES_192_CBC:
969       /* AES 192 bit CBC */
970       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_192_cbc);
971       ec = EVP_aes_192_cbc();
972       break;
973    case CRYPTO_CIPHER_AES_256_CBC:
974       /* AES 256 bit CBC */
975       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_256_cbc);
976       ec = EVP_aes_256_cbc();
977       break;
978    case CRYPTO_CIPHER_BLOWFISH_CBC:
979       /* Blowfish CBC */
980       cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_bf_cbc);
981       ec = EVP_bf_cbc();
982       break;
983    default:
984       Emsg0(M_ERROR, 0, _("Unsupported cipher type specified\n"));
985       crypto_session_free(cs);
986       return NULL;
987    }
988
989    /* Generate a symmetric session key */
990    cs->session_key_len = EVP_CIPHER_key_length(ec);
991    cs->session_key = (unsigned char *) malloc(cs->session_key_len);
992    if (RAND_bytes(cs->session_key, cs->session_key_len) <= 0) {
993       /* OpenSSL failure */
994       crypto_session_free(cs);
995       return NULL;
996    }
997
998    /* Generate an IV if possible */
999    if ((iv_len = EVP_CIPHER_iv_length(ec))) {
1000       iv = (unsigned char *) malloc(iv_len);
1001       if (!iv) {
1002          /* Malloc failure */
1003          crypto_session_free(cs);
1004          return NULL;
1005       }
1006
1007       /* Generate random IV */
1008       if (RAND_bytes(iv, iv_len) <= 0) {
1009          /* OpenSSL failure */
1010          crypto_session_free(cs);
1011          free(iv);
1012          return NULL;
1013       }
1014
1015       /* Store it in our ASN.1 structure */
1016       if (!M_ASN1_OCTET_STRING_set(cs->cryptoData->iv, iv, iv_len)) {
1017          /* Allocation failed in OpenSSL */
1018          crypto_session_free(cs);
1019          free(iv);
1020          return NULL;
1021       }
1022       free(iv);
1023    }
1024
1025    /*
1026     * Create RecipientInfo structures for supplied
1027     * public keys.
1028     */
1029    foreach_alist(keypair, pubkeys) {
1030       RecipientInfo *ri;
1031       unsigned char *ekey;
1032       int ekey_len;
1033
1034       ri = RecipientInfo_new();
1035       if (!ri) {
1036          /* Allocation failed in OpenSSL */
1037          crypto_session_free(cs);
1038          return NULL;
1039       }
1040
1041       /* Set the ASN.1 structure version number */
1042       ASN1_INTEGER_set(ri->version, BACULA_ASN1_VERSION);
1043
1044       /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
1045       M_ASN1_OCTET_STRING_free(ri->subjectKeyIdentifier);
1046       ri->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
1047
1048       /* Set our key encryption algorithm. We currently require RSA */
1049       assert(keypair->pubkey && EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
1050       ri->keyEncryptionAlgorithm = OBJ_nid2obj(NID_rsaEncryption);
1051
1052       /* Encrypt the session key */
1053       ekey = (unsigned char *) malloc(EVP_PKEY_size(keypair->pubkey));
1054       if (!ekey) {
1055          RecipientInfo_free(ri);
1056          crypto_session_free(cs);
1057          return NULL;
1058       }
1059
1060       if ((ekey_len = EVP_PKEY_encrypt(ekey, cs->session_key, cs->session_key_len, keypair->pubkey)) <= 0) {
1061          /* OpenSSL failure */
1062          RecipientInfo_free(ri);
1063          crypto_session_free(cs);
1064          free(ekey);
1065          return NULL;
1066       }
1067
1068       /* Store it in our ASN.1 structure */
1069       if (!M_ASN1_OCTET_STRING_set(ri->encryptedKey, ekey, ekey_len)) {
1070          /* Allocation failed in OpenSSL */
1071          RecipientInfo_free(ri);
1072          crypto_session_free(cs);
1073          free(ekey);
1074          return NULL;
1075       }
1076
1077       /* Free the encrypted key buffer */
1078       free(ekey);
1079
1080       /* Push the new RecipientInfo structure onto the stack */
1081       sk_RecipientInfo_push(cs->cryptoData->recipientInfo, ri);
1082    }
1083
1084    return cs;
1085 }
1086
1087 /*
1088  * Encodes the CryptoData structure. The length argument is used to specify the
1089  * size of dest. A length of 0 will cause no data to be written to dest, and the
1090  * required length to be written to length. The caller can then allocate sufficient
1091  * space for the output.
1092  *
1093  * Returns: true on success, stores the encoded data in dest, and the size in length.
1094  *          false on failure.
1095  */
1096 bool crypto_session_encode(CRYPTO_SESSION *cs, void *dest, size_t *length)
1097 {
1098    if (*length == 0) {
1099       *length = i2d_CryptoData(cs->cryptoData, NULL);
1100       return true;
1101    }
1102
1103    *length = i2d_CryptoData(cs->cryptoData, (unsigned char **) &dest);
1104    return true;
1105 }
1106
1107 /*
1108  * Decodes the CryptoData structure. The length argument is
1109  * used to specify the size of data.
1110  *
1111  * Returns: CRYPTO_SESSION instance on success.
1112  *          NULL on failure.
1113  * Returns: CRYPTO_ERROR_NONE and a pointer to a newly allocated CRYPTO_SESSION structure in *session on success.
1114  *          A crypto_error_t value on failure.
1115  */
1116 crypto_error_t crypto_session_decode(const void *data, size_t length, alist *keypairs, CRYPTO_SESSION **session)
1117 {
1118    CRYPTO_SESSION *cs;
1119    X509_KEYPAIR *keypair;
1120    STACK_OF(RecipientInfo) *recipients;
1121    crypto_error_t retval = CRYPTO_ERROR_NONE;
1122 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
1123    const unsigned char *p = (const unsigned char *) data;
1124 #else
1125    unsigned char *p = (unsigned char *) data;
1126 #endif
1127
1128    cs = (CRYPTO_SESSION *) malloc(sizeof(CRYPTO_SESSION));
1129    if (!cs) {
1130       return CRYPTO_ERROR_INTERNAL;
1131    }
1132
1133    /* d2i_CryptoData modifies the supplied pointer */
1134    cs->cryptoData = d2i_CryptoData(NULL, &p, length);
1135
1136    if (!cs->cryptoData) {
1137       /* Allocation / Decoding failed in OpenSSL */
1138       openssl_post_errors(M_ERROR, _("CryptoData decoding failed"));
1139       retval = CRYPTO_ERROR_INTERNAL;
1140       goto err;
1141    }
1142
1143    recipients = cs->cryptoData->recipientInfo;
1144
1145    /*
1146     * Find a matching RecipientInfo structure for a supplied
1147     * public key
1148     */
1149    foreach_alist(keypair, keypairs) {
1150       RecipientInfo *ri;
1151       int i;
1152
1153       /* Private key available? */
1154       if (keypair->privkey == NULL) {
1155          continue;
1156       }
1157
1158       for (i = 0; i < sk_RecipientInfo_num(recipients); i++) {
1159          ri = sk_RecipientInfo_value(recipients, i);
1160
1161          /* Match against the subjectKeyIdentifier */
1162          if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, ri->subjectKeyIdentifier) == 0) {
1163             /* Match found, extract symmetric encryption session data */
1164             
1165             /* RSA is required. */
1166             assert(EVP_PKEY_type(keypair->privkey->type) == EVP_PKEY_RSA);
1167
1168             /* If we recieve a RecipientInfo structure that does not use
1169              * RSA, return an error */
1170             if (OBJ_obj2nid(ri->keyEncryptionAlgorithm) != NID_rsaEncryption) {
1171                retval = CRYPTO_ERROR_INVALID_CRYPTO;
1172                goto err;
1173             }
1174
1175             /* Decrypt the session key */
1176             /* Allocate sufficient space for the largest possible decrypted data */
1177             cs->session_key = (unsigned char *) malloc(EVP_PKEY_size(keypair->privkey));
1178             cs->session_key_len = EVP_PKEY_decrypt(cs->session_key, M_ASN1_STRING_data(ri->encryptedKey),
1179                                   M_ASN1_STRING_length(ri->encryptedKey), keypair->privkey);
1180
1181             if (cs->session_key_len <= 0) {
1182                openssl_post_errors(M_ERROR, _("Failure decrypting the session key"));
1183                retval = CRYPTO_ERROR_DECRYPTION;
1184                goto err;
1185             }
1186
1187             /* Session key successfully extracted, return the CRYPTO_SESSION structure */
1188             *session = cs;
1189             return CRYPTO_ERROR_NONE;
1190          }
1191       }
1192    }
1193
1194    /* No matching recipient found */
1195    return CRYPTO_ERROR_NORECIPIENT;
1196
1197 err:
1198    crypto_session_free(cs);
1199    return retval;
1200 }
1201
1202 /*
1203  * Free memory associated with a crypto session object.
1204  */
1205 void crypto_session_free (CRYPTO_SESSION *cs)
1206 {
1207    if (cs->cryptoData) {
1208       CryptoData_free(cs->cryptoData);
1209    }
1210    if (cs->session_key){
1211       free(cs->session_key);
1212    }
1213    free(cs);
1214 }
1215
1216 /*
1217  * Perform global initialization of OpenSSL
1218  * This function is not thread safe.
1219  *  Returns: 0 on success
1220  *           errno on failure
1221  */
1222 int init_crypto (void)
1223 {
1224    int stat;
1225
1226    if ((stat = openssl_init_threads()) != 0) {
1227       Emsg1(M_ABORT, 0, _("Unable to init OpenSSL threading: ERR=%s\n"), strerror(stat));
1228    }
1229
1230    /* Load libssl and libcrypto human-readable error strings */
1231    SSL_load_error_strings();
1232
1233    /* Register OpenSSL ciphers */
1234    SSL_library_init();
1235
1236    if (!openssl_seed_prng()) {
1237       Emsg0(M_ERROR_TERM, 0, _("Failed to seed OpenSSL PRNG\n"));
1238    }
1239
1240    crypto_initialized = true;
1241
1242    return stat;
1243 }
1244
1245 /*
1246  * Perform global cleanup of OpenSSL
1247  * All cryptographic operations must be completed before calling this function.
1248  * This function is not thread safe.
1249  *  Returns: 0 on success
1250  *           errno on failure
1251  */
1252 int cleanup_crypto (void)
1253 {
1254    /*
1255     * Ensure that we've actually been initialized; Doing this here decreases the
1256     * complexity of client's termination/cleanup code.
1257     */
1258    if (!crypto_initialized) {
1259       return 0;
1260    }
1261
1262    if (!openssl_save_prng()) {
1263       Emsg0(M_ERROR, 0, _("Failed to save OpenSSL PRNG\n"));
1264    }
1265
1266    openssl_cleanup_threads();
1267
1268    /* Free libssl and libcrypto error strings */
1269    ERR_free_strings();
1270
1271    /* Free memory used by PRNG */
1272    RAND_cleanup();
1273
1274    crypto_initialized = false;
1275
1276    return 0;
1277 }
1278
1279
1280 #else /* HAVE_OPENSSL */
1281 # error No encryption library available
1282 #endif /* HAVE_OPENSSL */
1283
1284 #else /* HAVE_CRYPTO */
1285
1286 /*
1287  * Cryptography Support Disabled
1288  */
1289
1290 /* Message Digest Structure */
1291 struct Digest {
1292    crypto_digest_t type;
1293    union {
1294       SHA1Context sha1;
1295       MD5Context md5;
1296    };
1297 };
1298
1299 /* Dummy Signature Structure */
1300 struct Signature {
1301 };
1302
1303 DIGEST *crypto_digest_new (crypto_digest_t type)
1304 {
1305    DIGEST *digest;
1306
1307    digest = (DIGEST *) malloc(sizeof(DIGEST));
1308    digest->type = type;
1309
1310    switch (type) {
1311    case CRYPTO_DIGEST_MD5:
1312       MD5Init(&digest->md5);
1313       break;
1314    case CRYPTO_DIGEST_SHA1:
1315       SHA1Init(&digest->sha1);
1316       break;
1317    default:
1318       Emsg0(M_ERROR, 0, _("Unsupported digest type specified\n"));
1319       free(digest);
1320       return NULL;
1321    }
1322
1323    return (digest);
1324 }
1325
1326 bool crypto_digest_update (DIGEST *digest, const void *data, size_t length) {
1327    switch (digest->type) {
1328    case CRYPTO_DIGEST_MD5:
1329       /* Doesn't return anything ... */
1330       MD5Update(&digest->md5, (unsigned char *) data, length);
1331       return true;
1332    case CRYPTO_DIGEST_SHA1:
1333       int ret;
1334       if ((ret = SHA1Update(&digest->sha1, (const u_int8_t *) data, length)) == shaSuccess) {
1335          return true;
1336       } else {
1337          Emsg1(M_ERROR, 0, _("SHA1Update() returned an error: %d\n"), ret);
1338          return false;
1339       }
1340       break;
1341    default:
1342       return false;
1343    }
1344 }
1345
1346 bool crypto_digest_finalize (DIGEST *digest, void *dest, size_t *length) {
1347
1348    switch (digest->type) {
1349    case CRYPTO_DIGEST_MD5:
1350       /* Guard against programmer error by either the API client or
1351        * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1352       assert(*length >= CRYPTO_DIGEST_MD5_SIZE);
1353       *length = CRYPTO_DIGEST_MD5_SIZE;
1354       /* Doesn't return anything ... */
1355       MD5Final((unsigned char *) dest, &digest->md5);
1356       return true;
1357    case CRYPTO_DIGEST_SHA1:
1358       /* Guard against programmer error by either the API client or
1359        * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1360       assert(*length >= CRYPTO_DIGEST_SHA1_SIZE);
1361       *length = CRYPTO_DIGEST_SHA1_SIZE;
1362       if (SHA1Final(&digest->sha1, (u_int8_t *) dest) == shaSuccess) {
1363          return true;
1364       } else {
1365          return false;
1366       }
1367       break;
1368    default:
1369       return false;
1370    }
1371
1372    return false;
1373 }
1374
1375 void crypto_digest_free (DIGEST *digest)
1376 {
1377    free (digest);
1378 }
1379
1380 /* Dummy routines */
1381 int init_crypto (void) { return 0; }
1382 int cleanup_crypto (void) { return 0; }
1383
1384 SIGNATURE *crypto_sign_new (void) { return NULL; }
1385
1386 crypto_error_t crypto_sign_get_digest (SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST **digest) { return CRYPTO_ERROR_INTERNAL; }
1387 crypto_error_t crypto_sign_verify (SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest) { return CRYPTO_ERROR_INTERNAL; }
1388
1389 int crypto_sign_add_signer (SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair) { return false; }
1390 int crypto_sign_encode (SIGNATURE *sig, void *dest, size_t *length) { return false; }
1391
1392 SIGNATURE *crypto_sign_decode (const void *sigData, size_t length) { return NULL; }
1393 void crypto_sign_free (SIGNATURE *sig) { }
1394
1395
1396 X509_KEYPAIR *crypto_keypair_new (void) { return NULL; }
1397 X509_KEYPAIR *crypto_keypair_dup (X509_KEYPAIR *keypair) { return NULL; }
1398 int crypto_keypair_load_cert (X509_KEYPAIR *keypair, const char *file) { return false; }
1399 bool crypto_keypair_has_key (const char *file) { return false; }
1400 int crypto_keypair_load_key (X509_KEYPAIR *keypair, const char *file, CRYPTO_PEM_PASSWD_CB *pem_callback, const void *pem_userdata) { return false; }
1401 void crypto_keypair_free (X509_KEYPAIR *keypair) { }
1402
1403 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys) { return NULL; }
1404 void crypto_session_free (CRYPTO_SESSION *cs) { }
1405 bool crypto_session_encode(CRYPTO_SESSION *cs, void *dest, size_t *length) { return false; }
1406 crypto_error_t crypto_session_decode(const void *data, size_t length, alist *keypairs, CRYPTO_SESSION **session) { return CRYPTO_ERROR_INTERNAL; }
1407
1408 #endif /* HAVE_CRYPTO */
1409
1410 /* Shared Code */
1411
1412 /*
1413  * Default PEM encryption passphrase callback.
1414  * Returns an empty password.
1415  */
1416 int crypto_default_pem_callback(char *buf, int size, const void *userdata)
1417 {
1418    bstrncpy(buf, "", size);
1419    return (strlen(buf));
1420 }
1421
1422 /*
1423  * Returns the ASCII name of the digest type.
1424  * Returns: ASCII name of digest type.
1425  */
1426 const char *crypto_digest_name (DIGEST *digest) {
1427    switch (digest->type) {
1428    case CRYPTO_DIGEST_MD5:
1429       return "MD5";
1430    case CRYPTO_DIGEST_SHA1:
1431       return "SHA1";
1432    case CRYPTO_DIGEST_SHA256:
1433       return "SHA256";
1434    case CRYPTO_DIGEST_SHA512:
1435       return "SHA512";
1436    case CRYPTO_DIGEST_NONE:
1437       return "None";
1438    default:
1439       return "Invalid Digest Type";
1440    }
1441
1442 }
1443
1444 /*
1445  * Given a stream type, returns the associated
1446  * crypto_digest_t value.
1447  */
1448 crypto_digest_t crypto_digest_stream_type (int stream) {
1449    switch (stream) {
1450    case STREAM_MD5_DIGEST:
1451       return CRYPTO_DIGEST_MD5;
1452    case STREAM_SHA1_DIGEST:
1453       return CRYPTO_DIGEST_SHA1;
1454    case STREAM_SHA256_DIGEST:
1455       return CRYPTO_DIGEST_SHA256;
1456    case STREAM_SHA512_DIGEST:
1457       return CRYPTO_DIGEST_SHA512;
1458    default:
1459       return CRYPTO_DIGEST_NONE;
1460    }
1461 }
1462
1463 /*
1464  *  * Given a crypto_error_t value, return the associated
1465  *   * error string
1466  *    */
1467 const char *crypto_strerror(crypto_error_t error) {
1468    switch (error) {
1469    case CRYPTO_ERROR_NONE:
1470       return "No error";
1471    case CRYPTO_ERROR_NOSIGNER:
1472       return "Signer not found";
1473    case CRYPTO_ERROR_NORECIPIENT:
1474       return "Recipient not found";
1475    case CRYPTO_ERROR_INVALID_DIGEST:
1476       return "Unsupported digest algorithm";
1477    case CRYPTO_ERROR_INVALID_CRYPTO:
1478       return "Unsupported encryption algorithm";
1479    case CRYPTO_ERROR_BAD_SIGNATURE:
1480       return "Signature is invalid";
1481    case CRYPTO_ERROR_DECRYPTION:
1482       return "Decryption error";
1483    case CRYPTO_ERROR_INTERNAL:
1484       /* This shouldn't happen */
1485       return "Internal error";
1486    default:
1487       return "Unknown error";
1488    }
1489 }