forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathncrypto.cc
More file actions
4817 lines (4096 loc) · 140 KB
/
ncrypto.cc
File metadata and controls
4817 lines (4096 loc) · 140 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
#include "ncrypto.h"
#include <openssl/asn1.h>
#include <openssl/bn.h>
#include <openssl/dh.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/pkcs12.h>
#include <openssl/rand.h>
#include <openssl/x509v3.h>
#include <algorithm>
#include <cstring>
#if OPENSSL_VERSION_MAJOR >= 3
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/provider.h>
#if OPENSSL_VERSION_NUMBER >= 0x30200000L
#include <openssl/thread.h>
#endif
#endif
#if OPENSSL_WITH_PQC
struct PQCMapping {
const char* name;
int nid;
};
constexpr static PQCMapping pqc_mappings[] = {
{"ML-DSA-44", EVP_PKEY_ML_DSA_44},
{"ML-DSA-65", EVP_PKEY_ML_DSA_65},
{"ML-DSA-87", EVP_PKEY_ML_DSA_87},
{"ML-KEM-512", EVP_PKEY_ML_KEM_512},
{"ML-KEM-768", EVP_PKEY_ML_KEM_768},
{"ML-KEM-1024", EVP_PKEY_ML_KEM_1024},
{"SLH-DSA-SHA2-128f", EVP_PKEY_SLH_DSA_SHA2_128F},
{"SLH-DSA-SHA2-128s", EVP_PKEY_SLH_DSA_SHA2_128S},
{"SLH-DSA-SHA2-192f", EVP_PKEY_SLH_DSA_SHA2_192F},
{"SLH-DSA-SHA2-192s", EVP_PKEY_SLH_DSA_SHA2_192S},
{"SLH-DSA-SHA2-256f", EVP_PKEY_SLH_DSA_SHA2_256F},
{"SLH-DSA-SHA2-256s", EVP_PKEY_SLH_DSA_SHA2_256S},
{"SLH-DSA-SHAKE-128f", EVP_PKEY_SLH_DSA_SHAKE_128F},
{"SLH-DSA-SHAKE-128s", EVP_PKEY_SLH_DSA_SHAKE_128S},
{"SLH-DSA-SHAKE-192f", EVP_PKEY_SLH_DSA_SHAKE_192F},
{"SLH-DSA-SHAKE-192s", EVP_PKEY_SLH_DSA_SHAKE_192S},
{"SLH-DSA-SHAKE-256f", EVP_PKEY_SLH_DSA_SHAKE_256F},
{"SLH-DSA-SHAKE-256s", EVP_PKEY_SLH_DSA_SHAKE_256S},
};
#endif
// EVP_PKEY_CTX_set_dsa_paramgen_q_bits was added in OpenSSL 1.1.1e.
#if OPENSSL_VERSION_NUMBER < 0x1010105fL
#define EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, qbits) \
EVP_PKEY_CTX_ctrl((ctx), \
EVP_PKEY_DSA, \
EVP_PKEY_OP_PARAMGEN, \
EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS, \
(qbits), \
nullptr)
#endif
namespace ncrypto {
namespace {
using BignumCtxPointer = DeleteFnPtr<BN_CTX, BN_CTX_free>;
using BignumGenCallbackPointer = DeleteFnPtr<BN_GENCB, BN_GENCB_free>;
using NetscapeSPKIPointer = DeleteFnPtr<NETSCAPE_SPKI, NETSCAPE_SPKI_free>;
static constexpr int kX509NameFlagsRFC2253WithinUtf8JSON =
XN_FLAG_RFC2253 & ~ASN1_STRFLGS_ESC_MSB & ~ASN1_STRFLGS_ESC_CTRL;
} // namespace
// ============================================================================
ClearErrorOnReturn::ClearErrorOnReturn(CryptoErrorList* errors)
: errors_(errors) {
ERR_clear_error();
}
ClearErrorOnReturn::~ClearErrorOnReturn() {
if (errors_ != nullptr) errors_->capture();
ERR_clear_error();
}
int ClearErrorOnReturn::peekError() {
return ERR_peek_error();
}
MarkPopErrorOnReturn::MarkPopErrorOnReturn(CryptoErrorList* errors)
: errors_(errors) {
ERR_set_mark();
}
MarkPopErrorOnReturn::~MarkPopErrorOnReturn() {
if (errors_ != nullptr) errors_->capture();
ERR_pop_to_mark();
}
int MarkPopErrorOnReturn::peekError() {
return ERR_peek_error();
}
CryptoErrorList::CryptoErrorList(CryptoErrorList::Option option) {
if (option == Option::CAPTURE_ON_CONSTRUCT) capture();
}
void CryptoErrorList::capture() {
errors_.clear();
while (const auto err = ERR_get_error()) {
char buf[256];
ERR_error_string_n(err, buf, sizeof(buf));
errors_.emplace_front(buf);
}
}
void CryptoErrorList::add(std::string error) {
errors_.push_back(error);
}
std::optional<std::string> CryptoErrorList::pop_back() {
if (errors_.empty()) return std::nullopt;
std::string error = errors_.back();
errors_.pop_back();
return error;
}
std::optional<std::string> CryptoErrorList::pop_front() {
if (errors_.empty()) return std::nullopt;
std::string error = errors_.front();
errors_.pop_front();
return error;
}
// ============================================================================
DataPointer DataPointer::Alloc(size_t len) {
#ifdef OPENSSL_IS_BORINGSSL
// Boringssl does not implement OPENSSL_zalloc
auto ptr = OPENSSL_malloc(len);
if (ptr == nullptr) return {};
memset(ptr, 0, len);
return DataPointer(ptr, len);
#else
return DataPointer(OPENSSL_zalloc(len), len);
#endif
}
DataPointer DataPointer::SecureAlloc(size_t len) {
#ifndef OPENSSL_IS_BORINGSSL
auto ptr = OPENSSL_secure_zalloc(len);
if (ptr == nullptr) return {};
return DataPointer(ptr, len, true);
#else
// BoringSSL does not implement the OPENSSL_secure_zalloc API.
auto ptr = OPENSSL_malloc(len);
if (ptr == nullptr) return {};
memset(ptr, 0, len);
return DataPointer(ptr, len);
#endif
}
size_t DataPointer::GetSecureHeapUsed() {
#ifndef OPENSSL_IS_BORINGSSL
return CRYPTO_secure_malloc_initialized() ? CRYPTO_secure_used() : 0;
#else
// BoringSSL does not have the secure heap and therefore
// will always return 0.
return 0;
#endif
}
DataPointer::InitSecureHeapResult DataPointer::TryInitSecureHeap(size_t amount,
size_t min) {
#ifndef OPENSSL_IS_BORINGSSL
switch (CRYPTO_secure_malloc_init(amount, min)) {
case 0:
return InitSecureHeapResult::FAILED;
case 2:
return InitSecureHeapResult::UNABLE_TO_MEMORY_MAP;
case 1:
return InitSecureHeapResult::OK;
default:
return InitSecureHeapResult::FAILED;
}
#else
// BoringSSL does not actually support the secure heap
return InitSecureHeapResult::FAILED;
#endif
}
DataPointer DataPointer::Copy(const Buffer<const void>& buffer) {
return DataPointer(OPENSSL_memdup(buffer.data, buffer.len), buffer.len);
}
DataPointer::DataPointer(void* data, size_t length, bool secure)
: data_(data), len_(length), secure_(secure) {}
DataPointer::DataPointer(const Buffer<void>& buffer, bool secure)
: data_(buffer.data), len_(buffer.len), secure_(secure) {}
DataPointer::DataPointer(DataPointer&& other) noexcept
: data_(other.data_), len_(other.len_), secure_(other.secure_) {
other.data_ = nullptr;
other.len_ = 0;
other.secure_ = false;
}
DataPointer& DataPointer::operator=(DataPointer&& other) noexcept {
if (this == &other) return *this;
this->~DataPointer();
return *new (this) DataPointer(std::move(other));
}
DataPointer::~DataPointer() {
reset();
}
void DataPointer::zero() {
if (!data_) return;
OPENSSL_cleanse(data_, len_);
}
void DataPointer::reset(void* data, size_t length) {
if (data_ != nullptr) {
if (secure_) {
OPENSSL_secure_clear_free(data_, len_);
} else {
OPENSSL_clear_free(data_, len_);
}
}
data_ = data;
len_ = length;
}
void DataPointer::reset(const Buffer<void>& buffer) {
reset(buffer.data, buffer.len);
}
Buffer<void> DataPointer::release() {
Buffer<void> buf{
.data = data_,
.len = len_,
};
data_ = nullptr;
len_ = 0;
return buf;
}
DataPointer DataPointer::resize(size_t len) {
size_t actual_len = std::min(len_, len);
auto buf = release();
if (actual_len == len_) return DataPointer(buf.data, actual_len);
buf.data = OPENSSL_realloc(buf.data, actual_len);
buf.len = actual_len;
return DataPointer(buf);
}
// ============================================================================
bool isFipsEnabled() {
ClearErrorOnReturn clear_error_on_return;
#if OPENSSL_VERSION_MAJOR >= 3
return EVP_default_properties_is_fips_enabled(nullptr) == 1;
#else
return FIPS_mode() == 1;
#endif
}
bool setFipsEnabled(bool enable, CryptoErrorList* errors) {
if (isFipsEnabled() == enable) return true;
ClearErrorOnReturn clearErrorOnReturn(errors);
#if OPENSSL_VERSION_MAJOR >= 3
return EVP_default_properties_enable_fips(nullptr, enable ? 1 : 0) == 1 &&
EVP_default_properties_is_fips_enabled(nullptr);
#else
return FIPS_mode_set(enable ? 1 : 0) == 1;
#endif
}
bool testFipsEnabled() {
ClearErrorOnReturn clear_error_on_return;
#if OPENSSL_VERSION_MAJOR >= 3
OSSL_PROVIDER* fips_provider = nullptr;
if (OSSL_PROVIDER_available(nullptr, "fips")) {
fips_provider = OSSL_PROVIDER_load(nullptr, "fips");
}
if (fips_provider == nullptr) return false;
int result = OSSL_PROVIDER_self_test(fips_provider);
OSSL_PROVIDER_unload(fips_provider);
return result;
#else
#ifdef OPENSSL_FIPS
return FIPS_selftest();
#else // OPENSSL_FIPS
return false;
#endif // OPENSSL_FIPS
#endif
}
// ============================================================================
// Bignum
BignumPointer::BignumPointer(BIGNUM* bignum) : bn_(bignum) {}
BignumPointer::BignumPointer(const unsigned char* data, size_t len)
: BignumPointer(BN_bin2bn(data, len, nullptr)) {}
BignumPointer::BignumPointer(BignumPointer&& other) noexcept
: bn_(other.release()) {}
BignumPointer BignumPointer::New() {
return BignumPointer(BN_new());
}
BignumPointer BignumPointer::NewSecure() {
#ifdef OPENSSL_IS_BORINGSSL
// Boringssl does not implement BN_secure_new.
return New();
#else
return BignumPointer(BN_secure_new());
#endif
}
BignumPointer& BignumPointer::operator=(BignumPointer&& other) noexcept {
if (this == &other) return *this;
this->~BignumPointer();
return *new (this) BignumPointer(std::move(other));
}
BignumPointer::~BignumPointer() {
reset();
}
void BignumPointer::reset(BIGNUM* bn) {
bn_.reset(bn);
}
void BignumPointer::reset(const unsigned char* data, size_t len) {
reset(BN_bin2bn(data, len, nullptr));
}
BIGNUM* BignumPointer::release() {
return bn_.release();
}
size_t BignumPointer::byteLength() const {
if (bn_ == nullptr) return 0;
return BN_num_bytes(bn_.get());
}
DataPointer BignumPointer::encode() const {
return EncodePadded(bn_.get(), byteLength());
}
DataPointer BignumPointer::encodePadded(size_t size) const {
return EncodePadded(bn_.get(), size);
}
size_t BignumPointer::encodeInto(unsigned char* out) const {
if (!bn_) return 0;
return BN_bn2bin(bn_.get(), out);
}
size_t BignumPointer::encodePaddedInto(unsigned char* out, size_t size) const {
if (!bn_) return 0;
return BN_bn2binpad(bn_.get(), out, size);
}
DataPointer BignumPointer::Encode(const BIGNUM* bn) {
return EncodePadded(bn, bn != nullptr ? BN_num_bytes(bn) : 0);
}
bool BignumPointer::setWord(unsigned long w) { // NOLINT(runtime/int)
if (!bn_) return false;
return BN_set_word(bn_.get(), w) == 1;
}
unsigned long BignumPointer::GetWord(const BIGNUM* bn) { // NOLINT(runtime/int)
return BN_get_word(bn);
}
unsigned long BignumPointer::getWord() const { // NOLINT(runtime/int)
if (!bn_) return 0;
return GetWord(bn_.get());
}
DataPointer BignumPointer::EncodePadded(const BIGNUM* bn, size_t s) {
if (bn == nullptr) return DataPointer();
size_t size = std::max(s, static_cast<size_t>(GetByteCount(bn)));
auto buf = DataPointer::Alloc(size);
BN_bn2binpad(bn, reinterpret_cast<unsigned char*>(buf.get()), size);
return buf;
}
size_t BignumPointer::EncodePaddedInto(const BIGNUM* bn,
unsigned char* out,
size_t size) {
if (bn == nullptr) return 0;
return BN_bn2binpad(bn, out, size);
}
int BignumPointer::operator<=>(const BignumPointer& other) const noexcept {
if (bn_ == nullptr && other.bn_ != nullptr) return -1;
if (bn_ != nullptr && other.bn_ == nullptr) return 1;
if (bn_ == nullptr && other.bn_ == nullptr) return 0;
return BN_cmp(bn_.get(), other.bn_.get());
}
int BignumPointer::operator<=>(const BIGNUM* other) const noexcept {
if (bn_ == nullptr && other != nullptr) return -1;
if (bn_ != nullptr && other == nullptr) return 1;
if (bn_ == nullptr && other == nullptr) return 0;
return BN_cmp(bn_.get(), other);
}
DataPointer BignumPointer::toHex() const {
if (!bn_) return {};
char* hex = BN_bn2hex(bn_.get());
if (!hex) return {};
return DataPointer(hex, strlen(hex));
}
int BignumPointer::GetBitCount(const BIGNUM* bn) {
return BN_num_bits(bn);
}
int BignumPointer::GetByteCount(const BIGNUM* bn) {
return BN_num_bytes(bn);
}
bool BignumPointer::isZero() const {
return bn_ && BN_is_zero(bn_.get());
}
bool BignumPointer::isOne() const {
return bn_ && BN_is_one(bn_.get());
}
const BIGNUM* BignumPointer::One() {
return BN_value_one();
}
BignumPointer BignumPointer::clone() {
if (!bn_) return {};
return BignumPointer(BN_dup(bn_.get()));
}
int BignumPointer::isPrime(int nchecks,
BignumPointer::PrimeCheckCallback innerCb) const {
BignumCtxPointer ctx(BN_CTX_new());
BignumGenCallbackPointer cb(nullptr);
if (innerCb != nullptr) {
cb = BignumGenCallbackPointer(BN_GENCB_new());
if (!cb) [[unlikely]]
return -1;
BN_GENCB_set(
cb.get(),
// TODO(@jasnell): This could be refactored to allow inlining.
// Not too important right now tho.
[](int a, int b, BN_GENCB* ctx) mutable -> int {
PrimeCheckCallback& ptr =
*static_cast<PrimeCheckCallback*>(BN_GENCB_get_arg(ctx));
return ptr(a, b) ? 1 : 0;
},
&innerCb);
}
return BN_is_prime_ex(get(), nchecks, ctx.get(), cb.get());
}
BignumPointer BignumPointer::NewPrime(const PrimeConfig& params,
PrimeCheckCallback cb) {
BignumPointer prime(BN_new());
if (!prime || !prime.generate(params, std::move(cb))) {
return {};
}
return prime;
}
bool BignumPointer::generate(const PrimeConfig& params,
PrimeCheckCallback innerCb) const {
// BN_generate_prime_ex() calls RAND_bytes_ex() internally.
// Make sure the CSPRNG is properly seeded.
std::ignore = CSPRNG(nullptr, 0);
BignumGenCallbackPointer cb(nullptr);
if (innerCb != nullptr) {
cb = BignumGenCallbackPointer(BN_GENCB_new());
if (!cb) [[unlikely]]
return -1;
BN_GENCB_set(
cb.get(),
[](int a, int b, BN_GENCB* ctx) mutable -> int {
PrimeCheckCallback& ptr =
*static_cast<PrimeCheckCallback*>(BN_GENCB_get_arg(ctx));
return ptr(a, b) ? 1 : 0;
},
&innerCb);
}
if (BN_generate_prime_ex(get(),
params.bits,
params.safe ? 1 : 0,
params.add.get(),
params.rem.get(),
cb.get()) == 0) {
return false;
}
return true;
}
BignumPointer BignumPointer::NewSub(const BignumPointer& a,
const BignumPointer& b) {
BignumPointer res = New();
if (!res) return {};
if (!BN_sub(res.get(), a.get(), b.get())) {
return {};
}
return res;
}
BignumPointer BignumPointer::NewLShift(size_t length) {
BignumPointer res = New();
if (!res) return {};
if (!BN_lshift(res.get(), One(), length)) {
return {};
}
return res;
}
// ============================================================================
// Utility methods
bool CSPRNG(void* buffer, size_t length) {
auto buf = reinterpret_cast<unsigned char*>(buffer);
do {
if (1 == RAND_status()) {
#if OPENSSL_VERSION_MAJOR >= 3
if (1 == RAND_bytes_ex(nullptr, buf, length, 0)) {
return true;
}
#else
while (length > INT_MAX && 1 == RAND_bytes(buf, INT_MAX)) {
buf += INT_MAX;
length -= INT_MAX;
}
if (length <= INT_MAX && 1 == RAND_bytes(buf, static_cast<int>(length)))
return true;
#endif
}
#if OPENSSL_VERSION_MAJOR >= 3
const auto code = ERR_peek_last_error();
// A misconfigured OpenSSL 3 installation may report 1 from RAND_poll()
// and RAND_status() but fail in RAND_bytes() if it cannot look up
// a matching algorithm for the CSPRNG.
if (ERR_GET_LIB(code) == ERR_LIB_RAND) {
const auto reason = ERR_GET_REASON(code);
if (reason == RAND_R_ERROR_INSTANTIATING_DRBG ||
reason == RAND_R_UNABLE_TO_FETCH_DRBG ||
reason == RAND_R_UNABLE_TO_CREATE_DRBG) {
return false;
}
}
#endif
} while (1 == RAND_poll());
return false;
}
int NoPasswordCallback(char* buf, int size, int rwflag, void* u) {
return 0;
}
int PasswordCallback(char* buf, int size, int rwflag, void* u) {
auto passphrase = static_cast<const Buffer<char>*>(u);
if (passphrase != nullptr) {
size_t buflen = static_cast<size_t>(size);
size_t len = passphrase->len;
if (buflen < len) return -1;
memcpy(buf, reinterpret_cast<const char*>(passphrase->data), len);
return len;
}
return -1;
}
// Algorithm: http://howardhinnant.github.io/date_algorithms.html
constexpr int days_from_epoch(int y, unsigned m, unsigned d) {
y -= m <= 2;
const int era = (y >= 0 ? y : y - 399) / 400;
const unsigned yoe = static_cast<unsigned>(y - era * 400); // [0, 399]
const unsigned doy =
(153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; // [0, 365]
const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
return era * 146097 + static_cast<int>(doe) - 719468;
}
#ifndef OPENSSL_IS_BORINGSSL
// tm must be in UTC
// using time_t causes problems on 32-bit systems and windows x64.
int64_t PortableTimeGM(struct tm* t) {
int year = t->tm_year + 1900;
int month = t->tm_mon;
if (month > 11) {
year += month / 12;
month %= 12;
} else if (month < 0) {
int years_diff = (11 - month) / 12;
year -= years_diff;
month += 12 * years_diff;
}
int days_since_epoch = days_from_epoch(year, month + 1, t->tm_mday);
return 60 * (60 * (24LL * static_cast<int64_t>(days_since_epoch) +
t->tm_hour) +
t->tm_min) +
t->tm_sec;
}
#endif
// ============================================================================
// SPKAC
bool VerifySpkac(const char* input, size_t length) {
#ifdef OPENSSL_IS_BORINGSSL
// OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters,
// while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not.
// As such, we trim those characters here for compatibility.
//
// find_last_not_of can return npos, which is the maximum value of size_t.
// The + 1 will force a roll-ver to 0, which is the correct value. in that
// case.
length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1;
#endif
NetscapeSPKIPointer spki(NETSCAPE_SPKI_b64_decode(input, length));
if (!spki) return false;
EVPKeyPointer pkey(X509_PUBKEY_get(spki->spkac->pubkey));
return pkey ? NETSCAPE_SPKI_verify(spki.get(), pkey.get()) > 0 : false;
}
BIOPointer ExportPublicKey(const char* input, size_t length) {
BIOPointer bio(BIO_new(BIO_s_mem()));
if (!bio) return {};
#ifdef OPENSSL_IS_BORINGSSL
// OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters,
// while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not.
// As such, we trim those characters here for compatibility.
length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1;
#endif
NetscapeSPKIPointer spki(NETSCAPE_SPKI_b64_decode(input, length));
if (!spki) return {};
EVPKeyPointer pkey(NETSCAPE_SPKI_get_pubkey(spki.get()));
if (!pkey) return {};
if (PEM_write_bio_PUBKEY(bio.get(), pkey.get()) <= 0) return {};
return bio;
}
Buffer<char> ExportChallenge(const char* input, size_t length) {
#ifdef OPENSSL_IS_BORINGSSL
// OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters,
// while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not.
// As such, we trim those characters here for compatibility.
length = std::string_view(input, length).find_last_not_of(" \n\r\t") + 1;
#endif
NetscapeSPKIPointer sp(NETSCAPE_SPKI_b64_decode(input, length));
if (!sp) return {};
unsigned char* buf = nullptr;
int buf_size = ASN1_STRING_to_UTF8(&buf, sp->spkac->challenge);
if (buf_size >= 0) {
return {
.data = reinterpret_cast<char*>(buf),
.len = static_cast<size_t>(buf_size),
};
}
return {};
}
// ============================================================================
namespace {
enum class AltNameOption {
NONE,
UTF8,
};
bool IsSafeAltName(const char* name, size_t length, AltNameOption option) {
for (size_t i = 0; i < length; i++) {
char c = name[i];
switch (c) {
case '"':
case '\\':
// These mess with encoding rules.
// Fall through.
case ',':
// Commas make it impossible to split the list of subject alternative
// names unambiguously, which is why we have to escape.
// Fall through.
case '\'':
// Single quotes are unlikely to appear in any legitimate values, but
// they could be used to make a value look like it was escaped (i.e.,
// enclosed in single/double quotes).
return false;
default:
if (option == AltNameOption::UTF8) {
// In UTF8 strings, we require escaping for any ASCII control
// character, but NOT for non-ASCII characters. Note that all bytes of
// any code point that consists of more than a single byte have their
// MSB set.
if (static_cast<unsigned char>(c) < ' ' || c == '\x7f') {
return false;
}
} else {
// Check if the char is a control character or non-ASCII character.
// Note that char may or may not be a signed type. Regardless,
// non-ASCII values will always be outside of this range.
if (c < ' ' || c > '~') {
return false;
}
}
}
}
return true;
}
void PrintAltName(const BIOPointer& out,
const char* name,
size_t length,
AltNameOption option = AltNameOption::NONE,
const char* safe_prefix = nullptr) {
if (IsSafeAltName(name, length, option)) {
// For backward-compatibility, append "safe" names without any
// modifications.
if (safe_prefix != nullptr) {
BIO_printf(out.get(), "%s:", safe_prefix);
}
BIO_write(out.get(), name, length);
} else {
// If a name is not "safe", we cannot embed it without special
// encoding. This does not usually happen, but we don't want to hide
// it from the user either. We use JSON compatible escaping here.
BIO_write(out.get(), "\"", 1);
if (safe_prefix != nullptr) {
BIO_printf(out.get(), "%s:", safe_prefix);
}
for (size_t j = 0; j < length; j++) {
char c = static_cast<char>(name[j]);
if (c == '\\') {
BIO_write(out.get(), "\\\\", 2);
} else if (c == '"') {
BIO_write(out.get(), "\\\"", 2);
} else if ((c >= ' ' && c != ',' && c <= '~') ||
(option == AltNameOption::UTF8 && (c & 0x80))) {
// Note that the above condition explicitly excludes commas, which means
// that those are encoded as Unicode escape sequences in the "else"
// block. That is not strictly necessary, and Node.js itself would parse
// it correctly either way. We only do this to account for third-party
// code that might be splitting the string at commas (as Node.js itself
// used to do).
BIO_write(out.get(), &c, 1);
} else {
// Control character or non-ASCII character. We treat everything as
// Latin-1, which corresponds to the first 255 Unicode code points.
const char hex[] = "0123456789abcdef";
char u[] = {'\\', 'u', '0', '0', hex[(c & 0xf0) >> 4], hex[c & 0x0f]};
BIO_write(out.get(), u, sizeof(u));
}
}
BIO_write(out.get(), "\"", 1);
}
}
// This function emulates the behavior of i2v_GENERAL_NAME in a safer and less
// ambiguous way. "othername:" entries use the GENERAL_NAME_print format.
bool PrintGeneralName(const BIOPointer& out, const GENERAL_NAME* gen) {
if (gen->type == GEN_DNS) {
ASN1_IA5STRING* name = gen->d.dNSName;
BIO_write(out.get(), "DNS:", 4);
// Note that the preferred name syntax (see RFCs 5280 and 1034) with
// wildcards is a subset of what we consider "safe", so spec-compliant DNS
// names will never need to be escaped.
PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length);
} else if (gen->type == GEN_EMAIL) {
ASN1_IA5STRING* name = gen->d.rfc822Name;
BIO_write(out.get(), "email:", 6);
PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length);
} else if (gen->type == GEN_URI) {
ASN1_IA5STRING* name = gen->d.uniformResourceIdentifier;
BIO_write(out.get(), "URI:", 4);
// The set of "safe" names was designed to include just about any URI,
// with a few exceptions, most notably URIs that contains commas (see
// RFC 2396). In other words, most legitimate URIs will not require
// escaping.
PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length);
} else if (gen->type == GEN_DIRNAME) {
// Earlier versions of Node.js used X509_NAME_oneline to print the X509_NAME
// object. The format was non standard and should be avoided. The use of
// X509_NAME_oneline is discouraged by OpenSSL but was required for backward
// compatibility. Conveniently, X509_NAME_oneline produced ASCII and the
// output was unlikely to contains commas or other characters that would
// require escaping. However, it SHOULD NOT produce ASCII output since an
// RFC5280 AttributeValue may be a UTF8String.
// Newer versions of Node.js have since switched to X509_NAME_print_ex to
// produce a better format at the cost of backward compatibility. The new
// format may contain Unicode characters and it is likely to contain commas,
// which require escaping. Fortunately, the recently safeguarded function
// PrintAltName handles all of that safely.
BIO_printf(out.get(), "DirName:");
BIOPointer tmp(BIO_new(BIO_s_mem()));
NCRYPTO_ASSERT_TRUE(tmp);
if (X509_NAME_print_ex(
tmp.get(), gen->d.dirn, 0, kX509NameFlagsRFC2253WithinUtf8JSON) <
0) {
return false;
}
char* oline = nullptr;
long n_bytes = BIO_get_mem_data(tmp.get(), &oline); // NOLINT(runtime/int)
NCRYPTO_ASSERT_TRUE(n_bytes >= 0);
PrintAltName(out,
oline,
static_cast<size_t>(n_bytes),
ncrypto::AltNameOption::UTF8,
nullptr);
} else if (gen->type == GEN_IPADD) {
BIO_printf(out.get(), "IP Address:");
const ASN1_OCTET_STRING* ip = gen->d.ip;
const unsigned char* b = ip->data;
if (ip->length == 4) {
BIO_printf(out.get(), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]);
} else if (ip->length == 16) {
for (unsigned int j = 0; j < 8; j++) {
uint16_t pair = (b[2 * j] << 8) | b[2 * j + 1];
BIO_printf(out.get(), (j == 0) ? "%X" : ":%X", pair);
}
} else {
#if OPENSSL_VERSION_MAJOR >= 3
BIO_printf(out.get(), "<invalid length=%d>", ip->length);
#else
BIO_printf(out.get(), "<invalid>");
#endif
}
} else if (gen->type == GEN_RID) {
// Unlike OpenSSL's default implementation, never print the OID as text and
// instead always print its numeric representation.
char oline[256];
OBJ_obj2txt(oline, sizeof(oline), gen->d.rid, true);
BIO_printf(out.get(), "Registered ID:%s", oline);
} else if (gen->type == GEN_OTHERNAME) {
// The format that is used here is based on OpenSSL's implementation of
// GENERAL_NAME_print (as of OpenSSL 3.0.1). Earlier versions of Node.js
// instead produced the same format as i2v_GENERAL_NAME, which was somewhat
// awkward, especially when passed to translatePeerCertificate.
bool unicode = true;
const char* prefix = nullptr;
// OpenSSL 1.1.1 does not support othername in GENERAL_NAME_print and may
// not define these NIDs.
#if OPENSSL_VERSION_MAJOR >= 3
int nid = OBJ_obj2nid(gen->d.otherName->type_id);
switch (nid) {
case NID_id_on_SmtpUTF8Mailbox:
prefix = "SmtpUTF8Mailbox";
break;
case NID_XmppAddr:
prefix = "XmppAddr";
break;
case NID_SRVName:
prefix = "SRVName";
unicode = false;
break;
case NID_ms_upn:
prefix = "UPN";
break;
case NID_NAIRealm:
prefix = "NAIRealm";
break;
}
#endif // OPENSSL_VERSION_MAJOR >= 3
int val_type = gen->d.otherName->value->type;
if (prefix == nullptr || (unicode && val_type != V_ASN1_UTF8STRING) ||
(!unicode && val_type != V_ASN1_IA5STRING)) {
BIO_printf(out.get(), "othername:<unsupported>");
} else {
BIO_printf(out.get(), "othername:");
if (unicode) {
auto name = gen->d.otherName->value->value.utf8string;
PrintAltName(out,
reinterpret_cast<const char*>(name->data),
name->length,
AltNameOption::UTF8,
prefix);
} else {
auto name = gen->d.otherName->value->value.ia5string;
PrintAltName(out,
reinterpret_cast<const char*>(name->data),
name->length,
AltNameOption::NONE,
prefix);
}
}
} else if (gen->type == GEN_X400) {
// TODO(tniessen): this is what OpenSSL does, implement properly instead
BIO_printf(out.get(), "X400Name:<unsupported>");
} else if (gen->type == GEN_EDIPARTY) {
// TODO(tniessen): this is what OpenSSL does, implement properly instead
BIO_printf(out.get(), "EdiPartyName:<unsupported>");
} else {
// This is safe because X509V3_EXT_d2i would have returned nullptr in this
// case already.
unreachable();
}
return true;
}
} // namespace
bool SafeX509SubjectAltNamePrint(const BIOPointer& out, X509_EXTENSION* ext) {
auto ret = OBJ_obj2nid(X509_EXTENSION_get_object(ext));
if (ret != NID_subject_alt_name) return false;
GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
if (names == nullptr) return false;
bool ok = true;
for (OPENSSL_SIZE_T i = 0; i < sk_GENERAL_NAME_num(names); i++) {
GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
if (i != 0) BIO_write(out.get(), ", ", 2);
if (!(ok = ncrypto::PrintGeneralName(out, gen))) {
break;
}
}
sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
return ok;
}
bool SafeX509InfoAccessPrint(const BIOPointer& out, X509_EXTENSION* ext) {
auto ret = OBJ_obj2nid(X509_EXTENSION_get_object(ext));
if (ret != NID_info_access) return false;
AUTHORITY_INFO_ACCESS* descs =
static_cast<AUTHORITY_INFO_ACCESS*>(X509V3_EXT_d2i(ext));
if (descs == nullptr) return false;
bool ok = true;
for (OPENSSL_SIZE_T i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) {
ACCESS_DESCRIPTION* desc = sk_ACCESS_DESCRIPTION_value(descs, i);
if (i != 0) BIO_write(out.get(), "\n", 1);
char objtmp[80];
i2t_ASN1_OBJECT(objtmp, sizeof(objtmp), desc->method);
BIO_printf(out.get(), "%s - ", objtmp);
if (!(ok = ncrypto::PrintGeneralName(out, desc->location))) {
break;
}
}
sk_ACCESS_DESCRIPTION_pop_free(descs, ACCESS_DESCRIPTION_free);
#if OPENSSL_VERSION_MAJOR < 3
BIO_write(out.get(), "\n", 1);
#endif
return ok;
}
// ============================================================================
// X509Pointer
X509Pointer::X509Pointer(X509* x509) : cert_(x509) {}
X509Pointer::X509Pointer(X509Pointer&& other) noexcept
: cert_(other.release()) {}
X509Pointer& X509Pointer::operator=(X509Pointer&& other) noexcept {
if (this == &other) return *this;
this->~X509Pointer();
return *new (this) X509Pointer(std::move(other));
}
X509Pointer::~X509Pointer() {
reset();
}
void X509Pointer::reset(X509* x509) {
cert_.reset(x509);
}
X509* X509Pointer::release() {
return cert_.release();
}
X509View X509Pointer::view() const {
return X509View(cert_.get());
}
BIOPointer X509View::toPEM() const {
ClearErrorOnReturn clearErrorOnReturn;
if (cert_ == nullptr) return {};
BIOPointer bio(BIO_new(BIO_s_mem()));
if (!bio) return {};