-
Notifications
You must be signed in to change notification settings - Fork 58
/
crypto.c
2104 lines (1750 loc) · 54.6 KB
/
crypto.c
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
/*
* General cryptography helper functions
*
* Copyright IBM Corp. 2020
*
* s390-tools is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <glib.h>
#include <glib/gtypes.h>
#include <limits.h>
#include <openssl/aes.h>
#include <openssl/bn.h>
#include <openssl/ec.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/x509_vfy.h>
#include <openssl/err.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "boot/page.h"
#include "common.h"
#include "include/pv_crypto_def.h"
#include "pv/pv_error.h"
#include "buffer.h"
#include "curl.h"
#include "openssl_compat.h"
#include "crypto.h"
#define DEFINE_GSLIST_MAP(t2, t1) \
typedef t1 *(*g_slist_map_func_##t2##_##t1)(const t2 *x, \
GError **err); \
G_GNUC_UNUSED static GSList *g_slist_map_##t2##_##t1(const GSList *list, \
g_slist_map_func_##t2##_##t1 func, \
GError **err) \
{ \
g_autoslist(t1) ret = NULL; \
for (const GSList *iterator = list; iterator; \
iterator = iterator->next) { \
const t2 *value = iterator->data; \
t1 *new_value = NULL; \
g_assert(value); \
new_value = func(value, err); \
if (!new_value) \
return NULL; \
ret = g_slist_append(ret, g_steal_pointer(&new_value)); \
} \
return g_steal_pointer(&ret); \
}
#define DEFINE_GSLIST_TO_STACK(t1) \
G_GNUC_UNUSED static STACK_OF(t1) *g_slist_to_stack_of_##t1(GSList **list) \
{ \
g_assert(list); \
g_autoptr(STACK_OF_##t1) ret = sk_##t1##_new_null(); \
if (!ret) \
g_abort(); \
for (GSList *iterator = *list; iterator; \
iterator = iterator->next) { \
if (sk_##t1##_push(ret, g_steal_pointer(&iterator->data)) == 0) \
g_abort(); \
} \
g_clear_pointer(list, g_slist_free); \
return g_steal_pointer(&ret); \
}
DEFINE_GSLIST_MAP(x509_with_path, X509)
DEFINE_GSLIST_TO_STACK(X509)
EVP_MD_CTX *digest_ctx_new(const EVP_MD *md, GError **err)
{
g_autoptr(EVP_MD_CTX) ctx = EVP_MD_CTX_new();
if (!ctx)
g_abort();
if (EVP_DigestInit_ex(ctx, md, NULL) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("EVP_DigestInit_ex failed"));
return NULL;
}
return g_steal_pointer(&ctx);
}
PvBuffer *digest_ctx_finalize(EVP_MD_CTX *ctx, GError **err)
{
gint md_size = EVP_MD_size(EVP_MD_CTX_md(ctx));
g_autoptr(PvBuffer) ret = NULL;
guint digest_size;
g_assert(md_size > 0);
ret = pv_buffer_alloc((guint)md_size);
if (EVP_DigestFinal_ex(ctx, ret->data, &digest_size) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("EVP_DigestFinal_ex failed"));
return NULL;
}
g_assert(digest_size == (guint)md_size);
g_assert(digest_size == ret->size);
return g_steal_pointer(&ret);
}
/* Returns the digest of @buf using the hash algorithm @md */
static PvBuffer *digest_buffer(const EVP_MD *md, const PvBuffer *buf, GError **err)
{
g_autoptr(EVP_MD_CTX) md_ctx = NULL;
g_autoptr(PvBuffer) ret = NULL;
g_assert(buf);
md_ctx = digest_ctx_new(md, err);
if (!md_ctx)
return NULL;
if (EVP_DigestUpdate(md_ctx, buf->data, buf->size) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("EVP_DigestUpdate failed"));
return NULL;
}
ret = digest_ctx_finalize(md_ctx, err);
if (!ret)
return NULL;
return g_steal_pointer(&ret);
}
/* Returns the SHA256 digest of @buf */
PvBuffer *sha256_buffer(const PvBuffer *buf, GError **err)
{
g_autoptr(PvBuffer) ret = NULL;
ret = digest_buffer(EVP_sha256(), buf, err);
if (!ret)
return NULL;
g_assert(ret->size == SHA256_DIGEST_LENGTH);
return g_steal_pointer(&ret);
}
/* Convert a EVP_PKEY to the key format used in the PV header */
union ecdh_pub_key *evp_pkey_to_ecdh_pub_key(EVP_PKEY *key, GError **err)
{
g_autofree union ecdh_pub_key *ret = g_new0(union ecdh_pub_key, 1);
g_autoptr(BIGNUM) pub_x_big = NULL;
g_autoptr(BIGNUM) pub_y_big = NULL;
g_autoptr(EC_KEY) ec_key = NULL;
const EC_POINT *pub_key;
const EC_GROUP *grp;
ec_key = EVP_PKEY_get1_EC_KEY(key);
if (!ec_key) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("Key has the wrong type"));
return NULL;
}
pub_key = EC_KEY_get0_public_key(ec_key);
if (!pub_key) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("Failed to get public key"));
return NULL;
}
grp = EC_KEY_get0_group(ec_key);
if (!grp) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("Failed to get EC group"));
return NULL;
}
pub_x_big = BN_new();
if (!pub_x_big)
g_abort();
pub_y_big = BN_new();
if (!pub_y_big)
g_abort();
if (EC_POINT_get_affine_coordinates_GFp(grp, pub_key, pub_x_big,
pub_y_big, NULL) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("Cannot convert key to internal format"));
return NULL;
}
if (BN_bn2binpad(pub_x_big, ret->x, sizeof(ret->x)) < 0) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("Cannot convert key to internal format"));
return NULL;
}
if (BN_bn2binpad(pub_y_big, ret->y, sizeof(ret->y)) < 0) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("Cannot convert key to internal format"));
return NULL;
}
return g_steal_pointer(&ret);
}
static PvBuffer *derive_key(EVP_PKEY *cust, EVP_PKEY *host, GError **err)
{
g_autoptr(EVP_PKEY_CTX) ctx = NULL;
g_autoptr(PvBuffer) ret = NULL;
gsize key_size;
ctx = EVP_PKEY_CTX_new(cust, NULL);
if (!ctx)
g_abort();
if (EVP_PKEY_derive_init(ctx) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("Key derivation failed"));
return NULL;
}
if (EVP_PKEY_derive_set_peer(ctx, host) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("Key derivation failed"));
return NULL;
}
/* Determine buffer length */
if (EVP_PKEY_derive(ctx, NULL, &key_size) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_DERIVE,
_("Key derivation failed"));
return NULL;
}
ret = pv_buffer_alloc(key_size);
if (EVP_PKEY_derive(ctx, ret->data, &key_size) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_DERIVE,
_("Key derivation failed"));
return NULL;
}
g_assert(ret->size == key_size);
return g_steal_pointer(&ret);
}
PvBuffer *compute_exchange_key(EVP_PKEY *cust, EVP_PKEY *host, GError **err)
{
g_autoptr(PvBuffer) raw = pv_buffer_alloc(70);
g_autoptr(PvBuffer) ret = NULL;
g_autoptr(PvBuffer) key = NULL;
guchar *data;
key = derive_key(cust, host, err);
if (!key)
return NULL;
g_assert(key->size == 66);
g_assert(key->size < raw->size);
/* ANSI X.9.63-2011: 66 bytes x with leading 7 bits and
* concatenate 32 bit int '1'
*/
memcpy(raw->data, key->data, key->size);
data = raw->data;
data[66] = 0x00;
data[67] = 0x00;
data[68] = 0x00;
data[69] = 0x01;
ret = sha256_buffer(raw, err);
if (!ret)
return NULL;
return g_steal_pointer(&ret);
}
gint generate_tweak(union tweak *tweak, uint16_t i, GError **err)
{
tweak->cmp_idx.idx = GUINT16_TO_BE(i);
if (RAND_bytes(tweak->cmp_idx.rand, sizeof(tweak->cmp_idx.rand)) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_RANDOMIZATION,
_("Generating a tweak failed because the required amount of random data is not available"));
return -1;
}
return 0;
}
static PvBuffer *generate_rand_data(guint size, const gchar *err_msg,
GError **err)
{
g_autoptr(PvBuffer) buf = pv_buffer_alloc(size);
g_assert(size <= INT_MAX);
if (RAND_bytes(buf->data, (int)size) != 1) {
g_set_error_literal(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_RANDOMIZATION,
err_msg);
return NULL;
}
return g_steal_pointer(&buf);
}
PvBuffer *generate_aes_iv(guint size, GError **err)
{
return generate_rand_data(size,
_("Generating a IV failed because the required amount of random data is not available"),
err);
}
PvBuffer *generate_aes_key(guint size, GError **err)
{
return generate_rand_data(size,
_("Generating a key failed because the required amount of random data is not available"),
err);
}
EVP_PKEY *generate_ec_key(gint nid, GError **err)
{
g_autoptr(EVP_PKEY_CTX) ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
g_autoptr(EVP_PKEY) ret = NULL;
if (!ctx)
g_abort();
if (EVP_PKEY_keygen_init(ctx) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_KEYGENERATION,
_("EC key could not be auto-generated"));
return NULL;
}
if (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_KEYGENERATION,
_("EC key could not be auto-generated"));
return NULL;
}
if (EVP_PKEY_keygen(ctx, &ret) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_KEYGENERATION,
_("EC key could not be auto-generated"));
return NULL;
}
return g_steal_pointer(&ret);
}
static gboolean certificate_uses_correct_curve(EVP_PKEY *key, gint nid,
GError **err)
{
g_autoptr(EC_KEY) ec = NULL;
gint rc;
g_assert(key);
if (EVP_PKEY_id(key) != EVP_PKEY_EC) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INVALID_PARM,
_("No EC key found"));
return FALSE;
}
ec = EVP_PKEY_get1_EC_KEY(key);
if (!ec) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INVALID_PARM,
_("No EC key found"));
return FALSE;
}
if (EC_KEY_check_key(ec) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INVALID_PARM,
_("Invalid EC key"));
return FALSE;
}
rc = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
if (rc != nid) {
/* maybe the NID is unset */
if (rc == 0) {
g_autoptr(EC_GROUP) grp = EC_GROUP_new_by_curve_name(nid);
const EC_POINT *pub = EC_KEY_get0_public_key(ec);
g_autoptr(BN_CTX) ctx = BN_CTX_new();
if (EC_POINT_is_on_curve(grp, pub, ctx) != 1) {
g_set_error_literal(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_INVALID_PARM,
_("Invalid EC curve"));
return FALSE;
}
} else {
/* NID was set but doesn't match with the expected NID
*/
g_set_error(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_INVALID_PARM,
_("Wrong NID used: '%d'"),
EC_GROUP_get_curve_name(EC_KEY_get0_group(ec)));
return FALSE;
}
}
return TRUE;
}
/* Verify that the used public key algorithm matches the subject signature
* algorithm
*/
static int check_signature_algo_match(const EVP_PKEY *pkey, const X509 *subject,
GError **err)
{
gint pkey_nid;
if (!pkey) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_NO_PUBLIC_KEY,
_("no public key"));
return -1;
}
if (OBJ_find_sigid_algs(X509_get_signature_nid(subject), NULL,
&pkey_nid) != 1) {
g_set_error(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_INVALID_SIGNATURE_ALGORITHM,
_("unsupported signature algorithm"));
return -1;
}
if (EVP_PKEY_type(pkey_nid) != EVP_PKEY_base_id(pkey)) {
g_set_error(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_SIGNATURE_ALGORITHM_MISMATCH,
_("signature algorithm mismatch"));
return -1;
}
return 0;
}
static X509_CRL *load_crl_from_bio(BIO *bio)
{
g_autoptr(X509_CRL) crl = PEM_read_bio_X509_CRL(bio, NULL, NULL, NULL);
gint rc;
if (crl)
return g_steal_pointer(&crl);
ERR_clear_error();
rc = BIO_reset(bio);
if (rc != 1 && !(rc == 0 && BIO_method_type(bio) == BIO_TYPE_FILE))
return NULL;
/* maybe the CRL is stored in DER format */
crl = d2i_X509_CRL_bio(bio, NULL);
if (crl)
return g_steal_pointer(&crl);
return NULL;
}
static X509_CRL *GByteArray_to_X509_CRL(const GByteArray *data)
{
g_autoptr(X509_CRL) ret = NULL;
g_autoptr(BIO) bio = NULL;
g_assert(data);
if (data->len > INT_MAX)
return NULL;
bio = BIO_new_mem_buf(data->data, (int)data->len);
if (!bio)
g_abort();
ret = load_crl_from_bio(bio);
if (!ret)
return NULL;
return g_steal_pointer(&ret);
}
static gint load_crl_from_web(const gchar *url, X509_CRL **crl, GError **err)
{
g_autoptr(X509_CRL) tmp_crl = NULL;
g_autoptr(GByteArray) data = NULL;
g_assert(crl);
data = curl_download(url, CRL_DOWNLOAD_TIMEOUT_MS,
CRL_DOWNLOAD_MAX_SIZE, err);
if (!data) {
g_prefix_error(err, _("unable to download CRL: "));
return -1;
}
tmp_crl = GByteArray_to_X509_CRL(data);
if (!tmp_crl) {
g_set_error(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_CRL_DOWNLOAD_FAILED,
_("unable to load CRL from '%s'"), url);
return -1;
}
*crl = g_steal_pointer(&tmp_crl);
return 0;
}
static BIO *bio_read_from_file(const char *path)
{
g_autoptr(BIO) bio = BIO_new_file(path, "r");
if (!bio)
return NULL;
return g_steal_pointer(&bio);
}
/* This function reads in only the first certificate and ignores all other. This
* is only relevant for the PEM file format. For the host-key document and the
* root CA this behavior is expected.
*/
X509 *load_cert_from_file(const char *path, GError **err)
{
g_autoptr(BIO) bio = bio_read_from_file(path);
g_autoptr(X509) cert = NULL;
gint rc;
if (!bio) {
g_set_error(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_READ_CERTIFICATE,
_("unable to read certificate: '%s'"), path);
return NULL;
}
cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
if (cert)
return g_steal_pointer(&cert);
ERR_clear_error();
rc = BIO_reset(bio);
if (rc != 1 && !(rc == 0 && BIO_method_type(bio) == BIO_TYPE_FILE)) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_READ_CERTIFICATE,
_("unable to load certificate: '%s'"), path);
return NULL;
}
/* maybe the certificate is stored in DER format */
cert = d2i_X509_bio(bio, NULL);
if (cert)
return g_steal_pointer(&cert);
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_READ_CERTIFICATE,
_("unable to load certificate: '%s'"), path);
return NULL;
}
/* @crl_paths is allowed to be NULL */
static int load_crls_to_store(X509_STORE *store, const gchar *const *crl_paths,
gboolean err_out_empty_crls, GError **err)
{
for (const gchar *const *iterator = crl_paths;
iterator != NULL && *iterator != NULL; iterator++) {
const gchar *crl_path = *iterator;
X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
int count;
g_assert(crl_path);
if (!lookup) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("X509 store initialization failed"));
return -1;
}
/* support *.pem files containing multiple CRLs */
count = X509_load_crl_file(lookup, crl_path, X509_FILETYPE_PEM);
if (count > 0)
continue;
count = X509_load_crl_file(lookup, crl_path, X509_FILETYPE_ASN1);
if (count == 1)
continue;
if (err_out_empty_crls) {
g_set_error(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_LOAD_CRL,
_("unable to load CRL from: '%s'"), crl_path);
return -1;
}
}
return 0;
}
/* returns
* 0 when the certificate is valid,
* -1 when not yet valid,
* 1 when expired
*/
static int check_validity_period(const ASN1_TIME *not_before, const ASN1_TIME *not_after)
{
if (X509_cmp_current_time(not_before) != -1)
return -1;
if (X509_cmp_current_time(not_after) != 1)
return 1;
return 0;
}
static gint x509_name_entry_get_data0(X509_NAME_ENTRY *entry, const guchar **data,
gsize *data_len)
{
const ASN1_STRING *asn1_str;
gint tmp_data_len;
g_assert(data);
g_assert(data_len);
asn1_str = X509_NAME_ENTRY_get_data(entry);
if (!asn1_str)
return -1;
tmp_data_len = ASN1_STRING_length(asn1_str);
if (tmp_data_len < 0)
return -1;
*data = ASN1_STRING_get0_data(asn1_str);
*data_len = (gsize)tmp_data_len;
return 0;
}
/* The caller must not free *data! */
static gint x509_name_get_data0_by_NID(X509_NAME *name, gint nid,
const guchar **data, gsize *data_len)
{
X509_NAME_ENTRY *entry = NULL;
gint lastpos = -1;
lastpos = X509_NAME_get_index_by_NID(name, nid, lastpos);
if (lastpos == -1)
return -1;
entry = X509_NAME_get_entry(name, lastpos);
if (!entry)
return -1;
if (x509_name_entry_get_data0(entry, data, data_len) < 0)
return -1;
return 0;
}
/* @y must be a NULL-terminated string */
static gboolean x509_name_data_by_nid_equal(X509_NAME *name, gint nid,
const gchar *y)
{
const guchar *data = NULL;
gsize y_len = strlen(y);
gsize data_len;
if (x509_name_get_data0_by_NID(name, nid, &data, &data_len) < 0)
return FALSE;
if (data_len != y_len)
return FALSE;
return memcmp(data, y, data_len) == 0;
}
/* Checks whether the subject of @cert is a IBM signing key subject. For this we
* must check that the subject is equal to: 'C = US, ST = New York, L =
* Poughkeepsie or Armonk, O = International Business Machines Corporation, CN =
* International Business Machines Corporation' and the organization unit (OUT)
* must end with the suffix ' Key Signing Service'.
*/
static gboolean has_ibm_signing_subject(X509 *cert)
{
X509_NAME *subject = X509_get_subject_name(cert);
/* X509_NAME_entry_count is safe to be used with NULL */
gint entry_count = X509_NAME_entry_count(subject);
g_autofree gchar *data_str = NULL;
const guchar *data;
gsize data_len;
if (entry_count != PV_IMB_Z_SUBJECT_ENTRY_COUNT)
return FALSE;
if (!x509_name_data_by_nid_equal(subject, NID_countryName,
PV_IBM_Z_SUBJECT_COUNTRY_NAME))
return FALSE;
if (!x509_name_data_by_nid_equal(subject, NID_stateOrProvinceName,
PV_IBM_Z_SUBJECT_STATE))
return FALSE;
if (!(x509_name_data_by_nid_equal(subject, NID_localityName,
PV_IBM_Z_SUBJECT_LOCALITY_NAME_POUGHKEEPSIE) ||
x509_name_data_by_nid_equal(subject, NID_localityName,
PV_IBM_Z_SUBJECT_LOCALITY_NAME_ARMONK)))
return FALSE;
if (!x509_name_data_by_nid_equal(subject, NID_organizationName,
PV_IBM_Z_SUBJECT_ORGANIZATION_NAME))
return FALSE;
if (!x509_name_data_by_nid_equal(subject, NID_commonName,
PV_IBM_Z_SUBJECT_COMMON_NAME))
return FALSE;
if (x509_name_get_data0_by_NID(subject, NID_organizationalUnitName,
&data, &data_len) < 0)
return FALSE;
/* Make sure that data_str is null-terminated as in general it cannot be
* assumed that @data is null-terminated.
*/
data_str = g_strndup((const gchar *)data, data_len);
if (!g_str_has_suffix(data_str,
PV_IBM_Z_SUBJECT_ORGANIZATIONONAL_UNIT_NAME_SUFFIX))
return FALSE;
return TRUE;
}
static X509_NAME *x509_name_reorder_attributes(const X509_NAME *name, const gint nids[],
gsize nids_len)
{
gint entry_count = X509_NAME_entry_count(name);
g_autoptr(X509_NAME) ret = NULL;
if (entry_count < 0)
return NULL;
if (nids_len != (gsize) entry_count)
return NULL;
ret = X509_NAME_new();
if (!ret)
g_abort();
for (gsize i = 0; i < nids_len; i++) {
const X509_NAME_ENTRY *entry = NULL;
gint nid = nids[i];
gint lastpos = -1;
lastpos = X509_NAME_get_index_by_NID((X509_NAME *)name, nid, lastpos);
if (lastpos == -1)
return NULL;
entry = X509_NAME_get_entry(name, lastpos);
if (!entry)
return NULL;
if (X509_NAME_add_entry(ret, entry, -1, 0) != 1)
return NULL;
}
return g_steal_pointer(&ret);
}
/** Replace locality 'Armonk' with 'Pougkeepsie'. If Armonk was not set return
* `NULL`.
*/
static X509_NAME *x509_armonk_locality_fixup(const X509_NAME *name)
{
g_autoptr(X509_NAME) ret = NULL;
int pos;
/* Check if ``L=Armonk`` */
if (!x509_name_data_by_nid_equal((X509_NAME *)name, NID_localityName,
PV_IBM_Z_SUBJECT_LOCALITY_NAME_ARMONK))
return NULL;
ret = X509_NAME_dup(name);
if (!ret)
g_abort();
pos = X509_NAME_get_index_by_NID(ret, NID_localityName, -1);
if (pos == -1)
return NULL;
X509_NAME_ENTRY_free(X509_NAME_delete_entry(ret, pos));
/* Create a new name entry at the same position as before */
if (X509_NAME_add_entry_by_NID(
ret, NID_localityName, MBSTRING_UTF8,
(const unsigned char *)&PV_IBM_Z_SUBJECT_LOCALITY_NAME_POUGHKEEPSIE,
sizeof(PV_IBM_Z_SUBJECT_LOCALITY_NAME_POUGHKEEPSIE) - 1, pos, 0) != 1)
return NULL;
return g_steal_pointer(&ret);
}
/* In RFC 5280 the attributes of a (subject/issuer) name is not mandatory
* ordered. The problem is that our certificates are not consistent in the order
* (see https://tools.ietf.org/html/rfc5280#section-4.1.2.4 for details).
*
* This function converts a correct X509_NAME into the broken one. The caller is
* responsible to free the returned value.
*/
X509_NAME *c2b_name(const X509_NAME *name)
{
gint nids[] = { NID_countryName, NID_organizationName, NID_organizationalUnitName,
NID_localityName, NID_stateOrProvinceName, NID_commonName };
g_autoptr(X509_NAME) broken_name = NULL;
g_assert(name);
/* Try to reorder the attributes */
broken_name = x509_name_reorder_attributes(name, nids, G_N_ELEMENTS(nids));
if (broken_name)
return g_steal_pointer(&broken_name);
return X509_NAME_dup((X509_NAME *)name);
}
/* Verify that SKID(issuer) == AKID(crl) if available */
static gint check_crl_issuer(X509_CRL *crl, X509 *issuer, GError **err)
{
g_autoptr(AUTHORITY_KEYID) akid = NULL;
/* If AKID(@crl) is specified it must match with SKID(@issuer) */
akid = X509_CRL_get_ext_d2i(crl, NID_authority_key_identifier, NULL, NULL);
if (akid && X509_check_akid(issuer, akid) != X509_V_OK) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_SKID_AKID_MISMATCH,
_("AKID mismatch"));
return -1;
}
return 0;
}
/* Verify whether a revocation list @crl is valid and is issued by @cert. For
* this multiple steps must be done:
*
* 1. verify issuer of the CRL matches with the suject name of @cert
* 2. verify the validity period of the CRL
* 3. verify the signature of the CRL
*
* Important: This function doesn't verify whether @cert is allowed to issue a
* CRL. Returns 0 if @crl is valid and issued by @cert, otherwise -1.
*/
gint check_crl_valid_for_cert(X509_CRL *crl, X509 *cert,
gint verify_flags, GError **err)
{
EVP_PKEY *pkey = X509_get0_pubkey(cert);
g_assert(crl);
if (!pkey) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_INTERNAL,
_("failed to retrieve public key from the certificate"));
return -1;
}
if (check_crl_issuer(crl, cert, err) < 0)
return -1;
/* verify the validity period of the CRL */
if (!(verify_flags & X509_V_FLAG_NO_CHECK_TIME)) {
const ASN1_TIME *last = X509_CRL_get0_lastUpdate(crl);
const ASN1_TIME *next = X509_CRL_get0_nextUpdate(crl);
if (!last || !next || check_validity_period(last, next)) {
g_set_error(err, PV_CRYPTO_ERROR,
PV_CRYPTO_ERROR_INVALID_VALIDITY_PERIOD,
_("validity period is not valid"));
return -1;
}
} else {
verify_flags &= ~X509_V_FLAG_NO_CHECK_TIME;
}
/* verify the signature */
if (X509_CRL_verify(crl, pkey) != 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_CRL_SIGNATURE_INVALID,
_("signature is not valid"));
return -1;
}
g_assert(verify_flags == 0);
return 0;
}
/* This function contains work-arounds for some known subject(CRT)<->issuer(CRL)
* issues.
*/
static STACK_OF_X509_CRL *quirk_X509_STORE_ctx_get1_crls(X509_STORE_CTX *ctx,
const X509_NAME *subject, GError **err)
{
g_autoptr(X509_NAME) fixed_subject = NULL;
g_autoptr(STACK_OF_X509_CRL) ret = NULL;
ret = Pv_X509_STORE_CTX_get1_crls(ctx, subject);
if (ret && sk_X509_CRL_num(ret) > 0)
return g_steal_pointer(&ret);
/* Workaround to fix the mismatch between issuer name of the * IBM
* signing CRLs and the IBM signing key subject name. Locality name has
* changed from Poughkeepsie to Armonk.
*/
fixed_subject = x509_armonk_locality_fixup(subject);
/* Was the locality replaced? */
if (fixed_subject) {
X509_NAME *tmp;
sk_X509_CRL_free(ret);
ret = Pv_X509_STORE_CTX_get1_crls(ctx, fixed_subject);
if (ret && sk_X509_CRL_num(ret) > 0)
return g_steal_pointer(&ret);
/* Workaround to fix the ordering mismatch between issuer name
* of the IBM signing CRLs and the IBM signing key subject name.
*/
tmp = fixed_subject;
fixed_subject = c2b_name(fixed_subject);
X509_NAME_free(tmp);
sk_X509_CRL_free(ret);
ret = Pv_X509_STORE_CTX_get1_crls(ctx, fixed_subject);
if (ret && sk_X509_CRL_num(ret) > 0)
return g_steal_pointer(&ret);
X509_NAME_free(fixed_subject);
fixed_subject = NULL;
}
/* Workaround to fix the ordering mismatch between issuer name of the
* IBM signing CRLs and the IBM signing key subject name.
*/
fixed_subject = c2b_name(subject);
sk_X509_CRL_free(ret);
ret = Pv_X509_STORE_CTX_get1_crls(ctx, fixed_subject);
if (ret && sk_X509_CRL_num(ret) > 0)
return g_steal_pointer(&ret);
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_NO_CRL, _("no CRL found"));
return NULL;
}
/* Given a certificate @cert try to find valid revocation lists in @ctx. If no
* valid CRL was found NULL is returned.
*/
STACK_OF_X509_CRL *store_ctx_find_valid_crls(X509_STORE_CTX *ctx, X509 *cert,
GError **err)
{
g_autoptr(STACK_OF_X509_CRL) ret = NULL;
const gint verify_flags = 0;
X509_NAME *subject = NULL;
subject = X509_get_subject_name(cert);
if (!subject) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_MALFORMED_CERTIFICATE,
_("certificate is malformed"));
return NULL;
}
ret = quirk_X509_STORE_ctx_get1_crls(ctx, subject, err);
if (!ret)
return NULL;
/* Filter out non-valid CRLs for @cert */
for (gint i = 0; i < sk_X509_CRL_num(ret); i++) {
X509_CRL *crl = sk_X509_CRL_value(ret, i);
g_assert(crl);
/* If @crl is not valid remove it from the array and log a
* warning.
*/
if (check_crl_valid_for_cert(crl, cert, verify_flags, err) < 0) {
g_assert(err);
g_warning(_("CRL is not valid: %s"), (*err)->message);
g_clear_error(err);
/* Remove this certificate from the list and change i-- as the
* array has changed - this is not beautfiul, but right now the
* easiest solution I came up with
*/
if (sk_X509_CRL_delete(ret, i--) != crl)
g_abort();
g_clear_pointer(&crl, X509_CRL_free);
}
}
if (sk_X509_CRL_num(ret) < 1) {
g_set_error(err, PV_CRYPTO_ERROR, PV_CRYPTO_ERROR_NO_CRL,
_("no valid CRL found"));
return NULL;
}
return g_steal_pointer(&ret);
}
/* Return a list of all IBM Z signing key certificates in @certs and remove them
* from the chain. Return empty stack if no IBM Z signing key is found.
*/
STACK_OF_X509 *delete_ibm_signing_certs(STACK_OF_X509 *certs)
{
g_autoptr(STACK_OF_X509) ret = sk_X509_new_null();
for (gint i = 0; i < sk_X509_num(certs); i++) {
X509 *cert = sk_X509_value(certs, i);
g_assert(cert);
if (!has_ibm_signing_subject(cert))