-
Notifications
You must be signed in to change notification settings - Fork 30.5k
/
Copy pathcrypto_context.cc
1934 lines (1617 loc) Β· 62.8 KB
/
crypto_context.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 "crypto/crypto_context.h"
#include "base_object-inl.h"
#include "crypto/crypto_bio.h"
#include "crypto/crypto_common.h"
#include "crypto/crypto_util.h"
#include "env-inl.h"
#include "memory_tracker-inl.h"
#include "ncrypto.h"
#include "node.h"
#include "node_buffer.h"
#include "node_options.h"
#include "util.h"
#include "v8.h"
#include <openssl/x509.h>
#include <openssl/pkcs12.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif // !OPENSSL_NO_ENGINE
#ifdef __APPLE__
#include <Security/Security.h>
#endif
#ifdef _WIN32
#include <Windows.h>
#include <wincrypt.h>
#endif
namespace node {
using ncrypto::BignumPointer;
using ncrypto::BIOPointer;
using ncrypto::ClearErrorOnReturn;
using ncrypto::CryptoErrorList;
using ncrypto::DHPointer;
using ncrypto::EnginePointer;
using ncrypto::EVPKeyPointer;
using ncrypto::MarkPopErrorOnReturn;
using ncrypto::SSLPointer;
using ncrypto::StackOfX509;
using ncrypto::X509Pointer;
using ncrypto::X509View;
using v8::Array;
using v8::ArrayBufferView;
using v8::Boolean;
using v8::Context;
using v8::DontDelete;
using v8::Exception;
using v8::External;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Int32;
using v8::Integer;
using v8::Isolate;
using v8::JustVoid;
using v8::Local;
using v8::Maybe;
using v8::Nothing;
using v8::Object;
using v8::PropertyAttribute;
using v8::ReadOnly;
using v8::Signature;
using v8::String;
using v8::Value;
namespace crypto {
static const char* const root_certs[] = {
#include "node_root_certs.h" // NOLINT(build/include_order)
};
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
static std::string extra_root_certs_file; // NOLINT(runtime/string)
X509_STORE* GetOrCreateRootCertStore() {
// Guaranteed thread-safe by standard, just don't use -fno-threadsafe-statics.
static X509_STORE* store = NewRootCertStore();
return store;
}
// Takes a string or buffer and loads it into a BIO.
// Caller responsible for BIO_free_all-ing the returned object.
BIOPointer LoadBIO(Environment* env, Local<Value> v) {
if (v->IsString() || v->IsArrayBufferView()) {
auto bio = BIOPointer::NewSecMem();
if (!bio) return {};
ByteSource bsrc = ByteSource::FromStringOrBuffer(env, v);
if (bsrc.size() > INT_MAX) return {};
int written = BIOPointer::Write(
&bio, std::string_view(bsrc.data<char>(), bsrc.size()));
if (written < 0) return {};
if (static_cast<size_t>(written) != bsrc.size()) return {};
return bio;
}
return {};
}
namespace {
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
X509Pointer&& x,
STACK_OF(X509)* extra_certs,
X509Pointer* cert,
X509Pointer* issuer_) {
CHECK(!*issuer_);
CHECK(!*cert);
X509* issuer = nullptr;
int ret = SSL_CTX_use_certificate(ctx, x.get());
if (ret) {
// If we could set up our certificate, now proceed to
// the CA certificates.
SSL_CTX_clear_extra_chain_certs(ctx);
for (int i = 0; i < sk_X509_num(extra_certs); i++) {
X509* ca = sk_X509_value(extra_certs, i);
// NOTE: Increments reference count on `ca`
if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
ret = 0;
issuer = nullptr;
break;
}
// Note that we must not free r if it was successfully
// added to the chain (while we must free the main
// certificate, since its reference count is increased
// by SSL_CTX_use_certificate).
// Find issuer
if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
continue;
issuer = ca;
}
}
// Try getting issuer from a cert store
if (ret) {
if (issuer == nullptr) {
// TODO(tniessen): SSL_CTX_get_issuer does not allow the caller to
// distinguish between a failed operation and an empty result. Fix that
// and then handle the potential error properly here (set ret to 0).
*issuer_ = X509Pointer::IssuerFrom(ctx, x.view());
// NOTE: get_cert_store doesn't increment reference count,
// no need to free `store`
} else {
// Increment issuer reference count
issuer_->reset(X509_dup(issuer));
if (!*issuer_) {
ret = 0;
}
}
}
if (ret && x != nullptr) {
cert->reset(X509_dup(x.get()));
if (!*cert)
ret = 0;
}
return ret;
}
} // namespace
// Read a file that contains our certificate in "PEM" format,
// possibly followed by a sequence of CA certificates that should be
// sent to the peer in the Certificate message.
//
// Taken from OpenSSL - edited for style.
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
BIOPointer&& in,
X509Pointer* cert,
X509Pointer* issuer) {
// Just to ensure that `ERR_peek_last_error` below will return only errors
// that we are interested in
ERR_clear_error();
X509Pointer x(
PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
if (!x)
return 0;
unsigned long err = 0; // NOLINT(runtime/int)
StackOfX509 extra_certs(sk_X509_new_null());
if (!extra_certs)
return 0;
while (X509Pointer extra {PEM_read_bio_X509(in.get(),
nullptr,
NoPasswordCallback,
nullptr)}) {
if (sk_X509_push(extra_certs.get(), extra.get())) {
extra.release();
continue;
}
return 0;
}
// When the while loop ends, it's usually just EOF.
err = ERR_peek_last_error();
if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
ERR_clear_error();
} else {
// some real error
return 0;
}
return SSL_CTX_use_certificate_chain(ctx,
std::move(x),
extra_certs.get(),
cert,
issuer);
}
unsigned long LoadCertsFromFile( // NOLINT(runtime/int)
std::vector<X509*>* certs,
const char* file) {
MarkPopErrorOnReturn mark_pop_error_on_return;
auto bio = BIOPointer::NewFile(file, "r");
if (!bio) return ERR_get_error();
while (X509* x509 = PEM_read_bio_X509(
bio.get(), nullptr, NoPasswordCallback, nullptr)) {
certs->push_back(x509);
}
unsigned long err = ERR_peek_last_error(); // NOLINT(runtime/int)
// Ignore error if its EOF/no start line found.
if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
return 0;
} else {
return err;
}
}
// Indicates the trust status of a certificate.
enum class TrustStatus {
// Trust status is unknown / uninitialized.
UNKNOWN,
// Certificate inherits trust value from its issuer. If the certificate is the
// root of the chain, this implies distrust.
UNSPECIFIED,
// Certificate is a trust anchor.
TRUSTED,
// Certificate is blocked / explicitly distrusted.
DISTRUSTED
};
bool isSelfIssued(X509* cert) {
auto subject = X509_get_subject_name(cert);
auto issuer = X509_get_issuer_name(cert);
return X509_NAME_cmp(subject, issuer) == 0;
}
// TODO(joyeecheung): it is a bit excessive to do this X509 -> PEM -> X509
// dance when we could've just pass everything around in binary. Change the
// root_certs to be embedded as DER so that we can save the serialization
// and deserialization.
void X509VectorToPEMVector(const std::vector<X509Pointer>& src,
std::vector<std::string>* dest) {
for (size_t i = 0; i < src.size(); i++) {
X509View x509_view(src[i].get());
auto pem_bio = x509_view.toPEM();
if (!pem_bio) {
fprintf(stderr,
"Warning: converting system certificate to PEM format failed\n");
continue;
}
char* pem_data = nullptr;
auto pem_size = BIO_get_mem_data(pem_bio.get(), &pem_data);
if (pem_size <= 0 || !pem_data) {
fprintf(
stderr,
"Warning: cannot read PEM-encoded data from system certificate\n");
continue;
}
dest->emplace_back(pem_data, pem_size);
}
}
// The following code is loosely based on
// https://github.com/chromium/chromium/blob/54bd8e3/net/cert/internal/trust_store_mac.cc
// and
// https://github.com/chromium/chromium/blob/0192587/net/cert/internal/trust_store_win.cc
// Copyright 2015 The Chromium Authors
// Licensed under a BSD-style license
// See https://chromium.googlesource.com/chromium/src/+/HEAD/LICENSE for
// details.
#ifdef __APPLE__
TrustStatus IsTrustDictionaryTrustedForPolicy(CFDictionaryRef trust_dict,
bool is_self_issued) {
// Trust settings may be scoped to a single application
// skip as this is not supported
if (CFDictionaryContainsKey(trust_dict, kSecTrustSettingsApplication)) {
return TrustStatus::UNSPECIFIED;
}
// Trust settings may be scoped using policy-specific constraints. For
// example, SSL trust settings might be scoped to a single hostname, or EAP
// settings specific to a particular WiFi network.
// As this is not presently supported, skip any policy-specific trust
// settings.
if (CFDictionaryContainsKey(trust_dict, kSecTrustSettingsPolicyString)) {
return TrustStatus::UNSPECIFIED;
}
// If the trust settings are scoped to a specific policy (via
// kSecTrustSettingsPolicy), ensure that the policy is the same policy as
// |kSecPolicyAppleSSL|. If there is no kSecTrustSettingsPolicy key, it's
// considered a match for all policies.
if (CFDictionaryContainsKey(trust_dict, kSecTrustSettingsPolicy)) {
SecPolicyRef policy_ref = reinterpret_cast<SecPolicyRef>(const_cast<void*>(
CFDictionaryGetValue(trust_dict, kSecTrustSettingsPolicy)));
if (!policy_ref) {
return TrustStatus::UNSPECIFIED;
}
CFDictionaryRef policy_dict(SecPolicyCopyProperties(policy_ref));
// kSecPolicyOid is guaranteed to be present in the policy dictionary.
CFStringRef policy_oid = reinterpret_cast<CFStringRef>(
const_cast<void*>(CFDictionaryGetValue(policy_dict, kSecPolicyOid)));
if (!CFEqual(policy_oid, kSecPolicyAppleSSL)) {
return TrustStatus::UNSPECIFIED;
}
}
int trust_settings_result = kSecTrustSettingsResultTrustRoot;
if (CFDictionaryContainsKey(trust_dict, kSecTrustSettingsResult)) {
CFNumberRef trust_settings_result_ref =
reinterpret_cast<CFNumberRef>(const_cast<void*>(
CFDictionaryGetValue(trust_dict, kSecTrustSettingsResult)));
if (!trust_settings_result_ref ||
!CFNumberGetValue(trust_settings_result_ref,
kCFNumberIntType,
&trust_settings_result)) {
return TrustStatus::UNSPECIFIED;
}
if (trust_settings_result == kSecTrustSettingsResultDeny) {
return TrustStatus::DISTRUSTED;
}
// This is a bit of a hack: if the cert is self-issued allow either
// kSecTrustSettingsResultTrustRoot or kSecTrustSettingsResultTrustAsRoot on
// the basis that SecTrustSetTrustSettings should not allow creating an
// invalid trust record in the first place. (The spec is that
// kSecTrustSettingsResultTrustRoot can only be applied to root(self-signed)
// certs and kSecTrustSettingsResultTrustAsRoot is used for other certs.)
// This hack avoids having to check the signature on the cert which is slow
// if using the platform APIs, and may require supporting MD5 signature
// algorithms on some older OSX versions or locally added roots, which is
// undesirable in the built-in signature verifier.
if (is_self_issued) {
return trust_settings_result == kSecTrustSettingsResultTrustRoot ||
trust_settings_result == kSecTrustSettingsResultTrustAsRoot
? TrustStatus::TRUSTED
: TrustStatus::UNSPECIFIED;
}
// kSecTrustSettingsResultTrustAsRoot can only be applied to non-root certs.
return (trust_settings_result == kSecTrustSettingsResultTrustAsRoot)
? TrustStatus::TRUSTED
: TrustStatus::UNSPECIFIED;
}
return TrustStatus::UNSPECIFIED;
}
TrustStatus IsTrustSettingsTrustedForPolicy(CFArrayRef trust_settings,
bool is_self_issued) {
// The trust_settings parameter can return a valid but empty CFArrayRef.
// This empty trust-settings array means βalways trust this certificateβ
// with an overall trust setting for the certificate of
// kSecTrustSettingsResultTrustRoot
if (CFArrayGetCount(trust_settings) == 0) {
return is_self_issued ? TrustStatus::TRUSTED : TrustStatus::UNSPECIFIED;
}
for (CFIndex i = 0; i < CFArrayGetCount(trust_settings); ++i) {
CFDictionaryRef trust_dict = reinterpret_cast<CFDictionaryRef>(
const_cast<void*>(CFArrayGetValueAtIndex(trust_settings, i)));
TrustStatus trust =
IsTrustDictionaryTrustedForPolicy(trust_dict, is_self_issued);
if (trust == TrustStatus::DISTRUSTED || trust == TrustStatus::TRUSTED) {
return trust;
}
}
return TrustStatus::UNSPECIFIED;
}
bool IsCertificateTrustValid(SecCertificateRef ref) {
SecTrustRef sec_trust = nullptr;
CFMutableArrayRef subj_certs =
CFArrayCreateMutable(nullptr, 1, &kCFTypeArrayCallBacks);
CFArraySetValueAtIndex(subj_certs, 0, ref);
SecPolicyRef policy = SecPolicyCreateSSL(false, nullptr);
OSStatus ortn =
SecTrustCreateWithCertificates(subj_certs, policy, &sec_trust);
bool result = false;
if (ortn) {
/* should never happen */
} else {
result = SecTrustEvaluateWithError(sec_trust, nullptr);
}
if (policy) {
CFRelease(policy);
}
if (sec_trust) {
CFRelease(sec_trust);
}
if (subj_certs) {
CFRelease(subj_certs);
}
return result;
}
bool IsCertificateTrustedForPolicy(X509* cert, SecCertificateRef ref) {
OSStatus err;
bool trust_evaluated = false;
bool is_self_issued = isSelfIssued(cert);
// Evaluate user trust domain, then admin. User settings can override
// admin (and both override the system domain, but we don't check that).
for (const auto& trust_domain :
{kSecTrustSettingsDomainUser, kSecTrustSettingsDomainAdmin}) {
CFArrayRef trust_settings = nullptr;
err = SecTrustSettingsCopyTrustSettings(ref, trust_domain, &trust_settings);
if (err != errSecSuccess && err != errSecItemNotFound) {
fprintf(stderr,
"ERROR: failed to copy trust settings of system certificate%d\n",
err);
continue;
}
if (err == errSecSuccess && trust_settings != nullptr) {
TrustStatus result =
IsTrustSettingsTrustedForPolicy(trust_settings, is_self_issued);
if (result != TrustStatus::UNSPECIFIED) {
CFRelease(trust_settings);
return result == TrustStatus::TRUSTED;
}
}
// An empty trust settings array isnβt the same as no trust settings,
// where the trust_settings parameter returns NULL.
// No trust-settings array means
// βthis certificate must be verifiable using a known trusted certificateβ.
if (trust_settings == nullptr && !trust_evaluated) {
bool result = IsCertificateTrustValid(ref);
if (result) {
return true;
}
// no point re-evaluating this in the admin domain
trust_evaluated = true;
} else if (trust_settings) {
CFRelease(trust_settings);
}
}
return false;
}
void ReadMacOSKeychainCertificates(
std::vector<std::string>* system_root_certificates) {
CFTypeRef search_keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
CFTypeRef search_values[] = {
kSecClassCertificate, kSecMatchLimitAll, kCFBooleanTrue};
CFDictionaryRef search = CFDictionaryCreate(kCFAllocatorDefault,
search_keys,
search_values,
3,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFArrayRef curr_anchors = nullptr;
OSStatus ortn =
SecItemCopyMatching(search, reinterpret_cast<CFTypeRef*>(&curr_anchors));
CFRelease(search);
if (ortn) {
fprintf(stderr, "ERROR: SecItemCopyMatching failed %d\n", ortn);
}
CFIndex count = CFArrayGetCount(curr_anchors);
std::vector<X509Pointer> system_root_certificates_X509;
for (int i = 0; i < count; ++i) {
SecCertificateRef cert_ref = reinterpret_cast<SecCertificateRef>(
const_cast<void*>(CFArrayGetValueAtIndex(curr_anchors, i)));
CFDataRef der_data = SecCertificateCopyData(cert_ref);
if (!der_data) {
fprintf(stderr, "ERROR: SecCertificateCopyData failed\n");
continue;
}
auto data_buffer_pointer = CFDataGetBytePtr(der_data);
X509* cert =
d2i_X509(nullptr, &data_buffer_pointer, CFDataGetLength(der_data));
CFRelease(der_data);
bool is_valid = IsCertificateTrustedForPolicy(cert, cert_ref);
if (is_valid) {
system_root_certificates_X509.emplace_back(cert);
}
}
CFRelease(curr_anchors);
X509VectorToPEMVector(system_root_certificates_X509,
system_root_certificates);
}
#endif // __APPLE__
#ifdef _WIN32
// Returns true if the cert can be used for server authentication, based on
// certificate properties.
//
// While there are a variety of certificate properties that can affect how
// trust is computed, the main property is CERT_ENHKEY_USAGE_PROP_ID, which
// is intersected with the certificate's EKU extension (if present).
// The intersection is documented in the Remarks section of
// CertGetEnhancedKeyUsage, and is as follows:
// - No EKU property, and no EKU extension = Trusted for all purpose
// - Either an EKU property, or EKU extension, but not both = Trusted only
// for the listed purposes
// - Both an EKU property and an EKU extension = Trusted for the set
// intersection of the listed purposes
// CertGetEnhancedKeyUsage handles this logic, and if an empty set is
// returned, the distinction between the first and third case can be
// determined by GetLastError() returning CRYPT_E_NOT_FOUND.
//
// See:
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certgetenhancedkeyusage
//
// If we run into any errors reading the certificate properties, we fail
// closed.
bool IsCertTrustedForServerAuth(PCCERT_CONTEXT cert) {
DWORD usage_size = 0;
if (!CertGetEnhancedKeyUsage(cert, 0, nullptr, &usage_size)) {
return false;
}
std::vector<BYTE> usage_bytes(usage_size);
CERT_ENHKEY_USAGE* usage =
reinterpret_cast<CERT_ENHKEY_USAGE*>(usage_bytes.data());
if (!CertGetEnhancedKeyUsage(cert, 0, usage, &usage_size)) {
return false;
}
if (usage->cUsageIdentifier == 0) {
// check GetLastError
HRESULT error_code = GetLastError();
switch (error_code) {
case CRYPT_E_NOT_FOUND:
return true;
case S_OK:
return false;
default:
return false;
}
}
// SAFETY: `usage->rgpszUsageIdentifier` is an array of LPSTR (pointer to null
// terminated string) of length `usage->cUsageIdentifier`.
for (DWORD i = 0; i < usage->cUsageIdentifier; ++i) {
std::string_view eku(usage->rgpszUsageIdentifier[i]);
if ((eku == szOID_PKIX_KP_SERVER_AUTH) ||
(eku == szOID_ANY_ENHANCED_KEY_USAGE)) {
return true;
}
}
return false;
}
void GatherCertsForLocation(std::vector<X509Pointer>* vector,
DWORD location,
LPCWSTR store_name) {
if (!(location == CERT_SYSTEM_STORE_LOCAL_MACHINE ||
location == CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY ||
location == CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE ||
location == CERT_SYSTEM_STORE_CURRENT_USER ||
location == CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY)) {
return;
}
DWORD flags =
location | CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG;
HCERTSTORE opened_store(
CertOpenStore(CERT_STORE_PROV_SYSTEM,
0,
// The Windows API only accepts NULL for hCryptProv.
NULL, /* NOLINT (readability/null_usage) */
flags,
store_name));
if (!opened_store) {
return;
}
auto cleanup = OnScopeLeave(
[opened_store]() { CHECK_EQ(CertCloseStore(opened_store, 0), TRUE); });
PCCERT_CONTEXT cert_from_store = nullptr;
while ((cert_from_store = CertEnumCertificatesInStore(
opened_store, cert_from_store)) != nullptr) {
if (!IsCertTrustedForServerAuth(cert_from_store)) {
continue;
}
const unsigned char* cert_data =
reinterpret_cast<const unsigned char*>(cert_from_store->pbCertEncoded);
const size_t cert_size = cert_from_store->cbCertEncoded;
vector->emplace_back(d2i_X509(nullptr, &cert_data, cert_size));
}
}
void ReadWindowsCertificates(
std::vector<std::string>* system_root_certificates) {
std::vector<X509Pointer> system_root_certificates_X509;
// TODO(joyeecheung): match Chromium's policy, collect more certificates
// from user-added CAs and support disallowed (revoked) certificates.
// Grab the user-added roots.
GatherCertsForLocation(
&system_root_certificates_X509, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"ROOT");
GatherCertsForLocation(&system_root_certificates_X509,
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
L"ROOT");
GatherCertsForLocation(&system_root_certificates_X509,
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
L"ROOT");
GatherCertsForLocation(
&system_root_certificates_X509, CERT_SYSTEM_STORE_CURRENT_USER, L"ROOT");
GatherCertsForLocation(&system_root_certificates_X509,
CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
L"ROOT");
// Grab the user-added trusted server certs. Trusted end-entity certs are
// only allowed for server auth in the "local machine" store, but not in the
// "current user" store.
GatherCertsForLocation(&system_root_certificates_X509,
CERT_SYSTEM_STORE_LOCAL_MACHINE,
L"TrustedPeople");
GatherCertsForLocation(&system_root_certificates_X509,
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
L"TrustedPeople");
GatherCertsForLocation(&system_root_certificates_X509,
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
L"TrustedPeople");
X509VectorToPEMVector(system_root_certificates_X509,
system_root_certificates);
}
#endif
void ReadSystemStoreCertificates(
std::vector<std::string>* system_root_certificates) {
#ifdef __APPLE__
ReadMacOSKeychainCertificates(system_root_certificates);
#endif
#ifdef _WIN32
ReadWindowsCertificates(system_root_certificates);
#endif
}
std::vector<std::string> getCombinedRootCertificates() {
std::vector<std::string> combined_root_certs;
for (size_t i = 0; i < arraysize(root_certs); i++) {
combined_root_certs.emplace_back(root_certs[i]);
}
if (per_process::cli_options->use_system_ca) {
ReadSystemStoreCertificates(&combined_root_certs);
}
return combined_root_certs;
}
X509_STORE* NewRootCertStore() {
static std::vector<X509*> root_certs_vector;
static bool root_certs_vector_loaded = false;
static Mutex root_certs_vector_mutex;
Mutex::ScopedLock lock(root_certs_vector_mutex);
if (!root_certs_vector_loaded) {
if (per_process::cli_options->ssl_openssl_cert_store == false) {
std::vector<std::string> combined_root_certs =
getCombinedRootCertificates();
for (size_t i = 0; i < combined_root_certs.size(); i++) {
X509* x509 =
PEM_read_bio_X509(NodeBIO::NewFixed(combined_root_certs[i].data(),
combined_root_certs[i].length())
.get(),
nullptr, // no re-use of X509 structure
NoPasswordCallback,
nullptr); // no callback data
// Parse errors from the built-in roots are fatal.
CHECK_NOT_NULL(x509);
root_certs_vector.push_back(x509);
}
}
if (!extra_root_certs_file.empty()) {
unsigned long err = LoadCertsFromFile( // NOLINT(runtime/int)
&root_certs_vector,
extra_root_certs_file.c_str());
if (err) {
char buf[256];
ERR_error_string_n(err, buf, sizeof(buf));
fprintf(stderr,
"Warning: Ignoring extra certs from `%s`, load failed: %s\n",
extra_root_certs_file.c_str(),
buf);
}
}
root_certs_vector_loaded = true;
}
X509_STORE* store = X509_STORE_new();
CHECK_NOT_NULL(store);
if (*system_cert_path != '\0') {
ERR_set_mark();
X509_STORE_load_locations(store, system_cert_path, nullptr);
ERR_pop_to_mark();
}
Mutex::ScopedLock cli_lock(node::per_process::cli_options_mutex);
if (per_process::cli_options->ssl_openssl_cert_store) {
CHECK_EQ(1, X509_STORE_set_default_paths(store));
}
for (X509* cert : root_certs_vector) {
CHECK_EQ(1, X509_STORE_add_cert(store, cert));
}
return store;
}
void GetRootCertificates(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Local<Value> result[arraysize(root_certs)];
for (size_t i = 0; i < arraysize(root_certs); i++) {
if (!String::NewFromOneByte(
env->isolate(),
reinterpret_cast<const uint8_t*>(root_certs[i]))
.ToLocal(&result[i])) {
return;
}
}
args.GetReturnValue().Set(
Array::New(env->isolate(), result, arraysize(root_certs)));
}
bool SecureContext::HasInstance(Environment* env, const Local<Value>& value) {
return GetConstructorTemplate(env)->HasInstance(value);
}
Local<FunctionTemplate> SecureContext::GetConstructorTemplate(
Environment* env) {
Local<FunctionTemplate> tmpl = env->secure_context_constructor_template();
if (tmpl.IsEmpty()) {
Isolate* isolate = env->isolate();
tmpl = NewFunctionTemplate(isolate, New);
tmpl->InstanceTemplate()->SetInternalFieldCount(
SecureContext::kInternalFieldCount);
tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"));
SetProtoMethod(isolate, tmpl, "init", Init);
SetProtoMethod(isolate, tmpl, "setKey", SetKey);
SetProtoMethod(isolate, tmpl, "setCert", SetCert);
SetProtoMethod(isolate, tmpl, "addCACert", AddCACert);
SetProtoMethod(
isolate, tmpl, "setAllowPartialTrustChain", SetAllowPartialTrustChain);
SetProtoMethod(isolate, tmpl, "addCRL", AddCRL);
SetProtoMethod(isolate, tmpl, "addRootCerts", AddRootCerts);
SetProtoMethod(isolate, tmpl, "setCipherSuites", SetCipherSuites);
SetProtoMethod(isolate, tmpl, "setCiphers", SetCiphers);
SetProtoMethod(isolate, tmpl, "setSigalgs", SetSigalgs);
SetProtoMethod(isolate, tmpl, "setECDHCurve", SetECDHCurve);
SetProtoMethod(isolate, tmpl, "setDHParam", SetDHParam);
SetProtoMethod(isolate, tmpl, "setMaxProto", SetMaxProto);
SetProtoMethod(isolate, tmpl, "setMinProto", SetMinProto);
SetProtoMethod(isolate, tmpl, "getMaxProto", GetMaxProto);
SetProtoMethod(isolate, tmpl, "getMinProto", GetMinProto);
SetProtoMethod(isolate, tmpl, "setOptions", SetOptions);
SetProtoMethod(isolate, tmpl, "setSessionIdContext", SetSessionIdContext);
SetProtoMethod(isolate, tmpl, "setSessionTimeout", SetSessionTimeout);
SetProtoMethod(isolate, tmpl, "close", Close);
SetProtoMethod(isolate, tmpl, "loadPKCS12", LoadPKCS12);
SetProtoMethod(isolate, tmpl, "setTicketKeys", SetTicketKeys);
SetProtoMethod(
isolate, tmpl, "enableTicketKeyCallback", EnableTicketKeyCallback);
SetProtoMethodNoSideEffect(isolate, tmpl, "getTicketKeys", GetTicketKeys);
SetProtoMethodNoSideEffect(
isolate, tmpl, "getCertificate", GetCertificate<true>);
SetProtoMethodNoSideEffect(
isolate, tmpl, "getIssuer", GetCertificate<false>);
#ifndef OPENSSL_NO_ENGINE
SetProtoMethod(isolate, tmpl, "setEngineKey", SetEngineKey);
SetProtoMethod(isolate, tmpl, "setClientCertEngine", SetClientCertEngine);
#endif // !OPENSSL_NO_ENGINE
#define SET_INTEGER_CONSTANTS(name, value) \
tmpl->Set(FIXED_ONE_BYTE_STRING(isolate, name), \
Integer::NewFromUnsigned(isolate, value));
SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex);
SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex);
SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex);
SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex);
SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex);
#undef SET_INTEGER_CONSTANTS
Local<FunctionTemplate> ctx_getter_templ = FunctionTemplate::New(
isolate, CtxGetter, Local<Value>(), Signature::New(isolate, tmpl));
tmpl->PrototypeTemplate()->SetAccessorProperty(
FIXED_ONE_BYTE_STRING(isolate, "_external"),
ctx_getter_templ,
Local<FunctionTemplate>(),
static_cast<PropertyAttribute>(ReadOnly | DontDelete));
env->set_secure_context_constructor_template(tmpl);
}
return tmpl;
}
void SecureContext::Initialize(Environment* env, Local<Object> target) {
Local<Context> context = env->context();
SetConstructorFunction(context,
target,
"SecureContext",
GetConstructorTemplate(env),
SetConstructorFunctionFlag::NONE);
SetMethodNoSideEffect(
context, target, "getRootCertificates", GetRootCertificates);
}
void SecureContext::RegisterExternalReferences(
ExternalReferenceRegistry* registry) {
registry->Register(New);
registry->Register(Init);
registry->Register(SetKey);
registry->Register(SetCert);
registry->Register(AddCACert);
registry->Register(AddCRL);
registry->Register(AddRootCerts);
registry->Register(SetAllowPartialTrustChain);
registry->Register(SetCipherSuites);
registry->Register(SetCiphers);
registry->Register(SetSigalgs);
registry->Register(SetECDHCurve);
registry->Register(SetDHParam);
registry->Register(SetMaxProto);
registry->Register(SetMinProto);
registry->Register(GetMaxProto);
registry->Register(GetMinProto);
registry->Register(SetOptions);
registry->Register(SetSessionIdContext);
registry->Register(SetSessionTimeout);
registry->Register(Close);
registry->Register(LoadPKCS12);
registry->Register(SetTicketKeys);
registry->Register(EnableTicketKeyCallback);
registry->Register(GetTicketKeys);
registry->Register(GetCertificate<true>);
registry->Register(GetCertificate<false>);
#ifndef OPENSSL_NO_ENGINE
registry->Register(SetEngineKey);
registry->Register(SetClientCertEngine);
#endif // !OPENSSL_NO_ENGINE
registry->Register(CtxGetter);
registry->Register(GetRootCertificates);
}
SecureContext* SecureContext::Create(Environment* env) {
Local<Object> obj;
if (!GetConstructorTemplate(env)
->InstanceTemplate()
->NewInstance(env->context()).ToLocal(&obj)) {
return nullptr;
}
return new SecureContext(env, obj);
}
SecureContext::SecureContext(Environment* env, Local<Object> wrap)
: BaseObject(env, wrap) {
MakeWeak();
env->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
}
inline void SecureContext::Reset() {
if (ctx_ != nullptr) {
env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
}
ctx_.reset();
cert_.reset();
issuer_.reset();
}
SecureContext::~SecureContext() {
Reset();
}
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
new SecureContext(env, args.This());
}
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc;
ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
Environment* env = sc->env();
CHECK_EQ(args.Length(), 3);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
int min_version = args[1].As<Int32>()->Value();
int max_version = args[2].As<Int32>()->Value();
const SSL_METHOD* method = TLS_method();
if (max_version == 0)
max_version = kMaxSupportedVersion;
if (args[0]->IsString()) {
Utf8Value sslmethod(env->isolate(), args[0]);
// Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends
// are still accepted. They are OpenSSL's way of saying that all known
// protocols below TLS 1.3 are supported unless explicitly disabled (which
// we do below for SSLv2 and SSLv3.)
if (sslmethod == "SSLv2_method" ||
sslmethod == "SSLv2_server_method" ||
sslmethod == "SSLv2_client_method") {
THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
return;
} else if (sslmethod == "SSLv3_method" ||
sslmethod == "SSLv3_server_method" ||
sslmethod == "SSLv3_client_method") {
THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
return;
} else if (sslmethod == "SSLv23_method") {
max_version = TLS1_2_VERSION;
} else if (sslmethod == "SSLv23_server_method") {
max_version = TLS1_2_VERSION;
method = TLS_server_method();
} else if (sslmethod == "SSLv23_client_method") {
max_version = TLS1_2_VERSION;
method = TLS_client_method();
} else if (sslmethod == "TLS_method") {
min_version = 0;
max_version = kMaxSupportedVersion;
} else if (sslmethod == "TLS_server_method") {
min_version = 0;
max_version = kMaxSupportedVersion;
method = TLS_server_method();
} else if (sslmethod == "TLS_client_method") {
min_version = 0;
max_version = kMaxSupportedVersion;
method = TLS_client_method();
} else if (sslmethod == "TLSv1_method") {
min_version = TLS1_VERSION;