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