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