2 Bacula® - The Network Backup Solution
4 Copyright (C) 2005-2010 Free Software Foundation Europe e.V.
6 The main author of Bacula is Kern Sibbald, with contributions from
7 many others, a complete list can be found in the file AUTHORS.
8 This program is Free Software; you can redistribute it and/or
9 modify it under the terms of version two of the GNU General Public
10 License as published by the Free Software Foundation and included
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 Bacula® is a registered trademark of Kern Sibbald.
24 The licensor of Bacula is the Free Software Foundation Europe
25 (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26 Switzerland, email:ftf@fsfeurope.org.
29 * crypto.c Encryption support functions
31 * Author: Landon Fuller <landonf@opendarwin.org>
33 * This file was contributed to the Bacula project by Landon Fuller.
35 * Landon Fuller has been granted a perpetual, worldwide, non-exclusive,
36 * no-charge, royalty-free, irrevocable copyright license to reproduce,
37 * prepare derivative works of, publicly display, publicly perform,
38 * sublicense, and distribute the original work contributed by Landon Fuller
39 * to the Bacula project in source or object form.
41 * If you wish to license these contributions under an alternate open source
42 * license please contact Landon Fuller <landonf@opendarwin.org>.
51 * For OpenSSL version 1.x, EVP_PKEY_encrypt no longer
52 * exists. It was not an official API.
55 #define EVP_PKEY_encrypt EVP_PKEY_encrypt_old
56 #define EVP_PKEY_decrypt EVP_PKEY_decrypt_old
63 * Prefix: iso.org.dod.internet.private.enterprise.threerings.external.bacula (1.3.6.1.4.1.22054.500.2)
64 * Organization: Bacula Project
65 * Contact Name: Kern Sibbald
66 * Contact E-mail: kern@sibbald.com
68 * Top Level Allocations - 500.2
69 * 1 - Published Allocations
70 * 1.1 - Bacula Encryption
72 * Bacula Encryption - 500.2.1.1
75 * 2 - ASN.1 Object Identifiers
81 * BaculaCrypto { iso(1) identified-organization(3) usdod(6)
82 * internet(1) private(4) enterprises(1) three-rings(22054)
83 * external(500) bacula(2) published(1) bacula-encryption(1)
84 * asn1-modules(1) bacula-crypto(1) }
86 * DEFINITIONS AUTOMATIC TAGS ::=
89 * SignatureData ::= SEQUENCE {
90 * version Version DEFAULT v0,
91 * signerInfo SignerInfo }
93 * CryptoData ::= SEQUENCE {
94 * version Version DEFAULT v0,
95 * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
96 * iv InitializationVector,
97 * recipientInfo RecipientInfo
100 * SignerInfo ::= SET OF SignerInfo
101 * RecipientInfo ::= SET OF RecipientInfo
103 * Version ::= INTEGER { v0(0) }
105 * SignerInfo ::= SEQUENCE {
107 * subjectKeyIdentifier SubjectKeyIdentifier,
108 * digestAlgorithm DigestAlgorithmIdentifier,
109 * signatureAlgorithm SignatureAlgorithmIdentifier,
110 * signature SignatureValue }
112 * RecipientInfo ::= SEQUENCE {
114 * subjectKeyIdentifier SubjectKeyIdentifier
115 * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
116 * encryptedKey EncryptedKey
119 * SubjectKeyIdentifier ::= OCTET STRING
121 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
123 * SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
125 * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
127 * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
129 * InitializationVector ::= OCTET STRING
131 * SignatureValue ::= OCTET STRING
133 * EncryptedKey ::= OCTET STRING
135 * AlgorithmIdentifier ::= OBJECT IDENTIFIER
140 #ifdef HAVE_CRYPTO /* Is encryption enabled? */
141 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
143 /* Are we initialized? */
144 static int crypto_initialized = false;
146 /* ASN.1 Declarations */
147 #define BACULA_ASN1_VERSION 0
150 ASN1_INTEGER *version;
151 ASN1_OCTET_STRING *subjectKeyIdentifier;
152 ASN1_OBJECT *digestAlgorithm;
153 ASN1_OBJECT *signatureAlgorithm;
154 ASN1_OCTET_STRING *signature;
158 ASN1_INTEGER *version;
159 ASN1_OCTET_STRING *subjectKeyIdentifier;
160 ASN1_OBJECT *keyEncryptionAlgorithm;
161 ASN1_OCTET_STRING *encryptedKey;
164 ASN1_SEQUENCE(SignerInfo) = {
165 ASN1_SIMPLE(SignerInfo, version, ASN1_INTEGER),
166 ASN1_SIMPLE(SignerInfo, subjectKeyIdentifier, ASN1_OCTET_STRING),
167 ASN1_SIMPLE(SignerInfo, digestAlgorithm, ASN1_OBJECT),
168 ASN1_SIMPLE(SignerInfo, signatureAlgorithm, ASN1_OBJECT),
169 ASN1_SIMPLE(SignerInfo, signature, ASN1_OCTET_STRING)
170 } ASN1_SEQUENCE_END(SignerInfo);
172 ASN1_SEQUENCE(RecipientInfo) = {
173 ASN1_SIMPLE(RecipientInfo, version, ASN1_INTEGER),
174 ASN1_SIMPLE(RecipientInfo, subjectKeyIdentifier, ASN1_OCTET_STRING),
175 ASN1_SIMPLE(RecipientInfo, keyEncryptionAlgorithm, ASN1_OBJECT),
176 ASN1_SIMPLE(RecipientInfo, encryptedKey, ASN1_OCTET_STRING),
177 } ASN1_SEQUENCE_END(RecipientInfo);
180 ASN1_INTEGER *version;
181 STACK_OF(SignerInfo) *signerInfo;
185 ASN1_INTEGER *version;
186 ASN1_OBJECT *contentEncryptionAlgorithm;
187 ASN1_OCTET_STRING *iv;
188 STACK_OF(RecipientInfo) *recipientInfo;
191 ASN1_SEQUENCE(SignatureData) = {
192 ASN1_SIMPLE(SignatureData, version, ASN1_INTEGER),
193 ASN1_SET_OF(SignatureData, signerInfo, SignerInfo),
194 } ASN1_SEQUENCE_END(SignatureData);
196 ASN1_SEQUENCE(CryptoData) = {
197 ASN1_SIMPLE(CryptoData, version, ASN1_INTEGER),
198 ASN1_SIMPLE(CryptoData, contentEncryptionAlgorithm, ASN1_OBJECT),
199 ASN1_SIMPLE(CryptoData, iv, ASN1_OCTET_STRING),
200 ASN1_SET_OF(CryptoData, recipientInfo, RecipientInfo)
201 } ASN1_SEQUENCE_END(CryptoData);
203 IMPLEMENT_ASN1_FUNCTIONS(SignerInfo)
204 IMPLEMENT_ASN1_FUNCTIONS(RecipientInfo)
205 IMPLEMENT_ASN1_FUNCTIONS(SignatureData)
206 IMPLEMENT_ASN1_FUNCTIONS(CryptoData)
207 IMPLEMENT_STACK_OF(SignerInfo)
208 IMPLEMENT_STACK_OF(RecipientInfo)
211 * SignerInfo and RecipientInfo stack macros, generated by OpenSSL's util/mkstack.pl.
213 #define sk_SignerInfo_new(st) SKM_sk_new(SignerInfo, (st))
214 #define sk_SignerInfo_new_null() SKM_sk_new_null(SignerInfo)
215 #define sk_SignerInfo_free(st) SKM_sk_free(SignerInfo, (st))
216 #define sk_SignerInfo_num(st) SKM_sk_num(SignerInfo, (st))
217 #define sk_SignerInfo_value(st, i) SKM_sk_value(SignerInfo, (st), (i))
218 #define sk_SignerInfo_set(st, i, val) SKM_sk_set(SignerInfo, (st), (i), (val))
219 #define sk_SignerInfo_zero(st) SKM_sk_zero(SignerInfo, (st))
220 #define sk_SignerInfo_push(st, val) SKM_sk_push(SignerInfo, (st), (val))
221 #define sk_SignerInfo_unshift(st, val) SKM_sk_unshift(SignerInfo, (st), (val))
222 #define sk_SignerInfo_find(st, val) SKM_sk_find(SignerInfo, (st), (val))
223 #define sk_SignerInfo_delete(st, i) SKM_sk_delete(SignerInfo, (st), (i))
224 #define sk_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(SignerInfo, (st), (ptr))
225 #define sk_SignerInfo_insert(st, val, i) SKM_sk_insert(SignerInfo, (st), (val), (i))
226 #define sk_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(SignerInfo, (st), (cmp))
227 #define sk_SignerInfo_dup(st) SKM_sk_dup(SignerInfo, st)
228 #define sk_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(SignerInfo, (st), (free_func))
229 #define sk_SignerInfo_shift(st) SKM_sk_shift(SignerInfo, (st))
230 #define sk_SignerInfo_pop(st) SKM_sk_pop(SignerInfo, (st))
231 #define sk_SignerInfo_sort(st) SKM_sk_sort(SignerInfo, (st))
232 #define sk_SignerInfo_is_sorted(st) SKM_sk_is_sorted(SignerInfo, (st))
234 #define d2i_ASN1_SET_OF_SignerInfo(st, pp, length, d2i_func, free_func, ex_tag, ex_class) \
235 SKM_ASN1_SET_OF_d2i(SignerInfo, (st), (pp), (length), (d2i_func), (free_func), (ex_tag), (ex_class))
236 #define i2d_ASN1_SET_OF_SignerInfo(st, pp, i2d_func, ex_tag, ex_class, is_set) \
237 SKM_ASN1_SET_OF_i2d(SignerInfo, (st), (pp), (i2d_func), (ex_tag), (ex_class), (is_set))
238 #define ASN1_seq_pack_SignerInfo(st, i2d_func, buf, len) \
239 SKM_ASN1_seq_pack(SignerInfo, (st), (i2d_func), (buf), (len))
240 #define ASN1_seq_unpack_SignerInfo(buf, len, d2i_func, free_func) \
241 SKM_ASN1_seq_unpack(SignerInfo, (buf), (len), (d2i_func), (free_func))
243 #define sk_RecipientInfo_new(st) SKM_sk_new(RecipientInfo, (st))
244 #define sk_RecipientInfo_new_null() SKM_sk_new_null(RecipientInfo)
245 #define sk_RecipientInfo_free(st) SKM_sk_free(RecipientInfo, (st))
246 #define sk_RecipientInfo_num(st) SKM_sk_num(RecipientInfo, (st))
247 #define sk_RecipientInfo_value(st, i) SKM_sk_value(RecipientInfo, (st), (i))
248 #define sk_RecipientInfo_set(st, i, val) SKM_sk_set(RecipientInfo, (st), (i), (val))
249 #define sk_RecipientInfo_zero(st) SKM_sk_zero(RecipientInfo, (st))
250 #define sk_RecipientInfo_push(st, val) SKM_sk_push(RecipientInfo, (st), (val))
251 #define sk_RecipientInfo_unshift(st, val) SKM_sk_unshift(RecipientInfo, (st), (val))
252 #define sk_RecipientInfo_find(st, val) SKM_sk_find(RecipientInfo, (st), (val))
253 #define sk_RecipientInfo_delete(st, i) SKM_sk_delete(RecipientInfo, (st), (i))
254 #define sk_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(RecipientInfo, (st), (ptr))
255 #define sk_RecipientInfo_insert(st, val, i) SKM_sk_insert(RecipientInfo, (st), (val), (i))
256 #define sk_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(RecipientInfo, (st), (cmp))
257 #define sk_RecipientInfo_dup(st) SKM_sk_dup(RecipientInfo, st)
258 #define sk_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(RecipientInfo, (st), (free_func))
259 #define sk_RecipientInfo_shift(st) SKM_sk_shift(RecipientInfo, (st))
260 #define sk_RecipientInfo_pop(st) SKM_sk_pop(RecipientInfo, (st))
261 #define sk_RecipientInfo_sort(st) SKM_sk_sort(RecipientInfo, (st))
262 #define sk_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(RecipientInfo, (st))
264 #define d2i_ASN1_SET_OF_RecipientInfo(st, pp, length, d2i_func, free_func, ex_tag, ex_class) \
265 SKM_ASN1_SET_OF_d2i(RecipientInfo, (st), (pp), (length), (d2i_func), (free_func), (ex_tag), (ex_class))
266 #define i2d_ASN1_SET_OF_RecipientInfo(st, pp, i2d_func, ex_tag, ex_class, is_set) \
267 SKM_ASN1_SET_OF_i2d(RecipientInfo, (st), (pp), (i2d_func), (ex_tag), (ex_class), (is_set))
268 #define ASN1_seq_pack_RecipientInfo(st, i2d_func, buf, len) \
269 SKM_ASN1_seq_pack(RecipientInfo, (st), (i2d_func), (buf), (len))
270 #define ASN1_seq_unpack_RecipientInfo(buf, len, d2i_func, free_func) \
271 SKM_ASN1_seq_unpack(RecipientInfo, (buf), (len), (d2i_func), (free_func))
272 /* End of util/mkstack.pl block */
274 /* X509 Public/Private Key Pair Structure */
275 struct X509_Keypair {
276 ASN1_OCTET_STRING *keyid;
281 /* Message Digest Structure */
283 crypto_digest_t type;
288 /* Message Signature Structure */
290 SignatureData *sigData;
294 /* Encryption Session Data */
295 struct Crypto_Session {
296 CryptoData *cryptoData; /* ASN.1 Structure */
297 unsigned char *session_key; /* Private symmetric session key */
298 size_t session_key_len; /* Symmetric session key length */
301 /* Symmetric Cipher Context */
302 struct Cipher_Context {
306 /* PEM Password Dispatch Context */
307 typedef struct PEM_CB_Context {
308 CRYPTO_PEM_PASSWD_CB *pem_callback;
309 const void *pem_userdata;
313 * Extract subjectKeyIdentifier from x509 certificate.
314 * Returns: On success, an ASN1_OCTET_STRING that must be freed via M_ASN1_OCTET_STRING_free().
317 static ASN1_OCTET_STRING *openssl_cert_keyid(X509 *cert) {
319 const X509V3_EXT_METHOD *method;
320 ASN1_OCTET_STRING *keyid;
322 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
323 const unsigned char *ext_value_data;
325 unsigned char *ext_value_data;
329 /* Find the index to the subjectKeyIdentifier extension */
330 i = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
336 /* Grab the extension */
337 ext = X509_get_ext(cert, i);
339 /* Get x509 extension method structure */
340 if (!(method = X509V3_EXT_get(ext))) {
344 ext_value_data = ext->value->data;
346 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
350 /* Decode ASN1 item in data */
351 keyid = (ASN1_OCTET_STRING *) ASN1_item_d2i(NULL, &ext_value_data, ext->value->length,
352 ASN1_ITEM_ptr(method->it));
356 /* Decode ASN1 item in data */
357 keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
361 keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
368 * Create a new keypair object.
369 * Returns: A pointer to a X509 KEYPAIR object on success.
372 X509_KEYPAIR *crypto_keypair_new(void)
374 X509_KEYPAIR *keypair;
376 /* Allocate our keypair structure */
377 keypair = (X509_KEYPAIR *)malloc(sizeof(X509_KEYPAIR));
379 /* Initialize our keypair structure */
380 keypair->keyid = NULL;
381 keypair->pubkey = NULL;
382 keypair->privkey = NULL;
388 * Create a copy of a keypair object. The underlying
389 * EVP objects are not duplicated, as no EVP_PKEY_dup()
390 * API is available. Instead, the reference count is
393 X509_KEYPAIR *crypto_keypair_dup(X509_KEYPAIR *keypair)
395 X509_KEYPAIR *newpair;
397 newpair = crypto_keypair_new();
400 /* Allocation failed */
404 /* Increment the public key ref count */
405 if (keypair->pubkey) {
406 CRYPTO_add(&(keypair->pubkey->references), 1, CRYPTO_LOCK_EVP_PKEY);
407 newpair->pubkey = keypair->pubkey;
410 /* Increment the private key ref count */
411 if (keypair->privkey) {
412 CRYPTO_add(&(keypair->privkey->references), 1, CRYPTO_LOCK_EVP_PKEY);
413 newpair->privkey = keypair->privkey;
416 /* Duplicate the keyid */
417 if (keypair->keyid) {
418 newpair->keyid = M_ASN1_OCTET_STRING_dup(keypair->keyid);
419 if (!newpair->keyid) {
420 /* Allocation failed */
421 crypto_keypair_free(newpair);
431 * Load a public key from a PEM-encoded x509 certificate.
432 * Returns: true on success
435 int crypto_keypair_load_cert(X509_KEYPAIR *keypair, const char *file)
441 if (!(bio = BIO_new_file(file, "r"))) {
442 openssl_post_errors(M_ERROR, _("Unable to open certificate file"));
446 cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
449 openssl_post_errors(M_ERROR, _("Unable to read certificate from file"));
453 /* Extract the public key */
454 if (!(keypair->pubkey = X509_get_pubkey(cert))) {
455 openssl_post_errors(M_ERROR, _("Unable to extract public key from certificate"));
459 /* Extract the subjectKeyIdentifier extension field */
460 if ((keypair->keyid = openssl_cert_keyid(cert)) == NULL) {
461 Jmsg0(NULL, M_ERROR, 0,
462 _("Provided certificate does not include the required subjectKeyIdentifier extension."));
466 /* Validate the public key type (only RSA is supported) */
467 if (EVP_PKEY_type(keypair->pubkey->type) != EVP_PKEY_RSA) {
468 Jmsg1(NULL, M_ERROR, 0,
469 _("Unsupported key type provided: %d\n"), EVP_PKEY_type(keypair->pubkey->type));
478 if (keypair->pubkey) {
479 EVP_PKEY_free(keypair->pubkey);
484 /* Dispatch user PEM encryption callbacks */
485 static int crypto_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
487 PEM_CB_CONTEXT *ctx = (PEM_CB_CONTEXT *) userdata;
488 return (ctx->pem_callback(buf, size, ctx->pem_userdata));
492 * Check a PEM-encoded file
493 * for the existence of a private key.
494 * Returns: true if a private key is found
497 bool crypto_keypair_has_key(const char *file) {
501 unsigned char *data = NULL;
505 if (!(bio = BIO_new_file(file, "r"))) {
506 openssl_post_errors(M_ERROR, _("Unable to open private key file"));
510 while (PEM_read_bio(bio, &name, &header, &data, &len)) {
511 /* We don't care what the data is, just that it's there */
512 OPENSSL_free(header);
516 * PEM Header Found, check for a private key
517 * Due to OpenSSL limitations, we must specifically
518 * list supported PEM private key encodings.
520 if (strcmp(name, PEM_STRING_RSA) == 0
521 || strcmp(name, PEM_STRING_DSA) == 0
522 || strcmp(name, PEM_STRING_PKCS8) == 0
523 || strcmp(name, PEM_STRING_PKCS8INF) == 0) {
535 /* Post PEM-decoding error messages, if any */
536 openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
541 * Load a PEM-encoded private key.
542 * Returns: true on success
545 int crypto_keypair_load_key(X509_KEYPAIR *keypair, const char *file,
546 CRYPTO_PEM_PASSWD_CB *pem_callback,
547 const void *pem_userdata)
553 if (!(bio = BIO_new_file(file, "r"))) {
554 openssl_post_errors(M_ERROR, _("Unable to open private key file"));
558 /* Set up PEM encryption callback */
560 ctx.pem_callback = pem_callback;
561 ctx.pem_userdata = pem_userdata;
563 ctx.pem_callback = crypto_default_pem_callback;
564 ctx.pem_userdata = NULL;
567 keypair->privkey = PEM_read_bio_PrivateKey(bio, NULL, crypto_pem_callback_dispatch, &ctx);
569 if (!keypair->privkey) {
570 openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
578 * Free memory associated with a keypair object.
580 void crypto_keypair_free(X509_KEYPAIR *keypair)
582 if (keypair->pubkey) {
583 EVP_PKEY_free(keypair->pubkey);
585 if (keypair->privkey) {
586 EVP_PKEY_free(keypair->privkey);
588 if (keypair->keyid) {
589 M_ASN1_OCTET_STRING_free(keypair->keyid);
595 * Create a new message digest context of the specified type
596 * Returns: A pointer to a DIGEST object on success.
599 DIGEST *crypto_digest_new(JCR *jcr, crypto_digest_t type)
602 const EVP_MD *md = NULL; /* Quell invalid uninitialized warnings */
604 digest = (DIGEST *)malloc(sizeof(DIGEST));
607 Dmsg1(150, "crypto_digest_new jcr=%p\n", jcr);
609 /* Initialize the OpenSSL message digest context */
610 EVP_MD_CTX_init(&digest->ctx);
612 /* Determine the correct OpenSSL message digest type */
614 case CRYPTO_DIGEST_MD5:
617 case CRYPTO_DIGEST_SHA1:
621 case CRYPTO_DIGEST_SHA256:
624 case CRYPTO_DIGEST_SHA512:
629 Jmsg1(jcr, M_ERROR, 0, _("Unsupported digest type: %d\n"), type);
633 /* Initialize the backing OpenSSL context */
634 if (EVP_DigestInit_ex(&digest->ctx, md, NULL) == 0) {
641 /* This should not happen, but never say never ... */
642 Dmsg0(150, "Digest init failed.\n");
643 openssl_post_errors(jcr, M_ERROR, _("OpenSSL digest initialization failed"));
644 crypto_digest_free(digest);
649 * Hash length bytes of data into the provided digest context.
650 * Returns: true on success
653 bool crypto_digest_update(DIGEST *digest, const uint8_t *data, uint32_t length)
655 if (EVP_DigestUpdate(&digest->ctx, data, length) == 0) {
656 Dmsg0(150, "digest update failed\n");
657 openssl_post_errors(digest->jcr, M_ERROR, _("OpenSSL digest update failed"));
665 * Finalize the data in digest, storing the result in dest and the result size
666 * in length. The result size can be determined with crypto_digest_size().
668 * Returns: true on success
671 bool crypto_digest_finalize(DIGEST *digest, uint8_t *dest, uint32_t *length)
673 if (!EVP_DigestFinal(&digest->ctx, dest, (unsigned int *)length)) {
674 Dmsg0(150, "digest finalize failed\n");
675 openssl_post_errors(digest->jcr, M_ERROR, _("OpenSSL digest finalize failed"));
683 * Free memory associated with a digest object.
685 void crypto_digest_free(DIGEST *digest)
687 EVP_MD_CTX_cleanup(&digest->ctx);
692 * Create a new message signature context.
693 * Returns: A pointer to a SIGNATURE object on success.
696 SIGNATURE *crypto_sign_new(JCR *jcr)
700 sig = (SIGNATURE *)malloc(sizeof(SIGNATURE));
705 sig->sigData = SignatureData_new();
707 Dmsg1(150, "crypto_sign_new jcr=%p\n", jcr);
710 /* Allocation failed in OpenSSL */
715 /* Set the ASN.1 structure version number */
716 ASN1_INTEGER_set(sig->sigData->version, BACULA_ASN1_VERSION);
722 * For a given public key, find the associated SignatureInfo record
723 * and create a digest context for signature validation
725 * Returns: CRYPTO_ERROR_NONE on success, with the newly allocated DIGEST in digest.
726 * A crypto_error_t value on failure.
728 crypto_error_t crypto_sign_get_digest(SIGNATURE *sig, X509_KEYPAIR *keypair,
729 crypto_digest_t &type, DIGEST **digest)
731 STACK_OF(SignerInfo) *signers;
735 signers = sig->sigData->signerInfo;
737 for (i = 0; i < sk_SignerInfo_num(signers); i++) {
738 si = sk_SignerInfo_value(signers, i);
739 if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
740 /* Get the digest algorithm and allocate a digest context */
741 Dmsg1(150, "crypto_sign_get_digest jcr=%p\n", sig->jcr);
742 switch (OBJ_obj2nid(si->digestAlgorithm)) {
744 Dmsg0(100, "sign digest algorithm is MD5\n");
745 type = CRYPTO_DIGEST_MD5;
746 *digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_MD5);
749 Dmsg0(100, "sign digest algorithm is SHA1\n");
750 type = CRYPTO_DIGEST_SHA1;
751 *digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA1);
755 Dmsg0(100, "sign digest algorithm is SHA256\n");
756 type = CRYPTO_DIGEST_SHA256;
757 *digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA256);
760 Dmsg0(100, "sign digest algorithm is SHA512\n");
761 type = CRYPTO_DIGEST_SHA512;
762 *digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA512);
766 type = CRYPTO_DIGEST_NONE;
768 return CRYPTO_ERROR_INVALID_DIGEST;
771 /* Shouldn't happen */
772 if (*digest == NULL) {
773 openssl_post_errors(sig->jcr, M_ERROR, _("OpenSSL digest_new failed"));
774 return CRYPTO_ERROR_INVALID_DIGEST;
776 return CRYPTO_ERROR_NONE;
779 openssl_post_errors(sig->jcr, M_ERROR, _("OpenSSL sign get digest failed"));
784 return CRYPTO_ERROR_NOSIGNER;
788 * For a given signature, public key, and digest, verify the SIGNATURE.
789 * Returns: CRYPTO_ERROR_NONE on success.
790 * A crypto_error_t value on failure.
792 crypto_error_t crypto_sign_verify(SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest)
794 STACK_OF(SignerInfo) *signers;
798 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
799 const unsigned char *sigData;
801 unsigned char *sigData;
804 signers = sig->sigData->signerInfo;
806 /* Find the signer */
807 for (i = 0; i < sk_SignerInfo_num(signers); i++) {
808 si = sk_SignerInfo_value(signers, i);
809 if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
810 /* Extract the signature data */
811 sigLen = M_ASN1_STRING_length(si->signature);
812 sigData = M_ASN1_STRING_data(si->signature);
814 ok = EVP_VerifyFinal(&digest->ctx, sigData, sigLen, keypair->pubkey);
816 return CRYPTO_ERROR_NONE;
817 } else if (ok == 0) {
818 openssl_post_errors(sig->jcr, M_ERROR, _("OpenSSL digest Verify final failed"));
819 return CRYPTO_ERROR_BAD_SIGNATURE;
821 /* Shouldn't happen */
822 openssl_post_errors(sig->jcr, M_ERROR, _("OpenSSL digest Verify final failed"));
823 return CRYPTO_ERROR_INTERNAL;
827 Jmsg(sig->jcr, M_ERROR, 0, _("No signers found for crypto verify.\n"));
828 /* Signer wasn't found. */
829 return CRYPTO_ERROR_NOSIGNER;
835 * Returns: true on success
838 int crypto_sign_add_signer(SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair)
840 SignerInfo *si = NULL;
841 unsigned char *buf = NULL;
844 si = SignerInfo_new();
847 /* Allocation failed in OpenSSL */
851 /* Set the ASN.1 structure version number */
852 ASN1_INTEGER_set(si->version, BACULA_ASN1_VERSION);
854 /* Set the digest algorithm identifier */
855 switch (digest->type) {
856 case CRYPTO_DIGEST_MD5:
857 si->digestAlgorithm = OBJ_nid2obj(NID_md5);
859 case CRYPTO_DIGEST_SHA1:
860 si->digestAlgorithm = OBJ_nid2obj(NID_sha1);
863 case CRYPTO_DIGEST_SHA256:
864 si->digestAlgorithm = OBJ_nid2obj(NID_sha256);
866 case CRYPTO_DIGEST_SHA512:
867 si->digestAlgorithm = OBJ_nid2obj(NID_sha512);
871 /* This should never happen */
875 /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
876 M_ASN1_OCTET_STRING_free(si->subjectKeyIdentifier);
877 si->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
879 /* Set our signature algorithm. We currently require RSA */
880 assert(EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
881 /* This is slightly evil. Reach into the MD structure and grab the key type */
882 si->signatureAlgorithm = OBJ_nid2obj(digest->ctx.digest->pkey_type);
884 /* Finalize/Sign our Digest */
885 len = EVP_PKEY_size(keypair->privkey);
886 buf = (unsigned char *) malloc(len);
887 if (!EVP_SignFinal(&digest->ctx, buf, &len, keypair->privkey)) {
888 openssl_post_errors(M_ERROR, _("Signature creation failed"));
892 /* Add the signature to the SignerInfo structure */
893 if (!M_ASN1_OCTET_STRING_set(si->signature, buf, len)) {
894 /* Allocation failed in OpenSSL */
898 /* No longer needed */
901 /* Push the new SignerInfo structure onto the stack */
902 sk_SignerInfo_push(sig->sigData->signerInfo, si);
918 * Encodes the SignatureData structure. The length argument is used to specify the
919 * size of dest. A length of 0 will cause no data to be written to dest, and the
920 * required length to be written to length. The caller can then allocate sufficient
921 * space for the output.
923 * Returns: true on success, stores the encoded data in dest, and the size in length.
926 int crypto_sign_encode(SIGNATURE *sig, uint8_t *dest, uint32_t *length)
929 *length = i2d_SignatureData(sig->sigData, NULL);
933 *length = i2d_SignatureData(sig->sigData, (unsigned char **)&dest);
938 * Decodes the SignatureData structure. The length argument is used to specify the
941 * Returns: SIGNATURE instance on success.
946 SIGNATURE *crypto_sign_decode(JCR *jcr, const uint8_t *sigData, uint32_t length)
949 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
950 const unsigned char *p = (const unsigned char *) sigData;
952 unsigned char *p = (unsigned char *)sigData;
955 sig = (SIGNATURE *)malloc(sizeof(SIGNATURE));
961 /* d2i_SignatureData modifies the supplied pointer */
962 sig->sigData = d2i_SignatureData(NULL, &p, length);
965 /* Allocation / Decoding failed in OpenSSL */
966 openssl_post_errors(jcr, M_ERROR, _("Signature decoding failed"));
975 * Free memory associated with a signature object.
977 void crypto_sign_free(SIGNATURE *sig)
979 SignatureData_free(sig->sigData);
984 * Create a new encryption session.
985 * Returns: A pointer to a CRYPTO_SESSION object on success.
988 * Note! Bacula malloc() fails if out of memory.
990 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys)
993 X509_KEYPAIR *keypair;
994 const EVP_CIPHER *ec;
998 /* Allocate our session description structures */
999 cs = (CRYPTO_SESSION *)malloc(sizeof(CRYPTO_SESSION));
1001 /* Initialize required fields */
1002 cs->session_key = NULL;
1004 /* Allocate a CryptoData structure */
1005 cs->cryptoData = CryptoData_new();
1007 if (!cs->cryptoData) {
1008 /* Allocation failed in OpenSSL */
1013 /* Set the ASN.1 structure version number */
1014 ASN1_INTEGER_set(cs->cryptoData->version, BACULA_ASN1_VERSION);
1017 * Acquire a cipher instance and set the ASN.1 cipher NID
1020 case CRYPTO_CIPHER_AES_128_CBC:
1021 /* AES 128 bit CBC */
1022 cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_128_cbc);
1023 ec = EVP_aes_128_cbc();
1025 #ifndef HAVE_OPENSSL_EXPORT_LIBRARY
1026 case CRYPTO_CIPHER_AES_192_CBC:
1027 /* AES 192 bit CBC */
1028 cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_192_cbc);
1029 ec = EVP_aes_192_cbc();
1031 case CRYPTO_CIPHER_AES_256_CBC:
1032 /* AES 256 bit CBC */
1033 cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_256_cbc);
1034 ec = EVP_aes_256_cbc();
1037 case CRYPTO_CIPHER_BLOWFISH_CBC:
1039 cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_bf_cbc);
1043 Jmsg0(NULL, M_ERROR, 0, _("Unsupported cipher type specified\n"));
1044 crypto_session_free(cs);
1048 /* Generate a symmetric session key */
1049 cs->session_key_len = EVP_CIPHER_key_length(ec);
1050 cs->session_key = (unsigned char *) malloc(cs->session_key_len);
1051 if (RAND_bytes(cs->session_key, cs->session_key_len) <= 0) {
1052 /* OpenSSL failure */
1053 crypto_session_free(cs);
1057 /* Generate an IV if possible */
1058 if ((iv_len = EVP_CIPHER_iv_length(ec))) {
1059 iv = (unsigned char *)malloc(iv_len);
1061 /* Generate random IV */
1062 if (RAND_bytes(iv, iv_len) <= 0) {
1063 /* OpenSSL failure */
1064 crypto_session_free(cs);
1069 /* Store it in our ASN.1 structure */
1070 if (!M_ASN1_OCTET_STRING_set(cs->cryptoData->iv, iv, iv_len)) {
1071 /* Allocation failed in OpenSSL */
1072 crypto_session_free(cs);
1080 * Create RecipientInfo structures for supplied
1083 foreach_alist(keypair, pubkeys) {
1085 unsigned char *ekey;
1088 ri = RecipientInfo_new();
1090 /* Allocation failed in OpenSSL */
1091 crypto_session_free(cs);
1095 /* Set the ASN.1 structure version number */
1096 ASN1_INTEGER_set(ri->version, BACULA_ASN1_VERSION);
1098 /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
1099 M_ASN1_OCTET_STRING_free(ri->subjectKeyIdentifier);
1100 ri->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
1102 /* Set our key encryption algorithm. We currently require RSA */
1103 assert(keypair->pubkey && EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
1104 ri->keyEncryptionAlgorithm = OBJ_nid2obj(NID_rsaEncryption);
1106 /* Encrypt the session key */
1107 ekey = (unsigned char *)malloc(EVP_PKEY_size(keypair->pubkey));
1109 if ((ekey_len = EVP_PKEY_encrypt(ekey, cs->session_key, cs->session_key_len, keypair->pubkey)) <= 0) {
1110 /* OpenSSL failure */
1111 RecipientInfo_free(ri);
1112 crypto_session_free(cs);
1117 /* Store it in our ASN.1 structure */
1118 if (!M_ASN1_OCTET_STRING_set(ri->encryptedKey, ekey, ekey_len)) {
1119 /* Allocation failed in OpenSSL */
1120 RecipientInfo_free(ri);
1121 crypto_session_free(cs);
1126 /* Free the encrypted key buffer */
1129 /* Push the new RecipientInfo structure onto the stack */
1130 sk_RecipientInfo_push(cs->cryptoData->recipientInfo, ri);
1137 * Encodes the CryptoData structure. The length argument is used to specify the
1138 * size of dest. A length of 0 will cause no data to be written to dest, and the
1139 * required length to be written to length. The caller can then allocate sufficient
1140 * space for the output.
1142 * Returns: true on success, stores the encoded data in dest, and the size in length.
1145 bool crypto_session_encode(CRYPTO_SESSION *cs, uint8_t *dest, uint32_t *length)
1148 *length = i2d_CryptoData(cs->cryptoData, NULL);
1152 *length = i2d_CryptoData(cs->cryptoData, &dest);
1157 * Decodes the CryptoData structure. The length argument is
1158 * used to specify the size of data.
1160 * Returns: CRYPTO_SESSION instance on success.
1162 * Returns: CRYPTO_ERROR_NONE and a pointer to a newly allocated CRYPTO_SESSION structure in *session on success.
1163 * A crypto_error_t value on failure.
1165 crypto_error_t crypto_session_decode(const uint8_t *data, uint32_t length, alist *keypairs, CRYPTO_SESSION **session)
1168 X509_KEYPAIR *keypair;
1169 STACK_OF(RecipientInfo) *recipients;
1170 crypto_error_t retval = CRYPTO_ERROR_NONE;
1171 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
1172 const unsigned char *p = (const unsigned char *)data;
1174 unsigned char *p = (unsigned char *)data;
1177 /* bacula-fd.conf doesn't contains any key */
1179 return CRYPTO_ERROR_NORECIPIENT;
1182 cs = (CRYPTO_SESSION *)malloc(sizeof(CRYPTO_SESSION));
1184 /* Initialize required fields */
1185 cs->session_key = NULL;
1187 /* d2i_CryptoData modifies the supplied pointer */
1188 cs->cryptoData = d2i_CryptoData(NULL, &p, length);
1190 if (!cs->cryptoData) {
1191 /* Allocation / Decoding failed in OpenSSL */
1192 openssl_post_errors(M_ERROR, _("CryptoData decoding failed"));
1193 retval = CRYPTO_ERROR_INTERNAL;
1197 recipients = cs->cryptoData->recipientInfo;
1200 * Find a matching RecipientInfo structure for a supplied
1203 foreach_alist(keypair, keypairs) {
1207 /* Private key available? */
1208 if (keypair->privkey == NULL) {
1212 for (i = 0; i < sk_RecipientInfo_num(recipients); i++) {
1213 ri = sk_RecipientInfo_value(recipients, i);
1215 /* Match against the subjectKeyIdentifier */
1216 if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, ri->subjectKeyIdentifier) == 0) {
1217 /* Match found, extract symmetric encryption session data */
1219 /* RSA is required. */
1220 assert(EVP_PKEY_type(keypair->privkey->type) == EVP_PKEY_RSA);
1222 /* If we recieve a RecipientInfo structure that does not use
1223 * RSA, return an error */
1224 if (OBJ_obj2nid(ri->keyEncryptionAlgorithm) != NID_rsaEncryption) {
1225 retval = CRYPTO_ERROR_INVALID_CRYPTO;
1229 /* Decrypt the session key */
1230 /* Allocate sufficient space for the largest possible decrypted data */
1231 cs->session_key = (unsigned char *)malloc(EVP_PKEY_size(keypair->privkey));
1232 cs->session_key_len = EVP_PKEY_decrypt(cs->session_key, M_ASN1_STRING_data(ri->encryptedKey),
1233 M_ASN1_STRING_length(ri->encryptedKey), keypair->privkey);
1235 if (cs->session_key_len <= 0) {
1236 openssl_post_errors(M_ERROR, _("Failure decrypting the session key"));
1237 retval = CRYPTO_ERROR_DECRYPTION;
1241 /* Session key successfully extracted, return the CRYPTO_SESSION structure */
1243 return CRYPTO_ERROR_NONE;
1248 /* No matching recipient found */
1249 return CRYPTO_ERROR_NORECIPIENT;
1252 crypto_session_free(cs);
1257 * Free memory associated with a crypto session object.
1259 void crypto_session_free(CRYPTO_SESSION *cs)
1261 if (cs->cryptoData) {
1262 CryptoData_free(cs->cryptoData);
1264 if (cs->session_key){
1265 free(cs->session_key);
1271 * Create a new crypto cipher context with the specified session object
1272 * Returns: A pointer to a CIPHER_CONTEXT object on success. The cipher block size is returned in blocksize.
1275 CIPHER_CONTEXT *crypto_cipher_new(CRYPTO_SESSION *cs, bool encrypt, uint32_t *blocksize)
1277 CIPHER_CONTEXT *cipher_ctx;
1278 const EVP_CIPHER *ec;
1280 cipher_ctx = (CIPHER_CONTEXT *)malloc(sizeof(CIPHER_CONTEXT));
1283 * Acquire a cipher instance for the given ASN.1 cipher NID
1285 if ((ec = EVP_get_cipherbyobj(cs->cryptoData->contentEncryptionAlgorithm)) == NULL) {
1286 Jmsg1(NULL, M_ERROR, 0,
1287 _("Unsupported contentEncryptionAlgorithm: %d\n"), OBJ_obj2nid(cs->cryptoData->contentEncryptionAlgorithm));
1292 /* Initialize the OpenSSL cipher context */
1293 EVP_CIPHER_CTX_init(&cipher_ctx->ctx);
1295 /* Initialize for encryption */
1296 if (!EVP_CipherInit_ex(&cipher_ctx->ctx, ec, NULL, NULL, NULL, 1)) {
1297 openssl_post_errors(M_ERROR, _("OpenSSL cipher context initialization failed"));
1301 /* Initialize for decryption */
1302 if (!EVP_CipherInit_ex(&cipher_ctx->ctx, ec, NULL, NULL, NULL, 0)) {
1303 openssl_post_errors(M_ERROR, _("OpenSSL cipher context initialization failed"));
1308 /* Set the key size */
1309 if (!EVP_CIPHER_CTX_set_key_length(&cipher_ctx->ctx, cs->session_key_len)) {
1310 openssl_post_errors(M_ERROR, _("Encryption session provided an invalid symmetric key"));
1314 /* Validate the IV length */
1315 if (EVP_CIPHER_iv_length(ec) != M_ASN1_STRING_length(cs->cryptoData->iv)) {
1316 openssl_post_errors(M_ERROR, _("Encryption session provided an invalid IV"));
1320 /* Add the key and IV to the cipher context */
1321 if (!EVP_CipherInit_ex(&cipher_ctx->ctx, NULL, NULL, cs->session_key, M_ASN1_STRING_data(cs->cryptoData->iv), -1)) {
1322 openssl_post_errors(M_ERROR, _("OpenSSL cipher context key/IV initialization failed"));
1326 *blocksize = EVP_CIPHER_CTX_block_size(&cipher_ctx->ctx);
1330 crypto_cipher_free(cipher_ctx);
1336 * Encrypt/Decrypt length bytes of data using the provided cipher context
1337 * Returns: true on success, number of bytes output in written
1340 bool crypto_cipher_update(CIPHER_CONTEXT *cipher_ctx, const uint8_t *data, uint32_t length, const uint8_t *dest, uint32_t *written)
1342 if (!EVP_CipherUpdate(&cipher_ctx->ctx, (unsigned char *)dest, (int *)written, (const unsigned char *)data, length)) {
1343 /* This really shouldn't fail */
1351 * Finalize the cipher context, writing any remaining data and necessary padding
1352 * to dest, and the size in written.
1353 * The result size will either be one block of data or zero.
1355 * Returns: true on success
1358 bool crypto_cipher_finalize (CIPHER_CONTEXT *cipher_ctx, uint8_t *dest, uint32_t *written)
1360 if (!EVP_CipherFinal_ex(&cipher_ctx->ctx, (unsigned char *)dest, (int *) written)) {
1361 /* This really shouldn't fail */
1370 * Free memory associated with a cipher context.
1372 void crypto_cipher_free (CIPHER_CONTEXT *cipher_ctx)
1374 EVP_CIPHER_CTX_cleanup(&cipher_ctx->ctx);
1380 * Perform global initialization of OpenSSL
1381 * This function is not thread safe.
1382 * Returns: 0 on success
1385 int init_crypto (void)
1389 if ((stat = openssl_init_threads()) != 0) {
1391 Jmsg1(NULL, M_ABORT, 0,
1392 _("Unable to init OpenSSL threading: ERR=%s\n"), be.bstrerror(stat));
1395 /* Load libssl and libcrypto human-readable error strings */
1396 SSL_load_error_strings();
1398 /* Initialize OpenSSL SSL library */
1401 /* Register OpenSSL ciphers and digests */
1402 OpenSSL_add_all_algorithms();
1404 if (!openssl_seed_prng()) {
1405 Jmsg0(NULL, M_ERROR_TERM, 0, _("Failed to seed OpenSSL PRNG\n"));
1408 crypto_initialized = true;
1414 * Perform global cleanup of OpenSSL
1415 * All cryptographic operations must be completed before calling this function.
1416 * This function is not thread safe.
1417 * Returns: 0 on success
1420 int cleanup_crypto (void)
1423 * Ensure that we've actually been initialized; Doing this here decreases the
1424 * complexity of client's termination/cleanup code.
1426 if (!crypto_initialized) {
1430 if (!openssl_save_prng()) {
1431 Jmsg0(NULL, M_ERROR, 0, _("Failed to save OpenSSL PRNG\n"));
1434 openssl_cleanup_threads();
1436 /* Free libssl and libcrypto error strings */
1439 /* Free all ciphers and digests */
1442 /* Free memory used by PRNG */
1445 crypto_initialized = false;
1451 #else /* HAVE_OPENSSL */
1452 # error No encryption library available
1453 #endif /* HAVE_OPENSSL */
1455 #else /* HAVE_CRYPTO */
1458 * Cryptography Support Disabled
1461 /* Message Digest Structure */
1463 crypto_digest_t type;
1471 /* Dummy Signature Structure */
1476 DIGEST *crypto_digest_new(JCR *jcr, crypto_digest_t type)
1480 digest = (DIGEST *)malloc(sizeof(DIGEST));
1481 digest->type = type;
1485 case CRYPTO_DIGEST_MD5:
1486 MD5Init(&digest->md5);
1488 case CRYPTO_DIGEST_SHA1:
1489 SHA1Init(&digest->sha1);
1492 Jmsg1(jcr, M_ERROR, 0, _("Unsupported digest type=%d specified\n"), type);
1500 bool crypto_digest_update(DIGEST *digest, const uint8_t *data, uint32_t length)
1502 switch (digest->type) {
1503 case CRYPTO_DIGEST_MD5:
1504 /* Doesn't return anything ... */
1505 MD5Update(&digest->md5, (unsigned char *) data, length);
1507 case CRYPTO_DIGEST_SHA1:
1509 if ((ret = SHA1Update(&digest->sha1, (const u_int8_t *) data, length)) == shaSuccess) {
1512 Jmsg1(NULL, M_ERROR, 0, _("SHA1Update() returned an error: %d\n"), ret);
1521 bool crypto_digest_finalize(DIGEST *digest, uint8_t *dest, uint32_t *length)
1523 switch (digest->type) {
1524 case CRYPTO_DIGEST_MD5:
1525 /* Guard against programmer error by either the API client or
1526 * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1527 assert(*length >= CRYPTO_DIGEST_MD5_SIZE);
1528 *length = CRYPTO_DIGEST_MD5_SIZE;
1529 /* Doesn't return anything ... */
1530 MD5Final((unsigned char *)dest, &digest->md5);
1532 case CRYPTO_DIGEST_SHA1:
1533 /* Guard against programmer error by either the API client or
1534 * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1535 assert(*length >= CRYPTO_DIGEST_SHA1_SIZE);
1536 *length = CRYPTO_DIGEST_SHA1_SIZE;
1537 if (SHA1Final(&digest->sha1, (u_int8_t *) dest) == shaSuccess) {
1550 void crypto_digest_free(DIGEST *digest)
1555 /* Dummy routines */
1556 int init_crypto (void) { return 0; }
1557 int cleanup_crypto (void) { return 0; }
1559 SIGNATURE *crypto_sign_new(JCR *jcr) { return NULL; }
1561 crypto_error_t crypto_sign_get_digest (SIGNATURE *sig, X509_KEYPAIR *keypair,
1562 crypto_digest_t &type, DIGEST **digest)
1563 { return CRYPTO_ERROR_INTERNAL; }
1565 crypto_error_t crypto_sign_verify (SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest) { return CRYPTO_ERROR_INTERNAL; }
1567 int crypto_sign_add_signer (SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair) { return false; }
1568 int crypto_sign_encode (SIGNATURE *sig, uint8_t *dest, uint32_t *length) { return false; }
1570 SIGNATURE *crypto_sign_decode (JCR *jcr, const uint8_t *sigData, uint32_t length) { return NULL; }
1571 void crypto_sign_free (SIGNATURE *sig) { }
1574 X509_KEYPAIR *crypto_keypair_new(void) { return NULL; }
1575 X509_KEYPAIR *crypto_keypair_dup (X509_KEYPAIR *keypair) { return NULL; }
1576 int crypto_keypair_load_cert (X509_KEYPAIR *keypair, const char *file) { return false; }
1577 bool crypto_keypair_has_key (const char *file) { return false; }
1578 int crypto_keypair_load_key (X509_KEYPAIR *keypair, const char *file, CRYPTO_PEM_PASSWD_CB *pem_callback, const void *pem_userdata) { return false; }
1579 void crypto_keypair_free (X509_KEYPAIR *keypair) { }
1581 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys) { return NULL; }
1582 void crypto_session_free (CRYPTO_SESSION *cs) { }
1583 bool crypto_session_encode (CRYPTO_SESSION *cs, uint8_t *dest, uint32_t *length) { return false; }
1584 crypto_error_t crypto_session_decode(const uint8_t *data, uint32_t length, alist *keypairs, CRYPTO_SESSION **session) { return CRYPTO_ERROR_INTERNAL; }
1586 CIPHER_CONTEXT *crypto_cipher_new (CRYPTO_SESSION *cs, bool encrypt, uint32_t *blocksize) { return NULL; }
1587 bool crypto_cipher_update (CIPHER_CONTEXT *cipher_ctx, const uint8_t *data, uint32_t length, const uint8_t *dest, uint32_t *written) { return false; }
1588 bool crypto_cipher_finalize (CIPHER_CONTEXT *cipher_ctx, uint8_t *dest, uint32_t *written) { return false; }
1589 void crypto_cipher_free (CIPHER_CONTEXT *cipher_ctx) { }
1591 #endif /* HAVE_CRYPTO */
1596 * Default PEM encryption passphrase callback.
1597 * Returns an empty password.
1599 int crypto_default_pem_callback(char *buf, int size, const void *userdata)
1601 bstrncpy(buf, "", size);
1602 return (strlen(buf));
1606 * Returns the ASCII name of the digest type.
1607 * Returns: ASCII name of digest type.
1609 const char *crypto_digest_name(DIGEST *digest)
1611 switch (digest->type) {
1612 case CRYPTO_DIGEST_MD5:
1614 case CRYPTO_DIGEST_SHA1:
1616 case CRYPTO_DIGEST_SHA256:
1618 case CRYPTO_DIGEST_SHA512:
1620 case CRYPTO_DIGEST_NONE:
1623 return "Invalid Digest Type";
1629 * Given a stream type, returns the associated
1630 * crypto_digest_t value.
1632 crypto_digest_t crypto_digest_stream_type(int stream)
1635 case STREAM_MD5_DIGEST:
1636 return CRYPTO_DIGEST_MD5;
1637 case STREAM_SHA1_DIGEST:
1638 return CRYPTO_DIGEST_SHA1;
1639 case STREAM_SHA256_DIGEST:
1640 return CRYPTO_DIGEST_SHA256;
1641 case STREAM_SHA512_DIGEST:
1642 return CRYPTO_DIGEST_SHA512;
1644 return CRYPTO_DIGEST_NONE;
1649 * * Given a crypto_error_t value, return the associated
1652 const char *crypto_strerror(crypto_error_t error) {
1654 case CRYPTO_ERROR_NONE:
1655 return _("No error");
1656 case CRYPTO_ERROR_NOSIGNER:
1657 return _("Signer not found");
1658 case CRYPTO_ERROR_NORECIPIENT:
1659 return _("Recipient not found");
1660 case CRYPTO_ERROR_INVALID_DIGEST:
1661 return _("Unsupported digest algorithm");
1662 case CRYPTO_ERROR_INVALID_CRYPTO:
1663 return _("Unsupported encryption algorithm");
1664 case CRYPTO_ERROR_BAD_SIGNATURE:
1665 return _("Signature is invalid");
1666 case CRYPTO_ERROR_DECRYPTION:
1667 return _("Decryption error");
1668 case CRYPTO_ERROR_INTERNAL:
1669 /* This shouldn't happen */
1670 return _("Internal error");
1672 return _("Unknown error");