Repository navigation
Expand file tree
/
Copy pathdidx509cpp.h
More file actions
2197 lines (1985 loc) · 65.2 KB
/
Copy pathdidx509cpp.h
File metadata and controls
2197 lines (1985 loc) · 65.2 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <initializer_list>
#include <limits>
#include <map>
#include <memory>
#include <openssl/asn1.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/obj_mac.h>
#include <openssl/objects.h>
#include <openssl/opensslv.h>
#include <openssl/pem.h>
#include <openssl/safestack.h>
#include <openssl/types.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <openssl/x509v3.h>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_set>
#include <utility>
#include <vector>
#if OPENSSL_VERSION_NUMBER < 0x30300000L
# error "didx509cpp requires OpenSSL 3.3 or newer"
#endif
namespace didx509
{
namespace
{
inline std::string error_string(unsigned long ec)
#ifdef _DEBUG
__attribute__((noinline))
#endif
{
if (ec != 0)
{
return {ERR_error_string(ec, nullptr)};
}
return "unknown error";
}
/// Throws if rc is different from 1. OpenSSL does not always queue an
/// error for a failed call, so the error queue only informs the message
/// and never decides whether to throw.
inline void CHECK1(int rc)
#ifdef _DEBUG
__attribute__((noinline))
#endif
{
const unsigned long ec = ERR_get_error();
if (rc != 1)
{
throw std::runtime_error(
std::string("OpenSSL error: ") + error_string(ec));
}
}
/// Throws if rc is 0, see CHECK1 for the role of the error queue.
inline void CHECK0(int rc)
#ifdef _DEBUG
__attribute__((noinline))
#endif
{
const unsigned long ec = ERR_get_error();
if (rc == 0)
{
throw std::runtime_error(
std::string("OpenSSL error: ") + error_string(ec));
}
}
/// Throws if ptr is nullptr
inline void CHECKNULL(void* ptr)
#ifdef _DEBUG
__attribute__((noinline))
#endif
{
if (ptr == nullptr)
{
const unsigned long ec = ERR_get_error();
throw std::runtime_error(
std::string("OpenSSL error: missing object: ") + error_string(ec));
}
}
inline bool is_valid_utf8(std::string_view value)
{
for (size_t i = 0; i < value.size();)
{
const auto first = static_cast<uint8_t>(value[i++]);
if (first <= 0x7f)
{
continue;
}
size_t remaining = 0;
uint32_t scalar = 0;
uint32_t minimum = 0;
if (first >= 0xc2 && first <= 0xdf)
{
remaining = 1;
scalar = first & 0x1f;
minimum = 0x80;
}
else if (first >= 0xe0 && first <= 0xef)
{
remaining = 2;
scalar = first & 0x0f;
minimum = 0x800;
}
else if (first >= 0xf0 && first <= 0xf4)
{
remaining = 3;
scalar = first & 0x07;
minimum = 0x10000;
}
else
{
return false;
}
if (remaining > value.size() - i)
{
return false;
}
for (size_t j = 0; j < remaining; j++)
{
const auto next = static_cast<uint8_t>(value[i++]);
if (next < 0x80 || next > 0xbf)
{
return false;
}
scalar = (scalar << 6) | (next & 0x3f);
}
if (
scalar < minimum || scalar > 0x10ffff ||
(scalar >= 0xd800 && scalar <= 0xdfff))
{
return false;
}
}
return true;
}
inline std::string decode_der_utf8_string(const std::string& encoded)
{
if (encoded.empty() || static_cast<uint8_t>(encoded[0]) != 0x0c)
{
throw std::runtime_error("value is not a primitive DER UTF8String");
}
if (encoded.size() < 2)
{
throw std::runtime_error("DER UTF8String length is truncated");
}
size_t length = static_cast<uint8_t>(encoded[1]);
size_t offset = 2;
if (length >= 0x80)
{
if (length == 0x80 || length == 0xff)
{
throw std::runtime_error("DER UTF8String length is not definite");
}
const size_t octets = length & 0x7f;
if (octets > encoded.size() - offset)
{
throw std::runtime_error("DER UTF8String length is truncated");
}
if (encoded[offset] == 0 || octets > sizeof(size_t))
{
throw std::runtime_error("DER UTF8String length is invalid");
}
length = 0;
for (size_t i = 0; i < octets; i++)
{
length = (length << 8) | static_cast<uint8_t>(encoded[offset++]);
}
if (length < 0x80)
{
throw std::runtime_error("DER UTF8String length is not minimal");
}
}
if (length != encoded.size() - offset)
{
throw std::runtime_error(
"DER UTF8String must contain exactly one complete value");
}
auto value = encoded.substr(offset);
if (!is_valid_utf8(value))
{
throw std::runtime_error("DER UTF8String is not valid UTF-8");
}
return value;
}
inline constexpr auto fulcio_othername_oid = "1.3.6.1.4.1.57264.1.7";
inline const std::map<std::string, std::string>& fulcio_extension_oids()
{
static const std::map<std::string, std::string> oids = {
{"issuer", "1.3.6.1.4.1.57264.1.8"},
{"build-signer-uri", "1.3.6.1.4.1.57264.1.9"},
{"build-signer-digest", "1.3.6.1.4.1.57264.1.10"},
{"runner-environment", "1.3.6.1.4.1.57264.1.11"},
{"source-repository-uri", "1.3.6.1.4.1.57264.1.12"},
{"source-repository-digest", "1.3.6.1.4.1.57264.1.13"},
{"source-repository-ref", "1.3.6.1.4.1.57264.1.14"},
{"source-repository-identifier", "1.3.6.1.4.1.57264.1.15"},
{"source-repository-owner-uri", "1.3.6.1.4.1.57264.1.16"},
{"source-repository-owner-identifier", "1.3.6.1.4.1.57264.1.17"},
{"build-config-uri", "1.3.6.1.4.1.57264.1.18"},
{"build-config-digest", "1.3.6.1.4.1.57264.1.19"},
{"build-trigger", "1.3.6.1.4.1.57264.1.20"},
{"run-invocation-uri", "1.3.6.1.4.1.57264.1.21"},
{"source-repository-visibility-at-signing", "1.3.6.1.4.1.57264.1.22"},
{"deployment-environment", "1.3.6.1.4.1.57264.1.23"},
{"token-subject", "1.3.6.1.4.1.57264.1.24"}};
return oids;
}
inline std::string to_base64(const std::vector<uint8_t>& bytes)
{
// EVP_EncodeBlock produces nothing for empty input; return early so the
// padding-trim loop below does not call back() on an empty string (UB).
if (bytes.empty())
{
return {};
}
const int r_sz = 4 * ((bytes.size() + 2) / 3);
std::string r(r_sz, 0);
auto out_sz =
EVP_EncodeBlock((unsigned char*)r.data(), bytes.data(), bytes.size());
if (r_sz != out_sz)
{
throw std::runtime_error("base64 conversion failed");
}
while (!r.empty() && r.back() == '=')
{
r.pop_back();
}
return r;
}
inline std::string to_base64url(const std::vector<uint8_t>& bytes)
{
auto r = to_base64(bytes);
for (char & i: r)
{
if (i == '+')
{
i = '-';
}
else if (i == '/')
{
i = '_';
}
}
return r;
}
// RFC 8032 section 5.1.3: an Ed25519 public key encodes the y-coordinate
// in the low 255 bits, little-endian, with the sign of x in the top bit.
// Decoding fails if y >= p = 2^255 - 19, so the only non-canonical
// encodings are the 19 values p .. 2^255 - 1 (times two for the sign bit).
// OpenSSL accepts and re-exports these unchanged, so check here.
inline bool is_canonical_ed25519_public_key(const std::vector<uint8_t>& key)
{
if (key.size() != 32)
{
return false;
}
// y >= p iff bits 1..254 are all set and the low byte is >= 0xed.
if ((key[31] & 0x7f) != 0x7f)
{
return true;
}
for (size_t i = 1; i < 31; i++)
{
if (key[i] != 0xff)
{
return true;
}
}
return key[0] < 0xed;
}
template <class T, T* (*CTOR)(), void (*DTOR)(T*)>
class UqSSLOBJECT
{
protected:
std::unique_ptr<T, void (*)(T*)> p;
public:
UqSSLOBJECT() : p(CTOR(), DTOR)
{
CHECKNULL(p.get());
}
UqSSLOBJECT(T* ptr, void (*dtor)(T*), bool check_null = true) :
p(ptr, dtor)
{
if (check_null)
{
CHECKNULL(p.get());
}
}
UqSSLOBJECT(const UqSSLOBJECT&) = delete;
UqSSLOBJECT& operator=(const UqSSLOBJECT&) = delete;
operator T*()
{
return p.get();
}
operator T*() const
{
return p.get();
}
const T* operator->() const
{
return p.get();
}
void reset(T* other)
{
p.reset(other);
}
T* release()
{
return p.release();
}
};
struct UqBIGNUM : public UqSSLOBJECT<BIGNUM, BN_new, BN_free>
{
UqBIGNUM(const BIGNUM* n) : UqSSLOBJECT(BN_dup(n), BN_free) {}
UqBIGNUM(UqBIGNUM&& other) noexcept : UqSSLOBJECT(nullptr, BN_free, false)
{
p = std::move(other.p);
}
};
struct UqBIO : public UqSSLOBJECT<BIO, nullptr, nullptr>
{
UqBIO() : UqSSLOBJECT(BIO_new(BIO_s_mem()), [](auto x) { BIO_free(x); })
{}
UqBIO(const void* buf, int len) :
UqSSLOBJECT(BIO_new_mem_buf(buf, len), [](auto x) { BIO_free(x); })
{}
UqBIO(const std::string& s) :
UqSSLOBJECT(
BIO_new_mem_buf(s.data(), s.size()), [](auto x) { BIO_free(x); })
{}
UqBIO(const std::vector<uint8_t>& d) :
UqSSLOBJECT(
BIO_new_mem_buf(d.data(), d.size()), [](auto x) { BIO_free(x); })
{}
UqBIO(UqBIO&& b, UqBIO&& next) :
UqSSLOBJECT(BIO_push(b, next), [](auto x) { BIO_free_all(x); })
{
b.release();
next.release();
}
[[nodiscard]] std::string to_string() const
{
BUF_MEM* bptr = nullptr;
BIO_get_mem_ptr(p.get(), &bptr);
return {bptr->data, bptr->length};
}
[[nodiscard]] std::vector<uint8_t> to_vector() const
{
BUF_MEM* bptr = nullptr;
BIO_get_mem_ptr(p.get(), &bptr);
return {bptr->data, bptr->data + bptr->length};
}
};
struct UqASN1_OBJECT
: public UqSSLOBJECT<ASN1_OBJECT, ASN1_OBJECT_new, ASN1_OBJECT_free>
{
UqASN1_OBJECT(const std::string& oid) :
UqSSLOBJECT(OBJ_txt2obj(oid.c_str(), 1), ASN1_OBJECT_free)
{}
UqASN1_OBJECT(const ASN1_OBJECT* obj) :
UqSSLOBJECT(OBJ_dup(obj), ASN1_OBJECT_free, true)
{}
UqASN1_OBJECT(int nid) :
UqSSLOBJECT(OBJ_nid2obj(nid), ASN1_OBJECT_free, true)
{}
UqASN1_OBJECT(UqASN1_OBJECT&& other) noexcept :
UqSSLOBJECT(nullptr, ASN1_OBJECT_free, false)
{
p = std::move(other.p);
}
bool operator==(const UqASN1_OBJECT& other) const
{
return OBJ_cmp(*this, other) == 0;
}
bool operator!=(const UqASN1_OBJECT& other) const
{
return !(*this == other);
}
};
struct UqASN1_OCTET_STRING : public UqSSLOBJECT<
ASN1_OCTET_STRING,
ASN1_OCTET_STRING_new,
ASN1_OCTET_STRING_free>
{
UqASN1_OCTET_STRING(const ASN1_OCTET_STRING* str) :
UqSSLOBJECT(ASN1_OCTET_STRING_dup(str), ASN1_OCTET_STRING_free)
{}
UqASN1_OCTET_STRING(UqASN1_OCTET_STRING&& other) noexcept :
UqSSLOBJECT(nullptr, ASN1_OCTET_STRING_free, false)
{
p = std::move(other.p);
}
operator std::string() const
{
// Return the raw value bytes verbatim, using the explicit length.
// Unlike ASN1_STRING_print, this preserves embedded NUL bytes and does
// not lossily replace non-printable bytes with '.', which matters when
// the value is compared for equality (e.g. the fulcio-issuer policy).
const int len = ASN1_STRING_length(*this);
const unsigned char* data = ASN1_STRING_get0_data(*this);
if (data == nullptr || len < 0)
{
return {};
}
return {data, data + static_cast<size_t>(len)};
}
};
struct UqX509_EXTENSION : public UqSSLOBJECT<
X509_EXTENSION,
X509_EXTENSION_new,
X509_EXTENSION_free>
{
UqX509_EXTENSION(X509_EXTENSION* ext) :
UqSSLOBJECT(X509_EXTENSION_dup(ext), X509_EXTENSION_free, true)
{}
UqX509_EXTENSION(const UqX509_EXTENSION& ext) :
UqSSLOBJECT(X509_EXTENSION_dup(ext), X509_EXTENSION_free, true)
{}
UqX509_EXTENSION(UqX509_EXTENSION&& ext) noexcept :
UqSSLOBJECT(nullptr, X509_EXTENSION_free, false)
{
p = std::move(ext.p);
}
[[nodiscard]] UqASN1_OBJECT object() const
{
return X509_EXTENSION_get_object(*this);
}
[[nodiscard]] UqASN1_OCTET_STRING data() const
{
return X509_EXTENSION_get_data(*this);
}
[[nodiscard]] bool critical() const
{
return X509_EXTENSION_get_critical(*this) != 0;
}
};
struct UqGENERAL_NAME
: public UqSSLOBJECT<GENERAL_NAME, GENERAL_NAME_new, GENERAL_NAME_free>
{
UqGENERAL_NAME(GENERAL_NAME* n) :
UqSSLOBJECT(GENERAL_NAME_dup(n), GENERAL_NAME_free)
{}
UqGENERAL_NAME(UqGENERAL_NAME&& other) noexcept :
UqSSLOBJECT(nullptr, GENERAL_NAME_free, false)
{
p = std::move(other.p);
}
[[nodiscard]] std::string othername_value() const
{
if (p->type != GEN_OTHERNAME || p->d.otherName == nullptr)
{
throw std::runtime_error("invalid OtherName SAN");
}
const auto* name = p->d.otherName;
CHECKNULL(name->type_id);
CHECKNULL(name->value);
if (UqASN1_OBJECT(name->type_id) != UqASN1_OBJECT(fulcio_othername_oid))
{
throw std::runtime_error("unsupported OtherName SAN type OID");
}
UqBIO encoded;
CHECK1(
ASN1_item_i2d_bio(ASN1_ITEM_rptr(ASN1_ANY), encoded, name->value));
return decode_der_utf8_string(encoded.to_string());
}
[[nodiscard]] std::string ia5_value() const
{
ASN1_IA5STRING* value = nullptr;
switch (p->type)
{
case GEN_EMAIL:
value = p->d.rfc822Name;
break;
case GEN_DNS:
value = p->d.dNSName;
break;
case GEN_URI:
value = p->d.uniformResourceIdentifier;
break;
default:
throw std::runtime_error("SAN is not an IA5String");
}
CHECKNULL(value);
const int length = ASN1_STRING_length(value);
const auto* data = ASN1_STRING_get0_data(value);
if (length < 0 || (length > 0 && data == nullptr))
{
throw std::runtime_error("invalid IA5String SAN");
}
std::string result;
if (length > 0)
{
result.assign(data, data + static_cast<size_t>(length));
}
for (const char c : result)
{
if (static_cast<uint8_t>(c) > 0x7f)
{
throw std::runtime_error("SAN value is not a valid IA5String");
}
}
return result;
}
};
struct UqSUBJECT_ALT_NAME
: public UqSSLOBJECT<STACK_OF(GENERAL_NAME), nullptr, nullptr>
{
UqSUBJECT_ALT_NAME() :
UqSSLOBJECT(sk_GENERAL_NAME_new_null(), [](auto x) {
sk_GENERAL_NAME_pop_free(x, GENERAL_NAME_free);
})
{}
UqSUBJECT_ALT_NAME(const UqX509_EXTENSION& ext) :
UqSSLOBJECT(
nullptr,
[](auto x) { sk_GENERAL_NAME_pop_free(x, GENERAL_NAME_free); },
false)
{
const UqASN1_OBJECT ext_obj(X509_EXTENSION_get_object(ext));
const UqASN1_OBJECT ext_key_obj(NID_subject_alt_name);
if (ext_obj != ext_key_obj)
{
throw std::runtime_error("invalid extension type");
}
auto * data = static_cast<STACK_OF(GENERAL_NAME)*>(X509V3_EXT_d2i(ext));
if (data == nullptr)
{
throw std::runtime_error("SAN extension could not be decoded");
}
p.reset(data);
bool contains_othername = false;
for (size_t i = 0; i < size(); i++)
{
const auto name = at(i);
switch (name->type)
{
case GEN_OTHERNAME:
(void)name.othername_value();
contains_othername = true;
break;
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI:
(void)name.ia5_value();
break;
case GEN_DIRNAME:
break;
default:
throw std::runtime_error("unsupported SAN type");
}
}
if (contains_othername)
{
// OpenSSL accepts BER and normalizes ANY values. Check the original
// bytes too, so nonminimal OtherName lengths cannot become valid DER.
UqBIO canonical;
CHECK1(ASN1_item_i2d_bio(
ASN1_ITEM_rptr(GENERAL_NAMES), canonical, p.get()));
if (canonical.to_string() != static_cast<std::string>(ext.data()))
{
throw std::runtime_error("OtherName SAN is not canonical DER");
}
}
}
UqSUBJECT_ALT_NAME(UqSUBJECT_ALT_NAME&& other) noexcept :
UqSSLOBJECT(
nullptr,
[](auto x) { sk_GENERAL_NAME_pop_free(x, GENERAL_NAME_free); },
false)
{
p = std::move(other.p);
}
[[nodiscard]] size_t size() const
{
return sk_GENERAL_NAME_num(*this);
}
[[nodiscard]] UqGENERAL_NAME at(size_t i) const
{
if (i >= size())
{
throw std::out_of_range("extended key usage index out of range");
}
return sk_GENERAL_NAME_value(*this, i);
}
};
struct UqEXTENDED_KEY_USAGE : public UqSSLOBJECT<
EXTENDED_KEY_USAGE,
EXTENDED_KEY_USAGE_new,
EXTENDED_KEY_USAGE_free>
{
UqEXTENDED_KEY_USAGE(const UqX509_EXTENSION& ext) :
UqSSLOBJECT(nullptr, EXTENDED_KEY_USAGE_free, false)
{
const UqASN1_OBJECT ext_obj = UqASN1_OBJECT(X509_EXTENSION_get_object(ext));
const UqASN1_OBJECT ext_key_obj(NID_ext_key_usage);
if (ext_obj != ext_key_obj)
{
throw std::runtime_error("invalid extension type");
}
auto * data = static_cast<EXTENDED_KEY_USAGE*>(X509V3_EXT_d2i(ext));
if (data == nullptr)
{
throw std::runtime_error("key usage extension could not be decoded");
}
p.reset(data);
}
UqEXTENDED_KEY_USAGE(UqEXTENDED_KEY_USAGE&& other) noexcept :
UqSSLOBJECT(nullptr, EXTENDED_KEY_USAGE_free, false)
{
p = std::move(other.p);
}
[[nodiscard]] size_t size() const
{
return sk_ASN1_OBJECT_num(*this);
}
[[nodiscard]] UqASN1_OBJECT at(size_t i) const
{
if (i >= size())
{
throw std::out_of_range("extended key usage index out of range");
}
return {sk_ASN1_OBJECT_value(*this, i)};
}
};
struct UqX509;
struct UqEVP_PKEY
: public UqSSLOBJECT<EVP_PKEY, EVP_PKEY_new, EVP_PKEY_free>
{
UqEVP_PKEY(const UqX509& x509);
UqEVP_PKEY(const EVP_PKEY* key);
UqEVP_PKEY(UqEVP_PKEY&& other) noexcept :
UqSSLOBJECT(nullptr, EVP_PKEY_free, false)
{
p = std::move(other.p);
}
bool operator==(const UqEVP_PKEY& other) const
{
return EVP_PKEY_eq(*this, other) == 1;
}
bool operator!=(const UqEVP_PKEY& other) const
{
return !(*this == other);
}
UqBIGNUM get_bn_param(const char* key_name) const
{
BIGNUM* bn = nullptr;
CHECK1(EVP_PKEY_get_bn_param(*this, key_name, &bn));
UqBIGNUM r(bn);
BN_free(bn);
return r;
}
};
struct UqEVP_PKEY_CTX : public UqSSLOBJECT<EVP_PKEY_CTX, nullptr, nullptr>
{
UqEVP_PKEY_CTX(int nid) :
UqSSLOBJECT(EVP_PKEY_CTX_new_id(nid, nullptr), EVP_PKEY_CTX_free)
{}
};
struct UqX509 : public UqSSLOBJECT<X509, X509_new, X509_free>
{
UqX509(const std::string& pem, bool check_null = true) :
UqSSLOBJECT(
PEM_read_bio_X509(UqBIO(pem), nullptr, nullptr, nullptr),
X509_free,
check_null)
{}
UqX509(UqX509&& other) noexcept : UqSSLOBJECT(nullptr, X509_free, false)
{
X509* ptr = other;
other.release();
p.reset(ptr);
}
UqX509(X509* x509) : UqSSLOBJECT(x509, X509_free)
{
X509_up_ref(x509);
}
UqX509& operator=(const UqX509& other) noexcept
{
if (this != &other)
{
X509_up_ref(other);
p.reset(other.p.get());
}
return *this;
}
UqX509& operator=(UqX509&& other) noexcept
{
p = std::move(other.p);
return *this;
}
[[nodiscard]] bool is_ca() const
{
return X509_check_ca(p.get()) != 0;
}
[[nodiscard]] int extension_index(const std::string& oid) const
{
return X509_get_ext_by_OBJ(*this, UqASN1_OBJECT(oid), -1);
}
template <typename T>
[[nodiscard]] std::vector<T> extensions(const UqASN1_OBJECT& obj) const
{
std::vector<T> r;
auto count = X509_get_ext_count(*this);
int index = -1;
do
{
index = X509_get_ext_by_OBJ(*this, obj, index);
if (index != -1)
{
r.emplace_back(X509_get_ext(*this, index));
}
} while (index != -1 && index < count);
return r;
}
template <typename T>
[[nodiscard]] std::vector<T> extensions(const std::string& oid) const
{
return extensions<T>(UqASN1_OBJECT(oid));
}
[[nodiscard]] std::vector<UqSUBJECT_ALT_NAME> subject_alternative_name() const
{
auto names =
extensions<UqSUBJECT_ALT_NAME>(UqASN1_OBJECT(NID_subject_alt_name));
if (names.size() > 1)
{
throw std::runtime_error("duplicate SAN extension");
}
return names;
};
[[nodiscard]] std::map<std::string, std::string> fulcio_extensions() const
{
std::map<std::string, std::string> fields;
for (const auto& [field, oid] : fulcio_extension_oids())
{
const auto exts = extensions<UqX509_EXTENSION>(oid);
if (exts.size() > 1)
{
throw std::runtime_error("duplicate Fulcio extension: " + field);
}
if (!exts.empty())
{
const auto& ext = exts.front();
if (ext.critical())
{
throw std::runtime_error("critical Fulcio extension: " + field);
}
fields.emplace(
field,
decode_der_utf8_string(static_cast<std::string>(ext.data())));
}
}
const auto legacy =
extensions<UqX509_EXTENSION>("1.3.6.1.4.1.57264.1.1");
if (legacy.size() > 1)
{
throw std::runtime_error("duplicate fulcio-issuer extension");
}
for (const auto& ext : legacy)
{
if (ext.critical())
{
throw std::runtime_error("critical fulcio-issuer extension");
}
if (!is_valid_utf8(static_cast<std::string>(ext.data())))
{
throw std::runtime_error("fulcio-issuer is not valid UTF-8");
}
}
return fields;
}
[[nodiscard]] std::vector<UqEXTENDED_KEY_USAGE> extended_key_usage() const
{
return extensions<UqEXTENDED_KEY_USAGE>(
UqASN1_OBJECT(NID_ext_key_usage));
};
[[nodiscard]] bool has_key_usage() const
{
return (X509_get_extension_flags(*this) & EXFLAG_KUSAGE) != 0;
}
[[nodiscard]] bool has_key_usage_digital_signature() const
{
return has_key_usage() &&
(X509_get_key_usage(*this) & KU_DIGITAL_SIGNATURE) != 0;
}
[[nodiscard]] bool has_key_usage_key_agreement() const
{
return has_key_usage() &&
(X509_get_key_usage(*this) & KU_KEY_AGREEMENT) != 0;
}
[[nodiscard]] bool has_key_usage_encipherment() const
{
return has_key_usage() &&
(X509_get_key_usage(*this) &
(KU_KEY_ENCIPHERMENT | KU_DATA_ENCIPHERMENT | KU_ENCIPHER_ONLY |
KU_DECIPHER_ONLY)) != 0;
}
[[nodiscard]] bool has_common_name(const std::string& expected_name) const;
/// Maps the subject name to the did:x509 JSON model: one UTF-8 value per
/// attribute, keyed by RFC 4514 label or dotted OID. The model does not
/// support repeated attributes, so a name that carries the same
/// attribute type more than once (as separate RDNs or within a
/// multi-valued RDN) is rejected rather than matched against any one of
/// its values.
[[nodiscard]] std::map<std::string, std::string> subject() const
{
std::map<std::string, std::string> r;
auto * name = X509_get_subject_name(*this);
CHECKNULL(name);
auto n = X509_NAME_entry_count(name);
for (auto i = 0; i < n; i++)
{
X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, i);
CHECKNULL(entry);
ASN1_OBJECT* oid = X509_NAME_ENTRY_get_object(entry);
CHECKNULL(oid);
std::string key;
std::map<int, std::string> short_name_map = {
// As specified by the did-x509 spec
{NID_commonName, "CN"},
{NID_localityName, "L"},
{NID_stateOrProvinceName, "ST"},
{NID_organizationName, "O"},
{NID_organizationalUnitName, "OU"},
{NID_countryName, "C"},
{NID_streetAddress, "STREET"},
};
auto snit = short_name_map.find(OBJ_obj2nid(oid));
if (snit != short_name_map.end())
{
key = snit->second;
}
else
{
const int sz = OBJ_obj2txt(nullptr, 0, oid, 1);
if (sz < 0)
{
throw std::runtime_error("could not convert OID to a string");
}
// OBJ_obj2txt writes sz characters plus a NUL terminator, so the
// buffer needs room for sz + 1. Shrink back to sz afterwards so the
// map key does not carry a trailing NUL, which would otherwise stop
// a user-supplied OID key (without the NUL) from ever matching.
key.resize(static_cast<size_t>(sz) + 1, 0);
const int sz2 = OBJ_obj2txt(key.data(), key.size(), oid, 1);
if (sz2 < 0 || sz2 > sz)
{
throw std::runtime_error("could not convert OID to a string");
}
key.resize(static_cast<size_t>(sz2));
}
ASN1_STRING* val_asn1 = X509_NAME_ENTRY_get_data(entry);
CHECKNULL(val_asn1);
// The did:x509 spec requires subject attribute values to be compared
// as UTF-8. ASN1_STRING_to_UTF8 decodes the various X.509 string
// encodings (PrintableString, UTF8String, BMPString, ...) into UTF-8
// and, unlike ASN1_STRING_print, does not lossily replace non-ASCII
// or non-printable bytes with '.'.
unsigned char* utf8_raw = nullptr;
const int utf8_len = ASN1_STRING_to_UTF8(&utf8_raw, val_asn1);
if (utf8_len < 0)
{
throw std::runtime_error(
"could not convert subject attribute value to UTF-8");
}
const auto utf8_deleter = [](unsigned char* p) { OPENSSL_free(p); };
const std::unique_ptr<unsigned char, decltype(utf8_deleter)> utf8(
utf8_raw, utf8_deleter);
std::string value;
if (utf8_len > 0)
{
if (!utf8)
{
throw std::runtime_error(
"could not convert subject attribute value to UTF-8");
}
value.assign(utf8.get(), utf8.get() + utf8_len);
}
if (!r.emplace(key, std::move(value)).second)
{
throw std::runtime_error(
"certificate subject contains duplicate attribute: " + key);
}
}
return r;
}
[[nodiscard]] bool has_subject_key_id() const
{
return X509_get0_subject_key_id(*this) != nullptr;