2 * crypto.c Encryption support functions
4 * Author: Landon Fuller <landonf@opendarwin.org>
8 * Copyright (C) 2005 Kern Sibbald
10 * This file was contributed to the Bacula project by Landon Fuller.
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.
18 * If you wish to license these contributions under an alternate open source
19 * license please contact Landon Fuller <landonf@opendarwin.org>.
22 Copyright (C) 2005 Kern Sibbald
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.
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.
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
49 * Top Level Allocations - 500.2
50 * 1 - Published Allocations
51 * 1.1 - Bacula Encryption
53 * Bacula Encryption - 500.2.1.1
56 * 2 - ASN.1 Object Identifiers
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) }
67 * DEFINITIONS AUTOMATIC TAGS ::=
70 * SignatureData ::= SEQUENCE {
71 * version Version DEFAULT v0,
72 * signerInfo SignerInfo }
74 * CryptoData ::= SEQUENCE {
75 * version Version DEFAULT v0,
76 * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
77 * iv InitializationVector,
78 * recipientInfo RecipientInfo
81 * SignerInfo ::= SET OF SignerInfo
82 * RecipientInfo ::= SET OF RecipientInfo
84 * Version ::= INTEGER { v0(0) }
86 * SignerInfo ::= SEQUENCE {
88 * subjectKeyIdentifier SubjectKeyIdentifier,
89 * digestAlgorithm DigestAlgorithmIdentifier,
90 * signatureAlgorithm SignatureAlgorithmIdentifier,
91 * signature SignatureValue }
93 * RecipientInfo ::= SEQUENCE {
95 * subjectKeyIdentifier SubjectKeyIdentifier
96 * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier
97 * encryptedKey EncryptedKey
100 * SubjectKeyIdentifier ::= OCTET STRING
102 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
104 * SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
106 * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
108 * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
110 * InitializationVector ::= OCTET STRING
112 * SignatureValue ::= OCTET STRING
114 * EncryptedKey ::= OCTET STRING
116 * AlgorithmIdentifier ::= OBJECT IDENTIFIER
121 #ifdef HAVE_CRYPTO /* Is encryption enabled? */
122 #ifdef HAVE_OPENSSL /* How about OpenSSL? */
124 /* Are we initialized? */
125 static int crypto_initialized = false;
127 /* ASN.1 Declarations */
128 #define BACULA_ASN1_VERSION 0
131 ASN1_INTEGER *version;
132 ASN1_OCTET_STRING *subjectKeyIdentifier;
133 ASN1_OBJECT *digestAlgorithm;
134 ASN1_OBJECT *signatureAlgorithm;
135 ASN1_OCTET_STRING *signature;
139 ASN1_INTEGER *version;
140 ASN1_OCTET_STRING *subjectKeyIdentifier;
141 ASN1_OBJECT *keyEncryptionAlgorithm;
142 ASN1_OCTET_STRING *encryptedKey;
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);
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);
161 ASN1_INTEGER *version;
162 STACK_OF(SignerInfo) *signerInfo;
166 ASN1_INTEGER *version;
167 ASN1_OBJECT *contentEncryptionAlgorithm;
168 ASN1_OCTET_STRING *iv;
169 STACK_OF(RecipientInfo) *recipientInfo;
172 ASN1_SEQUENCE(SignatureData) = {
173 ASN1_SIMPLE(SignatureData, version, ASN1_INTEGER),
174 ASN1_SET_OF(SignatureData, signerInfo, SignerInfo),
175 } ASN1_SEQUENCE_END(SignatureData);
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);
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)
191 * SignerInfo and RecipientInfo stack macros, generated by OpenSSL's util/mkstack.pl.
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))
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))
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))
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 */
254 /* X509 Public/Private Key Pair Structure */
255 struct X509_Keypair {
256 ASN1_OCTET_STRING *keyid;
261 /* Message Digest Structure */
263 crypto_digest_t type;
267 /* Message Signature Structure */
269 SignatureData *sigData;
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 */
279 /* PEM Password Dispatch Context */
280 typedef struct PEM_CB_Context {
281 CRYPTO_PEM_PASSWD_CB *pem_callback;
282 const void *pem_userdata;
286 * Extract subjectKeyIdentifier from x509 certificate.
287 * Returns: On success, an ASN1_OCTET_STRING that must be freed via M_ASN1_OCTET_STRING_free().
290 static ASN1_OCTET_STRING *openssl_cert_keyid(X509 *cert){
292 X509V3_EXT_METHOD *method;
293 ASN1_OCTET_STRING *keyid;
295 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
296 const unsigned char *ext_value_data;
298 unsigned char *ext_value_data;
302 /* Find the index to the subjectKeyIdentifier extension */
303 i = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
309 /* Grab the extension */
310 ext = X509_get_ext(cert, i);
312 /* Get x509 extension method structure */
313 if (!(method = X509V3_EXT_get(ext))) {
317 ext_value_data = ext->value->data;
319 #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
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));
329 /* Decode ASN1 item in data */
330 keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
334 keyid = (ASN1_OCTET_STRING *) method->d2i(NULL, &ext_value_data, ext->value->length);
341 * Create a new keypair object.
342 * Returns: A pointer to a X509 KEYPAIR object on success.
345 X509_KEYPAIR *crypto_keypair_new (void) {
346 X509_KEYPAIR *keypair;
348 /* Allocate our keypair structure */
349 keypair = (X509_KEYPAIR *) malloc(sizeof(X509_KEYPAIR));
354 /* Initialize our keypair structure */
355 keypair->keyid = NULL;
356 keypair->pubkey = NULL;
357 keypair->privkey = NULL;
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
368 X509_KEYPAIR *crypto_keypair_dup (X509_KEYPAIR *keypair)
370 X509_KEYPAIR *newpair;
372 newpair = crypto_keypair_new();
375 /* Allocation failed */
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;
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;
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);
406 * Load a public key from a PEM-encoded x509 certificate.
407 * Returns: true on success
410 int crypto_keypair_load_cert (X509_KEYPAIR *keypair, const char *file)
416 if (!(bio = BIO_new_file(file, "r"))) {
417 openssl_post_errors(M_ERROR, _("Unable to open certificate file"));
421 cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
424 openssl_post_errors(M_ERROR, _("Unable to read certificate from file"));
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"));
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."));
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));
451 if (keypair->pubkey) {
452 EVP_PKEY_free(keypair->pubkey);
457 /* Dispatch user PEM encryption callbacks */
458 static int crypto_pem_callback_dispatch (char *buf, int size, int rwflag, void *userdata)
460 PEM_CB_CONTEXT *ctx = (PEM_CB_CONTEXT *) userdata;
461 return (ctx->pem_callback(buf, size, ctx->pem_userdata));
465 * Check a PEM-encoded file
466 * for the existence of a private key.
467 * Returns: true if a private key is found
470 bool crypto_keypair_has_key (const char *file) {
474 unsigned char *data = NULL;
478 if (!(bio = BIO_new_file(file, "r"))) {
479 openssl_post_errors(M_ERROR, _("Unable to open private key file"));
483 while (PEM_read_bio(bio, &name, &header, &data, &len)) {
484 /* We don't care what the data is, just that it's there */
485 OPENSSL_free(header);
489 * PEM Header Found, check for a private key
490 * Due to OpenSSL limitations, we must specifically
491 * list supported PEM private key encodings.
493 if (strcmp(name, PEM_STRING_RSA) == 0
494 || strcmp(name, PEM_STRING_DSA) == 0
495 || strcmp(name, PEM_STRING_PKCS8) == 0
496 || strcmp(name, PEM_STRING_PKCS8INF) == 0) {
508 /* Post PEM-decoding error messages, if any */
509 openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
514 * Load a PEM-encoded private key.
515 * Returns: true on success
518 int crypto_keypair_load_key (X509_KEYPAIR *keypair, const char *file,
519 CRYPTO_PEM_PASSWD_CB *pem_callback,
520 const void *pem_userdata)
526 if (!(bio = BIO_new_file(file, "r"))) {
527 openssl_post_errors(M_ERROR, _("Unable to open private key file"));
531 /* Set up PEM encryption callback */
533 ctx.pem_callback = pem_callback;
534 ctx.pem_userdata = pem_userdata;
536 ctx.pem_callback = crypto_default_pem_callback;
537 ctx.pem_userdata = NULL;
540 keypair->privkey = PEM_read_bio_PrivateKey(bio, NULL, crypto_pem_callback_dispatch, &ctx);
542 if (!keypair->privkey) {
543 openssl_post_errors(M_ERROR, _("Unable to read private key from file"));
551 * Free memory associated with a keypair object.
553 void crypto_keypair_free (X509_KEYPAIR *keypair)
555 if (keypair->pubkey) {
556 EVP_PKEY_free(keypair->pubkey);
558 if (keypair->privkey) {
559 EVP_PKEY_free(keypair->privkey);
561 if (keypair->keyid) {
562 M_ASN1_OCTET_STRING_free(keypair->keyid);
568 * Create a new message digest context of the specified type
569 * Returns: A pointer to a DIGEST object on success.
572 DIGEST *crypto_digest_new (crypto_digest_t type)
575 const EVP_MD *md = NULL; /* Quell invalid uninitialized warnings */
577 digest = (DIGEST *) malloc(sizeof(DIGEST));
580 /* Initialize the OpenSSL message digest context */
581 EVP_MD_CTX_init(&digest->ctx);
583 /* Determine the correct OpenSSL message digest type */
585 case CRYPTO_DIGEST_MD5:
588 case CRYPTO_DIGEST_SHA1:
592 case CRYPTO_DIGEST_SHA256:
595 case CRYPTO_DIGEST_SHA512:
600 Emsg1(M_ERROR, 0, _("Unsupported digest type: %d\n"), type);
604 /* Initialize the backing OpenSSL context */
605 if (EVP_DigestInit_ex(&digest->ctx, md, NULL) == 0) {
612 /* This should not happen, but never say never ... */
613 openssl_post_errors(M_ERROR, _("OpenSSL digest initialization failed"));
614 crypto_digest_free(digest);
619 * Hash length bytes of data into the provided digest context.
620 * Returns: true on success
623 bool crypto_digest_update (DIGEST *digest, const void *data, size_t length) {
624 if (EVP_DigestUpdate(&digest->ctx, data, length) == 0) {
632 * Finalize the data in digest, storing the result in dest and the result size
633 * in length. The result size can be determined with crypto_digest_size().
635 * Returns: true on success
638 bool crypto_digest_finalize (DIGEST *digest, void *dest, size_t *length) {
639 if (!EVP_DigestFinal(&digest->ctx, (unsigned char *) dest, (unsigned int *) length)) {
647 * Free memory associated with a digest object.
649 void crypto_digest_free (DIGEST *digest)
651 EVP_MD_CTX_cleanup(&digest->ctx);
656 * Create a new message signature context.
657 * Returns: A pointer to a SIGNATURE object on success.
660 SIGNATURE *crypto_sign_new (void)
664 sig = (SIGNATURE *) malloc(sizeof(SIGNATURE));
669 sig->sigData = SignatureData_new();
672 /* Allocation failed in OpenSSL */
677 /* Set the ASN.1 structure version number */
678 ASN1_INTEGER_set(sig->sigData->version, BACULA_ASN1_VERSION);
684 * For a given public key, find the associated SignatureInfo record
685 * and create a digest context for signature validation
686 * Returns: CRYPTO_ERROR_NONE on success, with the newly allocated DIGEST in digest.
687 * A crypto_error_t value on failure.
689 crypto_error_t crypto_sign_get_digest(SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST **digest)
691 STACK_OF(SignerInfo) *signers;
695 signers = sig->sigData->signerInfo;
697 for (i = 0; i < sk_SignerInfo_num(signers); i++) {
698 si = sk_SignerInfo_value(signers, i);
699 if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
700 /* Get the digest algorithm and allocate a digest context */
701 switch (OBJ_obj2nid(si->digestAlgorithm)) {
703 *digest = crypto_digest_new(CRYPTO_DIGEST_MD5);
706 *digest = crypto_digest_new(CRYPTO_DIGEST_SHA1);
710 *digest = crypto_digest_new(CRYPTO_DIGEST_SHA256);
713 *digest = crypto_digest_new(CRYPTO_DIGEST_SHA512);
718 return CRYPTO_ERROR_INVALID_DIGEST;
721 /* Shouldn't happen */
722 if (*digest == NULL) {
723 return CRYPTO_ERROR_INVALID_DIGEST;
725 return CRYPTO_ERROR_NONE;
730 return CRYPTO_ERROR_NOSIGNER;
734 * For a given signature, public key, and digest, verify the SIGNATURE.
735 * Returns: CRYPTO_ERROR_NONE on success.
736 * A crypto_error_t value on failure.
738 crypto_error_t crypto_sign_verify(SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest)
740 STACK_OF(SignerInfo) *signers;
744 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
745 const unsigned char *sigData;
747 unsigned char *sigData;
750 signers = sig->sigData->signerInfo;
752 /* Find the signer */
753 for (i = 0; i < sk_SignerInfo_num(signers); i++) {
754 si = sk_SignerInfo_value(signers, i);
755 if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) == 0) {
756 /* Extract the signature data */
757 sigLen = M_ASN1_STRING_length(si->signature);
758 sigData = M_ASN1_STRING_data(si->signature);
760 ok = EVP_VerifyFinal(&digest->ctx, sigData, sigLen, keypair->pubkey);
762 return CRYPTO_ERROR_NONE;
763 } else if (ok == 0) {
764 return CRYPTO_ERROR_BAD_SIGNATURE;
766 /* Shouldn't happen */
767 openssl_post_errors(M_ERROR, _("OpenSSL error occured"));
768 return CRYPTO_ERROR_INTERNAL;
773 /* Signer wasn't found. */
774 return CRYPTO_ERROR_NOSIGNER;
780 * Returns: true on success
783 int crypto_sign_add_signer(SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair)
785 SignerInfo *si = NULL;
786 unsigned char *buf = NULL;
789 si = SignerInfo_new();
792 /* Allocation failed in OpenSSL */
796 /* Set the ASN.1 structure version number */
797 ASN1_INTEGER_set(si->version, BACULA_ASN1_VERSION);
799 /* Set the digest algorithm identifier */
800 switch (digest->type) {
801 case CRYPTO_DIGEST_MD5:
802 si->digestAlgorithm = OBJ_nid2obj(NID_md5);
804 case CRYPTO_DIGEST_SHA1:
805 si->digestAlgorithm = OBJ_nid2obj(NID_sha1);
808 case CRYPTO_DIGEST_SHA256:
809 si->digestAlgorithm = OBJ_nid2obj(NID_sha256);
811 case CRYPTO_DIGEST_SHA512:
812 si->digestAlgorithm = OBJ_nid2obj(NID_sha512);
816 /* This should never happen */
820 /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
821 M_ASN1_OCTET_STRING_free(si->subjectKeyIdentifier);
822 si->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
824 /* Set our signature algorithm. We currently require RSA */
825 assert(EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
826 /* This is slightly evil. Reach into the MD structure and grab the key type */
827 si->signatureAlgorithm = OBJ_nid2obj(digest->ctx.digest->pkey_type);
829 /* Finalize/Sign our Digest */
830 len = EVP_PKEY_size(keypair->privkey);
831 buf = (unsigned char *) malloc(len);
832 if (!EVP_SignFinal(&digest->ctx, buf, &len, keypair->privkey)) {
833 openssl_post_errors(M_ERROR, _("Signature creation failed"));
837 /* Add the signature to the SignerInfo structure */
838 if (!M_ASN1_OCTET_STRING_set(si->signature, buf, len)) {
839 /* Allocation failed in OpenSSL */
843 /* No longer needed */
846 /* Push the new SignerInfo structure onto the stack */
847 sk_SignerInfo_push(sig->sigData->signerInfo, si);
863 * Encodes the SignatureData structure. The length argument is used to specify the
864 * size of dest. A length of 0 will cause no data to be written to dest, and the
865 * required length to be written to length. The caller can then allocate sufficient
866 * space for the output.
868 * Returns: true on success, stores the encoded data in dest, and the size in length.
871 int crypto_sign_encode(SIGNATURE *sig, void *dest, size_t *length)
874 *length = i2d_SignatureData(sig->sigData, NULL);
878 *length = i2d_SignatureData(sig->sigData, (unsigned char **) &dest);
883 * Decodes the SignatureData structure. The length argument is used to specify the
886 * Returns: SIGNATURE instance on success.
891 SIGNATURE *crypto_sign_decode(const void *sigData, size_t length)
894 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
895 const unsigned char *p = (const unsigned char *) sigData;
897 unsigned char *p = (unsigned char *) sigData;
900 sig = (SIGNATURE *) malloc(sizeof(SIGNATURE));
905 /* d2i_SignatureData modifies the supplied pointer */
906 sig->sigData = d2i_SignatureData(NULL, &p, length);
909 /* Allocation / Decoding failed in OpenSSL */
910 openssl_post_errors(M_ERROR, _("Signature decoding failed"));
918 * Free memory associated with a signature object.
920 void crypto_sign_free(SIGNATURE *sig)
922 SignatureData_free(sig->sigData);
927 * Create a new encryption session.
928 * Returns: A pointer to a CRYPTO_SESSION object on success.
931 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys)
934 X509_KEYPAIR *keypair;
935 const EVP_CIPHER *ec;
939 /* Allocate our session description structures */
940 cs = (CRYPTO_SESSION *) malloc(sizeof(CRYPTO_SESSION));
945 /* Initialize required fields */
946 cs->session_key = NULL;
948 /* Allocate a CryptoData structure */
949 cs->cryptoData = CryptoData_new();
951 if (!cs->cryptoData) {
952 /* Allocation failed in OpenSSL */
957 /* Set the ASN.1 structure version number */
958 ASN1_INTEGER_set(cs->cryptoData->version, BACULA_ASN1_VERSION);
961 * Acquire a cipher instance and set the ASN.1 cipher NID
964 case CRYPTO_CIPHER_AES_128_CBC:
965 /* AES 128 bit CBC */
966 cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_128_cbc);
967 ec = EVP_aes_128_cbc();
969 case CRYPTO_CIPHER_AES_192_CBC:
970 /* AES 192 bit CBC */
971 cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_192_cbc);
972 ec = EVP_aes_192_cbc();
974 case CRYPTO_CIPHER_AES_256_CBC:
975 /* AES 256 bit CBC */
976 cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_aes_256_cbc);
977 ec = EVP_aes_256_cbc();
979 case CRYPTO_CIPHER_BLOWFISH_CBC:
981 cs->cryptoData->contentEncryptionAlgorithm = OBJ_nid2obj(NID_bf_cbc);
985 Emsg0(M_ERROR, 0, _("Unsupported cipher type specified\n"));
986 crypto_session_free(cs);
990 /* Generate a symmetric session key */
991 cs->session_key_len = EVP_CIPHER_key_length(ec);
992 cs->session_key = (unsigned char *) malloc(cs->session_key_len);
993 if (RAND_bytes(cs->session_key, cs->session_key_len) <= 0) {
994 /* OpenSSL failure */
995 crypto_session_free(cs);
999 /* Generate an IV if possible */
1000 if ((iv_len = EVP_CIPHER_iv_length(ec))) {
1001 iv = (unsigned char *) malloc(iv_len);
1003 /* Malloc failure */
1004 crypto_session_free(cs);
1008 /* Generate random IV */
1009 if (RAND_bytes(iv, iv_len) <= 0) {
1010 /* OpenSSL failure */
1011 crypto_session_free(cs);
1016 /* Store it in our ASN.1 structure */
1017 if (!M_ASN1_OCTET_STRING_set(cs->cryptoData->iv, iv, iv_len)) {
1018 /* Allocation failed in OpenSSL */
1019 crypto_session_free(cs);
1027 * Create RecipientInfo structures for supplied
1030 foreach_alist(keypair, pubkeys) {
1032 unsigned char *ekey;
1035 ri = RecipientInfo_new();
1037 /* Allocation failed in OpenSSL */
1038 crypto_session_free(cs);
1042 /* Set the ASN.1 structure version number */
1043 ASN1_INTEGER_set(ri->version, BACULA_ASN1_VERSION);
1045 /* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
1046 M_ASN1_OCTET_STRING_free(ri->subjectKeyIdentifier);
1047 ri->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
1049 /* Set our key encryption algorithm. We currently require RSA */
1050 assert(keypair->pubkey && EVP_PKEY_type(keypair->pubkey->type) == EVP_PKEY_RSA);
1051 ri->keyEncryptionAlgorithm = OBJ_nid2obj(NID_rsaEncryption);
1053 /* Encrypt the session key */
1054 ekey = (unsigned char *) malloc(EVP_PKEY_size(keypair->pubkey));
1056 RecipientInfo_free(ri);
1057 crypto_session_free(cs);
1061 if ((ekey_len = EVP_PKEY_encrypt(ekey, cs->session_key, cs->session_key_len, keypair->pubkey)) <= 0) {
1062 /* OpenSSL failure */
1063 RecipientInfo_free(ri);
1064 crypto_session_free(cs);
1069 /* Store it in our ASN.1 structure */
1070 if (!M_ASN1_OCTET_STRING_set(ri->encryptedKey, ekey, ekey_len)) {
1071 /* Allocation failed in OpenSSL */
1072 RecipientInfo_free(ri);
1073 crypto_session_free(cs);
1078 /* Free the encrypted key buffer */
1081 /* Push the new RecipientInfo structure onto the stack */
1082 sk_RecipientInfo_push(cs->cryptoData->recipientInfo, ri);
1089 * Encodes the CryptoData structure. The length argument is used to specify the
1090 * size of dest. A length of 0 will cause no data to be written to dest, and the
1091 * required length to be written to length. The caller can then allocate sufficient
1092 * space for the output.
1094 * Returns: true on success, stores the encoded data in dest, and the size in length.
1097 bool crypto_session_encode(CRYPTO_SESSION *cs, void *dest, size_t *length)
1100 *length = i2d_CryptoData(cs->cryptoData, NULL);
1104 *length = i2d_CryptoData(cs->cryptoData, (unsigned char **) &dest);
1109 * Decodes the CryptoData structure. The length argument is
1110 * used to specify the size of data.
1112 * Returns: CRYPTO_SESSION instance on success.
1114 * Returns: CRYPTO_ERROR_NONE and a pointer to a newly allocated CRYPTO_SESSION structure in *session on success.
1115 * A crypto_error_t value on failure.
1117 crypto_error_t crypto_session_decode(const void *data, size_t length, alist *keypairs, CRYPTO_SESSION **session)
1120 X509_KEYPAIR *keypair;
1121 STACK_OF(RecipientInfo) *recipients;
1122 crypto_error_t retval = CRYPTO_ERROR_NONE;
1123 #if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
1124 const unsigned char *p = (const unsigned char *) data;
1126 unsigned char *p = (unsigned char *) data;
1129 cs = (CRYPTO_SESSION *) malloc(sizeof(CRYPTO_SESSION));
1131 return CRYPTO_ERROR_INTERNAL;
1134 /* d2i_CryptoData modifies the supplied pointer */
1135 cs->cryptoData = d2i_CryptoData(NULL, &p, length);
1137 if (!cs->cryptoData) {
1138 /* Allocation / Decoding failed in OpenSSL */
1139 openssl_post_errors(M_ERROR, _("CryptoData decoding failed"));
1140 retval = CRYPTO_ERROR_INTERNAL;
1144 recipients = cs->cryptoData->recipientInfo;
1147 * Find a matching RecipientInfo structure for a supplied
1150 foreach_alist(keypair, keypairs) {
1154 /* Private key available? */
1155 if (keypair->privkey == NULL) {
1159 for (i = 0; i < sk_RecipientInfo_num(recipients); i++) {
1160 ri = sk_RecipientInfo_value(recipients, i);
1162 /* Match against the subjectKeyIdentifier */
1163 if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, ri->subjectKeyIdentifier) == 0) {
1164 /* Match found, extract symmetric encryption session data */
1166 /* RSA is required. */
1167 assert(EVP_PKEY_type(keypair->privkey->type) == EVP_PKEY_RSA);
1169 /* If we recieve a RecipientInfo structure that does not use
1170 * RSA, return an error */
1171 if (OBJ_obj2nid(ri->keyEncryptionAlgorithm) != NID_rsaEncryption) {
1172 retval = CRYPTO_ERROR_INVALID_CRYPTO;
1176 /* Decrypt the session key */
1177 /* Allocate sufficient space for the largest possible decrypted data */
1178 cs->session_key = (unsigned char *) malloc(EVP_PKEY_size(keypair->privkey));
1179 cs->session_key_len = EVP_PKEY_decrypt(cs->session_key, M_ASN1_STRING_data(ri->encryptedKey),
1180 M_ASN1_STRING_length(ri->encryptedKey), keypair->privkey);
1182 if (cs->session_key_len <= 0) {
1183 openssl_post_errors(M_ERROR, _("Failure decrypting the session key"));
1184 retval = CRYPTO_ERROR_DECRYPTION;
1188 /* Session key successfully extracted, return the CRYPTO_SESSION structure */
1190 return CRYPTO_ERROR_NONE;
1195 /* No matching recipient found */
1196 return CRYPTO_ERROR_NORECIPIENT;
1199 crypto_session_free(cs);
1204 * Free memory associated with a crypto session object.
1206 void crypto_session_free (CRYPTO_SESSION *cs)
1208 if (cs->cryptoData) {
1209 CryptoData_free(cs->cryptoData);
1211 if (cs->session_key){
1212 free(cs->session_key);
1218 * Perform global initialization of OpenSSL
1219 * This function is not thread safe.
1220 * Returns: 0 on success
1223 int init_crypto (void)
1227 if ((stat = openssl_init_threads()) != 0) {
1228 Emsg1(M_ABORT, 0, _("Unable to init OpenSSL threading: ERR=%s\n"), strerror(stat));
1231 /* Load libssl and libcrypto human-readable error strings */
1232 SSL_load_error_strings();
1234 /* Register OpenSSL ciphers */
1237 if (!openssl_seed_prng()) {
1238 Emsg0(M_ERROR_TERM, 0, _("Failed to seed OpenSSL PRNG\n"));
1241 crypto_initialized = true;
1247 * Perform global cleanup of OpenSSL
1248 * All cryptographic operations must be completed before calling this function.
1249 * This function is not thread safe.
1250 * Returns: 0 on success
1253 int cleanup_crypto (void)
1256 * Ensure that we've actually been initialized; Doing this here decreases the
1257 * complexity of client's termination/cleanup code.
1259 if (!crypto_initialized) {
1263 if (!openssl_save_prng()) {
1264 Emsg0(M_ERROR, 0, _("Failed to save OpenSSL PRNG\n"));
1267 openssl_cleanup_threads();
1269 /* Free libssl and libcrypto error strings */
1272 /* Free memory used by PRNG */
1275 crypto_initialized = false;
1281 #else /* HAVE_OPENSSL */
1282 # error No encryption library available
1283 #endif /* HAVE_OPENSSL */
1285 #else /* HAVE_CRYPTO */
1288 * Cryptography Support Disabled
1291 /* Message Digest Structure */
1293 crypto_digest_t type;
1300 /* Dummy Signature Structure */
1304 DIGEST *crypto_digest_new (crypto_digest_t type)
1308 digest = (DIGEST *) malloc(sizeof(DIGEST));
1309 digest->type = type;
1312 case CRYPTO_DIGEST_MD5:
1313 MD5Init(&digest->md5);
1315 case CRYPTO_DIGEST_SHA1:
1316 SHA1Init(&digest->sha1);
1319 Emsg0(M_ERROR, 0, _("Unsupported digest type specified\n"));
1327 bool crypto_digest_update (DIGEST *digest, const void *data, size_t length) {
1328 switch (digest->type) {
1329 case CRYPTO_DIGEST_MD5:
1330 /* Doesn't return anything ... */
1331 MD5Update(&digest->md5, (unsigned char *) data, length);
1333 case CRYPTO_DIGEST_SHA1:
1335 if ((ret = SHA1Update(&digest->sha1, (const u_int8_t *) data, length)) == shaSuccess) {
1338 Emsg1(M_ERROR, 0, _("SHA1Update() returned an error: %d\n"), ret);
1347 bool crypto_digest_finalize (DIGEST *digest, void *dest, size_t *length) {
1349 switch (digest->type) {
1350 case CRYPTO_DIGEST_MD5:
1351 /* Guard against programmer error by either the API client or
1352 * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1353 assert(*length >= CRYPTO_DIGEST_MD5_SIZE);
1354 *length = CRYPTO_DIGEST_MD5_SIZE;
1355 /* Doesn't return anything ... */
1356 MD5Final((unsigned char *) dest, &digest->md5);
1358 case CRYPTO_DIGEST_SHA1:
1359 /* Guard against programmer error by either the API client or
1360 * an out-of-sync CRYPTO_DIGEST_MAX_SIZE */
1361 assert(*length >= CRYPTO_DIGEST_SHA1_SIZE);
1362 *length = CRYPTO_DIGEST_SHA1_SIZE;
1363 if (SHA1Final(&digest->sha1, (u_int8_t *) dest) == shaSuccess) {
1376 void crypto_digest_free (DIGEST *digest)
1381 /* Dummy routines */
1382 int init_crypto (void) { return 0; }
1383 int cleanup_crypto (void) { return 0; }
1385 SIGNATURE *crypto_sign_new (void) { return NULL; }
1387 crypto_error_t crypto_sign_get_digest (SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST **digest) { return CRYPTO_ERROR_INTERNAL; }
1388 crypto_error_t crypto_sign_verify (SIGNATURE *sig, X509_KEYPAIR *keypair, DIGEST *digest) { return CRYPTO_ERROR_INTERNAL; }
1390 int crypto_sign_add_signer (SIGNATURE *sig, DIGEST *digest, X509_KEYPAIR *keypair) { return false; }
1391 int crypto_sign_encode (SIGNATURE *sig, void *dest, size_t *length) { return false; }
1393 SIGNATURE *crypto_sign_decode (const void *sigData, size_t length) { return NULL; }
1394 void crypto_sign_free (SIGNATURE *sig) { }
1397 X509_KEYPAIR *crypto_keypair_new (void) { return NULL; }
1398 X509_KEYPAIR *crypto_keypair_dup (X509_KEYPAIR *keypair) { return NULL; }
1399 int crypto_keypair_load_cert (X509_KEYPAIR *keypair, const char *file) { return false; }
1400 bool crypto_keypair_has_key (const char *file) { return false; }
1401 int crypto_keypair_load_key (X509_KEYPAIR *keypair, const char *file, CRYPTO_PEM_PASSWD_CB *pem_callback, const void *pem_userdata) { return false; }
1402 void crypto_keypair_free (X509_KEYPAIR *keypair) { }
1404 CRYPTO_SESSION *crypto_session_new (crypto_cipher_t cipher, alist *pubkeys) { return NULL; }
1405 void crypto_session_free (CRYPTO_SESSION *cs) { }
1406 bool crypto_session_encode(CRYPTO_SESSION *cs, void *dest, size_t *length) { return false; }
1407 crypto_error_t crypto_session_decode(const void *data, size_t length, alist *keypairs, CRYPTO_SESSION **session) { return CRYPTO_ERROR_INTERNAL; }
1409 #endif /* HAVE_CRYPTO */
1414 * Default PEM encryption passphrase callback.
1415 * Returns an empty password.
1417 int crypto_default_pem_callback(char *buf, int size, const void *userdata)
1419 bstrncpy(buf, "", size);
1420 return (strlen(buf));
1424 * Returns the ASCII name of the digest type.
1425 * Returns: ASCII name of digest type.
1427 const char *crypto_digest_name (DIGEST *digest) {
1428 switch (digest->type) {
1429 case CRYPTO_DIGEST_MD5:
1431 case CRYPTO_DIGEST_SHA1:
1433 case CRYPTO_DIGEST_SHA256:
1435 case CRYPTO_DIGEST_SHA512:
1437 case CRYPTO_DIGEST_NONE:
1440 return "Invalid Digest Type";
1446 * Given a stream type, returns the associated
1447 * crypto_digest_t value.
1449 crypto_digest_t crypto_digest_stream_type (int stream) {
1451 case STREAM_MD5_DIGEST:
1452 return CRYPTO_DIGEST_MD5;
1453 case STREAM_SHA1_DIGEST:
1454 return CRYPTO_DIGEST_SHA1;
1455 case STREAM_SHA256_DIGEST:
1456 return CRYPTO_DIGEST_SHA256;
1457 case STREAM_SHA512_DIGEST:
1458 return CRYPTO_DIGEST_SHA512;
1460 return CRYPTO_DIGEST_NONE;
1465 * * Given a crypto_error_t value, return the associated
1468 const char *crypto_strerror(crypto_error_t error) {
1470 case CRYPTO_ERROR_NONE:
1472 case CRYPTO_ERROR_NOSIGNER:
1473 return "Signer not found";
1474 case CRYPTO_ERROR_NORECIPIENT:
1475 return "Recipient not found";
1476 case CRYPTO_ERROR_INVALID_DIGEST:
1477 return "Unsupported digest algorithm";
1478 case CRYPTO_ERROR_INVALID_CRYPTO:
1479 return "Unsupported encryption algorithm";
1480 case CRYPTO_ERROR_BAD_SIGNATURE:
1481 return "Signature is invalid";
1482 case CRYPTO_ERROR_DECRYPTION:
1483 return "Decryption error";
1484 case CRYPTO_ERROR_INTERNAL:
1485 /* This shouldn't happen */
1486 return "Internal error";
1488 return "Unknown error";