-
Notifications
You must be signed in to change notification settings - Fork 30k
/
node_crypto.cc
5184 lines (4036 loc) Β· 149 KB
/
node_crypto.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 "node.h"
#include "node_buffer.h"
#include "node_crypto.h"
#include "node_crypto_bio.h"
#include "node_crypto_groups.h"
#include "tls_wrap.h" // TLSWrap
#include "async-wrap.h"
#include "async-wrap-inl.h"
#include "env.h"
#include "env-inl.h"
#include "string_bytes.h"
#include "util.h"
#include "util-inl.h"
#include "v8.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#if defined(_MSC_VER)
#define strcasecmp _stricmp
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
#define OPENSSL_CONST const
#else
#define OPENSSL_CONST
#endif
#define THROW_AND_RETURN_IF_NOT_STRING_OR_BUFFER(val) \
do { \
if (!Buffer::HasInstance(val) && !val->IsString()) { \
return env->ThrowTypeError("Not a string or buffer"); \
} \
} while (0)
#define THROW_AND_RETURN_IF_NOT_BUFFER(val) \
do { \
if (!Buffer::HasInstance(val)) { \
return env->ThrowTypeError("Not a buffer"); \
} \
} while (0)
static const char PUBLIC_KEY_PFX[] = "-----BEGIN PUBLIC KEY-----";
static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
static const char PUBRSA_KEY_PFX[] = "-----BEGIN RSA PUBLIC KEY-----";
static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
static const char CERTIFICATE_PFX[] = "-----BEGIN CERTIFICATE-----";
static const int CERTIFICATE_PFX_LEN = sizeof(CERTIFICATE_PFX) - 1;
static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
| ASN1_STRFLGS_UTF8_CONVERT
| XN_FLAG_SEP_MULTILINE
| XN_FLAG_FN_SN;
namespace node {
namespace crypto {
using v8::Array;
using v8::Boolean;
using v8::Context;
using v8::DEFAULT;
using v8::DontDelete;
using v8::EscapableHandleScope;
using v8::Exception;
using v8::External;
using v8::False;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Integer;
using v8::Isolate;
using v8::Local;
using v8::Null;
using v8::Object;
using v8::Persistent;
using v8::PropertyAttribute;
using v8::PropertyCallbackInfo;
using v8::ReadOnly;
using v8::String;
using v8::V8;
using v8::Value;
// Forcibly clear OpenSSL's error stack on return. This stops stale errors
// from popping up later in the lifecycle of crypto operations where they
// would cause spurious failures. It's a rather blunt method, though.
// ERR_clear_error() isn't necessarily cheap either.
struct ClearErrorOnReturn {
~ClearErrorOnReturn() { ERR_clear_error(); }
};
static uv_rwlock_t* locks;
const char* const root_certs[] = {
#include "node_root_certs.h" // NOLINT(build/include_order)
};
X509_STORE* root_cert_store;
// Just to generate static methods
template class SSLWrap<TLSWrap>;
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
Handle<FunctionTemplate> t);
template void SSLWrap<TLSWrap>::InitNPN(SecureContext* sc);
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
SSL* s,
unsigned char* key,
int len,
int* copy);
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
SSL_SESSION* sess);
template void SSLWrap<TLSWrap>::OnClientHello(
void* arg,
const ClientHelloParser::ClientHello& hello);
#ifdef OPENSSL_NPN_NEGOTIATED
template int SSLWrap<TLSWrap>::AdvertiseNextProtoCallback(
SSL* s,
const unsigned char** data,
unsigned int* len,
void* arg);
template int SSLWrap<TLSWrap>::SelectNextProtoCallback(
SSL* s,
unsigned char** out,
unsigned char* outlen,
const unsigned char* in,
unsigned int inlen,
void* arg);
#endif
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
template void SSLWrap<TLSWrap>::DestroySSL();
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
static_assert(sizeof(uv_thread_t) <= sizeof(void*), // NOLINT(runtime/sizeof)
"uv_thread_t does not fit in a pointer");
CRYPTO_THREADID_set_pointer(tid, reinterpret_cast<void*>(uv_thread_self()));
}
static void crypto_lock_init(void) {
int i, n;
n = CRYPTO_num_locks();
locks = new uv_rwlock_t[n];
for (i = 0; i < n; i++)
if (uv_rwlock_init(locks + i))
abort();
}
static void crypto_lock_cb(int mode, int n, const char* file, int line) {
CHECK((mode & CRYPTO_LOCK) || (mode & CRYPTO_UNLOCK));
CHECK((mode & CRYPTO_READ) || (mode & CRYPTO_WRITE));
if (mode & CRYPTO_LOCK) {
if (mode & CRYPTO_READ)
uv_rwlock_rdlock(locks + n);
else
uv_rwlock_wrlock(locks + n);
} else {
if (mode & CRYPTO_READ)
uv_rwlock_rdunlock(locks + n);
else
uv_rwlock_wrunlock(locks + n);
}
}
static int CryptoPemCallback(char *buf, int size, int rwflag, void *u) {
if (u) {
size_t buflen = static_cast<size_t>(size);
size_t len = strlen(static_cast<const char*>(u));
len = len > buflen ? buflen : len;
memcpy(buf, u, len);
return len;
}
return 0;
}
void ThrowCryptoError(Environment* env,
unsigned long err,
const char* default_message = nullptr) {
HandleScope scope(env->isolate());
if (err != 0 || default_message == nullptr) {
char errmsg[128] = { 0 };
ERR_error_string_n(err, errmsg, sizeof(errmsg));
env->ThrowError(errmsg);
} else {
env->ThrowError(default_message);
}
}
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
// The entropy pool starts out empty and needs to fill up before the PRNG
// can be used securely. Once the pool is filled, it never dries up again;
// its contents is stirred and reused when necessary.
//
// OpenSSL normally fills the pool automatically but not when someone starts
// generating random numbers before the pool is full: in that case OpenSSL
// keeps lowering the entropy estimate to thwart attackers trying to guess
// the initial state of the PRNG.
//
// When that happens, we will have to wait until enough entropy is available.
// That should normally never take longer than a few milliseconds.
//
// OpenSSL draws from /dev/random and /dev/urandom. While /dev/random may
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
// block under normal circumstances.
//
// The only time when /dev/urandom may conceivably block is right after boot,
// when the whole system is still low on entropy. That's not something we can
// do anything about.
inline void CheckEntropy() {
for (;;) {
int status = RAND_status();
CHECK_GE(status, 0); // Cannot fail.
if (status != 0)
break;
// Give up, RAND_poll() not supported.
if (RAND_poll() == 0)
break;
}
}
bool EntropySource(unsigned char* buffer, size_t length) {
// Ensure that OpenSSL's PRNG is properly seeded.
CheckEntropy();
// RAND_bytes() can return 0 to indicate that the entropy data is not truly
// random. That's okay, it's still better than V8's stock source of entropy,
// which is /dev/urandom on UNIX platforms and the current time on Windows.
return RAND_bytes(buffer, length) != -1;
}
void SecureContext::Initialize(Environment* env, Handle<Object> target) {
Local<FunctionTemplate> t = env->NewFunctionTemplate(SecureContext::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"));
env->SetProtoMethod(t, "init", SecureContext::Init);
env->SetProtoMethod(t, "setKey", SecureContext::SetKey);
env->SetProtoMethod(t, "setCert", SecureContext::SetCert);
env->SetProtoMethod(t, "addCACert", SecureContext::AddCACert);
env->SetProtoMethod(t, "addCRL", SecureContext::AddCRL);
env->SetProtoMethod(t, "addRootCerts", SecureContext::AddRootCerts);
env->SetProtoMethod(t, "setCiphers", SecureContext::SetCiphers);
env->SetProtoMethod(t, "setECDHCurve", SecureContext::SetECDHCurve);
env->SetProtoMethod(t, "setDHParam", SecureContext::SetDHParam);
env->SetProtoMethod(t, "setOptions", SecureContext::SetOptions);
env->SetProtoMethod(t, "setSessionIdContext",
SecureContext::SetSessionIdContext);
env->SetProtoMethod(t, "setSessionTimeout",
SecureContext::SetSessionTimeout);
env->SetProtoMethod(t, "close", SecureContext::Close);
env->SetProtoMethod(t, "loadPKCS12", SecureContext::LoadPKCS12);
env->SetProtoMethod(t, "getTicketKeys", SecureContext::GetTicketKeys);
env->SetProtoMethod(t, "setTicketKeys", SecureContext::SetTicketKeys);
env->SetProtoMethod(t, "setFreeListLength", SecureContext::SetFreeListLength);
env->SetProtoMethod(t, "getCertificate", SecureContext::GetCertificate<true>);
env->SetProtoMethod(t, "getIssuer", SecureContext::GetCertificate<false>);
t->PrototypeTemplate()->SetAccessor(
FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
CtxGetter,
nullptr,
env->as_external(),
DEFAULT,
static_cast<PropertyAttribute>(ReadOnly | DontDelete));
target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"),
t->GetFunction());
env->set_secure_context_constructor_template(t);
}
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 = Unwrap<SecureContext>(args.Holder());
Environment* env = sc->env();
OPENSSL_CONST SSL_METHOD *method = SSLv23_method();
if (args.Length() == 1 && args[0]->IsString()) {
const node::Utf8Value sslmethod(env->isolate(), args[0]);
// Note that SSLv2 and SSLv3 are disallowed but SSLv2_method and friends
// are still accepted. They are OpenSSL's way of saying that all known
// protocols are supported unless explicitly disabled (which we do below
// for SSLv2 and SSLv3.)
if (strcmp(*sslmethod, "SSLv2_method") == 0) {
return env->ThrowError("SSLv2 methods disabled");
} else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
return env->ThrowError("SSLv2 methods disabled");
} else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
return env->ThrowError("SSLv2 methods disabled");
} else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
return env->ThrowError("SSLv3 methods disabled");
} else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
return env->ThrowError("SSLv3 methods disabled");
} else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
return env->ThrowError("SSLv3 methods disabled");
} else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
method = SSLv23_method();
} else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
method = SSLv23_server_method();
} else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
method = SSLv23_client_method();
} else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
method = TLSv1_method();
} else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
method = TLSv1_server_method();
} else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
method = TLSv1_client_method();
} else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
method = TLSv1_1_method();
} else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
method = TLSv1_1_server_method();
} else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
method = TLSv1_1_client_method();
} else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
method = TLSv1_2_method();
} else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
method = TLSv1_2_server_method();
} else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
method = TLSv1_2_client_method();
} else {
return env->ThrowError("Unknown method");
}
}
sc->ctx_ = SSL_CTX_new(method);
// Disable SSLv2 in the case when method == SSLv23_method() and the
// cipher list contains SSLv2 ciphers (not the default, should be rare.)
// The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
// SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv2);
SSL_CTX_set_options(sc->ctx_, SSL_OP_NO_SSLv3);
// SSL session cache configuration
SSL_CTX_set_session_cache_mode(sc->ctx_,
SSL_SESS_CACHE_SERVER |
SSL_SESS_CACHE_NO_INTERNAL |
SSL_SESS_CACHE_NO_AUTO_CLEAR);
SSL_CTX_sess_set_get_cb(sc->ctx_, SSLWrap<Connection>::GetSessionCallback);
SSL_CTX_sess_set_new_cb(sc->ctx_, SSLWrap<Connection>::NewSessionCallback);
sc->ca_store_ = nullptr;
}
// Takes a string or buffer and loads it into a BIO.
// Caller responsible for BIO_free_all-ing the returned object.
static BIO* LoadBIO(Environment* env, Handle<Value> v) {
BIO* bio = NodeBIO::New();
if (!bio)
return nullptr;
HandleScope scope(env->isolate());
int r = -1;
if (v->IsString()) {
const node::Utf8Value s(env->isolate(), v);
r = BIO_write(bio, *s, s.length());
} else if (Buffer::HasInstance(v)) {
char* buffer_data = Buffer::Data(v);
size_t buffer_length = Buffer::Length(v);
r = BIO_write(bio, buffer_data, buffer_length);
}
if (r <= 0) {
BIO_free_all(bio);
return nullptr;
}
return bio;
}
// Takes a string or buffer and loads it into an X509
// Caller responsible for X509_free-ing the returned object.
static X509* LoadX509(Environment* env, Handle<Value> v) {
HandleScope scope(env->isolate());
BIO *bio = LoadBIO(env, v);
if (!bio)
return nullptr;
X509 * x509 = PEM_read_bio_X509(bio, nullptr, CryptoPemCallback, nullptr);
if (!x509) {
BIO_free_all(bio);
return nullptr;
}
BIO_free_all(bio);
return x509;
}
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
unsigned int len = args.Length();
if (len != 1 && len != 2) {
return env->ThrowTypeError("Bad parameter");
}
if (len == 2 && !args[1]->IsString()) {
return env->ThrowTypeError("Bad parameter");
}
BIO *bio = LoadBIO(env, args[0]);
if (!bio)
return;
node::Utf8Value passphrase(env->isolate(), args[1]);
EVP_PKEY* key = PEM_read_bio_PrivateKey(bio,
nullptr,
CryptoPemCallback,
len == 1 ? nullptr : *passphrase);
if (!key) {
BIO_free_all(bio);
unsigned long err = ERR_get_error();
if (!err) {
return env->ThrowError("PEM_read_bio_PrivateKey");
}
return ThrowCryptoError(env, err);
}
int rv = SSL_CTX_use_PrivateKey(sc->ctx_, key);
EVP_PKEY_free(key);
BIO_free_all(bio);
if (!rv) {
unsigned long err = ERR_get_error();
if (!err)
return env->ThrowError("SSL_CTX_use_PrivateKey");
return ThrowCryptoError(env, err);
}
}
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
int ret;
X509_STORE* store = SSL_CTX_get_cert_store(ctx);
X509_STORE_CTX store_ctx;
ret = X509_STORE_CTX_init(&store_ctx, store, nullptr, nullptr);
if (!ret)
goto end;
ret = X509_STORE_CTX_get1_issuer(issuer, &store_ctx, cert);
X509_STORE_CTX_cleanup(&store_ctx);
end:
return ret;
}
// 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 - editted for style.
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
BIO* in,
X509** cert,
X509** issuer) {
int ret = 0;
X509* x = nullptr;
x = PEM_read_bio_X509_AUX(in, nullptr, CryptoPemCallback, nullptr);
if (x == nullptr) {
SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
goto end;
}
ret = SSL_CTX_use_certificate(ctx, x);
if (ret) {
// If we could set up our certificate, now proceed to
// the CA certificates.
X509 *ca;
int r;
unsigned long err;
if (ctx->extra_certs != nullptr) {
sk_X509_pop_free(ctx->extra_certs, X509_free);
ctx->extra_certs = nullptr;
}
while ((ca = PEM_read_bio_X509(in, nullptr, CryptoPemCallback, nullptr))) {
// NOTE: Increments reference count on `ca`
r = SSL_CTX_add1_chain_cert(ctx, ca);
if (!r) {
X509_free(ca);
ret = 0;
goto end;
}
// 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) != X509_V_OK)
continue;
*issuer = ca;
}
// 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
ret = 0;
}
}
// Try getting issuer from a cert store
if (ret) {
if (*issuer == nullptr) {
ret = SSL_CTX_get_issuer(ctx, x, issuer);
ret = ret < 0 ? 0 : 1;
// NOTE: get_cert_store doesn't increment reference count,
// no need to free `store`
} else {
// Increment issuer reference count
CRYPTO_add(&(*issuer)->references, 1, CRYPTO_LOCK_X509);
}
}
end:
if (x != nullptr)
*cert = x;
return ret;
}
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1) {
return env->ThrowTypeError("Bad parameter");
}
BIO* bio = LoadBIO(env, args[0]);
if (!bio)
return;
int rv = SSL_CTX_use_certificate_chain(sc->ctx_,
bio,
&sc->cert_,
&sc->issuer_);
BIO_free_all(bio);
if (!rv) {
unsigned long err = ERR_get_error();
if (!err) {
return env->ThrowError("SSL_CTX_use_certificate_chain");
}
return ThrowCryptoError(env, err);
}
}
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
bool newCAStore = false;
Environment* env = Environment::GetCurrent(args);
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence compiler warning.
if (args.Length() != 1) {
return env->ThrowTypeError("Bad parameter");
}
if (!sc->ca_store_) {
sc->ca_store_ = X509_STORE_new();
newCAStore = true;
}
X509* x509 = LoadX509(env, args[0]);
if (!x509)
return;
X509_STORE_add_cert(sc->ca_store_, x509);
SSL_CTX_add_client_CA(sc->ctx_, x509);
X509_free(x509);
if (newCAStore) {
SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
}
}
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1) {
return env->ThrowTypeError("Bad parameter");
}
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence compiler warning.
BIO *bio = LoadBIO(env, args[0]);
if (!bio)
return;
X509_CRL *x509 =
PEM_read_bio_X509_CRL(bio, nullptr, CryptoPemCallback, nullptr);
if (x509 == nullptr) {
BIO_free_all(bio);
return;
}
X509_STORE_add_crl(sc->ca_store_, x509);
X509_STORE_set_flags(sc->ca_store_, X509_V_FLAG_CRL_CHECK |
X509_V_FLAG_CRL_CHECK_ALL);
BIO_free_all(bio);
X509_CRL_free(x509);
}
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence compiler warning.
CHECK_EQ(sc->ca_store_, nullptr);
if (!root_cert_store) {
root_cert_store = X509_STORE_new();
for (size_t i = 0; i < ARRAY_SIZE(root_certs); i++) {
BIO* bp = NodeBIO::New();
if (!BIO_write(bp, root_certs[i], strlen(root_certs[i]))) {
BIO_free_all(bp);
return;
}
X509 *x509 = PEM_read_bio_X509(bp, nullptr, CryptoPemCallback, nullptr);
if (x509 == nullptr) {
BIO_free_all(bp);
return;
}
X509_STORE_add_cert(root_cert_store, x509);
BIO_free_all(bp);
X509_free(x509);
}
}
sc->ca_store_ = root_cert_store;
SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
}
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence compiler warning.
if (args.Length() != 1 || !args[0]->IsString()) {
return sc->env()->ThrowTypeError("Bad parameter");
}
const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
}
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
Environment* env = sc->env();
if (args.Length() != 1 || !args[0]->IsString())
return env->ThrowTypeError("First argument should be a string");
node::Utf8Value curve(env->isolate(), args[0]);
int nid = OBJ_sn2nid(*curve);
if (nid == NID_undef)
return env->ThrowTypeError("First argument should be a valid curve name");
EC_KEY* ecdh = EC_KEY_new_by_curve_name(nid);
if (ecdh == nullptr)
return env->ThrowTypeError("First argument should be a valid curve name");
SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_ECDH_USE);
SSL_CTX_set_tmp_ecdh(sc->ctx_, ecdh);
EC_KEY_free(ecdh);
}
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc = Unwrap<SecureContext>(args.This());
Environment* env = sc->env();
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence compiler warning.
// Auto DH is not supported in openssl 1.0.1, so dhparam needs
// to be specifed explicitly
if (args.Length() != 1)
return env->ThrowTypeError("Bad parameter");
// Invalid dhparam is silently discarded and DHE is no longer used.
BIO* bio = LoadBIO(env, args[0]);
if (!bio)
return;
DH* dh = PEM_read_bio_DHparams(bio, nullptr, nullptr, nullptr);
BIO_free_all(bio);
if (dh == nullptr)
return;
const int keylen = BN_num_bits(dh->p);
if (keylen < 1024)
return env->ThrowError("DH parameter is less than 1024 bits");
else if (keylen < 2048)
fprintf(stderr, "WARNING: DH parameter is less than 2048 bits\n");
SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE);
int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh);
DH_free(dh);
if (!r)
return env->ThrowTypeError("Error setting temp DH parameter");
}
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1 || !args[0]->IntegerValue()) {
return sc->env()->ThrowTypeError("Bad parameter");
}
SSL_CTX_set_options(sc->ctx_, static_cast<long>(args[0]->IntegerValue()));
}
void SecureContext::SetSessionIdContext(
const FunctionCallbackInfo<Value>& args) {
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1 || !args[0]->IsString()) {
return sc->env()->ThrowTypeError("Bad parameter");
}
const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
const unsigned char* sid_ctx =
reinterpret_cast<const unsigned char*>(*sessionIdContext);
unsigned int sid_ctx_len = sessionIdContext.length();
int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
if (r == 1)
return;
BIO* bio;
BUF_MEM* mem;
Local<String> message;
bio = BIO_new(BIO_s_mem());
if (bio == nullptr) {
message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
"SSL_CTX_set_session_id_context error");
} else {
ERR_print_errors(bio);
BIO_get_mem_ptr(bio, &mem);
message = OneByteString(args.GetIsolate(), mem->data, mem->length);
BIO_free_all(bio);
}
args.GetIsolate()->ThrowException(Exception::TypeError(message));
}
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1 || !args[0]->IsInt32()) {
return sc->env()->ThrowTypeError("Bad parameter");
}
int32_t sessionTimeout = args[0]->Int32Value();
SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
}
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
sc->FreeCTXMem();
}
// Takes .pfx or .p12 and password in string or buffer format
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
BIO* in = nullptr;
PKCS12* p12 = nullptr;
EVP_PKEY* pkey = nullptr;
X509* cert = nullptr;
STACK_OF(X509)* extraCerts = nullptr;
char* pass = nullptr;
bool ret = false;
SecureContext* sc = Unwrap<SecureContext>(args.Holder());
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence compiler warning.
if (args.Length() < 1) {
return env->ThrowTypeError("Bad parameter");
}
in = LoadBIO(env, args[0]);
if (in == nullptr) {
return env->ThrowError("Unable to load BIO");
}
if (args.Length() >= 2) {
THROW_AND_RETURN_IF_NOT_BUFFER(args[1]);
size_t passlen = Buffer::Length(args[1]);
pass = new char[passlen + 1];
memcpy(pass, Buffer::Data(args[1]), passlen);
pass[passlen] = '\0';
}
if (d2i_PKCS12_bio(in, &p12) &&
PKCS12_parse(p12, pass, &pkey, &cert, &extraCerts) &&
SSL_CTX_use_certificate(sc->ctx_, cert) &&
SSL_CTX_use_PrivateKey(sc->ctx_, pkey)) {
// set extra certs
while (X509* x509 = sk_X509_pop(extraCerts)) {
if (!sc->ca_store_) {
sc->ca_store_ = X509_STORE_new();
SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
}
X509_STORE_add_cert(sc->ca_store_, x509);
SSL_CTX_add_client_CA(sc->ctx_, x509);
X509_free(x509);
}
EVP_PKEY_free(pkey);
X509_free(cert);
sk_X509_free(extraCerts);
ret = true;
}
PKCS12_free(p12);
BIO_free_all(in);
delete[] pass;
if (!ret) {
unsigned long err = ERR_get_error();
const char* str = ERR_reason_error_string(err);
return env->ThrowError(str);
}
}
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
SecureContext* wrap = Unwrap<SecureContext>(args.Holder());
Local<Object> buff = Buffer::New(wrap->env(), 48);
if (SSL_CTX_get_tlsext_ticket_keys(wrap->ctx_,
Buffer::Data(buff),
Buffer::Length(buff)) != 1) {
return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
}
args.GetReturnValue().Set(buff);
#endif // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
}
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
SecureContext* wrap = Unwrap<SecureContext>(args.Holder());
if (args.Length() < 1 ||
!Buffer::HasInstance(args[0]) ||
Buffer::Length(args[0]) != 48) {
return wrap->env()->ThrowTypeError("Bad argument");
}
if (SSL_CTX_set_tlsext_ticket_keys(wrap->ctx_,
Buffer::Data(args[0]),
Buffer::Length(args[0])) != 1) {
return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
}
args.GetReturnValue().Set(true);
#endif // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
}
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
SecureContext* wrap = Unwrap<SecureContext>(args.Holder());
wrap->ctx_->freelist_max_len = args[0]->Int32Value();
}
void SecureContext::CtxGetter(Local<String> property,
const PropertyCallbackInfo<Value>& info) {
HandleScope scope(info.GetIsolate());
SSL_CTX* ctx = Unwrap<SecureContext>(info.Holder())->ctx_;
Local<External> ext = External::New(info.GetIsolate(), ctx);
info.GetReturnValue().Set(ext);
}
template <bool primary>
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
SecureContext* wrap = Unwrap<SecureContext>(args.Holder());
Environment* env = wrap->env();
X509* cert;
if (primary)
cert = wrap->cert_;
else
cert = wrap->issuer_;
if (cert == nullptr)
return args.GetReturnValue().Set(Null(env->isolate()));
int size = i2d_X509(cert, nullptr);
Local<Object> buff = Buffer::New(env, size);
unsigned char* serialized = reinterpret_cast<unsigned char*>(
Buffer::Data(buff));
i2d_X509(cert, &serialized);
args.GetReturnValue().Set(buff);
}
template <class Base>
void SSLWrap<Base>::AddMethods(Environment* env, Handle<FunctionTemplate> t) {
HandleScope scope(env->isolate());
env->SetProtoMethod(t, "getPeerCertificate", GetPeerCertificate);
env->SetProtoMethod(t, "getSession", GetSession);
env->SetProtoMethod(t, "setSession", SetSession);
env->SetProtoMethod(t, "loadSession", LoadSession);
env->SetProtoMethod(t, "isSessionReused", IsSessionReused);
env->SetProtoMethod(t, "isInitFinished", IsInitFinished);
env->SetProtoMethod(t, "verifyError", VerifyError);
env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
env->SetProtoMethod(t, "endParser", EndParser);
env->SetProtoMethod(t, "certCbDone", CertCbDone);
env->SetProtoMethod(t, "renegotiate", Renegotiate);