/
crypto_openssl.cc
1762 lines (1506 loc) · 49.6 KB
/
crypto_openssl.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
BAREOS® - Backup Archiving REcovery Open Sourced
Copyright (C) 2005-2011 Free Software Foundation Europe e.V.
Copyright (C) 2013-2020 Bareos GmbH & Co. KG
This program is Free Software; you can redistribute it and/or
modify it under the terms of version three of the GNU Affero General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
/*
* crypto_openssl.c Encryption support functions when OPENSSL backend.
*
* Author: Landon Fuller <landonf@opendarwin.org>
*/
#include "include/bareos.h"
#include "lib/berrno.h"
#include "lib/crypto_openssl.h"
#if defined(HAVE_OPENSSL)
#include <openssl/err.h>
#include <openssl/rand.h>
#if defined(HAVE_CRYPTO)
#include "jcr.h"
#include <assert.h>
#include "lib/alist.h"
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/engine.h>
#include <openssl/evp.h>
/*
* For OpenSSL version 1.x, EVP_PKEY_encrypt no longer exists. It was not an
* official API.
*/
#if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
#define EVP_PKEY_encrypt EVP_PKEY_encrypt_old
#define EVP_PKEY_decrypt EVP_PKEY_decrypt_old
#endif
/*
* Sanity checks.
*
* Various places in the bareos source code define arrays of size
* CRYPTO_DIGEST_MAX_SIZE. Make sure this is large enough for all EVP digest
* routines supported by openssl.
*/
#if (EVP_MAX_MD_SIZE > CRYPTO_DIGEST_MAX_SIZE)
#error \
"EVP_MAX_MD_SIZE > CRYPTO_DIGEST_MAX_SIZE, please update src/lib/crypto.h"
#endif
#if (EVP_MAX_BLOCK_LENGTH != CRYPTO_CIPHER_MAX_BLOCK_SIZE)
#error \
"EVP_MAX_BLOCK_LENGTH != CRYPTO_CIPHER_MAX_BLOCK_SIZE, please update src/lib/crypto.h"
#endif
/* ASN.1 Declarations */
#define BAREOS_ASN1_VERSION 0
typedef struct {
ASN1_INTEGER* version;
ASN1_OCTET_STRING* subjectKeyIdentifier;
ASN1_OBJECT* digestAlgorithm;
ASN1_OBJECT* signatureAlgorithm;
ASN1_OCTET_STRING* signature;
} SignerInfo;
typedef struct {
ASN1_INTEGER* version;
ASN1_OCTET_STRING* subjectKeyIdentifier;
ASN1_OBJECT* keyEncryptionAlgorithm;
ASN1_OCTET_STRING* encryptedKey;
} RecipientInfo;
ASN1_SEQUENCE(SignerInfo) = {
ASN1_SIMPLE(SignerInfo, version, ASN1_INTEGER),
ASN1_SIMPLE(SignerInfo, subjectKeyIdentifier, ASN1_OCTET_STRING),
ASN1_SIMPLE(SignerInfo, digestAlgorithm, ASN1_OBJECT),
ASN1_SIMPLE(SignerInfo, signatureAlgorithm, ASN1_OBJECT),
ASN1_SIMPLE(SignerInfo,
signature,
ASN1_OCTET_STRING)} ASN1_SEQUENCE_END(SignerInfo);
ASN1_SEQUENCE(RecipientInfo) = {
ASN1_SIMPLE(RecipientInfo, version, ASN1_INTEGER),
ASN1_SIMPLE(RecipientInfo, subjectKeyIdentifier, ASN1_OCTET_STRING),
ASN1_SIMPLE(RecipientInfo, keyEncryptionAlgorithm, ASN1_OBJECT),
ASN1_SIMPLE(RecipientInfo, encryptedKey, ASN1_OCTET_STRING),
} ASN1_SEQUENCE_END(RecipientInfo);
typedef struct {
ASN1_INTEGER* version;
STACK_OF(SignerInfo) * signerInfo;
} SignatureData;
typedef struct {
ASN1_INTEGER* version;
ASN1_OBJECT* contentEncryptionAlgorithm;
ASN1_OCTET_STRING* iv;
STACK_OF(RecipientInfo) * recipientInfo;
} CryptoData;
ASN1_SEQUENCE(SignatureData) = {
ASN1_SIMPLE(SignatureData, version, ASN1_INTEGER),
ASN1_SET_OF(SignatureData, signerInfo, SignerInfo),
} ASN1_SEQUENCE_END(SignatureData);
ASN1_SEQUENCE(CryptoData) = {
ASN1_SIMPLE(CryptoData, version, ASN1_INTEGER),
ASN1_SIMPLE(CryptoData, contentEncryptionAlgorithm, ASN1_OBJECT),
ASN1_SIMPLE(CryptoData, iv, ASN1_OCTET_STRING),
ASN1_SET_OF(CryptoData,
recipientInfo,
RecipientInfo)} ASN1_SEQUENCE_END(CryptoData);
IMPLEMENT_ASN1_FUNCTIONS(SignerInfo)
IMPLEMENT_ASN1_FUNCTIONS(RecipientInfo)
IMPLEMENT_ASN1_FUNCTIONS(SignatureData)
IMPLEMENT_ASN1_FUNCTIONS(CryptoData)
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
/* Openssl Version < 1.1 */
#define OBJ_get0_data(o) ((o)->data)
#define OBJ_length(o) ((o)->length)
#define X509_EXTENSION_get_data(ext) ((ext)->value)
#define EVP_PKEY_id(key) ((key)->type)
#define EVP_PKEY_up_ref(x509_key) \
CRYPTO_add(&(x509_key->references), 1, CRYPTO_LOCK_EVP_PKEY)
IMPLEMENT_STACK_OF(SignerInfo)
IMPLEMENT_STACK_OF(RecipientInfo)
/*
* SignerInfo and RecipientInfo stack macros, generated by OpenSSL's
* util/mkstack.pl.
*/
#define sk_SignerInfo_new(st) SKM_sk_new(SignerInfo, (st))
#define sk_SignerInfo_new_null() SKM_sk_new_null(SignerInfo)
#define sk_SignerInfo_free(st) SKM_sk_free(SignerInfo, (st))
#define sk_SignerInfo_num(st) SKM_sk_num(SignerInfo, (st))
#define sk_SignerInfo_value(st, i) SKM_sk_value(SignerInfo, (st), (i))
#define sk_SignerInfo_set(st, i, val) SKM_sk_set(SignerInfo, (st), (i), (val))
#define sk_SignerInfo_zero(st) SKM_sk_zero(SignerInfo, (st))
#define sk_SignerInfo_push(st, val) SKM_sk_push(SignerInfo, (st), (val))
#define sk_SignerInfo_unshift(st, val) SKM_sk_unshift(SignerInfo, (st), (val))
#define sk_SignerInfo_find(st, val) SKM_sk_find(SignerInfo, (st), (val))
#define sk_SignerInfo_delete(st, i) SKM_sk_delete(SignerInfo, (st), (i))
#define sk_SignerInfo_delete_ptr(st, ptr) \
SKM_sk_delete_ptr(SignerInfo, (st), (ptr))
#define sk_SignerInfo_insert(st, val, i) \
SKM_sk_insert(SignerInfo, (st), (val), (i))
#define sk_SignerInfo_set_cmp_func(st, cmp) \
SKM_sk_set_cmp_func(SignerInfo, (st), (cmp))
#define sk_SignerInfo_dup(st) SKM_sk_dup(SignerInfo, st)
#define sk_SignerInfo_pop_free(st, free_func) \
SKM_sk_pop_free(SignerInfo, (st), (free_func))
#define sk_SignerInfo_shift(st) SKM_sk_shift(SignerInfo, (st))
#define sk_SignerInfo_pop(st) SKM_sk_pop(SignerInfo, (st))
#define sk_SignerInfo_sort(st) SKM_sk_sort(SignerInfo, (st))
#define sk_SignerInfo_is_sorted(st) SKM_sk_is_sorted(SignerInfo, (st))
#define sk_RecipientInfo_new(st) SKM_sk_new(RecipientInfo, (st))
#define sk_RecipientInfo_new_null() SKM_sk_new_null(RecipientInfo)
#define sk_RecipientInfo_free(st) SKM_sk_free(RecipientInfo, (st))
#define sk_RecipientInfo_num(st) SKM_sk_num(RecipientInfo, (st))
#define sk_RecipientInfo_value(st, i) SKM_sk_value(RecipientInfo, (st), (i))
#define sk_RecipientInfo_set(st, i, val) \
SKM_sk_set(RecipientInfo, (st), (i), (val))
#define sk_RecipientInfo_zero(st) SKM_sk_zero(RecipientInfo, (st))
#define sk_RecipientInfo_push(st, val) SKM_sk_push(RecipientInfo, (st), (val))
#define sk_RecipientInfo_unshift(st, val) \
SKM_sk_unshift(RecipientInfo, (st), (val))
#define sk_RecipientInfo_find(st, val) SKM_sk_find(RecipientInfo, (st), (val))
#define sk_RecipientInfo_delete(st, i) SKM_sk_delete(RecipientInfo, (st), (i))
#define sk_RecipientInfo_delete_ptr(st, ptr) \
SKM_sk_delete_ptr(RecipientInfo, (st), (ptr))
#define sk_RecipientInfo_insert(st, val, i) \
SKM_sk_insert(RecipientInfo, (st), (val), (i))
#define sk_RecipientInfo_set_cmp_func(st, cmp) \
SKM_sk_set_cmp_func(RecipientInfo, (st), (cmp))
#define sk_RecipientInfo_dup(st) SKM_sk_dup(RecipientInfo, st)
#define sk_RecipientInfo_pop_free(st, free_func) \
SKM_sk_pop_free(RecipientInfo, (st), (free_func))
#define sk_RecipientInfo_shift(st) SKM_sk_shift(RecipientInfo, (st))
#define sk_RecipientInfo_pop(st) SKM_sk_pop(RecipientInfo, (st))
#define sk_RecipientInfo_sort(st) SKM_sk_sort(RecipientInfo, (st))
#define sk_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(RecipientInfo, (st))
#else
/* Openssl Version >= 1.1 */
/* ignore the suggest-override warnings caused by following DEFINE_STACK_OF() */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
DEFINE_STACK_OF(SignerInfo)
DEFINE_STACK_OF(RecipientInfo)
#pragma GCC diagnostic pop
#define M_ASN1_OCTET_STRING_free(a) ASN1_STRING_free((ASN1_STRING*)a)
#define M_ASN1_OCTET_STRING_cmp(a, b) \
ASN1_STRING_cmp((const ASN1_STRING*)a, (const ASN1_STRING*)b)
#define M_ASN1_OCTET_STRING_dup(a) \
(ASN1_OCTET_STRING*)ASN1_STRING_dup((const ASN1_STRING*)a)
#define M_ASN1_OCTET_STRING_set(a, b, c) ASN1_STRING_set((ASN1_STRING*)a, b, c)
#define M_ASN1_STRING_length(x) ((x)->length)
#define M_ASN1_STRING_data(x) ((x)->data)
#endif
#define d2i_ASN1_SET_OF_SignerInfo(st, pp, length, d2i_func, free_func, \
ex_tag, ex_class) \
SKM_ASN1_SET_OF_d2i(SignerInfo, (st), (pp), (length), (d2i_func), \
(free_func), (ex_tag), (ex_class))
#define i2d_ASN1_SET_OF_SignerInfo(st, pp, i2d_func, ex_tag, ex_class, is_set) \
SKM_ASN1_SET_OF_i2d(SignerInfo, (st), (pp), (i2d_func), (ex_tag), \
(ex_class), (is_set))
#define ASN1_seq_pack_SignerInfo(st, i2d_func, buf, len) \
SKM_ASN1_seq_pack(SignerInfo, (st), (i2d_func), (buf), (len))
#define ASN1_seq_unpack_SignerInfo(buf, len, d2i_func, free_func) \
SKM_ASN1_seq_unpack(SignerInfo, (buf), (len), (d2i_func), (free_func))
#define d2i_ASN1_SET_OF_RecipientInfo(st, pp, length, d2i_func, free_func, \
ex_tag, ex_class) \
SKM_ASN1_SET_OF_d2i(RecipientInfo, (st), (pp), (length), (d2i_func), \
(free_func), (ex_tag), (ex_class))
#define i2d_ASN1_SET_OF_RecipientInfo(st, pp, i2d_func, ex_tag, ex_class, \
is_set) \
SKM_ASN1_SET_OF_i2d(RecipientInfo, (st), (pp), (i2d_func), (ex_tag), \
(ex_class), (is_set))
#define ASN1_seq_pack_RecipientInfo(st, i2d_func, buf, len) \
SKM_ASN1_seq_pack(RecipientInfo, (st), (i2d_func), (buf), (len))
#define ASN1_seq_unpack_RecipientInfo(buf, len, d2i_func, free_func) \
SKM_ASN1_seq_unpack(RecipientInfo, (buf), (len), (d2i_func), (free_func))
/* End of util/mkstack.pl block */
/* X509 Public/Private Key Pair Structure */
struct X509_Keypair {
ASN1_OCTET_STRING* keyid;
EVP_PKEY* pubkey;
EVP_PKEY* privkey;
};
/* Message Digest Structure */
struct Digest {
JobControlRecord* jcr;
crypto_digest_t type;
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
/* Openssl Version < 1.1 */
private:
EVP_MD_CTX ctx;
public:
Digest(JobControlRecord* jcr, crypto_digest_t type) : jcr(jcr), type(type)
{
EVP_MD_CTX_init(&ctx);
}
~Digest() { EVP_MD_CTX_cleanup(&ctx); }
EVP_MD_CTX& get_ctx() { return ctx; }
#else
/* Openssl Version >= 1.1 */
private:
EVP_MD_CTX* ctx;
public:
EVP_MD_CTX& get_ctx() { return *ctx; }
Digest(JobControlRecord* jcr, crypto_digest_t type) : jcr(jcr), type(type)
{
ctx = EVP_MD_CTX_new();
EVP_MD_CTX_init(ctx);
}
~Digest()
{
EVP_MD_CTX_free(ctx);
ctx = NULL;
}
#endif
};
/* Message Signature Structure */
struct Signature {
SignatureData* sigData;
JobControlRecord* jcr;
};
/* Encryption Session Data */
struct Crypto_Session {
CryptoData* cryptoData; /* ASN.1 Structure */
unsigned char* session_key; /* Private symmetric session key */
size_t session_key_len; /* Symmetric session key length */
};
/* Symmetric Cipher Context */
struct Cipher_Context {
EVP_CIPHER_CTX* ctx;
Cipher_Context() { ctx = EVP_CIPHER_CTX_new(); }
~Cipher_Context() { EVP_CIPHER_CTX_free(ctx); }
};
/* PEM Password Dispatch Context */
typedef struct PEM_CB_Context {
CRYPTO_PEM_PASSWD_CB* pem_callback;
const void* pem_userdata;
} PEM_CB_CONTEXT;
/*
* Extract subjectKeyIdentifier from x509 certificate.
* Returns: On success, an ASN1_OCTET_STRING that must be freed via
* M_ASN1_OCTET_STRING_free(). NULL on failure.
*/
static ASN1_OCTET_STRING* openssl_cert_keyid(X509* cert)
{
X509_EXTENSION* ext = NULL;
const X509V3_EXT_METHOD* method;
ASN1_OCTET_STRING* keyid;
int i;
#if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
const unsigned char* ext_value_data;
#else
unsigned char* ext_value_data;
#endif
/* Find the index to the subjectKeyIdentifier extension */
i = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
if (i < 0) {
/* Not found */
return NULL;
}
/* Grab the extension */
ext = X509_get_ext(cert, i);
/* Get x509 extension method structure */
if (!(method = X509V3_EXT_get(ext))) { return NULL; }
ext_value_data = X509_EXTENSION_get_data(ext)->data;
#if (OPENSSL_VERSION_NUMBER > 0x00907000L)
if (method->it) {
/* New style ASN1 */
/* Decode ASN1 item in data */
keyid = (ASN1_OCTET_STRING*)ASN1_item_d2i(
NULL, &ext_value_data, X509_EXTENSION_get_data(ext)->length,
ASN1_ITEM_ptr(method->it));
} else {
/* Old style ASN1 */
/* Decode ASN1 item in data */
keyid = (ASN1_OCTET_STRING*)method->d2i(
NULL, &ext_value_data, X509_EXTENSION_get_data(ext)->length);
}
#else
keyid = (ASN1_OCTET_STRING*)method->d2i(NULL, &ext_value_data,
X509_EXTENSION_get_data(ext)->length);
#endif
return keyid;
}
/*
* Create a new keypair object.
* Returns: A pointer to a X509 KEYPAIR object on success.
* NULL on failure.
*/
X509_KEYPAIR* crypto_keypair_new(void)
{
X509_KEYPAIR* keypair;
/* Allocate our keypair structure */
keypair = (X509_KEYPAIR*)malloc(sizeof(X509_KEYPAIR));
/* Initialize our keypair structure */
keypair->keyid = NULL;
keypair->pubkey = NULL;
keypair->privkey = NULL;
return keypair;
}
/*
* Create a copy of a keypair object. The underlying
* EVP objects are not duplicated, as no EVP_PKEY_dup()
* API is available. Instead, the reference count is
* incremented.
*/
X509_KEYPAIR* crypto_keypair_dup(X509_KEYPAIR* keypair)
{
X509_KEYPAIR* newpair;
newpair = crypto_keypair_new();
if (!newpair) {
/* Allocation failed */
return NULL;
}
/* Increment the public key ref count */
if (keypair->pubkey) {
EVP_PKEY_up_ref(keypair->pubkey);
newpair->pubkey = keypair->pubkey;
}
/* Increment the private key ref count */
if (keypair->privkey) {
EVP_PKEY_up_ref(keypair->privkey);
newpair->privkey = keypair->privkey;
}
/* Duplicate the keyid */
if (keypair->keyid) {
newpair->keyid = M_ASN1_OCTET_STRING_dup(keypair->keyid);
if (!newpair->keyid) {
/* Allocation failed */
CryptoKeypairFree(newpair);
return NULL;
}
}
return newpair;
}
/*
* Load a public key from a PEM-encoded x509 certificate.
* Returns: true on success
* false on failure
*/
int CryptoKeypairLoadCert(X509_KEYPAIR* keypair, const char* file)
{
BIO* bio;
X509* cert;
/* Open the file */
if (!(bio = BIO_new_file(file, "r"))) {
OpensslPostErrors(M_ERROR, _("Unable to open certificate file"));
return false;
}
cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
BIO_free(bio);
if (!cert) {
OpensslPostErrors(M_ERROR, _("Unable to read certificate from file"));
return false;
}
/* Extract the public key */
if (!(keypair->pubkey = X509_get_pubkey(cert))) {
OpensslPostErrors(M_ERROR,
_("Unable to extract public key from certificate"));
goto err;
}
/* Extract the subjectKeyIdentifier extension field */
if ((keypair->keyid = openssl_cert_keyid(cert)) == NULL) {
Jmsg0(NULL, M_ERROR, 0,
_("Provided certificate does not include the required "
"subjectKeyIdentifier extension."));
goto err;
}
/* Validate the public key type (only RSA is supported) */
if (EVP_PKEY_type(EVP_PKEY_id(keypair->pubkey)) != EVP_PKEY_RSA) {
Jmsg1(NULL, M_ERROR, 0, _("Unsupported key type provided: %d\n"),
EVP_PKEY_type(EVP_PKEY_id(keypair->pubkey)));
goto err;
}
X509_free(cert);
return true;
err:
X509_free(cert);
if (keypair->pubkey) { EVP_PKEY_free(keypair->pubkey); }
return false;
}
/* Dispatch user PEM encryption callbacks */
static int CryptoPemCallbackDispatch(char* buf,
int size,
int rwflag,
void* userdata)
{
PEM_CB_CONTEXT* ctx = (PEM_CB_CONTEXT*)userdata;
return (ctx->pem_callback(buf, size, ctx->pem_userdata));
}
/*
* Check a PEM-encoded file
* for the existence of a private key.
* Returns: true if a private key is found
* false otherwise
*/
bool CryptoKeypairHasKey(const char* file)
{
BIO* bio;
char* name = NULL;
char* header = NULL;
unsigned char* data = NULL;
bool retval = false;
long len;
if (!(bio = BIO_new_file(file, "r"))) {
OpensslPostErrors(M_ERROR, _("Unable to open private key file"));
return false;
}
while (PEM_read_bio(bio, &name, &header, &data, &len)) {
/* We don't care what the data is, just that it's there */
OPENSSL_free(header);
OPENSSL_free(data);
/*
* PEM Header Found, check for a private key
* Due to OpenSSL limitations, we must specifically
* list supported PEM private key encodings.
*/
if (bstrcmp(name, PEM_STRING_RSA) || bstrcmp(name, PEM_STRING_DSA) ||
bstrcmp(name, PEM_STRING_PKCS8) || bstrcmp(name, PEM_STRING_PKCS8INF)) {
retval = true;
OPENSSL_free(name);
break;
} else {
OPENSSL_free(name);
}
}
/* Free our bio */
BIO_free(bio);
/* Post PEM-decoding error messages, if any */
OpensslPostErrors(M_ERROR, _("Unable to read private key from file"));
return retval;
}
/*
* Load a PEM-encoded private key.
* Returns: true on success
* false on failure
*/
int CryptoKeypairLoadKey(X509_KEYPAIR* keypair,
const char* file,
CRYPTO_PEM_PASSWD_CB* pem_callback,
const void* pem_userdata)
{
BIO* bio;
PEM_CB_CONTEXT ctx;
/* Open the file */
if (!(bio = BIO_new_file(file, "r"))) {
OpensslPostErrors(M_ERROR, _("Unable to open private key file"));
return false;
}
/* Set up PEM encryption callback */
if (pem_callback) {
ctx.pem_callback = pem_callback;
ctx.pem_userdata = pem_userdata;
} else {
ctx.pem_callback = CryptoDefaultPemCallback;
ctx.pem_userdata = NULL;
}
keypair->privkey =
PEM_read_bio_PrivateKey(bio, NULL, CryptoPemCallbackDispatch, &ctx);
BIO_free(bio);
if (!keypair->privkey) {
OpensslPostErrors(M_ERROR, _("Unable to read private key from file"));
return false;
}
return true;
}
/*
* Free memory associated with a keypair object.
*/
void CryptoKeypairFree(X509_KEYPAIR* keypair)
{
if (keypair->pubkey) { EVP_PKEY_free(keypair->pubkey); }
if (keypair->privkey) { EVP_PKEY_free(keypair->privkey); }
if (keypair->keyid) { M_ASN1_OCTET_STRING_free(keypair->keyid); }
free(keypair);
}
/*
* Create a new message digest context of the specified type
* Returns: A pointer to a DIGEST object on success.
* NULL on failure.
*/
DIGEST* crypto_digest_new(JobControlRecord* jcr, crypto_digest_t type)
{
DIGEST* digest = new DIGEST(jcr, type);
const EVP_MD* md = NULL; /* Quell invalid uninitialized warnings */
Dmsg1(150, "crypto_digest_new jcr=%p\n", jcr);
/* Determine the correct OpenSSL message digest type */
switch (type) {
case CRYPTO_DIGEST_MD5:
md = EVP_md5();
break;
case CRYPTO_DIGEST_SHA1:
md = EVP_sha1();
break;
#ifdef HAVE_SHA2
case CRYPTO_DIGEST_SHA256:
md = EVP_sha256();
break;
case CRYPTO_DIGEST_SHA512:
md = EVP_sha512();
break;
#endif
default:
Jmsg1(jcr, M_ERROR, 0, _("Unsupported digest type: %d\n"), type);
goto err;
}
/* Initialize the backing OpenSSL context */
if (EVP_DigestInit_ex(&digest->get_ctx(), md, NULL) == 0) { goto err; }
return digest;
err:
/* This should not happen, but never say never ... */
Dmsg0(150, "Digest init failed.\n");
OpensslPostErrors(jcr, M_ERROR, _("OpenSSL digest initialization failed"));
CryptoDigestFree(digest);
return NULL;
}
/*
* Hash length bytes of data into the provided digest context.
* Returns: true on success
* false on failure
*/
bool CryptoDigestUpdate(DIGEST* digest, const uint8_t* data, uint32_t length)
{
if (EVP_DigestUpdate(&digest->get_ctx(), data, length) == 0) {
Dmsg0(150, "digest update failed\n");
OpensslPostErrors(digest->jcr, M_ERROR, _("OpenSSL digest update failed"));
return false;
} else {
return true;
}
}
/*
* Finalize the data in digest, storing the result in dest and the result size
* in length. The result size can be determined with crypto_digest_size().
*
* Returns: true on success
* false on failure
*/
bool CryptoDigestFinalize(DIGEST* digest, uint8_t* dest, uint32_t* length)
{
if (!EVP_DigestFinal(&digest->get_ctx(), dest, (unsigned int*)length)) {
Dmsg0(150, "digest finalize failed\n");
OpensslPostErrors(digest->jcr, M_ERROR,
_("OpenSSL digest finalize failed"));
return false;
} else {
return true;
}
}
/*
* Free memory associated with a digest object.
*/
void CryptoDigestFree(DIGEST* digest) { delete digest; }
/*
* Create a new message signature context.
* Returns: A pointer to a SIGNATURE object on success.
* NULL on failure.
*/
SIGNATURE* crypto_sign_new(JobControlRecord* jcr)
{
SIGNATURE* sig;
sig = (SIGNATURE*)malloc(sizeof(SIGNATURE));
if (!sig) { return NULL; }
sig->sigData = SignatureData_new();
sig->jcr = jcr;
Dmsg1(150, "crypto_sign_new jcr=%p\n", jcr);
if (!sig->sigData) {
/* Allocation failed in OpenSSL */
free(sig);
return NULL;
}
/* Set the ASN.1 structure version number */
ASN1_INTEGER_set(sig->sigData->version, BAREOS_ASN1_VERSION);
return sig;
}
/*
* For a given public key, find the associated SignatureInfo record
* and create a digest context for signature validation
*
* Returns: CRYPTO_ERROR_NONE on success, with the newly allocated DIGEST in
* digest. A crypto_error_t value on failure.
*/
crypto_error_t CryptoSignGetDigest(SIGNATURE* sig,
X509_KEYPAIR* keypair,
crypto_digest_t& type,
DIGEST** digest)
{
STACK_OF(SignerInfo) * signers;
SignerInfo* si;
int i;
signers = sig->sigData->signerInfo;
for (i = 0; i < sk_SignerInfo_num(signers); i++) {
si = sk_SignerInfo_value(signers, i);
if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) ==
0) {
/* Get the digest algorithm and allocate a digest context */
Dmsg1(150, "CryptoSignGetDigest jcr=%p\n", sig->jcr);
switch (OBJ_obj2nid(si->digestAlgorithm)) {
case NID_md5:
Dmsg0(100, "sign digest algorithm is MD5\n");
type = CRYPTO_DIGEST_MD5;
*digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_MD5);
break;
case NID_sha1:
Dmsg0(100, "sign digest algorithm is SHA1\n");
type = CRYPTO_DIGEST_SHA1;
*digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA1);
break;
#ifdef HAVE_SHA2
case NID_sha256:
Dmsg0(100, "sign digest algorithm is SHA256\n");
type = CRYPTO_DIGEST_SHA256;
*digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA256);
break;
case NID_sha512:
Dmsg0(100, "sign digest algorithm is SHA512\n");
type = CRYPTO_DIGEST_SHA512;
*digest = crypto_digest_new(sig->jcr, CRYPTO_DIGEST_SHA512);
break;
#endif
default:
type = CRYPTO_DIGEST_NONE;
*digest = NULL;
return CRYPTO_ERROR_INVALID_DIGEST;
}
/* Shouldn't happen */
if (*digest == NULL) {
OpensslPostErrors(sig->jcr, M_ERROR, _("OpenSSL digest_new failed"));
return CRYPTO_ERROR_INVALID_DIGEST;
} else {
return CRYPTO_ERROR_NONE;
}
} else {
OpensslPostErrors(sig->jcr, M_ERROR, _("OpenSSL sign get digest failed"));
}
}
return CRYPTO_ERROR_NOSIGNER;
}
/*
* For a given signature, public key, and digest, verify the SIGNATURE.
* Returns: CRYPTO_ERROR_NONE on success.
* A crypto_error_t value on failure.
*/
crypto_error_t CryptoSignVerify(SIGNATURE* sig,
X509_KEYPAIR* keypair,
DIGEST* digest)
{
STACK_OF(SignerInfo) * signers;
SignerInfo* si;
int ok, i;
unsigned int sigLen;
#if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
const unsigned char* sigData;
#else
unsigned char* sigData;
#endif
signers = sig->sigData->signerInfo;
/* Find the signer */
for (i = 0; i < sk_SignerInfo_num(signers); i++) {
si = sk_SignerInfo_value(signers, i);
if (M_ASN1_OCTET_STRING_cmp(keypair->keyid, si->subjectKeyIdentifier) ==
0) {
/* Extract the signature data */
sigLen = M_ASN1_STRING_length(si->signature);
sigData = M_ASN1_STRING_data(si->signature);
ok =
EVP_VerifyFinal(&digest->get_ctx(), sigData, sigLen, keypair->pubkey);
if (ok >= 1) {
return CRYPTO_ERROR_NONE;
} else if (ok == 0) {
OpensslPostErrors(sig->jcr, M_ERROR,
_("OpenSSL digest Verify final failed"));
return CRYPTO_ERROR_BAD_SIGNATURE;
} else if (ok < 0) {
/* Shouldn't happen */
OpensslPostErrors(sig->jcr, M_ERROR,
_("OpenSSL digest Verify final failed"));
return CRYPTO_ERROR_INTERNAL;
}
}
}
Jmsg(sig->jcr, M_ERROR, 0, _("No signers found for crypto verify.\n"));
/* Signer wasn't found. */
return CRYPTO_ERROR_NOSIGNER;
}
/*
* Add a new signer
* Returns: true on success
* false on failure
*/
int CryptoSignAddSigner(SIGNATURE* sig, DIGEST* digest, X509_KEYPAIR* keypair)
{
SignerInfo* si = NULL;
unsigned char* buf = NULL;
unsigned int len;
si = SignerInfo_new();
if (!si) {
/* Allocation failed in OpenSSL */
return false;
}
/* Set the ASN.1 structure version number */
ASN1_INTEGER_set(si->version, BAREOS_ASN1_VERSION);
/* Set the digest algorithm identifier */
switch (digest->type) {
case CRYPTO_DIGEST_MD5:
si->digestAlgorithm = OBJ_nid2obj(NID_md5);
break;
case CRYPTO_DIGEST_SHA1:
si->digestAlgorithm = OBJ_nid2obj(NID_sha1);
break;
#ifdef HAVE_SHA2
case CRYPTO_DIGEST_SHA256:
si->digestAlgorithm = OBJ_nid2obj(NID_sha256);
break;
case CRYPTO_DIGEST_SHA512:
si->digestAlgorithm = OBJ_nid2obj(NID_sha512);
break;
#endif
default:
/* This should never happen */
goto err;
}
/* Drop the string allocated by OpenSSL, and add our subjectKeyIdentifier */
M_ASN1_OCTET_STRING_free(si->subjectKeyIdentifier);
si->subjectKeyIdentifier = M_ASN1_OCTET_STRING_dup(keypair->keyid);
/* Set our signature algorithm. We currently require RSA */
assert(EVP_PKEY_type(EVP_PKEY_id(keypair->pubkey)) == EVP_PKEY_RSA);
/* This is slightly evil. Reach into the BAREOS_LIB_MD_H_ structure and grab
* the key type */
si->signatureAlgorithm = OBJ_nid2obj(EVP_MD_CTX_type(&digest->get_ctx()));
/* Finalize/Sign our Digest */
len = EVP_PKEY_size(keypair->privkey);
buf = (unsigned char*)malloc(len);
if (!EVP_SignFinal(&digest->get_ctx(), buf, &len, keypair->privkey)) {
OpensslPostErrors(M_ERROR, _("Signature creation failed"));
goto err;
}
/* Add the signature to the SignerInfo structure */
if (!M_ASN1_OCTET_STRING_set(si->signature, buf, len)) {
/* Allocation failed in OpenSSL */
goto err;
}
/* No longer needed */
free(buf);
/* Push the new SignerInfo structure onto the stack */
sk_SignerInfo_push(sig->sigData->signerInfo, si);
return true;
err:
if (si) { SignerInfo_free(si); }
if (buf) { free(buf); }
return false;
}
/*
* Encodes the SignatureData structure. The length argument is used to specify
* the size of dest. A length of 0 will cause no data to be written to dest, and
* the required length to be written to length. The caller can then allocate
* sufficient space for the output.
*
* Returns: true on success, stores the encoded data in dest, and the size in
* length. false on failure.
*/
int CryptoSignEncode(SIGNATURE* sig, uint8_t* dest, uint32_t* length)
{
if (*length == 0) {
*length = i2d_SignatureData(sig->sigData, NULL);
return true;
}
*length = i2d_SignatureData(sig->sigData, (unsigned char**)&dest);
return true;
}
/*
* Decodes the SignatureData structure. The length argument is used to specify
the
* size of sigData.
*
* Returns: SIGNATURE instance on success.
* NULL on failure.
*/
SIGNATURE* crypto_sign_decode(JobControlRecord* jcr,
const uint8_t* sigData,
uint32_t length)
{
SIGNATURE* sig;
#if (OPENSSL_VERSION_NUMBER >= 0x0090800FL)
const unsigned char* p = (const unsigned char*)sigData;
#else
unsigned char* p = (unsigned char*)sigData;
#endif
sig = (SIGNATURE*)malloc(sizeof(SIGNATURE));
if (!sig) { return NULL; }
sig->jcr = jcr;
/* d2i_SignatureData modifies the supplied pointer */
sig->sigData = d2i_SignatureData(NULL, &p, length);
if (!sig->sigData) {
/* Allocation / Decoding failed in OpenSSL */
OpensslPostErrors(jcr, M_ERROR, _("Signature decoding failed"));
free(sig);
return NULL;
}
return sig;
}
/*
* Free memory associated with a signature object.
*/