1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "node_buffer.h" // Buffer
24 #include "node_crypto.h" // SecureContext
25 #include "node_crypto_bio.h" // NodeBIO
26 #include "node_crypto_clienthello.h" // ClientHelloParser
27 #include "node_crypto_clienthello-inl.h"
28 #include "node_wrap.h" // WithGenericStream
29 #include "node_counters.h"
33 using crypto::SecureContext;
38 using v8::FunctionCallbackInfo;
39 using v8::FunctionTemplate;
41 using v8::HandleScope;
50 static Cached<String> onread_sym;
51 static Cached<String> onerror_sym;
52 static Cached<String> onhandshakestart_sym;
53 static Cached<String> onhandshakedone_sym;
54 static Cached<String> onclienthello_sym;
55 static Cached<String> onnewsession_sym;
56 static Cached<String> subject_sym;
57 static Cached<String> subjectaltname_sym;
58 static Cached<String> modulus_sym;
59 static Cached<String> exponent_sym;
60 static Cached<String> issuer_sym;
61 static Cached<String> valid_from_sym;
62 static Cached<String> valid_to_sym;
63 static Cached<String> fingerprint_sym;
64 static Cached<String> name_sym;
65 static Cached<String> version_sym;
66 static Cached<String> ext_key_usage_sym;
67 static Cached<String> sessionid_sym;
68 static Cached<String> tls_ticket_sym;
69 static Cached<String> servername_sym;
70 static Cached<String> sni_context_sym;
72 static Persistent<Function> tlsWrap;
74 static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
75 | ASN1_STRFLGS_ESC_MSB
76 | XN_FLAG_SEP_MULTILINE
80 TLSCallbacks::TLSCallbacks(Kind kind,
82 StreamWrapCallbacks* old)
83 : StreamWrapCallbacks(old),
90 pending_write_item_(NULL),
94 session_callbacks_(false),
97 // Persist SecureContext
98 sc_ = ObjectWrap::Unwrap<SecureContext>(sc);
99 sc_handle_.Reset(node_isolate, sc);
101 Local<Object> object = NewInstance(tlsWrap);
102 object->SetAlignedPointerInInternalField(0, this);
103 persistent().Reset(node_isolate, object);
105 // Initialize queue for clearIn writes
106 QUEUE_INIT(&write_item_queue_);
108 // We've our own session callbacks
109 SSL_CTX_sess_set_get_cb(sc_->ctx_, GetSessionCallback);
110 SSL_CTX_sess_set_new_cb(sc_->ctx_, NewSessionCallback);
116 SSL_SESSION* TLSCallbacks::GetSessionCallback(SSL* s,
120 HandleScope scope(node_isolate);
122 TLSCallbacks* c = static_cast<TLSCallbacks*>(SSL_get_app_data(s));
125 SSL_SESSION* sess = c->next_sess_;
126 c->next_sess_ = NULL;
132 int TLSCallbacks::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133 HandleScope scope(node_isolate);
135 TLSCallbacks* c = static_cast<TLSCallbacks*>(SSL_get_app_data(s));
136 if (!c->session_callbacks_)
139 // Check if session is small enough to be stored
140 int size = i2d_SSL_SESSION(sess, NULL);
141 if (size > SecureContext::kMaxSessionSize)
145 Local<Object> buff = Buffer::New(size);
146 unsigned char* serialized = reinterpret_cast<unsigned char*>(
148 memset(serialized, 0, size);
149 i2d_SSL_SESSION(sess, &serialized);
151 Local<Object> session = Buffer::New(reinterpret_cast<char*>(sess->session_id),
152 sess->session_id_length);
153 Handle<Value> argv[2] = { session, buff };
154 MakeCallback(c->object(), onnewsession_sym, ARRAY_SIZE(argv), argv);
160 TLSCallbacks::~TLSCallbacks() {
169 sc_handle_.Dispose();
170 persistent().Dispose();
172 #ifdef OPENSSL_NPN_NEGOTIATED
173 npn_protos_.Dispose();
174 selected_npn_proto_.Dispose();
175 #endif // OPENSSL_NPN_NEGOTIATED
177 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
178 sni_context_.Dispose();
179 #endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
183 void TLSCallbacks::InvokeQueued(int status) {
184 // Empty queue - ignore call
185 if (pending_write_item_ == NULL)
188 QUEUE* q = &pending_write_item_->member_;
189 pending_write_item_ = NULL;
192 while (q != &write_item_queue_) {
193 QUEUE* next = static_cast<QUEUE*>(QUEUE_NEXT(q));
194 WriteItem* wi = container_of(q, WriteItem, member_);
195 wi->cb_(&wi->w_->req_, status);
202 static int VerifyCallback(int preverify_ok, X509_STORE_CTX *ctx) {
203 // Quoting SSL_set_verify(3ssl):
205 // The VerifyCallback function is used to control the behaviour when
206 // the SSL_VERIFY_PEER flag is set. It must be supplied by the
207 // application and receives two arguments: preverify_ok indicates,
208 // whether the verification of the certificate in question was passed
209 // (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to
210 // the complete context used for the certificate chain verification.
212 // The certificate chain is checked starting with the deepest nesting
213 // level (the root CA certificate) and worked upward to the peer's
214 // certificate. At each level signatures and issuer attributes are
215 // checked. Whenever a verification error is found, the error number is
216 // stored in x509_ctx and VerifyCallback is called with preverify_ok=0.
217 // By applying X509_CTX_store_* functions VerifyCallback can locate the
218 // certificate in question and perform additional steps (see EXAMPLES).
219 // If no error is found for a certificate, VerifyCallback is called
220 // with preverify_ok=1 before advancing to the next level.
222 // The return value of VerifyCallback controls the strategy of the
223 // further verification process. If VerifyCallback returns 0, the
224 // verification process is immediately stopped with "verification
225 // failed" state. If SSL_VERIFY_PEER is set, a verification failure
226 // alert is sent to the peer and the TLS/SSL handshake is terminated. If
227 // VerifyCallback returns 1, the verification process is continued. If
228 // VerifyCallback always returns 1, the TLS/SSL handshake will not be
229 // terminated with respect to verification failures and the connection
230 // will be established. The calling process can however retrieve the
231 // error code of the last verification error using
232 // SSL_get_verify_result(3) or by maintaining its own error storage
233 // managed by VerifyCallback.
235 // If no VerifyCallback is specified, the default callback will be
236 // used. Its return value is identical to preverify_ok, so that any
237 // verification failure will lead to a termination of the TLS/SSL
238 // handshake with an alert message, if SSL_VERIFY_PEER is set.
240 // Since we cannot perform I/O quickly enough in this callback, we ignore
241 // all preverify_ok errors and let the handshake continue. It is
242 // imparative that the user use Connection::VerifyError after the
243 // 'secure' callback has been made.
248 void TLSCallbacks::InitSSL() {
249 assert(ssl_ == NULL);
252 ssl_ = SSL_new(sc_->ctx_);
253 enc_in_ = BIO_new(NodeBIO::GetMethod());
254 enc_out_ = BIO_new(NodeBIO::GetMethod());
256 SSL_set_bio(ssl_, enc_in_, enc_out_);
258 // NOTE: This could be overriden in SetVerifyMode
259 SSL_set_verify(ssl_, SSL_VERIFY_NONE, VerifyCallback);
261 #ifdef SSL_MODE_RELEASE_BUFFERS
262 long mode = SSL_get_mode(ssl_);
263 SSL_set_mode(ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
264 #endif // SSL_MODE_RELEASE_BUFFERS
266 SSL_set_app_data(ssl_, this);
267 SSL_set_info_callback(ssl_, SSLInfoCallback);
269 if (kind_ == kTLSServer) {
270 SSL_set_accept_state(ssl_);
272 #ifdef OPENSSL_NPN_NEGOTIATED
273 // Server should advertise NPN protocols
274 SSL_CTX_set_next_protos_advertised_cb(sc_->ctx_,
275 AdvertiseNextProtoCallback,
277 #endif // OPENSSL_NPN_NEGOTIATED
279 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
280 SSL_CTX_set_tlsext_servername_callback(sc_->ctx_, SelectSNIContextCallback);
281 SSL_CTX_set_tlsext_servername_arg(sc_->ctx_, this);
282 #endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
283 } else if (kind_ == kTLSClient) {
284 SSL_set_connect_state(ssl_);
286 #ifdef OPENSSL_NPN_NEGOTIATED
287 // Client should select protocol from list of advertised
288 // If server supports NPN
289 SSL_CTX_set_next_proto_select_cb(sc_->ctx_,
290 SelectNextProtoCallback,
292 #endif // OPENSSL_NPN_NEGOTIATED
298 // Initialize ring for queud clear data
299 clear_in_ = new NodeBIO();
303 void TLSCallbacks::Wrap(const FunctionCallbackInfo<Value>& args) {
304 HandleScope scope(node_isolate);
306 if (args.Length() < 1 || !args[0]->IsObject())
307 return ThrowTypeError("First argument should be a StreamWrap instance");
308 if (args.Length() < 2 || !args[1]->IsObject())
309 return ThrowTypeError("Second argument should be a SecureContext instance");
310 if (args.Length() < 3 || !args[2]->IsBoolean())
311 return ThrowTypeError("Third argument should be boolean");
313 Local<Object> stream = args[0].As<Object>();
314 Local<Object> sc = args[1].As<Object>();
315 Kind kind = args[2]->IsTrue() ? kTLSServer : kTLSClient;
317 TLSCallbacks* callbacks = NULL;
318 WITH_GENERIC_STREAM(stream, {
319 callbacks = new TLSCallbacks(kind, sc, wrap->callbacks());
320 wrap->OverrideCallbacks(callbacks);
323 if (callbacks == NULL) {
324 return args.GetReturnValue().SetNull();
327 args.GetReturnValue().Set(callbacks->persistent());
331 void TLSCallbacks::Start(const FunctionCallbackInfo<Value>& args) {
332 HandleScope scope(node_isolate);
334 UNWRAP(TLSCallbacks);
337 return ThrowError("Already started.");
338 wrap->started_ = true;
340 // Send ClientHello handshake
341 assert(wrap->kind_ == kTLSClient);
347 void TLSCallbacks::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
348 // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
349 // a non-const SSL* in OpenSSL <= 0.9.7e.
350 SSL* ssl = const_cast<SSL*>(ssl_);
351 if (where & SSL_CB_HANDSHAKE_START) {
352 HandleScope scope(node_isolate);
353 TLSCallbacks* c = static_cast<TLSCallbacks*>(SSL_get_app_data(ssl));
354 Local<Object> object = c->object();
355 if (object->Has(onhandshakestart_sym))
356 MakeCallback(object, onhandshakestart_sym, 0, NULL);
358 if (where & SSL_CB_HANDSHAKE_DONE) {
359 HandleScope scope(node_isolate);
360 TLSCallbacks* c = static_cast<TLSCallbacks*>(SSL_get_app_data(ssl));
361 c->established_ = true;
362 Local<Object> object = c->object();
363 if (object->Has(onhandshakedone_sym))
364 MakeCallback(object, onhandshakedone_sym, 0, NULL);
369 void TLSCallbacks::EncOut() {
370 // Ignore cycling data if ClientHello wasn't yet parsed
371 if (!hello_.IsEnded())
375 if (write_size_ != 0)
379 if (established_ && !QUEUE_EMPTY(&write_item_queue_)) {
380 pending_write_item_ = container_of(QUEUE_NEXT(&write_item_queue_),
383 QUEUE_INIT(&write_item_queue_);
387 if (BIO_pending(enc_out_) == 0) {
392 char* data = NodeBIO::FromBIO(enc_out_)->Peek(&write_size_);
393 assert(write_size_ != 0);
395 write_req_.data = this;
396 uv_buf_t buf = uv_buf_init(data, write_size_);
397 int r = uv_write(&write_req_, wrap()->stream(), &buf, 1, EncOutCb);
399 // Ignore errors, this should be already handled in js
401 if (wrap()->stream()->type == UV_TCP) {
402 NODE_COUNT_NET_BYTES_SENT(write_size_);
403 } else if (wrap()->stream()->type == UV_NAMED_PIPE) {
404 NODE_COUNT_PIPE_BYTES_SENT(write_size_);
410 void TLSCallbacks::EncOutCb(uv_write_t* req, int status) {
411 HandleScope scope(node_isolate);
413 TLSCallbacks* callbacks = static_cast<TLSCallbacks*>(req->data);
417 // Ignore errors after shutdown
418 if (callbacks->shutdown_)
421 // Notify about error
422 Local<Value> arg = String::Concat(
423 String::New("write cb error, status: "),
424 Integer::New(status, node_isolate)->ToString());
425 MakeCallback(callbacks->object(), onerror_sym, 1, &arg);
426 callbacks->InvokeQueued(status);
431 NodeBIO::FromBIO(callbacks->enc_out_)->Read(NULL, callbacks->write_size_);
433 // Try writing more data
434 callbacks->write_size_ = 0;
439 Handle<Value> TLSCallbacks::GetSSLError(int status, int* err) {
440 HandleScope scope(node_isolate);
442 *err = SSL_get_error(ssl_, status);
445 case SSL_ERROR_WANT_READ:
446 case SSL_ERROR_WANT_WRITE:
448 case SSL_ERROR_ZERO_RETURN:
449 return scope.Close(String::NewSymbol("ZERO_RETURN"));
456 assert(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL);
458 bio = BIO_new(BIO_s_mem());
460 ERR_print_errors(bio);
461 BIO_get_mem_ptr(bio, &mem);
462 Handle<Value> r = Exception::Error(String::New(mem->data, mem->length));
465 return scope.Close(r);
468 return Handle<Value>();
472 void TLSCallbacks::ClearOut() {
473 // Ignore cycling data if ClientHello wasn't yet parsed
474 if (!hello_.IsEnded())
477 HandleScope scope(node_isolate);
479 assert(ssl_ != NULL);
481 char out[kClearOutChunkSize];
484 read = SSL_read(ssl_, out, sizeof(out));
486 Local<Value> argv[] = {
487 Integer::New(read, node_isolate),
488 Buffer::New(out, read)
490 MakeCallback(Self(), onread_sym, ARRAY_SIZE(argv), argv);
496 Handle<Value> argv = GetSSLError(read, &err);
499 MakeCallback(object(), onerror_sym, 1, &argv);
504 bool TLSCallbacks::ClearIn() {
505 // Ignore cycling data if ClientHello wasn't yet parsed
506 if (!hello_.IsEnded())
509 HandleScope scope(node_isolate);
512 while (clear_in_->Length() > 0) {
514 char* data = clear_in_->Peek(&avail);
515 written = SSL_write(ssl_, data, avail);
516 assert(written == -1 || written == static_cast<int>(avail));
519 clear_in_->Read(NULL, avail);
523 if (clear_in_->Length() == 0) {
524 assert(written >= 0);
528 // Error or partial write
530 Handle<Value> argv = GetSSLError(written, &err);
532 MakeCallback(object(), onerror_sym, 1, &argv);
538 int TLSCallbacks::DoWrite(WriteWrap* w,
541 uv_stream_t* send_handle,
543 HandleScope scope(node_isolate);
545 assert(send_handle == NULL);
547 // Queue callback to execute it on next tick
548 WriteItem* wi = new WriteItem(w, cb);
551 // Empty writes should not go through encryption process
553 for (i = 0; i < count; i++)
554 if (bufs[i].len > 0) {
560 // However if there any data that should be written to socket,
561 // callback should not be invoked immediately
562 if (BIO_pending(enc_out_) == 0)
563 return uv_write(&w->req_, wrap()->stream(), bufs, count, cb);
566 QUEUE_INSERT_TAIL(&write_item_queue_, &wi->member_);
574 // Process enqueued data first
576 // If there're still data to process - enqueue current one
577 for (i = 0; i < count; i++)
578 clear_in_->Write(bufs[i].base, bufs[i].len);
583 for (i = 0; i < count; i++) {
584 written = SSL_write(ssl_, bufs[i].base, bufs[i].len);
585 assert(written == -1 || written == static_cast<int>(bufs[i].len));
592 Handle<Value> argv = GetSSLError(written, &err);
593 if (!argv.IsEmpty()) {
594 MakeCallback(object(), onerror_sym, 1, &argv);
598 // No errors, queue rest
599 for (; i < count; i++)
600 clear_in_->Write(bufs[i].base, bufs[i].len);
603 // Try writing data immediately
610 void TLSCallbacks::AfterWrite(WriteWrap* w) {
611 // Intentionally empty
615 uv_buf_t TLSCallbacks::DoAlloc(uv_handle_t* handle, size_t suggested_size) {
616 size_t size = suggested_size;
617 char* data = NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
618 return uv_buf_init(data, size);
622 void TLSCallbacks::DoRead(uv_stream_t* handle,
625 uv_handle_type pending) {
627 // Error should be emitted only after all data was read
629 Local<Value> arg = Integer::New(nread, node_isolate);
630 MakeCallback(Self(), onread_sym, 1, &arg);
634 // Only client connections can receive data
635 assert(ssl_ != NULL);
638 NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
639 enc_in->Commit(nread);
641 // Parse ClientHello first
642 if (!hello_.IsEnded()) {
644 uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
645 assert(avail == 0 || data != NULL);
646 return hello_.Parse(data, avail);
649 // Cycle OpenSSL's state
654 int TLSCallbacks::DoShutdown(ShutdownWrap* req_wrap, uv_shutdown_cb cb) {
655 if (SSL_shutdown(ssl_) == 0)
659 return StreamWrapCallbacks::DoShutdown(req_wrap, cb);
663 #define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: reason = #CODE; break;
664 void TLSCallbacks::VerifyError(const FunctionCallbackInfo<Value>& args) {
665 HandleScope scope(node_isolate);
667 UNWRAP(TLSCallbacks);
669 // XXX Do this check in JS land?
670 X509* peer_cert = SSL_get_peer_certificate(wrap->ssl_);
671 if (peer_cert == NULL) {
672 // We requested a certificate and they did not send us one.
673 // Definitely an error.
674 // XXX is this the right error message?
675 Local<String> s = String::New("UNABLE_TO_GET_ISSUER_CERT");
676 return args.GetReturnValue().Set(Exception::Error(s));
678 X509_free(peer_cert);
680 long x509_verify_error = SSL_get_verify_result(wrap->ssl_);
682 const char* reason = NULL;
684 switch (x509_verify_error) {
686 return args.GetReturnValue().SetNull();
687 CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
688 CASE_X509_ERR(UNABLE_TO_GET_CRL)
689 CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
690 CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
691 CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
692 CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
693 CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
694 CASE_X509_ERR(CERT_NOT_YET_VALID)
695 CASE_X509_ERR(CERT_HAS_EXPIRED)
696 CASE_X509_ERR(CRL_NOT_YET_VALID)
697 CASE_X509_ERR(CRL_HAS_EXPIRED)
698 CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
699 CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
700 CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
701 CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
702 CASE_X509_ERR(OUT_OF_MEM)
703 CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
704 CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
705 CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
706 CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
707 CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
708 CASE_X509_ERR(CERT_REVOKED)
709 CASE_X509_ERR(INVALID_CA)
710 CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
711 CASE_X509_ERR(INVALID_PURPOSE)
712 CASE_X509_ERR(CERT_UNTRUSTED)
713 CASE_X509_ERR(CERT_REJECTED)
715 s = String::New(X509_verify_cert_error_string(x509_verify_error));
720 s = String::New(reason);
723 args.GetReturnValue().Set(Exception::Error(s));
728 void TLSCallbacks::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
729 HandleScope scope(node_isolate);
731 UNWRAP(TLSCallbacks);
733 if (args.Length() < 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
734 return ThrowTypeError("Bad arguments, expected two booleans");
737 if (wrap->kind_ == kTLSServer) {
738 bool request_cert = args[0]->IsTrue();
740 // Note reject_unauthorized ignored.
741 verify_mode = SSL_VERIFY_NONE;
743 bool reject_unauthorized = args[1]->IsTrue();
744 verify_mode = SSL_VERIFY_PEER;
745 if (reject_unauthorized) verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
748 // Note request_cert and reject_unauthorized are ignored for clients.
749 verify_mode = SSL_VERIFY_NONE;
752 // Always allow a connection. We'll reject in javascript.
753 SSL_set_verify(wrap->ssl_, verify_mode, VerifyCallback);
757 void TLSCallbacks::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
758 HandleScope scope(node_isolate);
759 UNWRAP(TLSCallbacks);
760 bool yes = SSL_session_reused(wrap->ssl_);
761 args.GetReturnValue().Set(yes);
765 void TLSCallbacks::EnableSessionCallbacks(
766 const FunctionCallbackInfo<Value>& args) {
767 HandleScope scope(node_isolate);
769 UNWRAP(TLSCallbacks);
771 wrap->session_callbacks_ = true;
772 EnableHelloParser(args);
776 void TLSCallbacks::EnableHelloParser(
777 const FunctionCallbackInfo<Value>& args) {
778 HandleScope scope(node_isolate);
780 UNWRAP(TLSCallbacks);
782 wrap->hello_.Start(OnClientHello, OnClientHelloParseEnd, wrap);
786 void TLSCallbacks::OnClientHello(void* arg,
787 const ClientHelloParser::ClientHello& hello) {
788 HandleScope scope(node_isolate);
790 TLSCallbacks* c = static_cast<TLSCallbacks*>(arg);
792 Local<Object> hello_obj = Object::New();
793 Local<Object> buff = Buffer::New(
794 reinterpret_cast<const char*>(hello.session_id()),
795 hello.session_size());
796 hello_obj->Set(sessionid_sym, buff);
797 if (hello.servername() == NULL) {
798 hello_obj->Set(servername_sym, String::Empty(node_isolate));
800 Local<String> servername = String::New(
801 reinterpret_cast<const char*>(hello.servername()),
802 hello.servername_size());
803 hello_obj->Set(servername_sym, servername);
805 hello_obj->Set(tls_ticket_sym, Boolean::New(hello.has_ticket()));
807 Handle<Value> argv[1] = { hello_obj };
808 MakeCallback(c->object(), onclienthello_sym, 1, argv);
812 void TLSCallbacks::OnClientHelloParseEnd(void* arg) {
813 TLSCallbacks* c = static_cast<TLSCallbacks*>(arg);
818 void TLSCallbacks::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
819 HandleScope scope(node_isolate);
821 UNWRAP(TLSCallbacks);
823 Local<Object> info = Object::New();
824 X509* peer_cert = SSL_get_peer_certificate(wrap->ssl_);
825 if (peer_cert != NULL) {
826 BIO* bio = BIO_new(BIO_s_mem());
828 if (X509_NAME_print_ex(bio,
829 X509_get_subject_name(peer_cert),
831 X509_NAME_FLAGS) > 0) {
832 BIO_get_mem_ptr(bio, &mem);
833 info->Set(subject_sym, String::New(mem->data, mem->length));
835 (void) BIO_reset(bio);
837 if (X509_NAME_print_ex(bio,
838 X509_get_issuer_name(peer_cert),
840 X509_NAME_FLAGS) > 0) {
841 BIO_get_mem_ptr(bio, &mem);
842 info->Set(issuer_sym, String::New(mem->data, mem->length));
844 (void) BIO_reset(bio);
846 int index = X509_get_ext_by_NID(peer_cert, NID_subject_alt_name, -1);
851 ext = X509_get_ext(peer_cert, index);
854 rv = X509V3_EXT_print(bio, ext, 0, 0);
857 BIO_get_mem_ptr(bio, &mem);
858 info->Set(subjectaltname_sym, String::New(mem->data, mem->length));
860 (void) BIO_reset(bio);
863 EVP_PKEY* pkey = NULL;
865 if (NULL != (pkey = X509_get_pubkey(peer_cert)) &&
866 NULL != (rsa = EVP_PKEY_get1_RSA(pkey))) {
867 BN_print(bio, rsa->n);
868 BIO_get_mem_ptr(bio, &mem);
869 info->Set(modulus_sym, String::New(mem->data, mem->length) );
870 (void) BIO_reset(bio);
872 BN_print(bio, rsa->e);
873 BIO_get_mem_ptr(bio, &mem);
874 info->Set(exponent_sym, String::New(mem->data, mem->length) );
875 (void) BIO_reset(bio);
887 ASN1_TIME_print(bio, X509_get_notBefore(peer_cert));
888 BIO_get_mem_ptr(bio, &mem);
889 info->Set(valid_from_sym, String::New(mem->data, mem->length));
890 (void) BIO_reset(bio);
892 ASN1_TIME_print(bio, X509_get_notAfter(peer_cert));
893 BIO_get_mem_ptr(bio, &mem);
894 info->Set(valid_to_sym, String::New(mem->data, mem->length));
897 unsigned int md_size, i;
898 unsigned char md[EVP_MAX_MD_SIZE];
899 if (X509_digest(peer_cert, EVP_sha1(), md, &md_size)) {
900 const char hex[] = "0123456789ABCDEF";
901 char fingerprint[EVP_MAX_MD_SIZE * 3];
903 for (i = 0; i < md_size; i++) {
904 fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
905 fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
906 fingerprint[(3*i)+2] = ':';
910 fingerprint[(3*(md_size-1))+2] = '\0';
912 fingerprint[0] = '\0';
914 info->Set(fingerprint_sym, String::New(fingerprint));
917 STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
918 X509_get_ext_d2i(peer_cert,
923 Local<Array> ext_key_usage = Array::New();
926 for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
927 memset(buf, 0, sizeof(buf));
928 OBJ_obj2txt(buf, sizeof(buf) - 1, sk_ASN1_OBJECT_value(eku, i), 1);
929 ext_key_usage->Set(Integer::New(i, node_isolate), String::New(buf));
932 sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
933 info->Set(ext_key_usage_sym, ext_key_usage);
936 X509_free(peer_cert);
939 args.GetReturnValue().Set(info);
943 void TLSCallbacks::GetSession(const FunctionCallbackInfo<Value>& args) {
944 HandleScope scope(node_isolate);
946 UNWRAP(TLSCallbacks);
948 SSL_SESSION* sess = SSL_get_session(wrap->ssl_);
951 int slen = i2d_SSL_SESSION(sess, NULL);
955 unsigned char* sbuf = new unsigned char[slen];
956 unsigned char* p = sbuf;
957 i2d_SSL_SESSION(sess, &p);
958 Local<Value> s = Encode(sbuf, slen, BINARY);
959 args.GetReturnValue().Set(s);
964 args.GetReturnValue().SetNull();
968 void TLSCallbacks::SetSession(const FunctionCallbackInfo<Value>& args) {
969 HandleScope scope(node_isolate);
971 UNWRAP(TLSCallbacks);
974 return ThrowError("Already started.");
976 if (args.Length() < 1 ||
977 (!args[0]->IsString() && !Buffer::HasInstance(args[0]))) {
978 return ThrowTypeError("Bad argument");
981 size_t slen = Buffer::Length(args[0]);
982 char* sbuf = new char[slen];
984 ssize_t wlen = DecodeWrite(sbuf, slen, args[0], BINARY);
985 assert(wlen == static_cast<ssize_t>(slen));
987 const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
988 SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, wlen);
994 int r = SSL_set_session(wrap->ssl_, sess);
995 SSL_SESSION_free(sess);
998 return ThrowError("SSL_set_session error");
1003 void TLSCallbacks::LoadSession(const FunctionCallbackInfo<Value>& args) {
1004 HandleScope scope(node_isolate);
1006 UNWRAP(TLSCallbacks);
1008 if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1009 ssize_t slen = Buffer::Length(args[0]);
1010 char* sbuf = Buffer::Data(args[0]);
1012 const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1013 SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, slen);
1015 // Setup next session and move hello to the BIO buffer
1016 if (wrap->next_sess_ != NULL)
1017 SSL_SESSION_free(wrap->next_sess_);
1018 wrap->next_sess_ = sess;
1020 Local<Object> info = Object::New();
1021 #ifndef OPENSSL_NO_TLSEXT
1022 if (sess->tlsext_hostname == NULL) {
1023 info->Set(servername_sym, False(node_isolate));
1025 info->Set(servername_sym, String::New(sess->tlsext_hostname));
1028 args.GetReturnValue().Set(info);
1032 void TLSCallbacks::EndParser(const FunctionCallbackInfo<Value>& args) {
1033 HandleScope scope(node_isolate);
1035 UNWRAP(TLSCallbacks);
1041 void TLSCallbacks::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
1042 HandleScope scope(node_isolate);
1044 UNWRAP(TLSCallbacks);
1046 const SSL_CIPHER* c;
1048 c = SSL_get_current_cipher(wrap->ssl_);
1052 const char* cipher_name = SSL_CIPHER_get_name(c);
1053 const char* cipher_version = SSL_CIPHER_get_version(c);
1055 Local<Object> info = Object::New();
1056 info->Set(name_sym, String::New(cipher_name));
1057 info->Set(version_sym, String::New(cipher_version));
1058 args.GetReturnValue().Set(info);
1062 #ifdef OPENSSL_NPN_NEGOTIATED
1063 int TLSCallbacks::AdvertiseNextProtoCallback(SSL* s,
1064 const unsigned char** data,
1067 TLSCallbacks* p = static_cast<TLSCallbacks*>(arg);
1069 if (p->npn_protos_.IsEmpty()) {
1070 // No initialization - no NPN protocols
1071 *data = reinterpret_cast<const unsigned char*>("");
1074 Local<Object> obj = PersistentToLocal(node_isolate, p->npn_protos_);
1075 *data = reinterpret_cast<const unsigned char*>(Buffer::Data(obj));
1076 *len = Buffer::Length(obj);
1079 return SSL_TLSEXT_ERR_OK;
1083 int TLSCallbacks::SelectNextProtoCallback(SSL* s,
1084 unsigned char** out,
1085 unsigned char* outlen,
1086 const unsigned char* in,
1089 TLSCallbacks* p = static_cast<TLSCallbacks*>(arg);
1091 // Release old protocol handler if present
1092 p->selected_npn_proto_.Dispose();
1094 if (p->npn_protos_.IsEmpty()) {
1095 // We should at least select one protocol
1096 // If server is using NPN
1097 *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
1100 // set status: unsupported
1101 p->selected_npn_proto_.Reset(node_isolate, False(node_isolate));
1103 return SSL_TLSEXT_ERR_OK;
1106 Local<Object> obj = PersistentToLocal(node_isolate, p->npn_protos_);
1107 const unsigned char* npn_protos =
1108 reinterpret_cast<const unsigned char*>(Buffer::Data(obj));
1109 size_t len = Buffer::Length(obj);
1111 int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
1112 Handle<Value> result;
1114 case OPENSSL_NPN_UNSUPPORTED:
1115 result = Null(node_isolate);
1117 case OPENSSL_NPN_NEGOTIATED:
1118 result = String::New(reinterpret_cast<const char*>(*out), *outlen);
1120 case OPENSSL_NPN_NO_OVERLAP:
1121 result = False(node_isolate);
1127 if (!result.IsEmpty())
1128 p->selected_npn_proto_.Reset(node_isolate, result);
1130 return SSL_TLSEXT_ERR_OK;
1134 void TLSCallbacks::GetNegotiatedProto(const FunctionCallbackInfo<Value>& args) {
1135 HandleScope scope(node_isolate);
1137 UNWRAP(TLSCallbacks);
1139 if (wrap->kind_ == kTLSClient) {
1140 if (wrap->selected_npn_proto_.IsEmpty() == false) {
1141 args.GetReturnValue().Set(wrap->selected_npn_proto_);
1146 const unsigned char* npn_proto;
1147 unsigned int npn_proto_len;
1149 SSL_get0_next_proto_negotiated(wrap->ssl_, &npn_proto, &npn_proto_len);
1152 return args.GetReturnValue().Set(false);
1155 args.GetReturnValue().Set(
1156 String::New(reinterpret_cast<const char*>(npn_proto), npn_proto_len));
1160 void TLSCallbacks::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
1161 HandleScope scope(node_isolate);
1163 UNWRAP(TLSCallbacks);
1165 if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1166 return ThrowTypeError("Must give a Buffer as first argument");
1168 wrap->npn_protos_.Reset(node_isolate, args[0].As<Object>());
1170 #endif // OPENSSL_NPN_NEGOTIATED
1173 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1174 void TLSCallbacks::GetServername(const FunctionCallbackInfo<Value>& args) {
1175 HandleScope scope(node_isolate);
1177 UNWRAP(TLSCallbacks);
1179 const char* servername = SSL_get_servername(wrap->ssl_,
1180 TLSEXT_NAMETYPE_host_name);
1181 if (servername != NULL) {
1182 args.GetReturnValue().Set(String::New(servername));
1184 args.GetReturnValue().Set(false);
1189 void TLSCallbacks::SetServername(const FunctionCallbackInfo<Value>& args) {
1190 HandleScope scope(node_isolate);
1192 UNWRAP(TLSCallbacks);
1194 if (args.Length() < 1 || !args[0]->IsString())
1195 return ThrowTypeError("First argument should be a string");
1198 return ThrowError("Already started.");
1200 if (wrap->kind_ != kTLSClient)
1203 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1204 String::Utf8Value servername(args[0].As<String>());
1205 SSL_set_tlsext_host_name(wrap->ssl_, *servername);
1206 #endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1210 int TLSCallbacks::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1211 HandleScope scope(node_isolate);
1213 TLSCallbacks* p = static_cast<TLSCallbacks*>(arg);
1215 const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1217 if (servername != NULL) {
1218 // Call the SNI callback and use its return value as context
1219 Local<Object> object = p->object();
1221 if (object->Has(sni_context_sym)) {
1222 ctx = object->Get(sni_context_sym);
1225 if (ctx.IsEmpty() || ctx->IsUndefined())
1226 return SSL_TLSEXT_ERR_NOACK;
1228 p->sni_context_.Dispose();
1229 p->sni_context_.Reset(node_isolate, ctx);
1231 SecureContext* sc = ObjectWrap::Unwrap<SecureContext>(ctx.As<Object>());
1232 SSL_set_SSL_CTX(s, sc->ctx_);
1235 return SSL_TLSEXT_ERR_OK;
1237 #endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1240 void TLSCallbacks::Initialize(Handle<Object> target) {
1241 HandleScope scope(node_isolate);
1243 NODE_SET_METHOD(target, "wrap", TLSCallbacks::Wrap);
1245 Local<FunctionTemplate> t = FunctionTemplate::New();
1246 t->InstanceTemplate()->SetInternalFieldCount(1);
1247 t->SetClassName(String::NewSymbol("TLSWrap"));
1249 NODE_SET_PROTOTYPE_METHOD(t, "start", Start);
1250 NODE_SET_PROTOTYPE_METHOD(t, "getPeerCertificate", GetPeerCertificate);
1251 NODE_SET_PROTOTYPE_METHOD(t, "getSession", GetSession);
1252 NODE_SET_PROTOTYPE_METHOD(t, "setSession", SetSession);
1253 NODE_SET_PROTOTYPE_METHOD(t, "loadSession", LoadSession);
1254 NODE_SET_PROTOTYPE_METHOD(t, "endParser", EndParser);
1255 NODE_SET_PROTOTYPE_METHOD(t, "getCurrentCipher", GetCurrentCipher);
1256 NODE_SET_PROTOTYPE_METHOD(t, "verifyError", VerifyError);
1257 NODE_SET_PROTOTYPE_METHOD(t, "setVerifyMode", SetVerifyMode);
1258 NODE_SET_PROTOTYPE_METHOD(t, "isSessionReused", IsSessionReused);
1259 NODE_SET_PROTOTYPE_METHOD(t,
1260 "enableSessionCallbacks",
1261 EnableSessionCallbacks);
1262 NODE_SET_PROTOTYPE_METHOD(t,
1263 "enableHelloParser",
1266 #ifdef OPENSSL_NPN_NEGOTIATED
1267 NODE_SET_PROTOTYPE_METHOD(t, "getNegotiatedProtocol", GetNegotiatedProto);
1268 NODE_SET_PROTOTYPE_METHOD(t, "setNPNProtocols", SetNPNProtocols);
1269 #endif // OPENSSL_NPN_NEGOTIATED
1271 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1272 NODE_SET_PROTOTYPE_METHOD(t, "getServername", GetServername);
1273 NODE_SET_PROTOTYPE_METHOD(t, "setServername", SetServername);
1274 #endif // SSL_CRT_SET_TLSEXT_SERVERNAME_CB
1276 tlsWrap.Reset(node_isolate, t->GetFunction());
1278 onread_sym = String::New("onread");
1279 onerror_sym = String::New("onerror");
1280 onhandshakestart_sym = String::New("onhandshakestart");
1281 onhandshakedone_sym = String::New("onhandshakedone");
1282 onclienthello_sym = String::New("onclienthello");
1283 onnewsession_sym = String::New("onnewsession");
1285 subject_sym = String::New("subject");
1286 issuer_sym = String::New("issuer");
1287 valid_from_sym = String::New("valid_from");
1288 valid_to_sym = String::New("valid_to");
1289 subjectaltname_sym = String::New("subjectaltname");
1290 modulus_sym = String::New("modulus");
1291 exponent_sym = String::New("exponent");
1292 fingerprint_sym = String::New("fingerprint");
1293 name_sym = String::New("name");
1294 version_sym = String::New("version");
1295 ext_key_usage_sym = String::New("ext_key_usage");
1296 sessionid_sym = String::New("sessionId");
1297 tls_ticket_sym = String::New("tlsTicket");
1298 servername_sym = String::New("servername");
1299 sni_context_sym = String::New("sni_context");
1304 NODE_MODULE(node_tls_wrap, node::TLSCallbacks::Initialize)