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.
22 #include "node_crypto.h"
23 #include "node_crypto_groups.h"
27 #include "node_buffer.h"
28 #include "node_root_certs.h"
32 #define strcasecmp _stricmp
38 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
39 # define OPENSSL_CONST const
41 # define OPENSSL_CONST
44 #define ASSERT_IS_BUFFER(val) \
45 if (!Buffer::HasInstance(val)) { \
46 return ThrowException(Exception::TypeError(String::New("Not a buffer"))); \
49 static const char PUBLIC_KEY_PFX[] = "-----BEGIN PUBLIC KEY-----";
50 static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
51 static const char PUBRSA_KEY_PFX[] = "-----BEGIN RSA PUBLIC KEY-----";
52 static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
53 static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
54 | ASN1_STRFLGS_ESC_MSB
55 | XN_FLAG_SEP_MULTILINE
63 static Persistent<String> errno_symbol;
64 static Persistent<String> syscall_symbol;
65 static Persistent<String> subject_symbol;
66 static Persistent<String> subjectaltname_symbol;
67 static Persistent<String> modulus_symbol;
68 static Persistent<String> exponent_symbol;
69 static Persistent<String> issuer_symbol;
70 static Persistent<String> valid_from_symbol;
71 static Persistent<String> valid_to_symbol;
72 static Persistent<String> fingerprint_symbol;
73 static Persistent<String> name_symbol;
74 static Persistent<String> version_symbol;
75 static Persistent<String> ext_key_usage_symbol;
76 static Persistent<String> onhandshakestart_sym;
77 static Persistent<String> onhandshakedone_sym;
78 static Persistent<String> onclienthello_sym;
79 static Persistent<String> onnewsession_sym;
80 static Persistent<String> sessionid_sym;
82 static Persistent<FunctionTemplate> secure_context_constructor;
84 static uv_rwlock_t* locks;
87 static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
88 CRYPTO_THREADID_set_numeric(tid, uv_thread_self());
92 static void crypto_lock_init(void) {
95 n = CRYPTO_num_locks();
96 locks = new uv_rwlock_t[n];
98 for (i = 0; i < n; i++)
99 if (uv_rwlock_init(locks + i))
104 static void crypto_lock_cb(int mode, int n, const char* file, int line) {
105 assert((mode & CRYPTO_LOCK) || (mode & CRYPTO_UNLOCK));
106 assert((mode & CRYPTO_READ) || (mode & CRYPTO_WRITE));
108 if (mode & CRYPTO_LOCK) {
109 if (mode & CRYPTO_READ)
110 uv_rwlock_rdlock(locks + n);
112 uv_rwlock_wrlock(locks + n);
114 if (mode & CRYPTO_READ)
115 uv_rwlock_rdunlock(locks + n);
117 uv_rwlock_wrunlock(locks + n);
122 Handle<Value> ThrowCryptoErrorHelper(unsigned long err, bool is_type_error) {
123 HandleScope scope(node_isolate);
125 ERR_error_string_n(err, errmsg, sizeof(errmsg));
126 return is_type_error ? ThrowTypeError(errmsg) : ThrowError(errmsg);
130 Handle<Value> ThrowCryptoError(unsigned long err) {
131 return ThrowCryptoErrorHelper(err, false);
135 Handle<Value> ThrowCryptoTypeError(unsigned long err) {
136 return ThrowCryptoErrorHelper(err, true);
140 void SecureContext::Initialize(Handle<Object> target) {
141 HandleScope scope(node_isolate);
143 Local<FunctionTemplate> t = FunctionTemplate::New(SecureContext::New);
144 secure_context_constructor = Persistent<FunctionTemplate>::New(node_isolate,
147 t->InstanceTemplate()->SetInternalFieldCount(1);
148 t->SetClassName(String::NewSymbol("SecureContext"));
150 NODE_SET_PROTOTYPE_METHOD(t, "init", SecureContext::Init);
151 NODE_SET_PROTOTYPE_METHOD(t, "setKey", SecureContext::SetKey);
152 NODE_SET_PROTOTYPE_METHOD(t, "setCert", SecureContext::SetCert);
153 NODE_SET_PROTOTYPE_METHOD(t, "addCACert", SecureContext::AddCACert);
154 NODE_SET_PROTOTYPE_METHOD(t, "addCRL", SecureContext::AddCRL);
155 NODE_SET_PROTOTYPE_METHOD(t, "addRootCerts", SecureContext::AddRootCerts);
156 NODE_SET_PROTOTYPE_METHOD(t, "setCiphers", SecureContext::SetCiphers);
157 NODE_SET_PROTOTYPE_METHOD(t, "setOptions", SecureContext::SetOptions);
158 NODE_SET_PROTOTYPE_METHOD(t, "setSessionIdContext",
159 SecureContext::SetSessionIdContext);
160 NODE_SET_PROTOTYPE_METHOD(t, "setSessionTimeout",
161 SecureContext::SetSessionTimeout);
162 NODE_SET_PROTOTYPE_METHOD(t, "close", SecureContext::Close);
163 NODE_SET_PROTOTYPE_METHOD(t, "loadPKCS12", SecureContext::LoadPKCS12);
165 target->Set(String::NewSymbol("SecureContext"), t->GetFunction());
169 Handle<Value> SecureContext::New(const Arguments& args) {
170 HandleScope scope(node_isolate);
171 SecureContext *p = new SecureContext();
172 p->Wrap(args.Holder());
177 Handle<Value> SecureContext::Init(const Arguments& args) {
178 HandleScope scope(node_isolate);
180 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
182 OPENSSL_CONST SSL_METHOD *method = SSLv23_method();
184 if (args.Length() == 1 && args[0]->IsString()) {
185 String::Utf8Value sslmethod(args[0]);
187 if (strcmp(*sslmethod, "SSLv2_method") == 0) {
188 #ifndef OPENSSL_NO_SSL2
189 method = SSLv2_method();
191 return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
193 } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
194 #ifndef OPENSSL_NO_SSL2
195 method = SSLv2_server_method();
197 return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
199 } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
200 #ifndef OPENSSL_NO_SSL2
201 method = SSLv2_client_method();
203 return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
205 } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
206 method = SSLv3_method();
207 } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
208 method = SSLv3_server_method();
209 } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
210 method = SSLv3_client_method();
211 } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
212 method = SSLv23_method();
213 } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
214 method = SSLv23_server_method();
215 } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
216 method = SSLv23_client_method();
217 } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
218 method = TLSv1_method();
219 } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
220 method = TLSv1_server_method();
221 } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
222 method = TLSv1_client_method();
224 return ThrowException(Exception::Error(String::New("Unknown method")));
228 sc->ctx_ = SSL_CTX_new(method);
230 // SSL session cache configuration
231 SSL_CTX_set_session_cache_mode(sc->ctx_,
232 SSL_SESS_CACHE_SERVER |
233 SSL_SESS_CACHE_NO_INTERNAL |
234 SSL_SESS_CACHE_NO_AUTO_CLEAR);
235 SSL_CTX_sess_set_get_cb(sc->ctx_, GetSessionCallback);
236 SSL_CTX_sess_set_new_cb(sc->ctx_, NewSessionCallback);
238 sc->ca_store_ = NULL;
239 return True(node_isolate);
243 SSL_SESSION* SecureContext::GetSessionCallback(SSL* s,
247 HandleScope scope(node_isolate);
249 Connection* p = static_cast<Connection*>(SSL_get_app_data(s));
252 SSL_SESSION* sess = p->next_sess_;
253 p->next_sess_ = NULL;
259 void SessionDataFree(char* data, void* hint) {
264 int SecureContext::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
265 HandleScope scope(node_isolate);
267 Connection* p = static_cast<Connection*>(SSL_get_app_data(s));
269 // Check if session is small enough to be stored
270 int size = i2d_SSL_SESSION(sess, NULL);
271 if (size > kMaxSessionSize) return 0;
274 char* serialized = new char[size];
275 unsigned char* pserialized = reinterpret_cast<unsigned char*>(serialized);
276 memset(serialized, 0, size);
277 i2d_SSL_SESSION(sess, &pserialized);
279 Handle<Value> argv[2] = {
280 Buffer::New(reinterpret_cast<char*>(sess->session_id),
281 sess->session_id_length)->handle_,
282 Buffer::New(serialized, size, SessionDataFree, NULL)->handle_
285 if (onnewsession_sym.IsEmpty()) {
286 onnewsession_sym = NODE_PSYMBOL("onnewsession");
288 MakeCallback(p->handle_, onnewsession_sym, ARRAY_SIZE(argv), argv);
294 // Takes a string or buffer and loads it into a BIO.
295 // Caller responsible for BIO_free_all-ing the returned object.
296 static BIO* LoadBIO (Handle<Value> v) {
297 BIO *bio = BIO_new(BIO_s_mem());
298 if (!bio) return NULL;
300 HandleScope scope(node_isolate);
305 String::Utf8Value s(v);
306 r = BIO_write(bio, *s, s.length());
307 } else if (Buffer::HasInstance(v)) {
308 char* buffer_data = Buffer::Data(v);
309 size_t buffer_length = Buffer::Length(v);
310 r = BIO_write(bio, buffer_data, buffer_length);
322 // Takes a string or buffer and loads it into an X509
323 // Caller responsible for X509_free-ing the returned object.
324 static X509* LoadX509 (Handle<Value> v) {
325 HandleScope scope(node_isolate); // necessary?
327 BIO *bio = LoadBIO(v);
328 if (!bio) return NULL;
330 X509 * x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
341 Handle<Value> SecureContext::SetKey(const Arguments& args) {
342 HandleScope scope(node_isolate);
344 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
346 unsigned int len = args.Length();
347 if (len != 1 && len != 2) {
348 return ThrowException(Exception::TypeError(String::New("Bad parameter")));
350 if (len == 2 && !args[1]->IsString()) {
351 return ThrowException(Exception::TypeError(String::New("Bad parameter")));
354 BIO *bio = LoadBIO(args[0]);
355 if (!bio) return False(node_isolate);
357 String::Utf8Value passphrase(args[1]);
359 EVP_PKEY* key = PEM_read_bio_PrivateKey(bio, NULL, NULL,
360 len == 1 ? NULL : *passphrase);
364 unsigned long err = ERR_get_error();
366 return ThrowException(Exception::Error(
367 String::New("PEM_read_bio_PrivateKey")));
369 return ThrowCryptoError(err);
372 SSL_CTX_use_PrivateKey(sc->ctx_, key);
376 return True(node_isolate);
380 // Read a file that contains our certificate in "PEM" format,
381 // possibly followed by a sequence of CA certificates that should be
382 // sent to the peer in the Certificate message.
384 // Taken from OpenSSL - editted for style.
385 int SSL_CTX_use_certificate_chain(SSL_CTX *ctx, BIO *in) {
389 x = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
392 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
396 ret = SSL_CTX_use_certificate(ctx, x);
398 if (ERR_peek_error() != 0) {
399 // Key/certificate mismatch doesn't imply ret==0 ...
404 // If we could set up our certificate, now proceed to
405 // the CA certificates.
410 if (ctx->extra_certs != NULL) {
411 sk_X509_pop_free(ctx->extra_certs, X509_free);
412 ctx->extra_certs = NULL;
415 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
416 r = SSL_CTX_add_extra_chain_cert(ctx, ca);
423 // Note that we must not free r if it was successfully
424 // added to the chain (while we must free the main
425 // certificate, since its reference count is increased
426 // by SSL_CTX_use_certificate).
429 // When the while loop ends, it's usually just EOF.
430 err = ERR_peek_last_error();
431 if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
432 ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
441 if (x != NULL) X509_free(x);
446 Handle<Value> SecureContext::SetCert(const Arguments& args) {
447 HandleScope scope(node_isolate);
449 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
451 if (args.Length() != 1) {
452 return ThrowException(Exception::TypeError(
453 String::New("Bad parameter")));
456 BIO* bio = LoadBIO(args[0]);
457 if (!bio) return False(node_isolate);
459 int rv = SSL_CTX_use_certificate_chain(sc->ctx_, bio);
464 unsigned long err = ERR_get_error();
466 return ThrowException(Exception::Error(
467 String::New("SSL_CTX_use_certificate_chain")));
469 return ThrowCryptoError(err);
472 return True(node_isolate);
476 Handle<Value> SecureContext::AddCACert(const Arguments& args) {
477 bool newCAStore = false;
478 HandleScope scope(node_isolate);
480 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
482 if (args.Length() != 1) {
483 return ThrowException(Exception::TypeError(String::New("Bad parameter")));
486 if (!sc->ca_store_) {
487 sc->ca_store_ = X509_STORE_new();
491 X509* x509 = LoadX509(args[0]);
492 if (!x509) return False(node_isolate);
494 X509_STORE_add_cert(sc->ca_store_, x509);
495 SSL_CTX_add_client_CA(sc->ctx_, x509);
500 SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
503 return True(node_isolate);
507 Handle<Value> SecureContext::AddCRL(const Arguments& args) {
508 HandleScope scope(node_isolate);
510 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
512 if (args.Length() != 1) {
513 return ThrowException(Exception::TypeError(String::New("Bad parameter")));
516 BIO *bio = LoadBIO(args[0]);
517 if (!bio) return False(node_isolate);
519 X509_CRL *x509 = PEM_read_bio_X509_CRL(bio, NULL, NULL, NULL);
523 return False(node_isolate);
526 X509_STORE_add_crl(sc->ca_store_, x509);
528 X509_STORE_set_flags(sc->ca_store_, X509_V_FLAG_CRL_CHECK |
529 X509_V_FLAG_CRL_CHECK_ALL);
534 return True(node_isolate);
539 Handle<Value> SecureContext::AddRootCerts(const Arguments& args) {
540 HandleScope scope(node_isolate);
542 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
544 assert(sc->ca_store_ == NULL);
546 if (!root_cert_store) {
547 root_cert_store = X509_STORE_new();
549 for (int i = 0; root_certs[i]; i++) {
550 BIO *bp = BIO_new(BIO_s_mem());
552 if (!BIO_write(bp, root_certs[i], strlen(root_certs[i]))) {
554 return False(node_isolate);
557 X509 *x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
561 return False(node_isolate);
564 X509_STORE_add_cert(root_cert_store, x509);
571 sc->ca_store_ = root_cert_store;
572 SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
574 return True(node_isolate);
578 Handle<Value> SecureContext::SetCiphers(const Arguments& args) {
579 HandleScope scope(node_isolate);
581 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
583 if (args.Length() != 1 || !args[0]->IsString()) {
584 return ThrowException(Exception::TypeError(String::New("Bad parameter")));
587 String::Utf8Value ciphers(args[0]);
588 SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
590 return True(node_isolate);
593 Handle<Value> SecureContext::SetOptions(const Arguments& args) {
594 HandleScope scope(node_isolate);
596 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
598 if (args.Length() != 1 || !args[0]->IntegerValue()) {
599 return ThrowException(Exception::TypeError(String::New("Bad parameter")));
602 SSL_CTX_set_options(sc->ctx_, args[0]->IntegerValue());
604 return True(node_isolate);
607 Handle<Value> SecureContext::SetSessionIdContext(const Arguments& args) {
608 HandleScope scope(node_isolate);
610 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
612 if (args.Length() != 1 || !args[0]->IsString()) {
613 return ThrowException(Exception::TypeError(String::New("Bad parameter")));
616 String::Utf8Value sessionIdContext(args[0]);
617 const unsigned char* sid_ctx = (const unsigned char*) *sessionIdContext;
618 unsigned int sid_ctx_len = sessionIdContext.length();
620 int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
622 Local<String> message;
625 if ((bio = BIO_new(BIO_s_mem()))) {
626 ERR_print_errors(bio);
627 BIO_get_mem_ptr(bio, &mem);
628 message = String::New(mem->data, mem->length);
631 message = String::New("SSL_CTX_set_session_id_context error");
633 return ThrowException(Exception::TypeError(message));
636 return True(node_isolate);
639 Handle<Value> SecureContext::SetSessionTimeout(const Arguments& args) {
642 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
644 if (args.Length() != 1 || !args[0]->IsInt32()) {
645 return ThrowTypeError("Bad parameter");
648 int32_t sessionTimeout = args[0]->Int32Value();
649 SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
654 Handle<Value> SecureContext::Close(const Arguments& args) {
655 HandleScope scope(node_isolate);
656 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
658 return False(node_isolate);
661 //Takes .pfx or .p12 and password in string or buffer format
662 Handle<Value> SecureContext::LoadPKCS12(const Arguments& args) {
663 HandleScope scope(node_isolate);
667 EVP_PKEY* pkey = NULL;
669 STACK_OF(X509)* extraCerts = NULL;
673 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
675 if (args.Length() < 1) {
676 return ThrowException(Exception::TypeError(
677 String::New("Bad parameter")));
680 in = LoadBIO(args[0]);
682 return ThrowException(Exception::Error(
683 String::New("Unable to load BIO")));
686 if (args.Length() >= 2) {
687 ASSERT_IS_BUFFER(args[1]);
689 int passlen = Buffer::Length(args[1]);
692 return ThrowException(Exception::TypeError(
693 String::New("Bad password")));
695 pass = new char[passlen + 1];
696 int pass_written = DecodeWrite(pass, passlen, args[1], BINARY);
698 assert(pass_written == passlen);
699 pass[passlen] = '\0';
702 if (d2i_PKCS12_bio(in, &p12) &&
703 PKCS12_parse(p12, pass, &pkey, &cert, &extraCerts) &&
704 SSL_CTX_use_certificate(sc->ctx_, cert) &&
705 SSL_CTX_use_PrivateKey(sc->ctx_, pkey))
708 while (X509* x509 = sk_X509_pop(extraCerts)) {
709 if (!sc->ca_store_) {
710 sc->ca_store_ = X509_STORE_new();
711 SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
714 X509_STORE_add_cert(sc->ca_store_, x509);
715 SSL_CTX_add_client_CA(sc->ctx_, x509);
720 sk_X509_free(extraCerts);
730 unsigned long err = ERR_get_error();
731 const char* str = ERR_reason_error_string(err);
732 return ThrowException(Exception::Error(String::New(str)));
735 return True(node_isolate);
739 size_t ClientHelloParser::Write(const uint8_t* data, size_t len) {
740 HandleScope scope(node_isolate);
742 // Just accumulate data, everything will be pushed to BIO later
743 if (state_ == kPaused) return 0;
745 // Copy incoming data to the internal buffer
746 // (which has a size of the biggest possible TLS frame)
747 size_t available = sizeof(data_) - offset_;
748 size_t copied = len < available ? len : available;
749 memcpy(data_ + offset_, data, copied);
752 // Vars for parsing hello
753 bool is_clienthello = false;
754 uint8_t session_size = -1;
755 uint8_t* session_id = NULL;
757 Handle<Value> argv[1];
761 // >= 5 bytes for header parsing
762 if (offset_ < 5) break;
764 if (data_[0] == kChangeCipherSpec || data_[0] == kAlert ||
765 data_[0] == kHandshake || data_[0] == kApplicationData) {
766 frame_len_ = (data_[3] << 8) + data_[4];
770 frame_len_ = (data_[0] << 8) + data_[1];
773 // header with padding
781 // Sanity check (too big frame, or too small)
782 if (frame_len_ >= sizeof(data_)) {
783 // Let OpenSSL handle it
789 // >= 5 + frame size bytes for frame parsing
790 if (offset_ < body_offset_ + frame_len_) break;
792 // Skip unsupported frames and gather some data from frame
794 // TODO: Check protocol version
795 if (data_[body_offset_] == kClientHello) {
796 is_clienthello = true;
798 size_t session_offset;
800 if (state_ == kTLSHeader) {
801 // Skip frame header, hello header, protocol version and random data
802 session_offset = body_offset_ + 4 + 2 + 32;
804 if (session_offset + 1 < offset_) {
805 body = data_ + session_offset;
806 session_size = *body;
807 session_id = body + 1;
809 } else if (state_ == kSSLHeader) {
810 // Skip header, version
811 session_offset = body_offset_ + 3;
813 if (session_offset + 4 < offset_) {
814 body = data_ + session_offset;
816 int ciphers_size = (body[0] << 8) + body[1];
818 if (body + 4 + ciphers_size < data_ + offset_) {
819 session_size = (body[2] << 8) + body[3];
820 session_id = body + 4 + ciphers_size;
824 // Whoa? How did we get here?
828 // Check if we overflowed (do not reply with any private data)
829 if (session_id == NULL ||
831 session_id + session_size > data_ + offset_) {
836 // TODO: Parse other things?
839 // Not client hello - let OpenSSL handle it
840 if (!is_clienthello) {
845 // Parse frame, call javascript handler and
846 // move parser into the paused state
847 if (onclienthello_sym.IsEmpty()) {
848 onclienthello_sym = NODE_PSYMBOL("onclienthello");
850 if (sessionid_sym.IsEmpty()) {
851 sessionid_sym = NODE_PSYMBOL("sessionId");
855 hello = Object::New();
856 hello->Set(sessionid_sym,
857 Buffer::New(reinterpret_cast<char*>(session_id),
858 session_size)->handle_);
861 MakeCallback(conn_->handle_, onclienthello_sym, 1, argv);
872 void ClientHelloParser::Finish() {
873 assert(state_ != kEnded);
876 // Write all accumulated data
877 int r = BIO_write(conn_->bio_read_, reinterpret_cast<char*>(data_), offset_);
878 conn_->HandleBIOError(conn_->bio_read_, "BIO_write", r);
879 conn_->SetShutdownFlags();
883 #ifdef SSL_PRINT_DEBUG
884 # define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
886 # define DEBUG_PRINT(...)
890 int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
891 if (rv >= 0) return rv;
893 int retry = BIO_should_retry(bio);
894 (void) retry; // unused if !defined(SSL_PRINT_DEBUG)
896 if (BIO_should_write(bio)) {
897 DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n", ssl_, func, retry);
900 } else if (BIO_should_read(bio)) {
901 DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
905 static char ssl_error_buf[512];
906 ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
908 HandleScope scope(node_isolate);
909 Local<Value> e = Exception::Error(String::New(ssl_error_buf));
910 handle_->Set(String::New("error"), e);
912 DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n", ssl_, func, rv, ssl_error_buf);
921 int Connection::HandleSSLError(const char* func, int rv, ZeroStatus zs) {
922 // Forcibly clear OpenSSL's error stack on return. This stops stale errors
923 // from popping up later in the lifecycle of the SSL connection where they
924 // would cause spurious failures. It's a rather blunt method, though.
925 // ERR_clear_error() isn't necessarily cheap either.
926 struct ClearErrorOnReturn {
927 ~ClearErrorOnReturn() { ERR_clear_error(); }
929 ClearErrorOnReturn clear_error_on_return;
930 (void) &clear_error_on_return; // Silence unused variable warning.
932 if (rv > 0) return rv;
933 if ((rv == 0) && (zs == kZeroIsNotAnError)) return rv;
935 int err = SSL_get_error(ssl_, rv);
937 if (err == SSL_ERROR_NONE) {
940 } else if (err == SSL_ERROR_WANT_WRITE) {
941 DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
944 } else if (err == SSL_ERROR_WANT_READ) {
945 DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
948 } else if (err == SSL_ERROR_ZERO_RETURN) {
949 handle_->Set(String::New("error"),
950 Exception::Error(String::New("ZERO_RETURN")));
954 HandleScope scope(node_isolate);
958 assert(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
960 // XXX We need to drain the error queue for this thread or else OpenSSL
961 // has the possibility of blocking connections? This problem is not well
962 // understood. And we should be somehow propagating these errors up
963 // into JavaScript. There is no test which demonstrates this problem.
964 // https://github.com/joyent/node/issues/1719
965 if ((bio = BIO_new(BIO_s_mem()))) {
966 ERR_print_errors(bio);
967 BIO_get_mem_ptr(bio, &mem);
968 Local<Value> e = Exception::Error(String::New(mem->data, mem->length));
969 handle_->Set(String::New("error"), e);
980 void Connection::ClearError() {
982 HandleScope scope(node_isolate);
984 // We should clear the error in JS-land
985 assert(handle_->Get(String::New("error"))->BooleanValue() == false);
990 void Connection::SetShutdownFlags() {
991 HandleScope scope(node_isolate);
993 int flags = SSL_get_shutdown(ssl_);
995 if (flags & SSL_SENT_SHUTDOWN) {
996 handle_->Set(String::New("sentShutdown"), True(node_isolate));
999 if (flags & SSL_RECEIVED_SHUTDOWN) {
1000 handle_->Set(String::New("receivedShutdown"), True(node_isolate));
1005 void Connection::Initialize(Handle<Object> target) {
1006 HandleScope scope(node_isolate);
1008 Local<FunctionTemplate> t = FunctionTemplate::New(Connection::New);
1009 t->InstanceTemplate()->SetInternalFieldCount(1);
1010 t->SetClassName(String::NewSymbol("Connection"));
1012 NODE_SET_PROTOTYPE_METHOD(t, "encIn", Connection::EncIn);
1013 NODE_SET_PROTOTYPE_METHOD(t, "clearOut", Connection::ClearOut);
1014 NODE_SET_PROTOTYPE_METHOD(t, "clearIn", Connection::ClearIn);
1015 NODE_SET_PROTOTYPE_METHOD(t, "encOut", Connection::EncOut);
1016 NODE_SET_PROTOTYPE_METHOD(t, "clearPending", Connection::ClearPending);
1017 NODE_SET_PROTOTYPE_METHOD(t, "encPending", Connection::EncPending);
1018 NODE_SET_PROTOTYPE_METHOD(t, "getPeerCertificate", Connection::GetPeerCertificate);
1019 NODE_SET_PROTOTYPE_METHOD(t, "getSession", Connection::GetSession);
1020 NODE_SET_PROTOTYPE_METHOD(t, "setSession", Connection::SetSession);
1021 NODE_SET_PROTOTYPE_METHOD(t, "loadSession", Connection::LoadSession);
1022 NODE_SET_PROTOTYPE_METHOD(t, "isSessionReused", Connection::IsSessionReused);
1023 NODE_SET_PROTOTYPE_METHOD(t, "isInitFinished", Connection::IsInitFinished);
1024 NODE_SET_PROTOTYPE_METHOD(t, "verifyError", Connection::VerifyError);
1025 NODE_SET_PROTOTYPE_METHOD(t, "getCurrentCipher", Connection::GetCurrentCipher);
1026 NODE_SET_PROTOTYPE_METHOD(t, "start", Connection::Start);
1027 NODE_SET_PROTOTYPE_METHOD(t, "shutdown", Connection::Shutdown);
1028 NODE_SET_PROTOTYPE_METHOD(t, "receivedShutdown", Connection::ReceivedShutdown);
1029 NODE_SET_PROTOTYPE_METHOD(t, "close", Connection::Close);
1031 #ifdef OPENSSL_NPN_NEGOTIATED
1032 NODE_SET_PROTOTYPE_METHOD(t, "getNegotiatedProtocol", Connection::GetNegotiatedProto);
1033 NODE_SET_PROTOTYPE_METHOD(t, "setNPNProtocols", Connection::SetNPNProtocols);
1037 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1038 NODE_SET_PROTOTYPE_METHOD(t, "getServername", Connection::GetServername);
1039 NODE_SET_PROTOTYPE_METHOD(t, "setSNICallback", Connection::SetSNICallback);
1042 target->Set(String::NewSymbol("Connection"), t->GetFunction());
1046 static int VerifyCallback(int preverify_ok, X509_STORE_CTX *ctx) {
1047 // Quoting SSL_set_verify(3ssl):
1049 // The VerifyCallback function is used to control the behaviour when
1050 // the SSL_VERIFY_PEER flag is set. It must be supplied by the
1051 // application and receives two arguments: preverify_ok indicates,
1052 // whether the verification of the certificate in question was passed
1053 // (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to
1054 // the complete context used for the certificate chain verification.
1056 // The certificate chain is checked starting with the deepest nesting
1057 // level (the root CA certificate) and worked upward to the peer's
1058 // certificate. At each level signatures and issuer attributes are
1059 // checked. Whenever a verification error is found, the error number is
1060 // stored in x509_ctx and VerifyCallback is called with preverify_ok=0.
1061 // By applying X509_CTX_store_* functions VerifyCallback can locate the
1062 // certificate in question and perform additional steps (see EXAMPLES).
1063 // If no error is found for a certificate, VerifyCallback is called
1064 // with preverify_ok=1 before advancing to the next level.
1066 // The return value of VerifyCallback controls the strategy of the
1067 // further verification process. If VerifyCallback returns 0, the
1068 // verification process is immediately stopped with "verification
1069 // failed" state. If SSL_VERIFY_PEER is set, a verification failure
1070 // alert is sent to the peer and the TLS/SSL handshake is terminated. If
1071 // VerifyCallback returns 1, the verification process is continued. If
1072 // VerifyCallback always returns 1, the TLS/SSL handshake will not be
1073 // terminated with respect to verification failures and the connection
1074 // will be established. The calling process can however retrieve the
1075 // error code of the last verification error using
1076 // SSL_get_verify_result(3) or by maintaining its own error storage
1077 // managed by VerifyCallback.
1079 // If no VerifyCallback is specified, the default callback will be
1080 // used. Its return value is identical to preverify_ok, so that any
1081 // verification failure will lead to a termination of the TLS/SSL
1082 // handshake with an alert message, if SSL_VERIFY_PEER is set.
1084 // Since we cannot perform I/O quickly enough in this callback, we ignore
1085 // all preverify_ok errors and let the handshake continue. It is
1086 // imparative that the user use Connection::VerifyError after the
1087 // 'secure' callback has been made.
1091 #ifdef OPENSSL_NPN_NEGOTIATED
1093 int Connection::AdvertiseNextProtoCallback_(SSL *s,
1094 const unsigned char** data,
1098 Connection *p = static_cast<Connection*>(SSL_get_app_data(s));
1100 if (p->npnProtos_.IsEmpty()) {
1101 // No initialization - no NPN protocols
1102 *data = reinterpret_cast<const unsigned char*>("");
1105 *data = reinterpret_cast<const unsigned char*>(Buffer::Data(p->npnProtos_));
1106 *len = Buffer::Length(p->npnProtos_);
1109 return SSL_TLSEXT_ERR_OK;
1112 int Connection::SelectNextProtoCallback_(SSL *s,
1113 unsigned char** out, unsigned char* outlen,
1114 const unsigned char* in,
1115 unsigned int inlen, void *arg) {
1116 Connection *p = static_cast<Connection*> SSL_get_app_data(s);
1118 // Release old protocol handler if present
1119 if (!p->selectedNPNProto_.IsEmpty()) {
1120 p->selectedNPNProto_.Dispose(node_isolate);
1123 if (p->npnProtos_.IsEmpty()) {
1124 // We should at least select one protocol
1125 // If server is using NPN
1126 *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
1129 // set status unsupported
1130 p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
1131 False(node_isolate));
1133 return SSL_TLSEXT_ERR_OK;
1136 const unsigned char* npnProtos =
1137 reinterpret_cast<const unsigned char*>(Buffer::Data(p->npnProtos_));
1139 int status = SSL_select_next_proto(out, outlen, in, inlen, npnProtos,
1140 Buffer::Length(p->npnProtos_));
1143 case OPENSSL_NPN_UNSUPPORTED:
1144 p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
1145 Null(node_isolate));
1147 case OPENSSL_NPN_NEGOTIATED:
1148 p->selectedNPNProto_ = Persistent<Value>::New(node_isolate, String::New(
1149 reinterpret_cast<const char*>(*out), *outlen
1152 case OPENSSL_NPN_NO_OVERLAP:
1153 p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
1154 False(node_isolate));
1160 return SSL_TLSEXT_ERR_OK;
1164 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1165 int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
1166 HandleScope scope(node_isolate);
1168 Connection *p = static_cast<Connection*> SSL_get_app_data(s);
1170 const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1173 if (!p->servername_.IsEmpty()) {
1174 p->servername_.Dispose(node_isolate);
1176 p->servername_ = Persistent<String>::New(node_isolate,
1177 String::New(servername));
1179 // Call the SNI callback and use its return value as context
1180 if (!p->sniObject_.IsEmpty()) {
1181 if (!p->sniContext_.IsEmpty()) {
1182 p->sniContext_.Dispose(node_isolate);
1185 // Get callback init args
1186 Local<Value> argv[1] = {*p->servername_};
1189 Local<Value> ret = Local<Value>::New(node_isolate,
1190 MakeCallback(p->sniObject_,
1195 // If ret is SecureContext
1196 if (secure_context_constructor->HasInstance(ret)) {
1197 p->sniContext_ = Persistent<Value>::New(node_isolate, ret);
1198 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(
1199 Local<Object>::Cast(ret));
1200 SSL_set_SSL_CTX(s, sc->ctx_);
1202 return SSL_TLSEXT_ERR_NOACK;
1207 return SSL_TLSEXT_ERR_OK;
1211 Handle<Value> Connection::New(const Arguments& args) {
1212 HandleScope scope(node_isolate);
1214 Connection *p = new Connection();
1215 p->Wrap(args.Holder());
1217 if (args.Length() < 1 || !args[0]->IsObject()) {
1218 return ThrowException(Exception::Error(String::New(
1219 "First argument must be a crypto module Credentials")));
1222 SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args[0]->ToObject());
1224 bool is_server = args[1]->BooleanValue();
1226 p->ssl_ = SSL_new(sc->ctx_);
1227 p->bio_read_ = BIO_new(BIO_s_mem());
1228 p->bio_write_ = BIO_new(BIO_s_mem());
1230 SSL_set_app_data(p->ssl_, p);
1232 if (is_server) SSL_set_info_callback(p->ssl_, SSLInfoCallback);
1234 #ifdef OPENSSL_NPN_NEGOTIATED
1236 // Server should advertise NPN protocols
1237 SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
1238 AdvertiseNextProtoCallback_,
1241 // Client should select protocol from advertised
1242 // If server supports NPN
1243 SSL_CTX_set_next_proto_select_cb(sc->ctx_,
1244 SelectNextProtoCallback_,
1249 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1251 SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
1253 String::Utf8Value servername(args[2]);
1254 SSL_set_tlsext_host_name(p->ssl_, *servername);
1258 SSL_set_bio(p->ssl_, p->bio_read_, p->bio_write_);
1260 #ifdef SSL_MODE_RELEASE_BUFFERS
1261 long mode = SSL_get_mode(p->ssl_);
1262 SSL_set_mode(p->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
1268 bool request_cert = args[2]->BooleanValue();
1269 if (!request_cert) {
1270 // Note reject_unauthorized ignored.
1271 verify_mode = SSL_VERIFY_NONE;
1273 bool reject_unauthorized = args[3]->BooleanValue();
1274 verify_mode = SSL_VERIFY_PEER;
1275 if (reject_unauthorized) verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1278 // Note request_cert and reject_unauthorized are ignored for clients.
1279 verify_mode = SSL_VERIFY_NONE;
1283 // Always allow a connection. We'll reject in javascript.
1284 SSL_set_verify(p->ssl_, verify_mode, VerifyCallback);
1286 if ((p->is_server_ = is_server)) {
1287 SSL_set_accept_state(p->ssl_);
1289 SSL_set_connect_state(p->ssl_);
1296 void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
1297 // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
1298 // a non-const SSL* in OpenSSL <= 0.9.7e.
1299 SSL* ssl = const_cast<SSL*>(ssl_);
1300 if (where & SSL_CB_HANDSHAKE_START) {
1301 HandleScope scope(node_isolate);
1302 Connection* c = static_cast<Connection*>(SSL_get_app_data(ssl));
1303 if (onhandshakestart_sym.IsEmpty()) {
1304 onhandshakestart_sym = NODE_PSYMBOL("onhandshakestart");
1306 MakeCallback(c->handle_, onhandshakestart_sym, 0, NULL);
1308 if (where & SSL_CB_HANDSHAKE_DONE) {
1309 HandleScope scope(node_isolate);
1310 Connection* c = static_cast<Connection*>(SSL_get_app_data(ssl));
1311 if (onhandshakedone_sym.IsEmpty()) {
1312 onhandshakedone_sym = NODE_PSYMBOL("onhandshakedone");
1314 MakeCallback(c->handle_, onhandshakedone_sym, 0, NULL);
1319 Handle<Value> Connection::EncIn(const Arguments& args) {
1320 HandleScope scope(node_isolate);
1322 Connection *ss = Connection::Unwrap(args);
1324 if (args.Length() < 3) {
1325 return ThrowException(Exception::TypeError(
1326 String::New("Takes 3 parameters")));
1329 if (!Buffer::HasInstance(args[0])) {
1330 return ThrowException(Exception::TypeError(
1331 String::New("Second argument should be a buffer")));
1334 char* buffer_data = Buffer::Data(args[0]);
1335 size_t buffer_length = Buffer::Length(args[0]);
1337 size_t off = args[1]->Int32Value();
1338 size_t len = args[2]->Int32Value();
1339 if (off + len > buffer_length) {
1340 return ThrowException(Exception::Error(
1341 String::New("off + len > buffer.length")));
1345 char* data = buffer_data + off;
1347 if (ss->is_server_ && !ss->hello_parser_.ended()) {
1348 bytes_written = ss->hello_parser_.Write(reinterpret_cast<uint8_t*>(data),
1351 bytes_written = BIO_write(ss->bio_read_, data, len);
1352 ss->HandleBIOError(ss->bio_read_, "BIO_write", bytes_written);
1353 ss->SetShutdownFlags();
1356 return scope.Close(Integer::New(bytes_written, node_isolate));
1360 Handle<Value> Connection::ClearOut(const Arguments& args) {
1361 HandleScope scope(node_isolate);
1363 Connection *ss = Connection::Unwrap(args);
1365 if (args.Length() < 3) {
1366 return ThrowException(Exception::TypeError(
1367 String::New("Takes 3 parameters")));
1370 if (!Buffer::HasInstance(args[0])) {
1371 return ThrowException(Exception::TypeError(
1372 String::New("Second argument should be a buffer")));
1375 char* buffer_data = Buffer::Data(args[0]);
1376 size_t buffer_length = Buffer::Length(args[0]);
1378 size_t off = args[1]->Int32Value();
1379 size_t len = args[2]->Int32Value();
1380 if (off + len > buffer_length) {
1381 return ThrowException(Exception::Error(
1382 String::New("off + len > buffer.length")));
1385 if (!SSL_is_init_finished(ss->ssl_)) {
1388 if (ss->is_server_) {
1389 rv = SSL_accept(ss->ssl_);
1390 ss->HandleSSLError("SSL_accept:ClearOut", rv, kZeroIsAnError);
1392 rv = SSL_connect(ss->ssl_);
1393 ss->HandleSSLError("SSL_connect:ClearOut", rv, kZeroIsAnError);
1396 if (rv < 0) return scope.Close(Integer::New(rv, node_isolate));
1399 int bytes_read = SSL_read(ss->ssl_, buffer_data + off, len);
1400 ss->HandleSSLError("SSL_read:ClearOut", bytes_read, kZeroIsNotAnError);
1401 ss->SetShutdownFlags();
1403 return scope.Close(Integer::New(bytes_read, node_isolate));
1407 Handle<Value> Connection::ClearPending(const Arguments& args) {
1408 HandleScope scope(node_isolate);
1410 Connection *ss = Connection::Unwrap(args);
1412 int bytes_pending = BIO_pending(ss->bio_read_);
1413 return scope.Close(Integer::New(bytes_pending, node_isolate));
1417 Handle<Value> Connection::EncPending(const Arguments& args) {
1418 HandleScope scope(node_isolate);
1420 Connection *ss = Connection::Unwrap(args);
1422 int bytes_pending = BIO_pending(ss->bio_write_);
1423 return scope.Close(Integer::New(bytes_pending, node_isolate));
1427 Handle<Value> Connection::EncOut(const Arguments& args) {
1428 HandleScope scope(node_isolate);
1430 Connection *ss = Connection::Unwrap(args);
1432 if (args.Length() < 3) {
1433 return ThrowException(Exception::TypeError(
1434 String::New("Takes 3 parameters")));
1437 if (!Buffer::HasInstance(args[0])) {
1438 return ThrowException(Exception::TypeError(
1439 String::New("Second argument should be a buffer")));
1442 char* buffer_data = Buffer::Data(args[0]);
1443 size_t buffer_length = Buffer::Length(args[0]);
1445 size_t off = args[1]->Int32Value();
1446 size_t len = args[2]->Int32Value();
1447 if (off + len > buffer_length) {
1448 return ThrowException(Exception::Error(
1449 String::New("off + len > buffer.length")));
1452 int bytes_read = BIO_read(ss->bio_write_, buffer_data + off, len);
1454 ss->HandleBIOError(ss->bio_write_, "BIO_read:EncOut", bytes_read);
1455 ss->SetShutdownFlags();
1457 return scope.Close(Integer::New(bytes_read, node_isolate));
1461 Handle<Value> Connection::ClearIn(const Arguments& args) {
1462 HandleScope scope(node_isolate);
1464 Connection *ss = Connection::Unwrap(args);
1466 if (args.Length() < 3) {
1467 return ThrowException(Exception::TypeError(
1468 String::New("Takes 3 parameters")));
1471 if (!Buffer::HasInstance(args[0])) {
1472 return ThrowException(Exception::TypeError(
1473 String::New("Second argument should be a buffer")));
1476 char* buffer_data = Buffer::Data(args[0]);
1477 size_t buffer_length = Buffer::Length(args[0]);
1479 size_t off = args[1]->Int32Value();
1480 size_t len = args[2]->Int32Value();
1481 if (off + len > buffer_length) {
1482 return ThrowException(Exception::Error(
1483 String::New("off + len > buffer.length")));
1486 if (!SSL_is_init_finished(ss->ssl_)) {
1488 if (ss->is_server_) {
1489 rv = SSL_accept(ss->ssl_);
1490 ss->HandleSSLError("SSL_accept:ClearIn", rv, kZeroIsAnError);
1492 rv = SSL_connect(ss->ssl_);
1493 ss->HandleSSLError("SSL_connect:ClearIn", rv, kZeroIsAnError);
1496 if (rv < 0) return scope.Close(Integer::New(rv, node_isolate));
1499 int bytes_written = SSL_write(ss->ssl_, buffer_data + off, len);
1501 ss->HandleSSLError("SSL_write:ClearIn", bytes_written, kZeroIsAnError);
1502 ss->SetShutdownFlags();
1504 return scope.Close(Integer::New(bytes_written, node_isolate));
1508 Handle<Value> Connection::GetPeerCertificate(const Arguments& args) {
1509 HandleScope scope(node_isolate);
1511 Connection *ss = Connection::Unwrap(args);
1513 if (ss->ssl_ == NULL) return Undefined(node_isolate);
1514 Local<Object> info = Object::New();
1515 X509* peer_cert = SSL_get_peer_certificate(ss->ssl_);
1516 if (peer_cert != NULL) {
1517 BIO* bio = BIO_new(BIO_s_mem());
1519 if (X509_NAME_print_ex(bio, X509_get_subject_name(peer_cert), 0,
1520 X509_NAME_FLAGS) > 0) {
1521 BIO_get_mem_ptr(bio, &mem);
1522 info->Set(subject_symbol, String::New(mem->data, mem->length));
1524 (void) BIO_reset(bio);
1526 if (X509_NAME_print_ex(bio, X509_get_issuer_name(peer_cert), 0,
1527 X509_NAME_FLAGS) > 0) {
1528 BIO_get_mem_ptr(bio, &mem);
1529 info->Set(issuer_symbol, String::New(mem->data, mem->length));
1531 (void) BIO_reset(bio);
1533 int index = X509_get_ext_by_NID(peer_cert, NID_subject_alt_name, -1);
1535 X509_EXTENSION* ext;
1538 ext = X509_get_ext(peer_cert, index);
1539 assert(ext != NULL);
1541 rv = X509V3_EXT_print(bio, ext, 0, 0);
1544 BIO_get_mem_ptr(bio, &mem);
1545 info->Set(subjectaltname_symbol, String::New(mem->data, mem->length));
1547 (void) BIO_reset(bio);
1550 EVP_PKEY *pkey = NULL;
1552 if( NULL != (pkey = X509_get_pubkey(peer_cert))
1553 && NULL != (rsa = EVP_PKEY_get1_RSA(pkey)) ) {
1554 BN_print(bio, rsa->n);
1555 BIO_get_mem_ptr(bio, &mem);
1556 info->Set(modulus_symbol, String::New(mem->data, mem->length) );
1557 (void) BIO_reset(bio);
1559 BN_print(bio, rsa->e);
1560 BIO_get_mem_ptr(bio, &mem);
1561 info->Set(exponent_symbol, String::New(mem->data, mem->length) );
1562 (void) BIO_reset(bio);
1566 EVP_PKEY_free(pkey);
1574 ASN1_TIME_print(bio, X509_get_notBefore(peer_cert));
1575 BIO_get_mem_ptr(bio, &mem);
1576 info->Set(valid_from_symbol, String::New(mem->data, mem->length));
1577 (void) BIO_reset(bio);
1579 ASN1_TIME_print(bio, X509_get_notAfter(peer_cert));
1580 BIO_get_mem_ptr(bio, &mem);
1581 info->Set(valid_to_symbol, String::New(mem->data, mem->length));
1584 unsigned int md_size, i;
1585 unsigned char md[EVP_MAX_MD_SIZE];
1586 if (X509_digest(peer_cert, EVP_sha1(), md, &md_size)) {
1587 const char hex[] = "0123456789ABCDEF";
1588 char fingerprint[EVP_MAX_MD_SIZE * 3];
1590 for (i=0; i<md_size; i++) {
1591 fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1592 fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1593 fingerprint[(3*i)+2] = ':';
1597 fingerprint[(3*(md_size-1))+2] = '\0';
1600 fingerprint[0] = '\0';
1603 info->Set(fingerprint_symbol, String::New(fingerprint));
1606 STACK_OF(ASN1_OBJECT) *eku = (STACK_OF(ASN1_OBJECT) *)X509_get_ext_d2i(
1607 peer_cert, NID_ext_key_usage, NULL, NULL);
1609 Local<Array> ext_key_usage = Array::New();
1612 for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1613 memset(buf, 0, sizeof(buf));
1614 OBJ_obj2txt(buf, sizeof(buf) - 1, sk_ASN1_OBJECT_value(eku, i), 1);
1615 ext_key_usage->Set(Integer::New(i, node_isolate), String::New(buf));
1618 sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1619 info->Set(ext_key_usage_symbol, ext_key_usage);
1622 X509_free(peer_cert);
1624 return scope.Close(info);
1627 Handle<Value> Connection::GetSession(const Arguments& args) {
1628 HandleScope scope(node_isolate);
1630 Connection *ss = Connection::Unwrap(args);
1632 if (ss->ssl_ == NULL) return Undefined(node_isolate);
1634 SSL_SESSION* sess = SSL_get_session(ss->ssl_);
1635 if (!sess) return Undefined(node_isolate);
1637 int slen = i2d_SSL_SESSION(sess, NULL);
1641 unsigned char* sbuf = new unsigned char[slen];
1642 unsigned char* p = sbuf;
1643 i2d_SSL_SESSION(sess, &p);
1644 Local<Value> s = Encode(sbuf, slen, BINARY);
1646 return scope.Close(s);
1649 return Null(node_isolate);
1652 Handle<Value> Connection::SetSession(const Arguments& args) {
1653 HandleScope scope(node_isolate);
1655 Connection *ss = Connection::Unwrap(args);
1657 if (args.Length() < 1 ||
1658 (!args[0]->IsString() && !Buffer::HasInstance(args[0]))) {
1659 Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
1660 return ThrowException(exception);
1663 ASSERT_IS_BUFFER(args[0]);
1664 ssize_t slen = Buffer::Length(args[0]);
1667 Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
1668 return ThrowException(exception);
1671 char* sbuf = new char[slen];
1673 ssize_t wlen = DecodeWrite(sbuf, slen, args[0], BINARY);
1674 assert(wlen == slen);
1676 const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1677 SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, wlen);
1682 return Undefined(node_isolate);
1684 int r = SSL_set_session(ss->ssl_, sess);
1685 SSL_SESSION_free(sess);
1688 Local<String> eStr = String::New("SSL_set_session error");
1689 return ThrowException(Exception::Error(eStr));
1692 return True(node_isolate);
1695 Handle<Value> Connection::LoadSession(const Arguments& args) {
1696 HandleScope scope(node_isolate);
1698 Connection *ss = Connection::Unwrap(args);
1700 if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1701 ssize_t slen = Buffer::Length(args[0].As<Object>());
1702 char* sbuf = Buffer::Data(args[0].As<Object>());
1704 const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1705 SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, slen);
1707 // Setup next session and move hello to the BIO buffer
1708 if (ss->next_sess_ != NULL) {
1709 SSL_SESSION_free(ss->next_sess_);
1711 ss->next_sess_ = sess;
1714 ss->hello_parser_.Finish();
1716 return True(node_isolate);
1719 Handle<Value> Connection::IsSessionReused(const Arguments& args) {
1720 HandleScope scope(node_isolate);
1722 Connection *ss = Connection::Unwrap(args);
1724 if (ss->ssl_ == NULL || SSL_session_reused(ss->ssl_) == false) {
1725 return False(node_isolate);
1728 return True(node_isolate);
1732 Handle<Value> Connection::Start(const Arguments& args) {
1733 HandleScope scope(node_isolate);
1735 Connection *ss = Connection::Unwrap(args);
1737 if (!SSL_is_init_finished(ss->ssl_)) {
1739 if (ss->is_server_) {
1740 rv = SSL_accept(ss->ssl_);
1741 ss->HandleSSLError("SSL_accept:Start", rv, kZeroIsAnError);
1743 rv = SSL_connect(ss->ssl_);
1744 ss->HandleSSLError("SSL_connect:Start", rv, kZeroIsAnError);
1747 return scope.Close(Integer::New(rv, node_isolate));
1750 return scope.Close(Integer::New(0, node_isolate));
1754 Handle<Value> Connection::Shutdown(const Arguments& args) {
1755 HandleScope scope(node_isolate);
1757 Connection *ss = Connection::Unwrap(args);
1759 if (ss->ssl_ == NULL) return False(node_isolate);
1760 int rv = SSL_shutdown(ss->ssl_);
1761 ss->HandleSSLError("SSL_shutdown", rv, kZeroIsNotAnError);
1762 ss->SetShutdownFlags();
1764 return scope.Close(Integer::New(rv, node_isolate));
1768 Handle<Value> Connection::ReceivedShutdown(const Arguments& args) {
1769 HandleScope scope(node_isolate);
1771 Connection *ss = Connection::Unwrap(args);
1773 if (ss->ssl_ == NULL) return False(node_isolate);
1774 int r = SSL_get_shutdown(ss->ssl_);
1776 if (r & SSL_RECEIVED_SHUTDOWN) return True(node_isolate);
1778 return False(node_isolate);
1782 Handle<Value> Connection::IsInitFinished(const Arguments& args) {
1783 HandleScope scope(node_isolate);
1785 Connection *ss = Connection::Unwrap(args);
1787 if (ss->ssl_ == NULL || SSL_is_init_finished(ss->ssl_) == false) {
1788 return False(node_isolate);
1791 return True(node_isolate);
1795 Handle<Value> Connection::VerifyError(const Arguments& args) {
1796 HandleScope scope(node_isolate);
1798 Connection *ss = Connection::Unwrap(args);
1800 if (ss->ssl_ == NULL) return Null(node_isolate);
1803 // XXX Do this check in JS land?
1804 X509* peer_cert = SSL_get_peer_certificate(ss->ssl_);
1805 if (peer_cert == NULL) {
1806 // We requested a certificate and they did not send us one.
1807 // Definitely an error.
1808 // XXX is this the right error message?
1809 return scope.Close(Exception::Error(
1810 String::New("UNABLE_TO_GET_ISSUER_CERT")));
1812 X509_free(peer_cert);
1815 long x509_verify_error = SSL_get_verify_result(ss->ssl_);
1819 switch (x509_verify_error) {
1821 return Null(node_isolate);
1823 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1824 s = String::New("UNABLE_TO_GET_ISSUER_CERT");
1827 case X509_V_ERR_UNABLE_TO_GET_CRL:
1828 s = String::New("UNABLE_TO_GET_CRL");
1831 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1832 s = String::New("UNABLE_TO_DECRYPT_CERT_SIGNATURE");
1835 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1836 s = String::New("UNABLE_TO_DECRYPT_CRL_SIGNATURE");
1839 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1840 s = String::New("UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY");
1843 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1844 s = String::New("CERT_SIGNATURE_FAILURE");
1847 case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1848 s = String::New("CRL_SIGNATURE_FAILURE");
1851 case X509_V_ERR_CERT_NOT_YET_VALID:
1852 s = String::New("CERT_NOT_YET_VALID");
1855 case X509_V_ERR_CERT_HAS_EXPIRED:
1856 s = String::New("CERT_HAS_EXPIRED");
1859 case X509_V_ERR_CRL_NOT_YET_VALID:
1860 s = String::New("CRL_NOT_YET_VALID");
1863 case X509_V_ERR_CRL_HAS_EXPIRED:
1864 s = String::New("CRL_HAS_EXPIRED");
1867 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1868 s = String::New("ERROR_IN_CERT_NOT_BEFORE_FIELD");
1871 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1872 s = String::New("ERROR_IN_CERT_NOT_AFTER_FIELD");
1875 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1876 s = String::New("ERROR_IN_CRL_LAST_UPDATE_FIELD");
1879 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1880 s = String::New("ERROR_IN_CRL_NEXT_UPDATE_FIELD");
1883 case X509_V_ERR_OUT_OF_MEM:
1884 s = String::New("OUT_OF_MEM");
1887 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1888 s = String::New("DEPTH_ZERO_SELF_SIGNED_CERT");
1891 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1892 s = String::New("SELF_SIGNED_CERT_IN_CHAIN");
1895 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1896 s = String::New("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
1899 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1900 s = String::New("UNABLE_TO_VERIFY_LEAF_SIGNATURE");
1903 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1904 s = String::New("CERT_CHAIN_TOO_LONG");
1907 case X509_V_ERR_CERT_REVOKED:
1908 s = String::New("CERT_REVOKED");
1911 case X509_V_ERR_INVALID_CA:
1912 s = String::New("INVALID_CA");
1915 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1916 s = String::New("PATH_LENGTH_EXCEEDED");
1919 case X509_V_ERR_INVALID_PURPOSE:
1920 s = String::New("INVALID_PURPOSE");
1923 case X509_V_ERR_CERT_UNTRUSTED:
1924 s = String::New("CERT_UNTRUSTED");
1927 case X509_V_ERR_CERT_REJECTED:
1928 s = String::New("CERT_REJECTED");
1932 s = String::New(X509_verify_cert_error_string(x509_verify_error));
1936 return scope.Close(Exception::Error(s));
1940 Handle<Value> Connection::GetCurrentCipher(const Arguments& args) {
1941 HandleScope scope(node_isolate);
1943 Connection *ss = Connection::Unwrap(args);
1945 OPENSSL_CONST SSL_CIPHER *c;
1947 if ( ss->ssl_ == NULL ) return Undefined(node_isolate);
1948 c = SSL_get_current_cipher(ss->ssl_);
1949 if ( c == NULL ) return Undefined(node_isolate);
1950 Local<Object> info = Object::New();
1951 const char* cipher_name = SSL_CIPHER_get_name(c);
1952 info->Set(name_symbol, String::New(cipher_name));
1953 const char* cipher_version = SSL_CIPHER_get_version(c);
1954 info->Set(version_symbol, String::New(cipher_version));
1955 return scope.Close(info);
1958 Handle<Value> Connection::Close(const Arguments& args) {
1959 HandleScope scope(node_isolate);
1961 Connection *ss = Connection::Unwrap(args);
1963 if (ss->ssl_ != NULL) {
1967 return True(node_isolate);
1970 #ifdef OPENSSL_NPN_NEGOTIATED
1971 Handle<Value> Connection::GetNegotiatedProto(const Arguments& args) {
1972 HandleScope scope(node_isolate);
1974 Connection *ss = Connection::Unwrap(args);
1976 if (ss->is_server_) {
1977 const unsigned char* npn_proto;
1978 unsigned int npn_proto_len;
1980 SSL_get0_next_proto_negotiated(ss->ssl_, &npn_proto, &npn_proto_len);
1983 return False(node_isolate);
1986 return String::New((const char*) npn_proto, npn_proto_len);
1988 return ss->selectedNPNProto_;
1992 Handle<Value> Connection::SetNPNProtocols(const Arguments& args) {
1993 HandleScope scope(node_isolate);
1995 Connection *ss = Connection::Unwrap(args);
1997 if (args.Length() < 1 || !Buffer::HasInstance(args[0])) {
1998 return ThrowException(Exception::Error(String::New(
1999 "Must give a Buffer as first argument")));
2002 // Release old handle
2003 if (!ss->npnProtos_.IsEmpty()) {
2004 ss->npnProtos_.Dispose(node_isolate);
2006 ss->npnProtos_ = Persistent<Object>::New(node_isolate, args[0]->ToObject());
2008 return True(node_isolate);
2012 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2013 Handle<Value> Connection::GetServername(const Arguments& args) {
2014 HandleScope scope(node_isolate);
2016 Connection *ss = Connection::Unwrap(args);
2018 if (ss->is_server_ && !ss->servername_.IsEmpty()) {
2019 return ss->servername_;
2021 return False(node_isolate);
2025 Handle<Value> Connection::SetSNICallback(const Arguments& args) {
2026 HandleScope scope(node_isolate);
2028 Connection *ss = Connection::Unwrap(args);
2030 if (args.Length() < 1 || !args[0]->IsFunction()) {
2031 return ThrowException(Exception::Error(String::New(
2032 "Must give a Function as first argument")));
2035 // Release old handle
2036 if (!ss->sniObject_.IsEmpty()) {
2037 ss->sniObject_.Dispose(node_isolate);
2039 ss->sniObject_ = Persistent<Object>::New(node_isolate, Object::New());
2040 ss->sniObject_->Set(String::New("onselect"), args[0]);
2042 return True(node_isolate);
2047 void CipherBase::Initialize(Handle<Object> target) {
2048 HandleScope scope(node_isolate);
2050 Local<FunctionTemplate> t = FunctionTemplate::New(New);
2052 t->InstanceTemplate()->SetInternalFieldCount(1);
2054 NODE_SET_PROTOTYPE_METHOD(t, "init", Init);
2055 NODE_SET_PROTOTYPE_METHOD(t, "initiv", InitIv);
2056 NODE_SET_PROTOTYPE_METHOD(t, "update", Update);
2057 NODE_SET_PROTOTYPE_METHOD(t, "final", Final);
2058 NODE_SET_PROTOTYPE_METHOD(t, "setAutoPadding", SetAutoPadding);
2060 target->Set(String::NewSymbol("CipherBase"), t->GetFunction());
2064 Handle<Value> CipherBase::New(const Arguments& args) {
2065 HandleScope scope(node_isolate);
2067 CipherBase* cipher = new CipherBase(args[0]->IsTrue() ? kCipher : kDecipher);
2068 cipher->Wrap(args.This());
2073 Handle<Value> CipherBase::Init(char* cipher_type,
2076 HandleScope scope(node_isolate);
2078 assert(cipher_ == NULL);
2079 cipher_ = EVP_get_cipherbyname(cipher_type);
2080 if (cipher_ == NULL) {
2081 return ThrowError("Unknown cipher");
2084 unsigned char key[EVP_MAX_KEY_LENGTH];
2085 unsigned char iv[EVP_MAX_IV_LENGTH];
2087 int key_len = EVP_BytesToKey(cipher_,
2090 reinterpret_cast<unsigned char*>(key_buf),
2096 EVP_CIPHER_CTX_init(&ctx_);
2097 EVP_CipherInit_ex(&ctx_, cipher_, NULL, NULL, NULL, kind_ == kCipher);
2098 if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
2099 EVP_CIPHER_CTX_cleanup(&ctx_);
2100 return ThrowError("Invalid key length");
2103 EVP_CipherInit_ex(&ctx_,
2106 reinterpret_cast<unsigned char*>(key),
2107 reinterpret_cast<unsigned char*>(iv),
2109 initialised_ = true;
2110 return Null(node_isolate);
2114 Handle<Value> CipherBase::Init(const Arguments& args) {
2115 HandleScope scope(node_isolate);
2117 CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2119 if (args.Length() < 2 ||
2120 !(args[0]->IsString() && Buffer::HasInstance(args[1]))) {
2121 return ThrowError("Must give cipher-type, key");
2124 String::Utf8Value cipher_type(args[0]);
2125 char* key_buf = Buffer::Data(args[1]);
2126 ssize_t key_buf_len = Buffer::Length(args[1]);
2128 Handle<Value> ret = cipher->Init(*cipher_type, key_buf, key_buf_len);
2130 if (ret->IsNull()) {
2134 return scope.Close(ret);
2139 Handle<Value> CipherBase::InitIv(char* cipher_type,
2144 HandleScope scope(node_isolate);
2146 cipher_ = EVP_get_cipherbyname(cipher_type);
2147 if (cipher_ == NULL) {
2148 return ThrowError("Unknown cipher");
2151 /* OpenSSL versions up to 0.9.8l failed to return the correct
2152 iv_length (0) for ECB ciphers */
2153 if (EVP_CIPHER_iv_length(cipher_) != iv_len &&
2154 !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_ECB_MODE && iv_len == 0)) {
2155 return ThrowError("Invalid IV length");
2157 EVP_CIPHER_CTX_init(&ctx_);
2158 EVP_CipherInit_ex(&ctx_, cipher_, NULL, NULL, NULL, kind_ == kCipher);
2159 if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
2160 EVP_CIPHER_CTX_cleanup(&ctx_);
2161 return ThrowError("Invalid key length");
2164 EVP_CipherInit_ex(&ctx_,
2167 reinterpret_cast<unsigned char*>(key),
2168 reinterpret_cast<unsigned char*>(iv),
2170 initialised_ = true;
2171 return Null(node_isolate);
2175 Handle<Value> CipherBase::InitIv(const Arguments& args) {
2176 HandleScope scope(node_isolate);
2178 CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2180 if (args.Length() < 3 || !args[0]->IsString()) {
2181 return ThrowError("Must give cipher-type, key, and iv as argument");
2184 ASSERT_IS_BUFFER(args[1]);
2185 ASSERT_IS_BUFFER(args[2]);
2187 String::Utf8Value cipher_type(args[0]);
2188 ssize_t key_len = Buffer::Length(args[1]);
2189 char* key_buf = Buffer::Data(args[1]);
2190 ssize_t iv_len = Buffer::Length(args[2]);
2191 char* iv_buf = Buffer::Data(args[2]);
2193 Handle<Value> ret = cipher->InitIv(*cipher_type,
2199 if (ret->IsNull()) {
2203 return scope.Close(ret);
2208 bool CipherBase::Update(char* data,
2210 unsigned char** out,
2212 if (!initialised_) return 0;
2213 *out_len = len + EVP_CIPHER_CTX_block_size(&ctx_);
2214 *out = new unsigned char[*out_len];
2215 return EVP_CipherUpdate(&ctx_,
2218 reinterpret_cast<unsigned char*>(data),
2223 Handle<Value> CipherBase::Update(const Arguments& args) {
2224 HandleScope scope(node_isolate);
2226 CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2228 ASSERT_IS_BUFFER(args[0]);
2230 unsigned char* out = NULL;
2233 char* buffer_data = Buffer::Data(args[0]);
2234 size_t buffer_length = Buffer::Length(args[0]);
2236 r = cipher->Update(buffer_data, buffer_length, &out, &out_len);
2240 return ThrowCryptoTypeError(ERR_get_error());
2243 Buffer* buf = Buffer::New(reinterpret_cast<char*>(out), out_len);
2245 return scope.Close(buf->handle_);
2249 bool CipherBase::SetAutoPadding(bool auto_padding) {
2250 if (!initialised_) return false;
2251 return EVP_CIPHER_CTX_set_padding(&ctx_, auto_padding);
2255 Handle<Value> CipherBase::SetAutoPadding(const Arguments& args) {
2256 HandleScope scope(node_isolate);
2258 CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2260 cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue());
2262 return Undefined(node_isolate);
2266 bool CipherBase::Final(unsigned char** out, int *out_len) {
2267 if (!initialised_) return false;
2269 *out = new unsigned char[EVP_CIPHER_CTX_block_size(&ctx_)];
2270 bool r = EVP_CipherFinal_ex(&ctx_, *out, out_len);
2271 EVP_CIPHER_CTX_cleanup(&ctx_);
2272 initialised_ = false;
2278 Handle<Value> CipherBase::Final(const Arguments& args) {
2279 HandleScope scope(node_isolate);
2281 CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2283 unsigned char* out_value = NULL;
2285 Local<Value> outString;
2287 bool r = cipher->Final(&out_value, &out_len);
2289 if (out_len <= 0 || !r) {
2293 if (!r) return ThrowCryptoTypeError(ERR_get_error());
2296 Buffer* buf = Buffer::New(reinterpret_cast<char*>(out_value), out_len);
2298 return scope.Close(buf->handle_);
2302 void Hmac::Initialize(v8::Handle<v8::Object> target) {
2303 HandleScope scope(node_isolate);
2305 Local<FunctionTemplate> t = FunctionTemplate::New(New);
2307 t->InstanceTemplate()->SetInternalFieldCount(1);
2309 NODE_SET_PROTOTYPE_METHOD(t, "init", HmacInit);
2310 NODE_SET_PROTOTYPE_METHOD(t, "update", HmacUpdate);
2311 NODE_SET_PROTOTYPE_METHOD(t, "digest", HmacDigest);
2313 target->Set(String::NewSymbol("Hmac"), t->GetFunction());
2317 Handle<Value> Hmac::New(const Arguments& args) {
2318 HandleScope scope(node_isolate);
2320 Hmac* hmac = new Hmac();
2321 hmac->Wrap(args.This());
2326 Handle<Value> Hmac::HmacInit(char* hashType, char* key, int key_len) {
2327 HandleScope scope(node_isolate);
2329 assert(md_ == NULL);
2330 md_ = EVP_get_digestbyname(hashType);
2332 return ThrowError("Unknown message digest");
2334 HMAC_CTX_init(&ctx_);
2336 HMAC_Init(&ctx_, "", 0, md_);
2338 HMAC_Init(&ctx_, key, key_len, md_);
2340 initialised_ = true;
2342 return Null(node_isolate);
2346 Handle<Value> Hmac::HmacInit(const Arguments& args) {
2347 HandleScope scope(node_isolate);
2349 Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
2351 if (args.Length() < 2 || !args[0]->IsString()) {
2352 return ThrowError("Must give hashtype string, key as arguments");
2355 ASSERT_IS_BUFFER(args[1]);
2357 String::Utf8Value hashType(args[0]);
2359 char* buffer_data = Buffer::Data(args[1]);
2360 size_t buffer_length = Buffer::Length(args[1]);
2362 Handle<Value> ret = hmac->HmacInit(*hashType, buffer_data, buffer_length);
2364 if (ret->IsNull()) {
2373 bool Hmac::HmacUpdate(char* data, int len) {
2374 if (!initialised_) return false;
2375 HMAC_Update(&ctx_, reinterpret_cast<unsigned char*>(data), len);
2380 Handle<Value> Hmac::HmacUpdate(const Arguments& args) {
2381 HandleScope scope(node_isolate);
2383 Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
2385 ASSERT_IS_BUFFER(args[0]);
2389 char* buffer_data = Buffer::Data(args[0]);
2390 size_t buffer_length = Buffer::Length(args[0]);
2392 r = hmac->HmacUpdate(buffer_data, buffer_length);
2395 return ThrowTypeError("HmacUpdate fail");
2402 bool Hmac::HmacDigest(unsigned char** md_value, unsigned int* md_len) {
2403 if (!initialised_) return false;
2404 *md_value = new unsigned char[EVP_MAX_MD_SIZE];
2405 HMAC_Final(&ctx_, *md_value, md_len);
2406 HMAC_CTX_cleanup(&ctx_);
2407 initialised_ = false;
2412 Handle<Value> Hmac::HmacDigest(const Arguments& args) {
2413 HandleScope scope(node_isolate);
2415 Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
2417 unsigned char* md_value = NULL;
2418 unsigned int md_len = 0;
2419 Local<Value> outString;
2421 bool r = hmac->HmacDigest(&md_value, &md_len);
2427 Buffer* buf = Buffer::New(reinterpret_cast<char*>(md_value), md_len);
2429 return scope.Close(buf->handle_);
2433 void Hash::Initialize(v8::Handle<v8::Object> target) {
2434 HandleScope scope(node_isolate);
2436 Local<FunctionTemplate> t = FunctionTemplate::New(New);
2438 t->InstanceTemplate()->SetInternalFieldCount(1);
2440 NODE_SET_PROTOTYPE_METHOD(t, "update", HashUpdate);
2441 NODE_SET_PROTOTYPE_METHOD(t, "digest", HashDigest);
2443 target->Set(String::NewSymbol("Hash"), t->GetFunction());
2447 Handle<Value> Hash::New(const Arguments& args) {
2448 HandleScope scope(node_isolate);
2450 if (args.Length() == 0 || !args[0]->IsString()) {
2451 return ThrowError("Must give hashtype string as argument");
2454 String::Utf8Value hashType(args[0]);
2456 Hash* hash = new Hash();
2457 if (!hash->HashInit(*hashType)) {
2459 return ThrowError("Digest method not supported");
2462 hash->Wrap(args.This());
2467 bool Hash::HashInit(const char* hashType) {
2468 assert(md_ == NULL);
2469 md_ = EVP_get_digestbyname(hashType);
2470 if (md_ == NULL) return false;
2471 EVP_MD_CTX_init(&mdctx_);
2472 EVP_DigestInit_ex(&mdctx_, md_, NULL);
2473 initialised_ = true;
2478 bool Hash::HashUpdate(char* data, int len) {
2479 if (!initialised_) return false;
2480 EVP_DigestUpdate(&mdctx_, data, len);
2485 Handle<Value> Hash::HashUpdate(const Arguments& args) {
2486 HandleScope scope(node_isolate);
2488 Hash* hash = ObjectWrap::Unwrap<Hash>(args.This());
2490 ASSERT_IS_BUFFER(args[0]);
2494 char* buffer_data = Buffer::Data(args[0]);
2495 size_t buffer_length = Buffer::Length(args[0]);
2496 r = hash->HashUpdate(buffer_data, buffer_length);
2499 return ThrowTypeError("HashUpdate fail");
2506 Handle<Value> Hash::HashDigest(const Arguments& args) {
2507 HandleScope scope(node_isolate);
2509 Hash* hash = ObjectWrap::Unwrap<Hash>(args.This());
2511 if (!hash->initialised_) {
2512 return ThrowError("Not initialized");
2515 unsigned char md_value[EVP_MAX_MD_SIZE];
2516 unsigned int md_len;
2518 EVP_DigestFinal_ex(&hash->mdctx_, md_value, &md_len);
2519 EVP_MD_CTX_cleanup(&hash->mdctx_);
2520 hash->initialised_ = false;
2522 Buffer* buf = Buffer::New(reinterpret_cast<char*>(md_value), md_len);
2524 return scope.Close(buf->handle_);
2528 void Sign::Initialize(v8::Handle<v8::Object> target) {
2529 HandleScope scope(node_isolate);
2531 Local<FunctionTemplate> t = FunctionTemplate::New(New);
2533 t->InstanceTemplate()->SetInternalFieldCount(1);
2535 NODE_SET_PROTOTYPE_METHOD(t, "init", SignInit);
2536 NODE_SET_PROTOTYPE_METHOD(t, "update", SignUpdate);
2537 NODE_SET_PROTOTYPE_METHOD(t, "sign", SignFinal);
2539 target->Set(String::NewSymbol("Sign"), t->GetFunction());
2543 Handle<Value> Sign::New(const Arguments& args) {
2544 HandleScope scope(node_isolate);
2546 Sign* sign = new Sign();
2547 sign->Wrap(args.This());
2553 Handle<Value> Sign::SignInit(const char* sign_type) {
2554 HandleScope scope(node_isolate);
2556 assert(md_ == NULL);
2557 md_ = EVP_get_digestbyname(sign_type);
2559 return ThrowError("Uknown message digest");
2561 EVP_MD_CTX_init(&mdctx_);
2562 EVP_SignInit_ex(&mdctx_, md_, NULL);
2563 initialised_ = true;
2564 return Null(node_isolate);
2568 Handle<Value> Sign::SignInit(const Arguments& args) {
2569 HandleScope scope(node_isolate);
2571 Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
2573 if (args.Length() == 0 || !args[0]->IsString()) {
2574 return ThrowError("Must give signtype string as argument");
2577 String::Utf8Value sign_type(args[0]);
2579 Handle<Value> ret = sign->SignInit(*sign_type);
2581 if (ret->IsNull()) {
2585 return scope.Close(ret);
2590 bool Sign::SignUpdate(char* data, int len) {
2591 if (!initialised_) return false;
2592 EVP_SignUpdate(&mdctx_, data, len);
2597 Handle<Value> Sign::SignUpdate(const Arguments& args) {
2598 HandleScope scope(node_isolate);
2600 Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
2602 ASSERT_IS_BUFFER(args[0]);
2606 char* buffer_data = Buffer::Data(args[0]);
2607 size_t buffer_length = Buffer::Length(args[0]);
2609 r = sign->SignUpdate(buffer_data, buffer_length);
2612 return ThrowTypeError("SignUpdate fail");
2619 bool Sign::SignFinal(unsigned char** md_value,
2620 unsigned int *md_len,
2623 if (!initialised_) return false;
2626 EVP_PKEY* pkey = NULL;
2627 bp = BIO_new(BIO_s_mem());
2628 if (!BIO_write(bp, key_pem, key_pem_len)) return false;
2630 pkey = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL);
2631 if (pkey == NULL) return 0;
2633 EVP_SignFinal(&mdctx_, *md_value, md_len, pkey);
2634 EVP_MD_CTX_cleanup(&mdctx_);
2635 initialised_ = false;
2636 EVP_PKEY_free(pkey);
2642 Handle<Value> Sign::SignFinal(const Arguments& args) {
2643 HandleScope scope(node_isolate);
2645 Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
2647 unsigned char* md_value;
2648 unsigned int md_len;
2649 Local<Value> outString;
2651 md_len = 8192; // Maximum key size is 8192 bits
2652 md_value = new unsigned char[md_len];
2654 ASSERT_IS_BUFFER(args[0]);
2655 ssize_t len = Buffer::Length(args[0]);
2656 char* buf = Buffer::Data(args[0]);
2658 bool r = sign->SignFinal(&md_value, &md_len, buf, len);
2665 Buffer* ret = Buffer::New(reinterpret_cast<char*>(md_value), md_len);
2668 return scope.Close(ret->handle_);
2672 void Verify::Initialize(v8::Handle<v8::Object> target) {
2673 HandleScope scope(node_isolate);
2675 Local<FunctionTemplate> t = FunctionTemplate::New(New);
2677 t->InstanceTemplate()->SetInternalFieldCount(1);
2679 NODE_SET_PROTOTYPE_METHOD(t, "init", VerifyInit);
2680 NODE_SET_PROTOTYPE_METHOD(t, "update", VerifyUpdate);
2681 NODE_SET_PROTOTYPE_METHOD(t, "verify", VerifyFinal);
2683 target->Set(String::NewSymbol("Verify"), t->GetFunction());
2687 Handle<Value> Verify::New(const Arguments& args) {
2688 HandleScope scope(node_isolate);
2690 Verify* verify = new Verify();
2691 verify->Wrap(args.This());
2697 Handle<Value> Verify::VerifyInit(const char* verify_type) {
2698 HandleScope scope(node_isolate);
2700 assert(md_ == NULL);
2701 md_ = EVP_get_digestbyname(verify_type);
2703 return ThrowError("Unknown message digest");
2706 EVP_MD_CTX_init(&mdctx_);
2707 EVP_VerifyInit_ex(&mdctx_, md_, NULL);
2708 initialised_ = true;
2710 return Null(node_isolate);
2714 Handle<Value> Verify::VerifyInit(const Arguments& args) {
2715 HandleScope scope(node_isolate);
2717 Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
2719 if (args.Length() == 0 || !args[0]->IsString()) {
2720 return ThrowError("Must give verifytype string as argument");
2723 String::Utf8Value verify_type(args[0]);
2725 Handle<Value> ret = verify->VerifyInit(*verify_type);
2727 if (ret->IsNull()) {
2731 return scope.Close(ret);
2736 bool Verify::VerifyUpdate(char* data, int len) {
2737 if (!initialised_) return false;
2738 EVP_VerifyUpdate(&mdctx_, data, len);
2743 Handle<Value> Verify::VerifyUpdate(const Arguments& args) {
2744 HandleScope scope(node_isolate);
2746 Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
2748 ASSERT_IS_BUFFER(args[0]);
2752 char* buffer_data = Buffer::Data(args[0]);
2753 size_t buffer_length = Buffer::Length(args[0]);
2755 r = verify->VerifyUpdate(buffer_data, buffer_length);
2758 return ThrowTypeError("VerifyUpdate fail");
2765 Handle<Value> Verify::VerifyFinal(char* key_pem,
2769 HandleScope scope(node_isolate);
2771 if (!initialised_) {
2772 return ThrowError("Verify not initalised");
2775 EVP_PKEY* pkey = NULL;
2781 bp = BIO_new(BIO_s_mem());
2785 if (!BIO_write(bp, key_pem, key_pem_len))
2788 // Check if this is a PKCS#8 or RSA public key before trying as X.509.
2789 // Split this out into a separate function once we have more than one
2790 // consumer of public keys.
2791 if (strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
2792 pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL);
2795 } else if (strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
2796 RSA* rsa = PEM_read_bio_RSAPublicKey(bp, NULL, NULL, NULL);
2798 pkey = EVP_PKEY_new();
2799 if (pkey) EVP_PKEY_set1_RSA(pkey, rsa);
2806 x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
2810 pkey = X509_get_pubkey(x509);
2816 r = EVP_VerifyFinal(&mdctx_, sig, siglen, pkey);
2820 EVP_PKEY_free(pkey);
2826 EVP_MD_CTX_cleanup(&mdctx_);
2827 initialised_ = false;
2830 unsigned long err = ERR_get_error();
2831 return ThrowCryptoError(err);
2834 return scope.Close(r ? True() : False(node_isolate));
2838 Handle<Value> Verify::VerifyFinal(const Arguments& args) {
2839 HandleScope scope(node_isolate);
2841 Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
2843 ASSERT_IS_BUFFER(args[0]);
2844 char* kbuf = Buffer::Data(args[0]);
2845 ssize_t klen = Buffer::Length(args[0]);
2847 ASSERT_IS_BUFFER(args[1]);
2848 unsigned char* hbuf = reinterpret_cast<unsigned char*>(Buffer::Data(args[1]));
2849 ssize_t hlen = Buffer::Length(args[1]);
2851 return scope.Close(verify->VerifyFinal(kbuf, klen, hbuf, hlen));
2855 void DiffieHellman::Initialize(v8::Handle<v8::Object> target) {
2856 HandleScope scope(node_isolate);
2858 Local<FunctionTemplate> t = FunctionTemplate::New(New);
2860 t->InstanceTemplate()->SetInternalFieldCount(1);
2862 NODE_SET_PROTOTYPE_METHOD(t, "generateKeys", GenerateKeys);
2863 NODE_SET_PROTOTYPE_METHOD(t, "computeSecret", ComputeSecret);
2864 NODE_SET_PROTOTYPE_METHOD(t, "getPrime", GetPrime);
2865 NODE_SET_PROTOTYPE_METHOD(t, "getGenerator", GetGenerator);
2866 NODE_SET_PROTOTYPE_METHOD(t, "getPublicKey", GetPublicKey);
2867 NODE_SET_PROTOTYPE_METHOD(t, "getPrivateKey", GetPrivateKey);
2868 NODE_SET_PROTOTYPE_METHOD(t, "setPublicKey", SetPublicKey);
2869 NODE_SET_PROTOTYPE_METHOD(t, "setPrivateKey", SetPrivateKey);
2871 target->Set(String::NewSymbol("DiffieHellman"), t->GetFunction());
2873 Local<FunctionTemplate> t2 = FunctionTemplate::New(DiffieHellmanGroup);
2874 t2->InstanceTemplate()->SetInternalFieldCount(1);
2876 NODE_SET_PROTOTYPE_METHOD(t2, "generateKeys", GenerateKeys);
2877 NODE_SET_PROTOTYPE_METHOD(t2, "computeSecret", ComputeSecret);
2878 NODE_SET_PROTOTYPE_METHOD(t2, "getPrime", GetPrime);
2879 NODE_SET_PROTOTYPE_METHOD(t2, "getGenerator", GetGenerator);
2880 NODE_SET_PROTOTYPE_METHOD(t2, "getPublicKey", GetPublicKey);
2881 NODE_SET_PROTOTYPE_METHOD(t2, "getPrivateKey", GetPrivateKey);
2883 target->Set(String::NewSymbol("DiffieHellmanGroup"), t2->GetFunction());
2887 bool DiffieHellman::Init(int primeLength) {
2889 DH_generate_parameters_ex(dh, primeLength, DH_GENERATOR_2, 0);
2890 bool result = VerifyContext();
2891 if (!result) return false;
2892 initialised_ = true;
2897 bool DiffieHellman::Init(unsigned char* p, int p_len) {
2899 dh->p = BN_bin2bn(p, p_len, 0);
2901 if (!BN_set_word(dh->g, 2)) return false;
2902 bool result = VerifyContext();
2903 if (!result) return false;
2904 initialised_ = true;
2909 bool DiffieHellman::Init(unsigned char* p,
2914 dh->p = BN_bin2bn(p, p_len, 0);
2915 dh->g = BN_bin2bn(g, g_len, 0);
2916 initialised_ = true;
2921 Handle<Value> DiffieHellman::DiffieHellmanGroup(const Arguments& args) {
2922 HandleScope scope(node_isolate);
2924 DiffieHellman* diffieHellman = new DiffieHellman();
2926 if (args.Length() != 1 || !args[0]->IsString()) {
2927 return ThrowError("No group name given");
2930 String::Utf8Value group_name(args[0]);
2932 modp_group* it = modp_groups;
2934 while(it->name != NULL) {
2935 if (!strcasecmp(*group_name, it->name))
2940 if (it->name != NULL) {
2941 diffieHellman->Init(it->prime,
2946 return ThrowError("Unknown group");
2949 diffieHellman->Wrap(args.This());
2955 Handle<Value> DiffieHellman::New(const Arguments& args) {
2956 HandleScope scope(node_isolate);
2958 DiffieHellman* diffieHellman = new DiffieHellman();
2959 bool initialized = false;
2961 if (args.Length() > 0) {
2962 if (args[0]->IsInt32()) {
2963 initialized = diffieHellman->Init(args[0]->Int32Value());
2965 initialized = diffieHellman->Init(
2966 reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
2967 Buffer::Length(args[0]));
2972 return ThrowError("Initialization failed");
2975 diffieHellman->Wrap(args.This());
2981 Handle<Value> DiffieHellman::GenerateKeys(const Arguments& args) {
2982 HandleScope scope(node_isolate);
2984 DiffieHellman* diffieHellman =
2985 ObjectWrap::Unwrap<DiffieHellman>(args.This());
2987 if (!diffieHellman->initialised_) {
2988 return ThrowError("Not initialized");
2991 if (!DH_generate_key(diffieHellman->dh)) {
2992 return ThrowError("Key generation failed");
2995 Local<Value> outString;
2997 int dataSize = BN_num_bytes(diffieHellman->dh->pub_key);
2998 char* data = new char[dataSize];
2999 BN_bn2bin(diffieHellman->dh->pub_key,
3000 reinterpret_cast<unsigned char*>(data));
3002 outString = Encode(data, dataSize, BUFFER);
3005 return scope.Close(outString);
3009 Handle<Value> DiffieHellman::GetPrime(const Arguments& args) {
3010 HandleScope scope(node_isolate);
3012 DiffieHellman* diffieHellman =
3013 ObjectWrap::Unwrap<DiffieHellman>(args.This());
3015 if (!diffieHellman->initialised_) {
3016 return ThrowError("Not initialized");
3019 int dataSize = BN_num_bytes(diffieHellman->dh->p);
3020 char* data = new char[dataSize];
3021 BN_bn2bin(diffieHellman->dh->p, reinterpret_cast<unsigned char*>(data));
3023 Local<Value> outString;
3025 outString = Encode(data, dataSize, BUFFER);
3029 return scope.Close(outString);
3033 Handle<Value> DiffieHellman::GetGenerator(const Arguments& args) {
3034 HandleScope scope(node_isolate);
3036 DiffieHellman* diffieHellman =
3037 ObjectWrap::Unwrap<DiffieHellman>(args.This());
3039 if (!diffieHellman->initialised_) {
3040 return ThrowError("Not initialized");
3043 int dataSize = BN_num_bytes(diffieHellman->dh->g);
3044 char* data = new char[dataSize];
3045 BN_bn2bin(diffieHellman->dh->g, reinterpret_cast<unsigned char*>(data));
3047 Local<Value> outString;
3049 outString = Encode(data, dataSize, BUFFER);
3053 return scope.Close(outString);
3057 Handle<Value> DiffieHellman::GetPublicKey(const Arguments& args) {
3058 HandleScope scope(node_isolate);
3060 DiffieHellman* diffieHellman =
3061 ObjectWrap::Unwrap<DiffieHellman>(args.This());
3063 if (!diffieHellman->initialised_) {
3064 return ThrowError("Not initialized");
3067 if (diffieHellman->dh->pub_key == NULL) {
3068 return ThrowError("No public key - did you forget to generate one?");
3071 int dataSize = BN_num_bytes(diffieHellman->dh->pub_key);
3072 char* data = new char[dataSize];
3073 BN_bn2bin(diffieHellman->dh->pub_key,
3074 reinterpret_cast<unsigned char*>(data));
3076 Local<Value> outString;
3078 outString = Encode(data, dataSize, BUFFER);
3082 return scope.Close(outString);
3086 Handle<Value> DiffieHellman::GetPrivateKey(const Arguments& args) {
3087 HandleScope scope(node_isolate);
3089 DiffieHellman* diffieHellman =
3090 ObjectWrap::Unwrap<DiffieHellman>(args.This());
3092 if (!diffieHellman->initialised_) {
3093 return ThrowError("Not initialized");
3096 if (diffieHellman->dh->priv_key == NULL) {
3097 return ThrowError("No private key - did you forget to generate one?");
3100 int dataSize = BN_num_bytes(diffieHellman->dh->priv_key);
3101 char* data = new char[dataSize];
3102 BN_bn2bin(diffieHellman->dh->priv_key,
3103 reinterpret_cast<unsigned char*>(data));
3105 Local<Value> outString;
3107 outString = Encode(data, dataSize, BUFFER);
3111 return scope.Close(outString);
3115 Handle<Value> DiffieHellman::ComputeSecret(const Arguments& args) {
3116 HandleScope scope(node_isolate);
3118 DiffieHellman* diffieHellman =
3119 ObjectWrap::Unwrap<DiffieHellman>(args.This());
3121 if (!diffieHellman->initialised_) {
3122 return ThrowError("Not initialized");
3127 if (args.Length() == 0) {
3128 return ThrowError("First argument must be other party's public key");
3130 ASSERT_IS_BUFFER(args[0]);
3132 reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3133 Buffer::Length(args[0]),
3137 int dataSize = DH_size(diffieHellman->dh);
3138 char* data = new char[dataSize];
3140 int size = DH_compute_key(reinterpret_cast<unsigned char*>(data),
3148 checked = DH_check_pub_key(diffieHellman->dh, key, &checkResult);
3153 return ThrowError("Invalid key");
3154 } else if (checkResult) {
3155 if (checkResult & DH_CHECK_PUBKEY_TOO_SMALL) {
3156 return ThrowError("Supplied key is too small");
3157 } else if (checkResult & DH_CHECK_PUBKEY_TOO_LARGE) {
3158 return ThrowError("Supplied key is too large");
3160 return ThrowError("Invalid key");
3163 return ThrowError("Invalid key");
3170 // DH_size returns number of bytes in a prime number
3171 // DH_compute_key returns number of bytes in a remainder of exponent, which
3172 // may have less bytes than a prime number. Therefore add 0-padding to the
3173 // allocated buffer.
3174 if (size != dataSize) {
3175 assert(dataSize > size);
3176 memset(data + size, 0, dataSize - size);
3179 Local<Value> outString;
3181 outString = Encode(data, dataSize, BUFFER);
3184 return scope.Close(outString);
3188 Handle<Value> DiffieHellman::SetPublicKey(const Arguments& args) {
3189 HandleScope scope(node_isolate);
3191 DiffieHellman* diffieHellman =
3192 ObjectWrap::Unwrap<DiffieHellman>(args.This());
3194 if (!diffieHellman->initialised_) {
3195 return ThrowError("Not initialized");
3198 if (args.Length() == 0) {
3199 return ThrowError("First argument must be public key");
3201 ASSERT_IS_BUFFER(args[0]);
3202 diffieHellman->dh->pub_key = BN_bin2bn(
3203 reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3204 Buffer::Length(args[0]), 0);
3211 Handle<Value> DiffieHellman::SetPrivateKey(const Arguments& args) {
3212 HandleScope scope(node_isolate);
3214 DiffieHellman* diffieHellman =
3215 ObjectWrap::Unwrap<DiffieHellman>(args.This());
3217 if (!diffieHellman->initialised_) {
3218 return ThrowError("Not initialized");
3221 if (args.Length() == 0) {
3222 return ThrowError("First argument must be private key");
3224 ASSERT_IS_BUFFER(args[0]);
3225 diffieHellman->dh->priv_key = BN_bin2bn(
3226 reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3227 Buffer::Length(args[0]),
3235 bool DiffieHellman::VerifyContext() {
3237 if (!DH_check(dh, &codes)) return false;
3238 if (codes & DH_CHECK_P_NOT_SAFE_PRIME) return false;
3239 if (codes & DH_CHECK_P_NOT_PRIME) return false;
3240 if (codes & DH_UNABLE_TO_CHECK_GENERATOR) return false;
3241 if (codes & DH_NOT_SUITABLE_GENERATOR) return false;
3256 Persistent<Object> obj;
3260 void EIO_PBKDF2(pbkdf2_req* req) {
3261 req->err = PKCS5_PBKDF2_HMAC_SHA1(
3264 (unsigned char*)req->salt,
3268 (unsigned char*)req->key);
3269 memset(req->pass, 0, req->passlen);
3270 memset(req->salt, 0, req->saltlen);
3274 void EIO_PBKDF2(uv_work_t* work_req) {
3275 pbkdf2_req* req = container_of(work_req, pbkdf2_req, work_req);
3280 void EIO_PBKDF2After(pbkdf2_req* req, Local<Value> argv[2]) {
3282 argv[0] = Local<Value>::New(node_isolate, Undefined(node_isolate));
3283 argv[1] = Encode(req->key, req->keylen, BUFFER);
3284 memset(req->key, 0, req->keylen);
3286 argv[0] = Exception::Error(String::New("PBKDF2 error"));
3287 argv[1] = Local<Value>::New(node_isolate, Undefined(node_isolate));
3297 void EIO_PBKDF2After(uv_work_t* work_req, int status) {
3298 assert(status == 0);
3299 pbkdf2_req* req = container_of(work_req, pbkdf2_req, work_req);
3300 HandleScope scope(node_isolate);
3301 Local<Value> argv[2];
3302 Persistent<Object> obj = req->obj;
3303 EIO_PBKDF2After(req, argv);
3304 MakeCallback(obj, "ondone", ARRAY_SIZE(argv), argv);
3305 obj.Dispose(node_isolate);
3309 Handle<Value> PBKDF2(const Arguments& args) {
3310 HandleScope scope(node_isolate);
3312 const char* type_error = NULL;
3315 ssize_t passlen = -1;
3316 ssize_t saltlen = -1;
3317 ssize_t keylen = -1;
3318 ssize_t pass_written = -1;
3319 ssize_t salt_written = -1;
3321 pbkdf2_req* req = NULL;
3323 if (args.Length() != 4 && args.Length() != 5) {
3324 type_error = "Bad parameter";
3328 ASSERT_IS_BUFFER(args[0]);
3329 passlen = Buffer::Length(args[0]);
3331 type_error = "Bad password";
3335 pass = new char[passlen];
3336 pass_written = DecodeWrite(pass, passlen, args[0], BINARY);
3337 assert(pass_written == passlen);
3339 ASSERT_IS_BUFFER(args[1]);
3340 saltlen = Buffer::Length(args[1]);
3342 type_error = "Bad salt";
3346 salt = new char[saltlen];
3347 salt_written = DecodeWrite(salt, saltlen, args[1], BINARY);
3348 assert(salt_written == saltlen);
3350 if (!args[2]->IsNumber()) {
3351 type_error = "Iterations not a number";
3355 iter = args[2]->Int32Value();
3357 type_error = "Bad iterations";
3361 if (!args[3]->IsNumber()) {
3362 type_error = "Key length not a number";
3366 keylen = args[3]->Int32Value();
3368 type_error = "Bad key length";
3372 req = new pbkdf2_req;
3375 req->passlen = passlen;
3377 req->saltlen = saltlen;
3379 req->key = new char[keylen];
3380 req->keylen = keylen;
3382 if (args[4]->IsFunction()) {
3383 req->obj = Persistent<Object>::New(node_isolate, Object::New());
3384 req->obj->Set(String::New("ondone"), args[4]);
3385 uv_queue_work(uv_default_loop(),
3389 return Undefined(node_isolate);
3391 Local<Value> argv[2];
3393 EIO_PBKDF2After(req, argv);
3394 if (argv[0]->IsObject()) return ThrowException(argv[0]);
3395 return scope.Close(argv[1]);
3401 return ThrowException(Exception::TypeError(String::New(type_error)));
3405 struct RandomBytesRequest {
3406 ~RandomBytesRequest();
3407 Persistent<Object> obj_;
3408 unsigned long error_; // openssl error code or zero
3409 uv_work_t work_req_;
3415 RandomBytesRequest::~RandomBytesRequest() {
3416 if (obj_.IsEmpty()) return;
3417 obj_.Dispose(node_isolate);
3422 void RandomBytesFree(char* data, void* hint) {
3427 template <bool pseudoRandom>
3428 void RandomBytesWork(uv_work_t* work_req) {
3429 RandomBytesRequest* req = container_of(work_req,
3434 if (pseudoRandom == true) {
3435 r = RAND_pseudo_bytes(reinterpret_cast<unsigned char*>(req->data_),
3438 r = RAND_bytes(reinterpret_cast<unsigned char*>(req->data_), req->size_);
3441 // RAND_bytes() returns 0 on error. RAND_pseudo_bytes() returns 0 when the
3442 // result is not cryptographically strong - but that's not an error.
3443 if (r == 0 && pseudoRandom == false) {
3444 req->error_ = ERR_get_error();
3445 } else if (r == -1) {
3446 req->error_ = static_cast<unsigned long>(-1);
3451 // don't call this function without a valid HandleScope
3452 void RandomBytesCheck(RandomBytesRequest* req, Local<Value> argv[2]) {
3454 char errmsg[256] = "Operation not supported";
3456 if (req->error_ != (unsigned long) -1)
3457 ERR_error_string_n(req->error_, errmsg, sizeof errmsg);
3459 argv[0] = Exception::Error(String::New(errmsg));
3460 argv[1] = Local<Value>::New(node_isolate, Null(node_isolate));
3463 // avoids the malloc + memcpy
3464 Buffer* buffer = Buffer::New(req->data_, req->size_, RandomBytesFree, NULL);
3465 argv[0] = Local<Value>::New(node_isolate, Null(node_isolate));
3466 argv[1] = Local<Object>::New(node_isolate, buffer->handle_);
3471 void RandomBytesAfter(uv_work_t* work_req, int status) {
3472 assert(status == 0);
3473 RandomBytesRequest* req = container_of(work_req,
3476 HandleScope scope(node_isolate);
3477 Local<Value> argv[2];
3478 RandomBytesCheck(req, argv);
3479 MakeCallback(req->obj_, "ondone", ARRAY_SIZE(argv), argv);
3484 template <bool pseudoRandom>
3485 Handle<Value> RandomBytes(const Arguments& args) {
3486 HandleScope scope(node_isolate);
3488 // maybe allow a buffer to write to? cuts down on object creation
3489 // when generating random data in a loop
3490 if (!args[0]->IsUint32()) {
3491 return ThrowTypeError("Argument #1 must be number > 0");
3494 const uint32_t size = args[0]->Uint32Value();
3495 if (size > Buffer::kMaxLength) {
3496 return ThrowTypeError("size > Buffer::kMaxLength");
3499 RandomBytesRequest* req = new RandomBytesRequest();
3501 req->data_ = new char[size];
3504 if (args[1]->IsFunction()) {
3505 req->obj_ = Persistent<Object>::New(node_isolate, Object::New());
3506 req->obj_->Set(String::New("ondone"), args[1]);
3508 uv_queue_work(uv_default_loop(),
3510 RandomBytesWork<pseudoRandom>,
3516 Local<Value> argv[2];
3517 RandomBytesWork<pseudoRandom>(&req->work_req_);
3518 RandomBytesCheck(req, argv);
3521 if (!argv[0]->IsNull())
3522 return ThrowException(argv[0]);
3529 Handle<Value> GetSSLCiphers(const Arguments& args) {
3530 HandleScope scope(node_isolate);
3532 SSL_CTX* ctx = SSL_CTX_new(TLSv1_server_method());
3534 return ThrowError("SSL_CTX_new() failed.");
3537 SSL* ssl = SSL_new(ctx);
3540 return ThrowError("SSL_new() failed.");
3543 Local<Array> arr = Array::New();
3544 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl);
3546 for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
3547 SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
3548 arr->Set(i, String::New(SSL_CIPHER_get_name(cipher)));
3554 return scope.Close(arr);
3558 template <class TypeName>
3559 static void array_push_back(const TypeName* md,
3563 Local<Array>& arr = *static_cast<Local<Array>*>(arg);
3564 arr->Set(arr->Length(), String::New(from));
3568 Handle<Value> GetCiphers(const Arguments& args) {
3570 Local<Array> arr = Array::New();
3571 EVP_CIPHER_do_all_sorted(array_push_back<EVP_CIPHER>, &arr);
3572 return scope.Close(arr);
3576 Handle<Value> GetHashes(const Arguments& args) {
3577 HandleScope scope(node_isolate);
3578 Local<Array> arr = Array::New();
3579 EVP_MD_do_all_sorted(array_push_back<EVP_MD>, &arr);
3580 return scope.Close(arr);
3584 void InitCrypto(Handle<Object> target) {
3585 HandleScope scope(node_isolate);
3588 OpenSSL_add_all_algorithms();
3589 OpenSSL_add_all_digests();
3590 SSL_load_error_strings();
3591 ERR_load_crypto_strings();
3594 CRYPTO_set_locking_callback(crypto_lock_cb);
3595 CRYPTO_THREADID_set_callback(crypto_threadid_cb);
3597 // Turn off compression. Saves memory - do it in userland.
3598 #if !defined(OPENSSL_NO_COMP)
3599 STACK_OF(SSL_COMP)* comp_methods =
3600 #if OPENSSL_VERSION_NUMBER < 0x00908000L
3601 SSL_COMP_get_compression_method()
3603 SSL_COMP_get_compression_methods()
3606 sk_SSL_COMP_zero(comp_methods);
3607 assert(sk_SSL_COMP_num(comp_methods) == 0);
3610 SecureContext::Initialize(target);
3611 Connection::Initialize(target);
3612 CipherBase::Initialize(target);
3613 DiffieHellman::Initialize(target);
3614 Hmac::Initialize(target);
3615 Hash::Initialize(target);
3616 Sign::Initialize(target);
3617 Verify::Initialize(target);
3619 NODE_SET_METHOD(target, "PBKDF2", PBKDF2);
3620 NODE_SET_METHOD(target, "randomBytes", RandomBytes<false>);
3621 NODE_SET_METHOD(target, "pseudoRandomBytes", RandomBytes<true>);
3622 NODE_SET_METHOD(target, "getSSLCiphers", GetSSLCiphers);
3623 NODE_SET_METHOD(target, "getCiphers", GetCiphers);
3624 NODE_SET_METHOD(target, "getHashes", GetHashes);
3626 subject_symbol = NODE_PSYMBOL("subject");
3627 issuer_symbol = NODE_PSYMBOL("issuer");
3628 valid_from_symbol = NODE_PSYMBOL("valid_from");
3629 valid_to_symbol = NODE_PSYMBOL("valid_to");
3630 subjectaltname_symbol = NODE_PSYMBOL("subjectaltname");
3631 modulus_symbol = NODE_PSYMBOL("modulus");
3632 exponent_symbol = NODE_PSYMBOL("exponent");
3633 fingerprint_symbol = NODE_PSYMBOL("fingerprint");
3634 name_symbol = NODE_PSYMBOL("name");
3635 version_symbol = NODE_PSYMBOL("version");
3636 ext_key_usage_symbol = NODE_PSYMBOL("ext_key_usage");
3639 } // namespace crypto
3642 NODE_MODULE(node_crypto, node::crypto::InitCrypto)