forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_crypto.cc
4200 lines (3233 loc) · 114 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
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "node_crypto.h"
#include "node_crypto_groups.h"
#include "v8.h"
#include "node.h"
#include "node_buffer.h"
#include "string_bytes.h"
#include <string.h>
#ifdef _MSC_VER
#define strcasecmp _stricmp
#endif
#include <stdlib.h>
#include <errno.h>
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
# define OPENSSL_CONST const
#else
# define OPENSSL_CONST
#endif
#define ASSERT_IS_STRING_OR_BUFFER(val) \
if (!Buffer::HasInstance(val) && !val->IsString()) { \
return ThrowException(Exception::TypeError(String::New( \
"Not a string or buffer"))); \
}
#define ASSERT_IS_BUFFER(val) \
if (!Buffer::HasInstance(val)) { \
return ThrowException(Exception::TypeError(String::New("Not a buffer"))); \
}
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 int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
| ASN1_STRFLGS_ESC_MSB
| XN_FLAG_SEP_MULTILINE
| XN_FLAG_FN_SN;
namespace node {
const char* root_certs[] = {
#include "node_root_certs.h" // NOLINT(build/include_order)
NULL
};
namespace crypto {
using namespace v8;
// 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 Persistent<String> errno_symbol;
static Persistent<String> syscall_symbol;
static Persistent<String> subject_symbol;
static Persistent<String> subjectaltname_symbol;
static Persistent<String> modulus_symbol;
static Persistent<String> exponent_symbol;
static Persistent<String> issuer_symbol;
static Persistent<String> valid_from_symbol;
static Persistent<String> valid_to_symbol;
static Persistent<String> fingerprint_symbol;
static Persistent<String> name_symbol;
static Persistent<String> version_symbol;
static Persistent<String> ext_key_usage_symbol;
static Persistent<String> onhandshakestart_sym;
static Persistent<String> onhandshakedone_sym;
static Persistent<String> onclienthello_sym;
static Persistent<String> onnewsession_sym;
static Persistent<String> sessionid_sym;
static Persistent<FunctionTemplate> secure_context_constructor;
static uv_rwlock_t* locks;
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
CRYPTO_THREADID_set_numeric(tid, 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) {
assert((mode & CRYPTO_LOCK) || (mode & CRYPTO_UNLOCK));
assert((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);
}
}
Handle<Value> ThrowCryptoErrorHelper(unsigned long err, bool is_type_error) {
HandleScope scope;
char errmsg[128];
ERR_error_string_n(err, errmsg, sizeof(errmsg));
return is_type_error ? ThrowTypeError(errmsg) : ThrowError(errmsg);
}
Handle<Value> ThrowCryptoError(unsigned long err) {
return ThrowCryptoErrorHelper(err, false);
}
Handle<Value> ThrowCryptoTypeError(unsigned long err) {
return ThrowCryptoErrorHelper(err, true);
}
void SecureContext::Initialize(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(SecureContext::New);
secure_context_constructor = Persistent<FunctionTemplate>::New(t);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(String::NewSymbol("SecureContext"));
NODE_SET_PROTOTYPE_METHOD(t, "init", SecureContext::Init);
NODE_SET_PROTOTYPE_METHOD(t, "setKey", SecureContext::SetKey);
NODE_SET_PROTOTYPE_METHOD(t, "setCert", SecureContext::SetCert);
NODE_SET_PROTOTYPE_METHOD(t, "addCACert", SecureContext::AddCACert);
NODE_SET_PROTOTYPE_METHOD(t, "addCRL", SecureContext::AddCRL);
NODE_SET_PROTOTYPE_METHOD(t, "addRootCerts", SecureContext::AddRootCerts);
NODE_SET_PROTOTYPE_METHOD(t, "setCiphers", SecureContext::SetCiphers);
NODE_SET_PROTOTYPE_METHOD(t, "setOptions", SecureContext::SetOptions);
NODE_SET_PROTOTYPE_METHOD(t, "setSessionIdContext",
SecureContext::SetSessionIdContext);
NODE_SET_PROTOTYPE_METHOD(t, "close", SecureContext::Close);
NODE_SET_PROTOTYPE_METHOD(t, "loadPKCS12", SecureContext::LoadPKCS12);
target->Set(String::NewSymbol("SecureContext"), t->GetFunction());
}
Handle<Value> SecureContext::New(const Arguments& args) {
HandleScope scope;
SecureContext *p = new SecureContext();
p->Wrap(args.Holder());
return args.This();
}
Handle<Value> SecureContext::Init(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
OPENSSL_CONST SSL_METHOD *method = SSLv23_method();
if (args.Length() == 1 && args[0]->IsString()) {
String::Utf8Value sslmethod(args[0]);
if (strcmp(*sslmethod, "SSLv2_method") == 0) {
#ifndef OPENSSL_NO_SSL2
method = SSLv2_method();
#else
return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
#endif
} else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
#ifndef OPENSSL_NO_SSL2
method = SSLv2_server_method();
#else
return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
#endif
} else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
#ifndef OPENSSL_NO_SSL2
method = SSLv2_client_method();
#else
return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
#endif
} else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
method = SSLv3_method();
} else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
method = SSLv3_server_method();
} else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
method = SSLv3_client_method();
} 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 {
return ThrowException(Exception::Error(String::New("Unknown method")));
}
}
sc->ctx_ = SSL_CTX_new(method);
// 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_, GetSessionCallback);
SSL_CTX_sess_set_new_cb(sc->ctx_, NewSessionCallback);
sc->ca_store_ = NULL;
return True();
}
SSL_SESSION* SecureContext::GetSessionCallback(SSL* s,
unsigned char* key,
int len,
int* copy) {
HandleScope scope;
Connection* p = static_cast<Connection*>(SSL_get_app_data(s));
*copy = 0;
SSL_SESSION* sess = p->next_sess_;
p->next_sess_ = NULL;
return sess;
}
void SessionDataFree(char* data, void* hint) {
delete[] data;
}
int SecureContext::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
HandleScope scope;
Connection* p = static_cast<Connection*>(SSL_get_app_data(s));
// Check if session is small enough to be stored
int size = i2d_SSL_SESSION(sess, NULL);
if (size > kMaxSessionSize) return 0;
// Serialize session
char* serialized = new char[size];
unsigned char* pserialized = reinterpret_cast<unsigned char*>(serialized);
memset(serialized, 0, size);
i2d_SSL_SESSION(sess, &pserialized);
Handle<Value> argv[2] = {
Buffer::New(reinterpret_cast<char*>(sess->session_id),
sess->session_id_length)->handle_,
Buffer::New(serialized, size, SessionDataFree, NULL)->handle_
};
if (onnewsession_sym.IsEmpty()) {
onnewsession_sym = NODE_PSYMBOL("onnewsession");
}
MakeCallback(p->handle_, onnewsession_sym, ARRAY_SIZE(argv), argv);
return 0;
}
// Takes a string or buffer and loads it into a BIO.
// Caller responsible for BIO_free-ing the returned object.
static BIO* LoadBIO (Handle<Value> v) {
BIO *bio = BIO_new(BIO_s_mem());
if (!bio) return NULL;
HandleScope scope;
int r = -1;
if (v->IsString()) {
String::Utf8Value s(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(bio);
return NULL;
}
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 (Handle<Value> v) {
HandleScope scope; // necessary?
BIO *bio = LoadBIO(v);
if (!bio) return NULL;
X509 * x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
if (!x509) {
BIO_free(bio);
return NULL;
}
BIO_free(bio);
return x509;
}
Handle<Value> SecureContext::SetKey(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
unsigned int len = args.Length();
if (len != 1 && len != 2) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
if (len == 2 && !args[1]->IsString()) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
BIO *bio = LoadBIO(args[0]);
if (!bio) return False();
String::Utf8Value passphrase(args[1]);
EVP_PKEY* key = PEM_read_bio_PrivateKey(bio, NULL, NULL,
len == 1 ? NULL : *passphrase);
if (!key) {
BIO_free(bio);
unsigned long err = ERR_get_error();
if (!err) {
return ThrowException(Exception::Error(
String::New("PEM_read_bio_PrivateKey")));
}
return ThrowCryptoError(err);
}
SSL_CTX_use_PrivateKey(sc->ctx_, key);
EVP_PKEY_free(key);
BIO_free(bio);
return True();
}
// 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) {
int ret = 0;
X509 *x = NULL;
x = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
if (x == NULL) {
SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
goto end;
}
ret = SSL_CTX_use_certificate(ctx, x);
if (ERR_peek_error() != 0) {
// Key/certificate mismatch doesn't imply ret==0 ...
ret = 0;
}
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 != NULL) {
sk_X509_pop_free(ctx->extra_certs, X509_free);
ctx->extra_certs = NULL;
}
while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
r = SSL_CTX_add_extra_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).
}
// 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;
}
}
end:
if (x != NULL) X509_free(x);
return ret;
}
Handle<Value> SecureContext::SetCert(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1) {
return ThrowException(Exception::TypeError(
String::New("Bad parameter")));
}
BIO* bio = LoadBIO(args[0]);
if (!bio) return False();
int rv = SSL_CTX_use_certificate_chain(sc->ctx_, bio);
BIO_free(bio);
if (!rv) {
unsigned long err = ERR_get_error();
if (!err) {
return ThrowException(Exception::Error(
String::New("SSL_CTX_use_certificate_chain")));
}
return ThrowCryptoError(err);
}
return True();
}
Handle<Value> SecureContext::AddCACert(const Arguments& args) {
bool newCAStore = false;
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
if (!sc->ca_store_) {
sc->ca_store_ = X509_STORE_new();
newCAStore = true;
}
X509* x509 = LoadX509(args[0]);
if (!x509) return False();
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_);
}
return True();
}
Handle<Value> SecureContext::AddCRL(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
BIO *bio = LoadBIO(args[0]);
if (!bio) return False();
X509_CRL *x509 = PEM_read_bio_X509_CRL(bio, NULL, NULL, NULL);
if (x509 == NULL) {
BIO_free(bio);
return False();
}
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(bio);
X509_CRL_free(x509);
return True();
}
Handle<Value> SecureContext::AddRootCerts(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
assert(sc->ca_store_ == NULL);
if (!root_cert_store) {
root_cert_store = X509_STORE_new();
for (int i = 0; root_certs[i]; i++) {
BIO *bp = BIO_new(BIO_s_mem());
if (!BIO_write(bp, root_certs[i], strlen(root_certs[i]))) {
BIO_free(bp);
return False();
}
X509 *x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
if (x509 == NULL) {
BIO_free(bp);
return False();
}
X509_STORE_add_cert(root_cert_store, x509);
BIO_free(bp);
X509_free(x509);
}
}
sc->ca_store_ = root_cert_store;
SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
return True();
}
Handle<Value> SecureContext::SetCiphers(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1 || !args[0]->IsString()) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
String::Utf8Value ciphers(args[0]);
SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
return True();
}
Handle<Value> SecureContext::SetOptions(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1 || !args[0]->IntegerValue()) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
SSL_CTX_set_options(sc->ctx_, args[0]->IntegerValue());
return True();
}
Handle<Value> SecureContext::SetSessionIdContext(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
if (args.Length() != 1 || !args[0]->IsString()) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
String::Utf8Value sessionIdContext(args[0]);
const unsigned char* sid_ctx = (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) {
Local<String> message;
BIO* bio;
BUF_MEM* mem;
if ((bio = BIO_new(BIO_s_mem()))) {
ERR_print_errors(bio);
BIO_get_mem_ptr(bio, &mem);
message = String::New(mem->data, mem->length);
BIO_free(bio);
} else {
message = String::New("SSL_CTX_set_session_id_context error");
}
return ThrowException(Exception::TypeError(message));
}
return True();
}
Handle<Value> SecureContext::Close(const Arguments& args) {
HandleScope scope;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
sc->FreeCTXMem();
return False();
}
//Takes .pfx or .p12 and password in string or buffer format
Handle<Value> SecureContext::LoadPKCS12(const Arguments& args) {
HandleScope scope;
BIO* in = NULL;
PKCS12* p12 = NULL;
EVP_PKEY* pkey = NULL;
X509* cert = NULL;
STACK_OF(X509)* extraCerts = NULL;
char* pass = NULL;
bool ret = false;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
if (args.Length() < 1) {
return ThrowException(Exception::TypeError(
String::New("Bad parameter")));
}
in = LoadBIO(args[0]);
if (in == NULL) {
return ThrowException(Exception::Error(
String::New("Unable to load BIO")));
}
if (args.Length() >= 2) {
ASSERT_IS_BUFFER(args[1]);
int passlen = Buffer::Length(args[1]);
if (passlen < 0) {
BIO_free(in);
return ThrowException(Exception::TypeError(
String::New("Bad password")));
}
pass = new char[passlen + 1];
int pass_written = DecodeWrite(pass, passlen, args[1], BINARY);
assert(pass_written == 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(in);
delete[] pass;
if (!ret) {
unsigned long err = ERR_get_error();
const char* str = ERR_reason_error_string(err);
return ThrowException(Exception::Error(String::New(str)));
}
return True();
}
size_t ClientHelloParser::Write(const uint8_t* data, size_t len) {
HandleScope scope;
// Just accumulate data, everything will be pushed to BIO later
if (state_ == kPaused) return 0;
// Copy incoming data to the internal buffer
// (which has a size of the biggest possible TLS frame)
size_t available = sizeof(data_) - offset_;
size_t copied = len < available ? len : available;
memcpy(data_ + offset_, data, copied);
offset_ += copied;
// Vars for parsing hello
bool is_clienthello = false;
uint8_t session_size = -1;
uint8_t* session_id = NULL;
Local<Object> hello;
Handle<Value> argv[1];
switch (state_) {
case kWaiting:
// >= 5 bytes for header parsing
if (offset_ < 5) break;
if (data_[0] == kChangeCipherSpec || data_[0] == kAlert ||
data_[0] == kHandshake || data_[0] == kApplicationData) {
frame_len_ = (data_[3] << 8) + data_[4];
state_ = kTLSHeader;
body_offset_ = 5;
} else {
frame_len_ = (data_[0] << 8) + data_[1];
state_ = kSSLHeader;
if (*data_ & 0x40) {
// header with padding
body_offset_ = 3;
} else {
// without padding
body_offset_ = 2;
}
}
// Sanity check (too big frame, or too small)
if (frame_len_ >= sizeof(data_)) {
// Let OpenSSL handle it
Finish();
return copied;
}
case kTLSHeader:
case kSSLHeader:
// >= 5 + frame size bytes for frame parsing
if (offset_ < body_offset_ + frame_len_) break;
// Skip unsupported frames and gather some data from frame
// TODO: Check protocol version
if (data_[body_offset_] == kClientHello) {
is_clienthello = true;
uint8_t* body;
size_t session_offset;
if (state_ == kTLSHeader) {
// Skip frame header, hello header, protocol version and random data
session_offset = body_offset_ + 4 + 2 + 32;
if (session_offset + 1 < offset_) {
body = data_ + session_offset;
session_size = *body;
session_id = body + 1;
}
} else if (state_ == kSSLHeader) {
// Skip header, version
session_offset = body_offset_ + 3;
if (session_offset + 4 < offset_) {
body = data_ + session_offset;
int ciphers_size = (body[0] << 8) + body[1];
if (body + 4 + ciphers_size < data_ + offset_) {
session_size = (body[2] << 8) + body[3];
session_id = body + 4 + ciphers_size;
}
}
} else {
// Whoa? How did we get here?
abort();
}
// Check if we overflowed (do not reply with any private data)
if (session_id == NULL ||
session_size > 32 ||
session_id + session_size > data_ + offset_) {
Finish();
return copied;
}
// TODO: Parse other things?
}
// Not client hello - let OpenSSL handle it
if (!is_clienthello) {
Finish();
return copied;
}
// Parse frame, call javascript handler and
// move parser into the paused state
if (onclienthello_sym.IsEmpty()) {
onclienthello_sym = NODE_PSYMBOL("onclienthello");
}
if (sessionid_sym.IsEmpty()) {
sessionid_sym = NODE_PSYMBOL("sessionId");
}
state_ = kPaused;
hello = Object::New();
hello->Set(sessionid_sym,
Buffer::New(reinterpret_cast<char*>(session_id),
session_size)->handle_);
argv[0] = hello;
MakeCallback(conn_->handle_, onclienthello_sym, 1, argv);
break;
case kEnded:
default:
break;
}
return copied;
}
void ClientHelloParser::Finish() {
assert(state_ != kEnded);
state_ = kEnded;
// Write all accumulated data
int r = BIO_write(conn_->bio_read_, reinterpret_cast<char*>(data_), offset_);
conn_->HandleBIOError(conn_->bio_read_, "BIO_write", r);
conn_->SetShutdownFlags();
}
#ifdef SSL_PRINT_DEBUG
# define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
#else
# define DEBUG_PRINT(...)
#endif
int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
if (rv >= 0) return rv;
int retry = BIO_should_retry(bio);
(void) retry; // unused if !defined(SSL_PRINT_DEBUG)
if (BIO_should_write(bio)) {
DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n", ssl_, func, retry);
return 0;
} else if (BIO_should_read(bio)) {
DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
return 0;
} else {
static char ssl_error_buf[512];
ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
HandleScope scope;
Local<Value> e = Exception::Error(String::New(ssl_error_buf));
handle_->Set(String::New("error"), e);
DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n", ssl_, func, rv, ssl_error_buf);
return rv;
}
return 0;
}
int Connection::HandleSSLError(const char* func,
int rv,
ZeroStatus zs,
SyscallStatus ss) {
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence unused variable warning.
if (rv > 0) return rv;
if ((rv == 0) && (zs == kZeroIsNotAnError)) return rv;
int err = SSL_get_error(ssl_, rv);
if (err == SSL_ERROR_NONE) {
return 0;
} else if (err == SSL_ERROR_WANT_WRITE) {
DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
return 0;
} else if (err == SSL_ERROR_WANT_READ) {
DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
return 0;
} else if (err == SSL_ERROR_ZERO_RETURN) {
handle_->Set(String::New("error"),
Exception::Error(String::New("ZERO_RETURN")));
return rv;
} else if ((err == SSL_ERROR_SYSCALL) && (ss == kIgnoreSyscall)) {
return 0;
} else {
HandleScope scope;
BUF_MEM* mem;
BIO *bio;
assert(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
// XXX We need to drain the error queue for this thread or else OpenSSL
// has the possibility of blocking connections? This problem is not well
// understood. And we should be somehow propagating these errors up
// into JavaScript. There is no test which demonstrates this problem.
// https://github.com/joyent/node/issues/1719
if ((bio = BIO_new(BIO_s_mem()))) {
ERR_print_errors(bio);
BIO_get_mem_ptr(bio, &mem);
Local<Value> e = Exception::Error(String::New(mem->data, mem->length));
handle_->Set(String::New("error"), e);
BIO_free(bio);
}
return rv;
}
return 0;
}
void Connection::ClearError() {
#ifndef NDEBUG
HandleScope scope;
// We should clear the error in JS-land
assert(handle_->Get(String::New("error"))->BooleanValue() == false);
#endif // NDEBUG
}
void Connection::SetShutdownFlags() {
HandleScope scope;
int flags = SSL_get_shutdown(ssl_);
if (flags & SSL_SENT_SHUTDOWN) {
handle_->Set(String::New("sentShutdown"), True());
}