-
Notifications
You must be signed in to change notification settings - Fork 29.7k
/
crypto_common.cc
1479 lines (1301 loc) Β· 46.4 KB
/
crypto_common.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
#include "allocated_buffer-inl.h"
#include "base_object-inl.h"
#include "env-inl.h"
#include "node_buffer.h"
#include "node_crypto.h"
#include "crypto/crypto_common.h"
#include "node.h"
#include "node_internals.h"
#include "node_url.h"
#include "string_bytes.h"
#include "memory_tracker-inl.h"
#include "v8.h"
#include <openssl/ec.h>
#include <openssl/ecdh.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/x509v3.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <openssl/pkcs12.h>
#include <string>
#include <unordered_map>
namespace node {
using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BackingStore;
using v8::Context;
using v8::EscapableHandleScope;
using v8::Integer;
using v8::Local;
using v8::MaybeLocal;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Undefined;
using v8::Value;
namespace crypto {
static constexpr int kX509NameFlagsMultiline =
ASN1_STRFLGS_ESC_2253 |
ASN1_STRFLGS_ESC_CTRL |
ASN1_STRFLGS_UTF8_CONVERT |
XN_FLAG_SEP_MULTILINE |
XN_FLAG_FN_SN;
static constexpr int kX509NameFlagsRFC2253WithinUtf8JSON =
XN_FLAG_RFC2253 &
~ASN1_STRFLGS_ESC_MSB &
~ASN1_STRFLGS_ESC_CTRL;
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
X509_STORE* store = SSL_CTX_get_cert_store(ctx);
DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
X509_STORE_CTX_new());
return store_ctx.get() != nullptr &&
X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
X509_STORE_CTX_get1_issuer(issuer, store_ctx.get(), cert) == 1;
}
void LogSecret(
const SSLPointer& ssl,
const char* name,
const unsigned char* secret,
size_t secretlen) {
auto keylog_cb = SSL_CTX_get_keylog_callback(SSL_get_SSL_CTX(ssl.get()));
unsigned char crandom[32];
if (keylog_cb == nullptr ||
SSL_get_client_random(ssl.get(), crandom, 32) != 32) {
return;
}
std::string line = name;
line += " " + StringBytes::hex_encode(
reinterpret_cast<const char*>(crandom), 32);
line += " " + StringBytes::hex_encode(
reinterpret_cast<const char*>(secret), secretlen);
keylog_cb(ssl.get(), line.c_str());
}
bool SetALPN(const SSLPointer& ssl, const std::string& alpn) {
return SSL_set_alpn_protos(
ssl.get(),
reinterpret_cast<const uint8_t*>(alpn.c_str()),
alpn.length()) == 0;
}
bool SetALPN(const SSLPointer& ssl, Local<Value> alpn) {
if (!alpn->IsArrayBufferView())
return false;
ArrayBufferViewContents<unsigned char> protos(alpn.As<ArrayBufferView>());
return SSL_set_alpn_protos(ssl.get(), protos.data(), protos.length()) == 0;
}
MaybeLocal<Value> GetSSLOCSPResponse(
Environment* env,
SSL* ssl,
Local<Value> default_value) {
const unsigned char* resp;
int len = SSL_get_tlsext_status_ocsp_resp(ssl, &resp);
if (resp == nullptr)
return default_value;
Local<Value> ret;
MaybeLocal<Object> maybe_buffer =
Buffer::Copy(env, reinterpret_cast<const char*>(resp), len);
if (!maybe_buffer.ToLocal(&ret))
return MaybeLocal<Value>();
return ret;
}
bool SetTLSSession(
const SSLPointer& ssl,
const unsigned char* buf,
size_t length) {
SSLSessionPointer s(d2i_SSL_SESSION(nullptr, &buf, length));
return s == nullptr ? false : SetTLSSession(ssl, s);
}
bool SetTLSSession(
const SSLPointer& ssl,
const SSLSessionPointer& session) {
return session != nullptr && SSL_set_session(ssl.get(), session.get()) == 1;
}
SSLSessionPointer GetTLSSession(Local<Value> val) {
if (!val->IsArrayBufferView())
return SSLSessionPointer();
ArrayBufferViewContents<unsigned char> sbuf(val.As<ArrayBufferView>());
return GetTLSSession(sbuf.data(), sbuf.length());
}
SSLSessionPointer GetTLSSession(const unsigned char* buf, size_t length) {
return SSLSessionPointer(d2i_SSL_SESSION(nullptr, &buf, length));
}
long VerifyPeerCertificate( // NOLINT(runtime/int)
const SSLPointer& ssl,
long def) { // NOLINT(runtime/int)
long err = def; // NOLINT(runtime/int)
if (X509* peer_cert = SSL_get_peer_certificate(ssl.get())) {
X509_free(peer_cert);
err = SSL_get_verify_result(ssl.get());
} else {
const SSL_CIPHER* curr_cipher = SSL_get_current_cipher(ssl.get());
const SSL_SESSION* sess = SSL_get_session(ssl.get());
// Allow no-cert for PSK authentication in TLS1.2 and lower.
// In TLS1.3 check that session was reused because TLS1.3 PSK
// looks like session resumption.
if (SSL_CIPHER_get_auth_nid(curr_cipher) == NID_auth_psk ||
(SSL_SESSION_get_protocol_version(sess) == TLS1_3_VERSION &&
SSL_session_reused(ssl.get()))) {
return X509_V_OK;
}
}
return err;
}
int UseSNIContext(const SSLPointer& ssl, BaseObjectPtr<SecureContext> context) {
SSL_CTX* ctx = context->ctx_.get();
X509* x509 = SSL_CTX_get0_certificate(ctx);
EVP_PKEY* pkey = SSL_CTX_get0_privatekey(ctx);
STACK_OF(X509)* chain;
int err = SSL_CTX_get0_chain_certs(ctx, &chain);
if (err == 1) err = SSL_use_certificate(ssl.get(), x509);
if (err == 1) err = SSL_use_PrivateKey(ssl.get(), pkey);
if (err == 1 && chain != nullptr) err = SSL_set1_chain(ssl.get(), chain);
return err;
}
const char* GetClientHelloALPN(const SSLPointer& ssl) {
const unsigned char* buf;
size_t len;
size_t rem;
if (!SSL_client_hello_get0_ext(
ssl.get(),
TLSEXT_TYPE_application_layer_protocol_negotiation,
&buf,
&rem) ||
rem < 2) {
return nullptr;
}
len = (buf[0] << 8) | buf[1];
if (len + 2 != rem) return nullptr;
return reinterpret_cast<const char*>(buf + 3);
}
const char* GetClientHelloServerName(const SSLPointer& ssl) {
const unsigned char* buf;
size_t len;
size_t rem;
if (!SSL_client_hello_get0_ext(
ssl.get(),
TLSEXT_TYPE_server_name,
&buf,
&rem) || rem <= 2) {
return nullptr;
}
len = (*buf << 8) | *(buf + 1);
if (len + 2 != rem)
return nullptr;
rem = len;
if (rem == 0 || *(buf + 2) != TLSEXT_NAMETYPE_host_name) return nullptr;
rem--;
if (rem <= 2)
return nullptr;
len = (*(buf + 3) << 8) | *(buf + 4);
if (len + 2 > rem)
return nullptr;
return reinterpret_cast<const char*>(buf + 5);
}
const char* GetServerName(SSL* ssl) {
return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
}
bool SetGroups(SecureContext* sc, const char* groups) {
return SSL_CTX_set1_groups_list(**sc, groups) == 1;
}
const char* X509ErrorCode(long err) { // NOLINT(runtime/int)
const char* code = "UNSPECIFIED";
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
switch (err) {
// if you modify anything in here, *please* update the respective section in
// doc/api/tls.md as well
CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
CASE_X509_ERR(UNABLE_TO_GET_CRL)
CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
CASE_X509_ERR(CERT_NOT_YET_VALID)
CASE_X509_ERR(CERT_HAS_EXPIRED)
CASE_X509_ERR(CRL_NOT_YET_VALID)
CASE_X509_ERR(CRL_HAS_EXPIRED)
CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
CASE_X509_ERR(OUT_OF_MEM)
CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
CASE_X509_ERR(CERT_REVOKED)
CASE_X509_ERR(INVALID_CA)
CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
CASE_X509_ERR(INVALID_PURPOSE)
CASE_X509_ERR(CERT_UNTRUSTED)
CASE_X509_ERR(CERT_REJECTED)
CASE_X509_ERR(HOSTNAME_MISMATCH)
}
#undef CASE_X509_ERR
return code;
}
MaybeLocal<Value> GetValidationErrorReason(Environment* env, int err) {
if (err == 0)
return Undefined(env->isolate());
const char* reason = X509_verify_cert_error_string(err);
return OneByteString(env->isolate(), reason);
}
MaybeLocal<Value> GetValidationErrorCode(Environment* env, int err) {
if (err == 0)
return Undefined(env->isolate());
return OneByteString(env->isolate(), X509ErrorCode(err));
}
MaybeLocal<Value> GetCert(Environment* env, const SSLPointer& ssl) {
ClearErrorOnReturn clear_error_on_return;
X509* cert = SSL_get_certificate(ssl.get());
if (cert == nullptr)
return Undefined(env->isolate());
MaybeLocal<Object> maybe_cert = X509ToObject(env, cert);
return maybe_cert.FromMaybe<Value>(Local<Value>());
}
Local<Value> ToV8Value(Environment* env, const BIOPointer& bio) {
BUF_MEM* mem;
BIO_get_mem_ptr(bio.get(), &mem);
MaybeLocal<String> ret =
String::NewFromUtf8(
env->isolate(),
mem->data,
NewStringType::kNormal,
mem->length);
USE(BIO_reset(bio.get()));
return ret.FromMaybe(Local<Value>());
}
namespace {
template <typename T>
bool Set(
Local<Context> context,
Local<Object> target,
Local<Value> name,
MaybeLocal<T> maybe_value) {
Local<Value> value;
if (!maybe_value.ToLocal(&value))
return false;
// Undefined is ignored, but still considered successful
if (value->IsUndefined())
return true;
return !target->Set(context, name, value).IsNothing();
}
MaybeLocal<Value> GetCipherValue(Environment* env,
const SSL_CIPHER* cipher,
const char* (*getstr)(const SSL_CIPHER* cipher)) {
if (cipher == nullptr)
return Undefined(env->isolate());
return OneByteString(env->isolate(), getstr(cipher));
}
MaybeLocal<Value> GetCipherName(Environment* env, const SSL_CIPHER* cipher) {
return GetCipherValue(env, cipher, SSL_CIPHER_get_name);
}
MaybeLocal<Value> GetCipherStandardName(
Environment* env,
const SSL_CIPHER* cipher) {
return GetCipherValue(env, cipher, SSL_CIPHER_standard_name);
}
MaybeLocal<Value> GetCipherVersion(Environment* env, const SSL_CIPHER* cipher) {
return GetCipherValue(env, cipher, SSL_CIPHER_get_version);
}
StackOfX509 CloneSSLCerts(X509Pointer&& cert,
const STACK_OF(X509)* const ssl_certs) {
StackOfX509 peer_certs(sk_X509_new(nullptr));
if (cert)
sk_X509_push(peer_certs.get(), cert.release());
for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
return StackOfX509();
// `cert` is now managed by the stack.
cert.release();
}
return peer_certs;
}
MaybeLocal<Object> AddIssuerChainToObject(
X509Pointer* cert,
Local<Object> object,
StackOfX509&& peer_certs,
Environment* const env) {
Local<Context> context = env->isolate()->GetCurrentContext();
cert->reset(sk_X509_delete(peer_certs.get(), 0));
for (;;) {
int i;
for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
X509* ca = sk_X509_value(peer_certs.get(), i);
if (X509_check_issued(ca, cert->get()) != X509_V_OK)
continue;
Local<Object> ca_info;
MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
if (!maybe_ca_info.ToLocal(&ca_info))
return MaybeLocal<Object>();
if (!Set<Object>(context, object, env->issuercert_string(), ca_info))
return MaybeLocal<Object>();
object = ca_info;
// NOTE: Intentionally freeing cert that is not used anymore.
// Delete cert and continue aggregating issuers.
cert->reset(sk_X509_delete(peer_certs.get(), i));
break;
}
// Issuer not found, break out of the loop.
if (i == sk_X509_num(peer_certs.get()))
break;
}
return MaybeLocal<Object>(object);
}
MaybeLocal<Object> GetLastIssuedCert(
X509Pointer* cert,
const SSLPointer& ssl,
Local<Object> issuer_chain,
Environment* const env) {
Local<Context> context = env->isolate()->GetCurrentContext();
while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
X509* ca;
if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
break;
Local<Object> ca_info;
MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
if (!maybe_ca_info.ToLocal(&ca_info))
return MaybeLocal<Object>();
if (!Set<Object>(context, issuer_chain, env->issuercert_string(), ca_info))
return MaybeLocal<Object>();
issuer_chain = ca_info;
// Take the value of cert->get() before the call to cert->reset()
// in order to compare it to ca after and provide a way to exit this loop
// in case it gets stuck.
X509* value_before_reset = cert->get();
// Delete previous cert and continue aggregating issuers.
cert->reset(ca);
if (value_before_reset == ca)
break;
}
return MaybeLocal<Object>(issuer_chain);
}
void AddFingerprintDigest(
const unsigned char* md,
unsigned int md_size,
char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) {
unsigned int i;
const char hex[] = "0123456789ABCDEF";
for (i = 0; i < md_size; i++) {
(*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4];
(*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)];
(*fingerprint)[(3*i)+2] = ':';
}
if (md_size > 0) {
(*fingerprint)[(3*(md_size-1))+2] = '\0';
} else {
(*fingerprint)[0] = '\0';
}
}
MaybeLocal<Value> GetCurveASN1Name(Environment* env, const int nid) {
const char* nist = OBJ_nid2sn(nid);
return nist != nullptr ?
MaybeLocal<Value>(OneByteString(env->isolate(), nist)) :
MaybeLocal<Value>(Undefined(env->isolate()));
}
MaybeLocal<Value> GetCurveNistName(Environment* env, const int nid) {
const char* nist = EC_curve_nid2nist(nid);
return nist != nullptr ?
MaybeLocal<Value>(OneByteString(env->isolate(), nist)) :
MaybeLocal<Value>(Undefined(env->isolate()));
}
MaybeLocal<Value> GetECPubKey(
Environment* env,
const EC_GROUP* group,
const ECPointer& ec) {
const EC_POINT* pubkey = EC_KEY_get0_public_key(ec.get());
if (pubkey == nullptr)
return Undefined(env->isolate());
return ECPointToBuffer(
env,
group,
pubkey,
EC_KEY_get_conv_form(ec.get()),
nullptr).FromMaybe(Local<Object>());
}
MaybeLocal<Value> GetECGroup(
Environment* env,
const EC_GROUP* group,
const ECPointer& ec) {
if (group == nullptr)
return Undefined(env->isolate());
int bits = EC_GROUP_order_bits(group);
if (bits <= 0)
return Undefined(env->isolate());
return Integer::New(env->isolate(), bits);
}
MaybeLocal<Object> GetPubKey(Environment* env, const RSAPointer& rsa) {
int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
CHECK_GE(size, 0);
std::unique_ptr<BackingStore> bs;
{
NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
bs = ArrayBuffer::NewBackingStore(env->isolate(), size);
}
unsigned char* serialized = reinterpret_cast<unsigned char*>(bs->Data());
CHECK_GE(i2d_RSA_PUBKEY(rsa.get(), &serialized), 0);
Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Object>());
}
MaybeLocal<Value> GetExponentString(
Environment* env,
const BIOPointer& bio,
const BIGNUM* e) {
uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
uint32_t lo = static_cast<uint32_t>(exponent_word);
uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
if (hi == 0)
BIO_printf(bio.get(), "0x%x", lo);
else
BIO_printf(bio.get(), "0x%x%08x", hi, lo);
return ToV8Value(env, bio);
}
Local<Value> GetBits(Environment* env, const BIGNUM* n) {
return Integer::New(env->isolate(), BN_num_bits(n));
}
MaybeLocal<Value> GetModulusString(
Environment* env,
const BIOPointer& bio,
const BIGNUM* n) {
BN_print(bio.get(), n);
return ToV8Value(env, bio);
}
} // namespace
MaybeLocal<Object> GetRawDERCertificate(Environment* env, X509* cert) {
int size = i2d_X509(cert, nullptr);
std::unique_ptr<BackingStore> bs;
{
NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
bs = ArrayBuffer::NewBackingStore(env->isolate(), size);
}
unsigned char* serialized = reinterpret_cast<unsigned char*>(bs->Data());
CHECK_GE(i2d_X509(cert, &serialized), 0);
Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Object>());
}
MaybeLocal<Value> GetSerialNumber(Environment* env, X509* cert) {
if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
if (bn) {
char* data = BN_bn2hex(bn.get());
ByteSource buf = ByteSource::Allocated(data, strlen(data));
if (buf)
return OneByteString(env->isolate(), buf.get());
}
}
return Undefined(env->isolate());
}
MaybeLocal<Value> GetKeyUsage(Environment* env, X509* cert) {
StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
if (eku) {
const int count = sk_ASN1_OBJECT_num(eku.get());
MaybeStackBuffer<Local<Value>, 16> ext_key_usage(count);
char buf[256];
int j = 0;
for (int i = 0; i < count; i++) {
if (OBJ_obj2txt(buf,
sizeof(buf),
sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
ext_key_usage[j++] = OneByteString(env->isolate(), buf);
}
}
return Array::New(env->isolate(), ext_key_usage.out(), count);
}
return Undefined(env->isolate());
}
MaybeLocal<Value> GetFingerprintDigest(
Environment* env,
const EVP_MD* method,
X509* cert) {
unsigned char md[EVP_MAX_MD_SIZE];
unsigned int md_size;
char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
if (X509_digest(cert, method, md, &md_size)) {
AddFingerprintDigest(md, md_size, &fingerprint);
return OneByteString(env->isolate(), fingerprint);
}
return Undefined(env->isolate());
}
MaybeLocal<Value> GetValidTo(
Environment* env,
X509* cert,
const BIOPointer& bio) {
ASN1_TIME_print(bio.get(), X509_get0_notAfter(cert));
return ToV8Value(env, bio);
}
MaybeLocal<Value> GetValidFrom(
Environment* env,
X509* cert,
const BIOPointer& bio) {
ASN1_TIME_print(bio.get(), X509_get0_notBefore(cert));
return ToV8Value(env, bio);
}
static inline bool IsSafeAltName(const char* name, size_t length, bool utf8) {
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 (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;
}
static inline void PrintAltName(const BIOPointer& out, const char* name,
size_t length, bool utf8,
const char* safe_prefix) {
if (IsSafeAltName(name, length, utf8)) {
// 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 <= '~') || (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);
}
}
static inline void PrintLatin1AltName(const BIOPointer& out,
const ASN1_IA5STRING* name,
const char* safe_prefix = nullptr) {
PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length,
false, safe_prefix);
}
static inline void PrintUtf8AltName(const BIOPointer& out,
const ASN1_UTF8STRING* name,
const char* safe_prefix = nullptr) {
PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length,
true, safe_prefix);
}
// This function currently emulates the behavior of i2v_GENERAL_NAME in a safer
// and less ambiguous way.
// TODO(tniessen): gradually improve the format in the next major version(s)
static 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.
PrintLatin1AltName(out, name);
} else if (gen->type == GEN_EMAIL) {
ASN1_IA5STRING* name = gen->d.rfc822Name;
BIO_write(out.get(), "email:", 6);
PrintLatin1AltName(out, name);
} 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.
PrintLatin1AltName(out, name);
} 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()));
CHECK(tmp);
if (X509_NAME_print_ex(tmp.get(),
gen->d.dirn,
0,
kX509NameFlagsRFC2253WithinUtf8JSON) < 0) {
return false;
}
char* oline = nullptr;
size_t n_bytes = BIO_get_mem_data(tmp.get(), &oline);
CHECK_IMPLIES(n_bytes != 0, oline != nullptr);
PrintAltName(out, oline, n_bytes, true, 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) {
// TODO(tniessen): the format that is used here is based on OpenSSL's
// implementation of i2v_GENERAL_NAME (as of OpenSSL 3.0.1), mostly for
// backward compatibility. It is somewhat awkward, especially when passed to
// translatePeerCertificate, and should be changed in the future, probably
// to the format used by GENERAL_NAME_print (in a major release).
bool unicode = true;
const char* prefix = nullptr;
// OpenSSL 1.1.1 does not support othername in i2v_GENERAL_NAME 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) {
PrintUtf8AltName(out, gen->d.otherName->value->value.utf8string,
prefix);
} else {
PrintLatin1AltName(out, gen->d.otherName->value->value.ia5string,
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;
}
bool SafeX509SubjectAltNamePrint(const BIOPointer& out, X509_EXTENSION* ext) {
const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
CHECK(method == X509V3_EXT_get_nid(NID_subject_alt_name));
GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
if (names == nullptr)
return false;
bool ok = true;
for (int 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 = PrintGeneralName(out, gen))) {
break;
}
}
sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
return ok;
}
bool SafeX509InfoAccessPrint(const BIOPointer& out, X509_EXTENSION* ext) {
const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
CHECK(method == X509V3_EXT_get_nid(NID_info_access));
AUTHORITY_INFO_ACCESS* descs =
static_cast<AUTHORITY_INFO_ACCESS*>(X509V3_EXT_d2i(ext));
if (descs == nullptr)
return false;
bool ok = true;
for (int 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 = 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;
}
v8::MaybeLocal<v8::Value> GetSubjectAltNameString(
Environment* env,
const BIOPointer& bio,
X509* cert) {
int index = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (index < 0)
return Undefined(env->isolate());
X509_EXTENSION* ext = X509_get_ext(cert, index);
CHECK_NOT_NULL(ext);
if (!SafeX509SubjectAltNamePrint(bio, ext)) {
USE(BIO_reset(bio.get()));
return v8::Null(env->isolate());
}
return ToV8Value(env, bio);
}
v8::MaybeLocal<v8::Value> GetInfoAccessString(
Environment* env,
const BIOPointer& bio,
X509* cert) {
int index = X509_get_ext_by_NID(cert, NID_info_access, -1);
if (index < 0)
return Undefined(env->isolate());
X509_EXTENSION* ext = X509_get_ext(cert, index);
CHECK_NOT_NULL(ext);
if (!SafeX509InfoAccessPrint(bio, ext)) {
USE(BIO_reset(bio.get()));
return v8::Null(env->isolate());
}
return ToV8Value(env, bio);
}
MaybeLocal<Value> GetIssuerString(
Environment* env,
const BIOPointer& bio,
X509* cert) {
X509_NAME* issuer_name = X509_get_issuer_name(cert);
if (X509_NAME_print_ex(
bio.get(),
issuer_name,
0,
kX509NameFlagsMultiline) <= 0) {
USE(BIO_reset(bio.get()));
return Undefined(env->isolate());
}
return ToV8Value(env, bio);
}
MaybeLocal<Value> GetSubject(
Environment* env,
const BIOPointer& bio,
X509* cert) {
if (X509_NAME_print_ex(
bio.get(),
X509_get_subject_name(cert),
0,
kX509NameFlagsMultiline) <= 0) {
USE(BIO_reset(bio.get()));
return Undefined(env->isolate());
}
return ToV8Value(env, bio);
}
template <X509_NAME* get_name(const X509*)>
static MaybeLocal<Value> GetX509NameObject(Environment* env, X509* cert) {
X509_NAME* name = get_name(cert);
CHECK_NOT_NULL(name);
int cnt = X509_NAME_entry_count(name);
CHECK_GE(cnt, 0);
Local<Object> result =
Object::New(env->isolate(), Null(env->isolate()), nullptr, nullptr, 0);
if (result.IsEmpty()) {
return MaybeLocal<Value>();
}