src: deduplicate CHECK_EQ/CHECK_NE macros
[platform/upstream/nodejs.git] / src / node_crypto.cc
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
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:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
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.
21
22 #include "node.h"
23 #include "node_buffer.h"
24 #include "node_crypto.h"
25 #include "node_crypto_bio.h"
26 #include "node_crypto_groups.h"
27 #include "tls_wrap.h"  // TLSCallbacks
28
29 #include "async-wrap.h"
30 #include "async-wrap-inl.h"
31 #include "env.h"
32 #include "env-inl.h"
33 #include "string_bytes.h"
34 #include "util.h"
35 #include "util-inl.h"
36 #include "v8.h"
37
38 #include <errno.h>
39 #include <stdlib.h>
40 #include <string.h>
41
42 #if defined(_MSC_VER)
43 #define strcasecmp _stricmp
44 #endif
45
46 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
47 #define OPENSSL_CONST const
48 #else
49 #define OPENSSL_CONST
50 #endif
51
52 #define ASSERT_IS_STRING_OR_BUFFER(val) do {                  \
53     if (!Buffer::HasInstance(val) && !val->IsString()) {      \
54       return env->ThrowTypeError("Not a string or buffer");   \
55     }                                                         \
56   } while (0)
57
58 #define ASSERT_IS_BUFFER(val) do {                            \
59     if (!Buffer::HasInstance(val)) {                          \
60       return env->ThrowTypeError("Not a buffer");             \
61     }                                                         \
62   } while (0)
63
64 static const char PUBLIC_KEY_PFX[] =  "-----BEGIN PUBLIC KEY-----";
65 static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
66 static const char PUBRSA_KEY_PFX[] =  "-----BEGIN RSA PUBLIC KEY-----";
67 static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
68 static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
69                                  | ASN1_STRFLGS_ESC_MSB
70                                  | XN_FLAG_SEP_MULTILINE
71                                  | XN_FLAG_FN_SN;
72
73 namespace node {
74 namespace crypto {
75
76 using v8::Array;
77 using v8::Boolean;
78 using v8::Context;
79 using v8::Exception;
80 using v8::False;
81 using v8::FunctionCallbackInfo;
82 using v8::FunctionTemplate;
83 using v8::Handle;
84 using v8::HandleScope;
85 using v8::Integer;
86 using v8::Isolate;
87 using v8::Local;
88 using v8::Null;
89 using v8::Object;
90 using v8::Persistent;
91 using v8::PropertyAttribute;
92 using v8::PropertyCallbackInfo;
93 using v8::String;
94 using v8::V8;
95 using v8::Value;
96
97
98 // Forcibly clear OpenSSL's error stack on return. This stops stale errors
99 // from popping up later in the lifecycle of crypto operations where they
100 // would cause spurious failures. It's a rather blunt method, though.
101 // ERR_clear_error() isn't necessarily cheap either.
102 struct ClearErrorOnReturn {
103   ~ClearErrorOnReturn() { ERR_clear_error(); }
104 };
105
106 static uv_rwlock_t* locks;
107
108 const char* root_certs[] = {
109 #include "node_root_certs.h"  // NOLINT(build/include_order)
110   NULL
111 };
112
113 X509_STORE* root_cert_store;
114
115 // Just to generate static methods
116 template class SSLWrap<TLSCallbacks>;
117 template void SSLWrap<TLSCallbacks>::AddMethods(Environment* env,
118                                                 Handle<FunctionTemplate> t);
119 template void SSLWrap<TLSCallbacks>::InitNPN(SecureContext* sc,
120                                              TLSCallbacks* base);
121 template SSL_SESSION* SSLWrap<TLSCallbacks>::GetSessionCallback(
122     SSL* s,
123     unsigned char* key,
124     int len,
125     int* copy);
126 template int SSLWrap<TLSCallbacks>::NewSessionCallback(SSL* s,
127                                                        SSL_SESSION* sess);
128 template void SSLWrap<TLSCallbacks>::OnClientHello(
129     void* arg,
130     const ClientHelloParser::ClientHello& hello);
131
132 #ifdef OPENSSL_NPN_NEGOTIATED
133 template int SSLWrap<TLSCallbacks>::AdvertiseNextProtoCallback(
134     SSL* s,
135     const unsigned char** data,
136     unsigned int* len,
137     void* arg);
138 template int SSLWrap<TLSCallbacks>::SelectNextProtoCallback(
139     SSL* s,
140     unsigned char** out,
141     unsigned char* outlen,
142     const unsigned char* in,
143     unsigned int inlen,
144     void* arg);
145 #endif
146
147
148 static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
149   CRYPTO_THREADID_set_numeric(tid, uv_thread_self());
150 }
151
152
153 static void crypto_lock_init(void) {
154   int i, n;
155
156   n = CRYPTO_num_locks();
157   locks = new uv_rwlock_t[n];
158
159   for (i = 0; i < n; i++)
160     if (uv_rwlock_init(locks + i))
161       abort();
162 }
163
164
165 static void crypto_lock_cb(int mode, int n, const char* file, int line) {
166   assert((mode & CRYPTO_LOCK) || (mode & CRYPTO_UNLOCK));
167   assert((mode & CRYPTO_READ) || (mode & CRYPTO_WRITE));
168
169   if (mode & CRYPTO_LOCK) {
170     if (mode & CRYPTO_READ)
171       uv_rwlock_rdlock(locks + n);
172     else
173       uv_rwlock_wrlock(locks + n);
174   } else {
175     if (mode & CRYPTO_READ)
176       uv_rwlock_rdunlock(locks + n);
177     else
178       uv_rwlock_wrunlock(locks + n);
179   }
180 }
181
182
183 static int CryptoPemCallback(char *buf, int size, int rwflag, void *u) {
184   if (u) {
185     size_t buflen = static_cast<size_t>(size);
186     size_t len = strlen(static_cast<const char*>(u));
187     len = len > buflen ? buflen : len;
188     memcpy(buf, u, len);
189     return len;
190   }
191
192   return 0;
193 }
194
195
196 void ThrowCryptoErrorHelper(Environment* env,
197                             unsigned long err,
198                             bool is_type_error) {
199   HandleScope scope(env->isolate());
200   char errmsg[128];
201   ERR_error_string_n(err, errmsg, sizeof(errmsg));
202   if (is_type_error)
203     env->ThrowTypeError(errmsg);
204   else
205     env->ThrowError(errmsg);
206 }
207
208
209 void ThrowCryptoError(Environment* env, unsigned long err) {
210   ThrowCryptoErrorHelper(env, err, false);
211 }
212
213
214 void ThrowCryptoTypeError(Environment* env, unsigned long err) {
215   ThrowCryptoErrorHelper(env, err, true);
216 }
217
218
219 bool EntropySource(unsigned char* buffer, size_t length) {
220   // RAND_bytes() can return 0 to indicate that the entropy data is not truly
221   // random. That's okay, it's still better than V8's stock source of entropy,
222   // which is /dev/urandom on UNIX platforms and the current time on Windows.
223   return RAND_bytes(buffer, length) != -1;
224 }
225
226
227 void SecureContext::Initialize(Environment* env, Handle<Object> target) {
228   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(),
229                                                     SecureContext::New);
230   t->InstanceTemplate()->SetInternalFieldCount(1);
231   t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"));
232
233   NODE_SET_PROTOTYPE_METHOD(t, "init", SecureContext::Init);
234   NODE_SET_PROTOTYPE_METHOD(t, "setKey", SecureContext::SetKey);
235   NODE_SET_PROTOTYPE_METHOD(t, "setCert", SecureContext::SetCert);
236   NODE_SET_PROTOTYPE_METHOD(t, "addCACert", SecureContext::AddCACert);
237   NODE_SET_PROTOTYPE_METHOD(t, "addCRL", SecureContext::AddCRL);
238   NODE_SET_PROTOTYPE_METHOD(t, "addRootCerts", SecureContext::AddRootCerts);
239   NODE_SET_PROTOTYPE_METHOD(t, "setCiphers", SecureContext::SetCiphers);
240   NODE_SET_PROTOTYPE_METHOD(t, "setECDHCurve", SecureContext::SetECDHCurve);
241   NODE_SET_PROTOTYPE_METHOD(t, "setOptions", SecureContext::SetOptions);
242   NODE_SET_PROTOTYPE_METHOD(t, "setSessionIdContext",
243                                SecureContext::SetSessionIdContext);
244   NODE_SET_PROTOTYPE_METHOD(t, "setSessionTimeout",
245                                SecureContext::SetSessionTimeout);
246   NODE_SET_PROTOTYPE_METHOD(t, "close", SecureContext::Close);
247   NODE_SET_PROTOTYPE_METHOD(t, "loadPKCS12", SecureContext::LoadPKCS12);
248   NODE_SET_PROTOTYPE_METHOD(t, "getTicketKeys", SecureContext::GetTicketKeys);
249   NODE_SET_PROTOTYPE_METHOD(t, "setTicketKeys", SecureContext::SetTicketKeys);
250
251   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"),
252               t->GetFunction());
253   env->set_secure_context_constructor_template(t);
254 }
255
256
257 void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
258   HandleScope handle_scope(args.GetIsolate());
259   Environment* env = Environment::GetCurrent(args.GetIsolate());
260   new SecureContext(env, args.This());
261 }
262
263
264 void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
265   HandleScope scope(args.GetIsolate());
266
267   SecureContext* sc = Unwrap<SecureContext>(args.This());
268   Environment* env = sc->env();
269
270   OPENSSL_CONST SSL_METHOD *method = SSLv23_method();
271
272   if (args.Length() == 1 && args[0]->IsString()) {
273     const String::Utf8Value sslmethod(args[0]);
274
275     if (strcmp(*sslmethod, "SSLv2_method") == 0) {
276 #ifndef OPENSSL_NO_SSL2
277       method = SSLv2_method();
278 #else
279       return env->ThrowError("SSLv2 methods disabled");
280 #endif
281     } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
282 #ifndef OPENSSL_NO_SSL2
283       method = SSLv2_server_method();
284 #else
285       return env->ThrowError("SSLv2 methods disabled");
286 #endif
287     } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
288 #ifndef OPENSSL_NO_SSL2
289       method = SSLv2_client_method();
290 #else
291       return env->ThrowError("SSLv2 methods disabled");
292 #endif
293     } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
294       method = SSLv3_method();
295     } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
296       method = SSLv3_server_method();
297     } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
298       method = SSLv3_client_method();
299     } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
300       method = SSLv23_method();
301     } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
302       method = SSLv23_server_method();
303     } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
304       method = SSLv23_client_method();
305     } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
306       method = TLSv1_method();
307     } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
308       method = TLSv1_server_method();
309     } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
310       method = TLSv1_client_method();
311     } else if (strcmp(*sslmethod, "TLSv1_1_method") == 0) {
312       method = TLSv1_1_method();
313     } else if (strcmp(*sslmethod, "TLSv1_1_server_method") == 0) {
314       method = TLSv1_1_server_method();
315     } else if (strcmp(*sslmethod, "TLSv1_1_client_method") == 0) {
316       method = TLSv1_1_client_method();
317     } else if (strcmp(*sslmethod, "TLSv1_2_method") == 0) {
318       method = TLSv1_2_method();
319     } else if (strcmp(*sslmethod, "TLSv1_2_server_method") == 0) {
320       method = TLSv1_2_server_method();
321     } else if (strcmp(*sslmethod, "TLSv1_2_client_method") == 0) {
322       method = TLSv1_2_client_method();
323     } else {
324       return env->ThrowError("Unknown method");
325     }
326   }
327
328   sc->ctx_ = SSL_CTX_new(method);
329
330   // SSL session cache configuration
331   SSL_CTX_set_session_cache_mode(sc->ctx_,
332                                  SSL_SESS_CACHE_SERVER |
333                                  SSL_SESS_CACHE_NO_INTERNAL |
334                                  SSL_SESS_CACHE_NO_AUTO_CLEAR);
335   SSL_CTX_sess_set_get_cb(sc->ctx_, SSLWrap<Connection>::GetSessionCallback);
336   SSL_CTX_sess_set_new_cb(sc->ctx_, SSLWrap<Connection>::NewSessionCallback);
337
338   sc->ca_store_ = NULL;
339 }
340
341
342 // Takes a string or buffer and loads it into a BIO.
343 // Caller responsible for BIO_free_all-ing the returned object.
344 static BIO* LoadBIO(Environment* env, Handle<Value> v) {
345   BIO* bio = NodeBIO::New();
346   if (!bio)
347     return NULL;
348
349   HandleScope scope(env->isolate());
350
351   int r = -1;
352
353   if (v->IsString()) {
354     const String::Utf8Value s(v);
355     r = BIO_write(bio, *s, s.length());
356   } else if (Buffer::HasInstance(v)) {
357     char* buffer_data = Buffer::Data(v);
358     size_t buffer_length = Buffer::Length(v);
359     r = BIO_write(bio, buffer_data, buffer_length);
360   }
361
362   if (r <= 0) {
363     BIO_free_all(bio);
364     return NULL;
365   }
366
367   return bio;
368 }
369
370
371 // Takes a string or buffer and loads it into an X509
372 // Caller responsible for X509_free-ing the returned object.
373 static X509* LoadX509(Environment* env, Handle<Value> v) {
374   HandleScope scope(env->isolate());
375
376   BIO *bio = LoadBIO(env, v);
377   if (!bio)
378     return NULL;
379
380   X509 * x509 = PEM_read_bio_X509(bio, NULL, CryptoPemCallback, NULL);
381   if (!x509) {
382     BIO_free_all(bio);
383     return NULL;
384   }
385
386   BIO_free_all(bio);
387   return x509;
388 }
389
390
391 void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
392   Environment* env = Environment::GetCurrent(args.GetIsolate());
393   HandleScope scope(env->isolate());
394
395   SecureContext* sc = Unwrap<SecureContext>(args.This());
396
397   unsigned int len = args.Length();
398   if (len != 1 && len != 2) {
399     return env->ThrowTypeError("Bad parameter");
400   }
401   if (len == 2 && !args[1]->IsString()) {
402     return env->ThrowTypeError("Bad parameter");
403   }
404
405   BIO *bio = LoadBIO(env, args[0]);
406   if (!bio)
407     return;
408
409   String::Utf8Value passphrase(args[1]);
410
411   EVP_PKEY* key = PEM_read_bio_PrivateKey(bio,
412                                           NULL,
413                                           CryptoPemCallback,
414                                           len == 1 ? NULL : *passphrase);
415
416   if (!key) {
417     BIO_free_all(bio);
418     unsigned long err = ERR_get_error();
419     if (!err) {
420       return env->ThrowError("PEM_read_bio_PrivateKey");
421     }
422     return ThrowCryptoError(env, err);
423   }
424
425   SSL_CTX_use_PrivateKey(sc->ctx_, key);
426   EVP_PKEY_free(key);
427   BIO_free_all(bio);
428 }
429
430
431 // Read a file that contains our certificate in "PEM" format,
432 // possibly followed by a sequence of CA certificates that should be
433 // sent to the peer in the Certificate message.
434 //
435 // Taken from OpenSSL - editted for style.
436 int SSL_CTX_use_certificate_chain(SSL_CTX *ctx, BIO *in) {
437   int ret = 0;
438   X509 *x = NULL;
439
440   x = PEM_read_bio_X509_AUX(in, NULL, CryptoPemCallback, NULL);
441
442   if (x == NULL) {
443     SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
444     goto end;
445   }
446
447   ret = SSL_CTX_use_certificate(ctx, x);
448
449   if (ERR_peek_error() != 0) {
450     // Key/certificate mismatch doesn't imply ret==0 ...
451     ret = 0;
452   }
453
454   if (ret) {
455     // If we could set up our certificate, now proceed to
456     // the CA certificates.
457     X509 *ca;
458     int r;
459     unsigned long err;
460
461     if (ctx->extra_certs != NULL) {
462       sk_X509_pop_free(ctx->extra_certs, X509_free);
463       ctx->extra_certs = NULL;
464     }
465
466     while ((ca = PEM_read_bio_X509(in, NULL, CryptoPemCallback, NULL))) {
467       r = SSL_CTX_add_extra_chain_cert(ctx, ca);
468
469       if (!r) {
470         X509_free(ca);
471         ret = 0;
472         goto end;
473       }
474       // Note that we must not free r if it was successfully
475       // added to the chain (while we must free the main
476       // certificate, since its reference count is increased
477       // by SSL_CTX_use_certificate).
478     }
479
480     // When the while loop ends, it's usually just EOF.
481     err = ERR_peek_last_error();
482     if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
483         ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
484       ERR_clear_error();
485     } else  {
486       // some real error
487       ret = 0;
488     }
489   }
490
491  end:
492   if (x != NULL)
493     X509_free(x);
494   return ret;
495 }
496
497
498 void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
499   Environment* env = Environment::GetCurrent(args.GetIsolate());
500   HandleScope scope(env->isolate());
501
502   SecureContext* sc = Unwrap<SecureContext>(args.This());
503
504   if (args.Length() != 1) {
505     return env->ThrowTypeError("Bad parameter");
506   }
507
508   BIO* bio = LoadBIO(env, args[0]);
509   if (!bio)
510     return;
511
512   int rv = SSL_CTX_use_certificate_chain(sc->ctx_, bio);
513
514   BIO_free_all(bio);
515
516   if (!rv) {
517     unsigned long err = ERR_get_error();
518     if (!err) {
519       return env->ThrowError("SSL_CTX_use_certificate_chain");
520     }
521     return ThrowCryptoError(env, err);
522   }
523 }
524
525
526 void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
527   bool newCAStore = false;
528   Environment* env = Environment::GetCurrent(args.GetIsolate());
529   HandleScope scope(env->isolate());
530
531   SecureContext* sc = Unwrap<SecureContext>(args.This());
532
533   if (args.Length() != 1) {
534     return env->ThrowTypeError("Bad parameter");
535   }
536
537   if (!sc->ca_store_) {
538     sc->ca_store_ = X509_STORE_new();
539     newCAStore = true;
540   }
541
542   X509* x509 = LoadX509(env, args[0]);
543   if (!x509)
544     return;
545
546   X509_STORE_add_cert(sc->ca_store_, x509);
547   SSL_CTX_add_client_CA(sc->ctx_, x509);
548
549   X509_free(x509);
550
551   if (newCAStore) {
552     SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
553   }
554 }
555
556
557 void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
558   Environment* env = Environment::GetCurrent(args.GetIsolate());
559   HandleScope scope(env->isolate());
560
561   SecureContext* sc = Unwrap<SecureContext>(args.This());
562
563   if (args.Length() != 1) {
564     return env->ThrowTypeError("Bad parameter");
565   }
566
567   ClearErrorOnReturn clear_error_on_return;
568   (void) &clear_error_on_return;  // Silence compiler warning.
569
570   BIO *bio = LoadBIO(env, args[0]);
571   if (!bio)
572     return;
573
574   X509_CRL *x509 = PEM_read_bio_X509_CRL(bio, NULL, CryptoPemCallback, NULL);
575
576   if (x509 == NULL) {
577     BIO_free_all(bio);
578     return;
579   }
580
581   X509_STORE_add_crl(sc->ca_store_, x509);
582   X509_STORE_set_flags(sc->ca_store_, X509_V_FLAG_CRL_CHECK |
583                                       X509_V_FLAG_CRL_CHECK_ALL);
584   BIO_free_all(bio);
585   X509_CRL_free(x509);
586 }
587
588
589
590 void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
591   HandleScope scope(args.GetIsolate());
592
593   SecureContext* sc = Unwrap<SecureContext>(args.This());
594
595   assert(sc->ca_store_ == NULL);
596
597   if (!root_cert_store) {
598     root_cert_store = X509_STORE_new();
599
600     for (int i = 0; root_certs[i]; i++) {
601       BIO* bp = NodeBIO::New();
602
603       if (!BIO_write(bp, root_certs[i], strlen(root_certs[i]))) {
604         BIO_free_all(bp);
605         return;
606       }
607
608       X509 *x509 = PEM_read_bio_X509(bp, NULL, CryptoPemCallback, NULL);
609
610       if (x509 == NULL) {
611         BIO_free_all(bp);
612         return;
613       }
614
615       X509_STORE_add_cert(root_cert_store, x509);
616
617       BIO_free_all(bp);
618       X509_free(x509);
619     }
620   }
621
622   sc->ca_store_ = root_cert_store;
623   SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
624 }
625
626
627 void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
628   HandleScope scope(args.GetIsolate());
629
630   SecureContext* sc = Unwrap<SecureContext>(args.This());
631
632   if (args.Length() != 1 || !args[0]->IsString()) {
633     return sc->env()->ThrowTypeError("Bad parameter");
634   }
635
636   const String::Utf8Value ciphers(args[0]);
637   SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
638 }
639
640
641 void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
642   HandleScope scope(args.GetIsolate());
643
644   SecureContext* sc = Unwrap<SecureContext>(args.This());
645   Environment* env = sc->env();
646
647   if (args.Length() != 1 || !args[0]->IsString())
648     return env->ThrowTypeError("First argument should be a string");
649
650   String::Utf8Value curve(args[0]);
651
652   int nid = OBJ_sn2nid(*curve);
653
654   if (nid == NID_undef)
655     return env->ThrowTypeError("First argument should be a valid curve name");
656
657   EC_KEY* ecdh = EC_KEY_new_by_curve_name(nid);
658
659   if (ecdh == NULL)
660     return env->ThrowTypeError("First argument should be a valid curve name");
661
662   SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_ECDH_USE);
663   SSL_CTX_set_tmp_ecdh(sc->ctx_, ecdh);
664
665   EC_KEY_free(ecdh);
666 }
667
668
669 void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
670   HandleScope scope(args.GetIsolate());
671
672   SecureContext* sc = Unwrap<SecureContext>(args.This());
673
674   if (args.Length() != 1 || !args[0]->IntegerValue()) {
675     return sc->env()->ThrowTypeError("Bad parameter");
676   }
677
678   SSL_CTX_set_options(sc->ctx_, args[0]->IntegerValue());
679 }
680
681
682 void SecureContext::SetSessionIdContext(
683     const FunctionCallbackInfo<Value>& args) {
684   HandleScope scope(args.GetIsolate());
685
686   SecureContext* sc = Unwrap<SecureContext>(args.This());
687
688   if (args.Length() != 1 || !args[0]->IsString()) {
689     return sc->env()->ThrowTypeError("Bad parameter");
690   }
691
692   const String::Utf8Value sessionIdContext(args[0]);
693   const unsigned char* sid_ctx =
694       reinterpret_cast<const unsigned char*>(*sessionIdContext);
695   unsigned int sid_ctx_len = sessionIdContext.length();
696
697   int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
698   if (r == 1)
699     return;
700
701   BIO* bio;
702   BUF_MEM* mem;
703   Local<String> message;
704
705   bio = BIO_new(BIO_s_mem());
706   if (bio == NULL) {
707     message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
708                                     "SSL_CTX_set_session_id_context error");
709   } else {
710     ERR_print_errors(bio);
711     BIO_get_mem_ptr(bio, &mem);
712     message = OneByteString(args.GetIsolate(), mem->data, mem->length);
713     BIO_free_all(bio);
714   }
715
716   args.GetIsolate()->ThrowException(Exception::TypeError(message));
717 }
718
719
720 void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
721   HandleScope scope(args.GetIsolate());
722
723   SecureContext* sc = Unwrap<SecureContext>(args.This());
724
725   if (args.Length() != 1 || !args[0]->IsInt32()) {
726     return sc->env()->ThrowTypeError("Bad parameter");
727   }
728
729   int32_t sessionTimeout = args[0]->Int32Value();
730   SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
731 }
732
733
734 void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
735   HandleScope scope(args.GetIsolate());
736   SecureContext* sc = Unwrap<SecureContext>(args.This());
737   sc->FreeCTXMem();
738 }
739
740
741 // Takes .pfx or .p12 and password in string or buffer format
742 void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
743   Environment* env = Environment::GetCurrent(args.GetIsolate());
744   HandleScope scope(env->isolate());
745
746   BIO* in = NULL;
747   PKCS12* p12 = NULL;
748   EVP_PKEY* pkey = NULL;
749   X509* cert = NULL;
750   STACK_OF(X509)* extraCerts = NULL;
751   char* pass = NULL;
752   bool ret = false;
753
754   SecureContext* sc = Unwrap<SecureContext>(args.This());
755
756   if (args.Length() < 1) {
757     return env->ThrowTypeError("Bad parameter");
758   }
759
760   in = LoadBIO(env, args[0]);
761   if (in == NULL) {
762     return env->ThrowError("Unable to load BIO");
763   }
764
765   if (args.Length() >= 2) {
766     ASSERT_IS_BUFFER(args[1]);
767
768     int passlen = Buffer::Length(args[1]);
769     if (passlen < 0) {
770       BIO_free_all(in);
771       return env->ThrowTypeError("Bad password");
772     }
773     pass = new char[passlen + 1];
774     int pass_written = DecodeWrite(env->isolate(),
775                                    pass,
776                                    passlen,
777                                    args[1],
778                                    BINARY);
779
780     assert(pass_written == passlen);
781     pass[passlen] = '\0';
782   }
783
784   if (d2i_PKCS12_bio(in, &p12) &&
785       PKCS12_parse(p12, pass, &pkey, &cert, &extraCerts) &&
786       SSL_CTX_use_certificate(sc->ctx_, cert) &&
787       SSL_CTX_use_PrivateKey(sc->ctx_, pkey)) {
788     // set extra certs
789     while (X509* x509 = sk_X509_pop(extraCerts)) {
790       if (!sc->ca_store_) {
791         sc->ca_store_ = X509_STORE_new();
792         SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
793       }
794
795       X509_STORE_add_cert(sc->ca_store_, x509);
796       SSL_CTX_add_client_CA(sc->ctx_, x509);
797       X509_free(x509);
798     }
799
800     EVP_PKEY_free(pkey);
801     X509_free(cert);
802     sk_X509_free(extraCerts);
803
804     ret = true;
805   }
806
807   PKCS12_free(p12);
808   BIO_free_all(in);
809   delete[] pass;
810
811   if (!ret) {
812     unsigned long err = ERR_get_error();
813     const char* str = ERR_reason_error_string(err);
814     return env->ThrowError(str);
815   }
816 }
817
818
819 void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
820 #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
821   HandleScope handle_scope(args.GetIsolate());
822
823   SecureContext* wrap = Unwrap<SecureContext>(args.This());
824
825   Local<Object> buff = Buffer::New(wrap->env(), 48);
826   if (SSL_CTX_get_tlsext_ticket_keys(wrap->ctx_,
827                                      Buffer::Data(buff),
828                                      Buffer::Length(buff)) != 1) {
829     return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
830   }
831
832   args.GetReturnValue().Set(buff);
833 #endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
834 }
835
836
837 void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
838 #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
839   HandleScope scope(args.GetIsolate());
840   SecureContext* wrap = Unwrap<SecureContext>(args.This());
841
842   if (args.Length() < 1 ||
843       !Buffer::HasInstance(args[0]) ||
844       Buffer::Length(args[0]) != 48) {
845     return wrap->env()->ThrowTypeError("Bad argument");
846   }
847
848   if (SSL_CTX_set_tlsext_ticket_keys(wrap->ctx_,
849                                      Buffer::Data(args[0]),
850                                      Buffer::Length(args[0])) != 1) {
851     return wrap->env()->ThrowError("Failed to fetch tls ticket keys");
852   }
853
854   args.GetReturnValue().Set(true);
855 #endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
856 }
857
858
859 template <class Base>
860 void SSLWrap<Base>::AddMethods(Environment* env, Handle<FunctionTemplate> t) {
861   HandleScope scope(env->isolate());
862
863   NODE_SET_PROTOTYPE_METHOD(t, "getPeerCertificate", GetPeerCertificate);
864   NODE_SET_PROTOTYPE_METHOD(t, "getSession", GetSession);
865   NODE_SET_PROTOTYPE_METHOD(t, "setSession", SetSession);
866   NODE_SET_PROTOTYPE_METHOD(t, "loadSession", LoadSession);
867   NODE_SET_PROTOTYPE_METHOD(t, "isSessionReused", IsSessionReused);
868   NODE_SET_PROTOTYPE_METHOD(t, "isInitFinished", IsInitFinished);
869   NODE_SET_PROTOTYPE_METHOD(t, "verifyError", VerifyError);
870   NODE_SET_PROTOTYPE_METHOD(t, "getCurrentCipher", GetCurrentCipher);
871   NODE_SET_PROTOTYPE_METHOD(t, "endParser", EndParser);
872   NODE_SET_PROTOTYPE_METHOD(t, "renegotiate", Renegotiate);
873   NODE_SET_PROTOTYPE_METHOD(t, "shutdown", Shutdown);
874   NODE_SET_PROTOTYPE_METHOD(t, "getTLSTicket", GetTLSTicket);
875   NODE_SET_PROTOTYPE_METHOD(t, "newSessionDone", NewSessionDone);
876
877 #ifdef SSL_set_max_send_fragment
878   NODE_SET_PROTOTYPE_METHOD(t, "setMaxSendFragment", SetMaxSendFragment);
879 #endif  // SSL_set_max_send_fragment
880
881 #ifdef OPENSSL_NPN_NEGOTIATED
882   NODE_SET_PROTOTYPE_METHOD(t, "getNegotiatedProtocol", GetNegotiatedProto);
883   NODE_SET_PROTOTYPE_METHOD(t, "setNPNProtocols", SetNPNProtocols);
884 #endif  // OPENSSL_NPN_NEGOTIATED
885 }
886
887
888 template <class Base>
889 void SSLWrap<Base>::InitNPN(SecureContext* sc, Base* base) {
890   if (base->is_server()) {
891 #ifdef OPENSSL_NPN_NEGOTIATED
892     // Server should advertise NPN protocols
893     SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
894                                           AdvertiseNextProtoCallback,
895                                           base);
896 #endif  // OPENSSL_NPN_NEGOTIATED
897   } else {
898 #ifdef OPENSSL_NPN_NEGOTIATED
899     // Client should select protocol from list of advertised
900     // If server supports NPN
901     SSL_CTX_set_next_proto_select_cb(sc->ctx_, SelectNextProtoCallback, base);
902 #endif  // OPENSSL_NPN_NEGOTIATED
903   }
904 }
905
906
907 template <class Base>
908 SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
909                                                unsigned char* key,
910                                                int len,
911                                                int* copy) {
912   Base* w = static_cast<Base*>(SSL_get_app_data(s));
913
914   *copy = 0;
915   SSL_SESSION* sess = w->next_sess_;
916   w->next_sess_ = NULL;
917
918   return sess;
919 }
920
921
922 template <class Base>
923 int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
924   Base* w = static_cast<Base*>(SSL_get_app_data(s));
925   Environment* env = w->ssl_env();
926   HandleScope handle_scope(env->isolate());
927   Context::Scope context_scope(env->context());
928
929   if (!w->session_callbacks_)
930     return 0;
931
932   // Check if session is small enough to be stored
933   int size = i2d_SSL_SESSION(sess, NULL);
934   if (size > SecureContext::kMaxSessionSize)
935     return 0;
936
937   // Serialize session
938   Local<Object> buff = Buffer::New(env, size);
939   unsigned char* serialized = reinterpret_cast<unsigned char*>(
940       Buffer::Data(buff));
941   memset(serialized, 0, size);
942   i2d_SSL_SESSION(sess, &serialized);
943
944   Local<Object> session = Buffer::New(env,
945                                       reinterpret_cast<char*>(sess->session_id),
946                                       sess->session_id_length);
947   Local<Value> argv[] = { session, buff };
948   w->new_session_wait_ = true;
949   w->MakeCallback(env->onnewsession_string(), ARRAY_SIZE(argv), argv);
950
951   return 0;
952 }
953
954
955 template <class Base>
956 void SSLWrap<Base>::OnClientHello(void* arg,
957                                   const ClientHelloParser::ClientHello& hello) {
958   Base* w = static_cast<Base*>(arg);
959   Environment* env = w->ssl_env();
960   HandleScope handle_scope(env->isolate());
961   Context::Scope context_scope(env->context());
962
963   Local<Object> hello_obj = Object::New(env->isolate());
964   Local<Object> buff = Buffer::New(
965       env,
966       reinterpret_cast<const char*>(hello.session_id()),
967       hello.session_size());
968   hello_obj->Set(env->session_id_string(), buff);
969   if (hello.servername() == NULL) {
970     hello_obj->Set(env->servername_string(), String::Empty(env->isolate()));
971   } else {
972     Local<String> servername = OneByteString(env->isolate(),
973                                              hello.servername(),
974                                              hello.servername_size());
975     hello_obj->Set(env->servername_string(), servername);
976   }
977   hello_obj->Set(env->tls_ticket_string(),
978                  Boolean::New(env->isolate(), hello.has_ticket()));
979
980   Local<Value> argv[] = { hello_obj };
981   w->MakeCallback(env->onclienthello_string(), ARRAY_SIZE(argv), argv);
982 }
983
984
985 // TODO(indutny): Split it into multiple smaller functions
986 template <class Base>
987 void SSLWrap<Base>::GetPeerCertificate(
988     const FunctionCallbackInfo<Value>& args) {
989   HandleScope scope(args.GetIsolate());
990
991   Base* w = Unwrap<Base>(args.This());
992   Environment* env = w->ssl_env();
993
994   ClearErrorOnReturn clear_error_on_return;
995   (void) &clear_error_on_return;  // Silence unused variable warning.
996
997   Local<Object> info = Object::New(env->isolate());
998   X509* peer_cert = SSL_get_peer_certificate(w->ssl_);
999   if (peer_cert != NULL) {
1000     BIO* bio = BIO_new(BIO_s_mem());
1001     BUF_MEM* mem;
1002     if (X509_NAME_print_ex(bio,
1003                            X509_get_subject_name(peer_cert),
1004                            0,
1005                            X509_NAME_FLAGS) > 0) {
1006       BIO_get_mem_ptr(bio, &mem);
1007       info->Set(env->subject_string(),
1008                 OneByteString(args.GetIsolate(), mem->data, mem->length));
1009     }
1010     (void) BIO_reset(bio);
1011
1012     X509_NAME* issuer_name = X509_get_issuer_name(peer_cert);
1013     if (X509_NAME_print_ex(bio, issuer_name, 0, X509_NAME_FLAGS) > 0) {
1014       BIO_get_mem_ptr(bio, &mem);
1015       info->Set(env->issuer_string(),
1016                 OneByteString(args.GetIsolate(), mem->data, mem->length));
1017     }
1018     (void) BIO_reset(bio);
1019
1020     int index = X509_get_ext_by_NID(peer_cert, NID_subject_alt_name, -1);
1021     if (index >= 0) {
1022       X509_EXTENSION* ext;
1023       int rv;
1024
1025       ext = X509_get_ext(peer_cert, index);
1026       assert(ext != NULL);
1027
1028       rv = X509V3_EXT_print(bio, ext, 0, 0);
1029       assert(rv == 1);
1030
1031       BIO_get_mem_ptr(bio, &mem);
1032       info->Set(env->subjectaltname_string(),
1033                 OneByteString(args.GetIsolate(), mem->data, mem->length));
1034
1035       (void) BIO_reset(bio);
1036     }
1037
1038     EVP_PKEY* pkey = X509_get_pubkey(peer_cert);
1039     RSA* rsa = NULL;
1040     if (pkey != NULL)
1041       rsa = EVP_PKEY_get1_RSA(pkey);
1042
1043     if (rsa != NULL) {
1044         BN_print(bio, rsa->n);
1045         BIO_get_mem_ptr(bio, &mem);
1046         info->Set(env->modulus_string(),
1047                   OneByteString(args.GetIsolate(), mem->data, mem->length));
1048         (void) BIO_reset(bio);
1049
1050         BN_print(bio, rsa->e);
1051         BIO_get_mem_ptr(bio, &mem);
1052         info->Set(env->exponent_string(),
1053                   OneByteString(args.GetIsolate(), mem->data, mem->length));
1054         (void) BIO_reset(bio);
1055     }
1056
1057     if (pkey != NULL) {
1058       EVP_PKEY_free(pkey);
1059       pkey = NULL;
1060     }
1061     if (rsa != NULL) {
1062       RSA_free(rsa);
1063       rsa = NULL;
1064     }
1065
1066     ASN1_TIME_print(bio, X509_get_notBefore(peer_cert));
1067     BIO_get_mem_ptr(bio, &mem);
1068     info->Set(env->valid_from_string(),
1069               OneByteString(args.GetIsolate(), mem->data, mem->length));
1070     (void) BIO_reset(bio);
1071
1072     ASN1_TIME_print(bio, X509_get_notAfter(peer_cert));
1073     BIO_get_mem_ptr(bio, &mem);
1074     info->Set(env->valid_to_string(),
1075               OneByteString(args.GetIsolate(), mem->data, mem->length));
1076     BIO_free_all(bio);
1077
1078     unsigned int md_size, i;
1079     unsigned char md[EVP_MAX_MD_SIZE];
1080     if (X509_digest(peer_cert, EVP_sha1(), md, &md_size)) {
1081       const char hex[] = "0123456789ABCDEF";
1082       char fingerprint[EVP_MAX_MD_SIZE * 3];
1083
1084       // TODO(indutny): Unify it with buffer's code
1085       for (i = 0; i < md_size; i++) {
1086         fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1087         fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1088         fingerprint[(3*i)+2] = ':';
1089       }
1090
1091       if (md_size > 0) {
1092         fingerprint[(3*(md_size-1))+2] = '\0';
1093       } else {
1094         fingerprint[0] = '\0';
1095       }
1096
1097       info->Set(env->fingerprint_string(),
1098                 OneByteString(args.GetIsolate(), fingerprint));
1099     }
1100
1101     STACK_OF(ASN1_OBJECT)* eku = static_cast<STACK_OF(ASN1_OBJECT)*>(
1102         X509_get_ext_d2i(peer_cert, NID_ext_key_usage, NULL, NULL));
1103     if (eku != NULL) {
1104       Local<Array> ext_key_usage = Array::New(env->isolate());
1105       char buf[256];
1106
1107       int j = 0;
1108       for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1109         if (OBJ_obj2txt(buf, sizeof(buf), sk_ASN1_OBJECT_value(eku, i), 1) >= 0)
1110           ext_key_usage->Set(j++, OneByteString(args.GetIsolate(), buf));
1111       }
1112
1113       sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1114       info->Set(env->ext_key_usage_string(), ext_key_usage);
1115     }
1116
1117     if (ASN1_INTEGER* serial_number = X509_get_serialNumber(peer_cert)) {
1118       if (BIGNUM* bn = ASN1_INTEGER_to_BN(serial_number, NULL)) {
1119         if (char* buf = BN_bn2hex(bn)) {
1120           info->Set(env->serial_number_string(),
1121                     OneByteString(args.GetIsolate(), buf));
1122           OPENSSL_free(buf);
1123         }
1124         BN_free(bn);
1125       }
1126     }
1127
1128     X509_free(peer_cert);
1129   }
1130
1131   args.GetReturnValue().Set(info);
1132 }
1133
1134
1135 template <class Base>
1136 void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1137   Environment* env = Environment::GetCurrent(args.GetIsolate());
1138   HandleScope scope(env->isolate());
1139
1140   Base* w = Unwrap<Base>(args.This());
1141
1142   SSL_SESSION* sess = SSL_get_session(w->ssl_);
1143   if (sess == NULL)
1144     return;
1145
1146   int slen = i2d_SSL_SESSION(sess, NULL);
1147   assert(slen > 0);
1148
1149   unsigned char* sbuf = new unsigned char[slen];
1150   unsigned char* p = sbuf;
1151   i2d_SSL_SESSION(sess, &p);
1152   args.GetReturnValue().Set(Encode(env->isolate(), sbuf, slen, BUFFER));
1153   delete[] sbuf;
1154 }
1155
1156
1157 template <class Base>
1158 void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1159   Environment* env = Environment::GetCurrent(args.GetIsolate());
1160   HandleScope scope(env->isolate());
1161
1162   Base* w = Unwrap<Base>(args.This());
1163
1164   if (args.Length() < 1 ||
1165       (!args[0]->IsString() && !Buffer::HasInstance(args[0]))) {
1166     return env->ThrowTypeError("Bad argument");
1167   }
1168
1169   ASSERT_IS_BUFFER(args[0]);
1170   ssize_t slen = Buffer::Length(args[0]);
1171
1172   if (slen < 0)
1173     return env->ThrowTypeError("Bad argument");
1174
1175   char* sbuf = new char[slen];
1176
1177   ssize_t wlen = DecodeWrite(env->isolate(), sbuf, slen, args[0], BINARY);
1178   assert(wlen == slen);
1179
1180   const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1181   SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, wlen);
1182
1183   delete[] sbuf;
1184
1185   if (sess == NULL)
1186     return;
1187
1188   int r = SSL_set_session(w->ssl_, sess);
1189   SSL_SESSION_free(sess);
1190
1191   if (!r)
1192     return env->ThrowError("SSL_set_session error");
1193 }
1194
1195
1196 template <class Base>
1197 void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1198   HandleScope scope(args.GetIsolate());
1199
1200   Base* w = Unwrap<Base>(args.This());
1201   Environment* env = w->ssl_env();
1202
1203   if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1204     ssize_t slen = Buffer::Length(args[0]);
1205     char* sbuf = Buffer::Data(args[0]);
1206
1207     const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1208     SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, slen);
1209
1210     // Setup next session and move hello to the BIO buffer
1211     if (w->next_sess_ != NULL)
1212       SSL_SESSION_free(w->next_sess_);
1213     w->next_sess_ = sess;
1214
1215     Local<Object> info = Object::New(env->isolate());
1216 #ifndef OPENSSL_NO_TLSEXT
1217     if (sess->tlsext_hostname == NULL) {
1218       info->Set(env->servername_string(), False(args.GetIsolate()));
1219     } else {
1220       info->Set(env->servername_string(),
1221                 OneByteString(args.GetIsolate(), sess->tlsext_hostname));
1222     }
1223 #endif
1224     args.GetReturnValue().Set(info);
1225   }
1226 }
1227
1228
1229 template <class Base>
1230 void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1231   HandleScope scope(args.GetIsolate());
1232   Base* w = Unwrap<Base>(args.This());
1233   bool yes = SSL_session_reused(w->ssl_);
1234   args.GetReturnValue().Set(yes);
1235 }
1236
1237
1238 template <class Base>
1239 void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
1240   HandleScope scope(args.GetIsolate());
1241   Base* w = Unwrap<Base>(args.This());
1242   w->hello_parser_.End();
1243 }
1244
1245
1246 template <class Base>
1247 void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1248   HandleScope scope(args.GetIsolate());
1249
1250   Base* w = Unwrap<Base>(args.This());
1251
1252   ClearErrorOnReturn clear_error_on_return;
1253   (void) &clear_error_on_return;  // Silence unused variable warning.
1254
1255   bool yes = SSL_renegotiate(w->ssl_) == 1;
1256   args.GetReturnValue().Set(yes);
1257 }
1258
1259
1260 template <class Base>
1261 void SSLWrap<Base>::Shutdown(const FunctionCallbackInfo<Value>& args) {
1262   HandleScope scope(args.GetIsolate());
1263
1264   Base* w = Unwrap<Base>(args.This());
1265
1266   int rv = SSL_shutdown(w->ssl_);
1267   args.GetReturnValue().Set(rv);
1268 }
1269
1270
1271 template <class Base>
1272 void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1273   HandleScope scope(args.GetIsolate());
1274
1275   Base* w = Unwrap<Base>(args.This());
1276   Environment* env = w->ssl_env();
1277
1278   SSL_SESSION* sess = SSL_get_session(w->ssl_);
1279   if (sess == NULL || sess->tlsext_tick == NULL)
1280     return;
1281
1282   Local<Object> buf = Buffer::New(env,
1283                                   reinterpret_cast<char*>(sess->tlsext_tick),
1284                                   sess->tlsext_ticklen);
1285
1286   args.GetReturnValue().Set(buf);
1287 }
1288
1289
1290 template <class Base>
1291 void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1292   HandleScope scope(args.GetIsolate());
1293
1294   Base* w = Unwrap<Base>(args.This());
1295   w->new_session_wait_ = false;
1296   w->NewSessionDoneCb();
1297 }
1298
1299
1300 #ifdef SSL_set_max_send_fragment
1301 template <class Base>
1302 void SSLWrap<Base>::SetMaxSendFragment(
1303     const v8::FunctionCallbackInfo<v8::Value>& args) {
1304   HandleScope scope(args.GetIsolate());
1305   CHECK(args.Length() >= 1 && args[0]->IsNumber());
1306
1307   Base* w = Unwrap<Base>(args.This());
1308
1309   int rv = SSL_set_max_send_fragment(w->ssl_, args[0]->Int32Value());
1310   args.GetReturnValue().Set(rv);
1311 }
1312 #endif  // SSL_set_max_send_fragment
1313
1314
1315 template <class Base>
1316 void SSLWrap<Base>::IsInitFinished(const FunctionCallbackInfo<Value>& args) {
1317   HandleScope scope(args.GetIsolate());
1318   Base* w = Unwrap<Base>(args.This());
1319   bool yes = SSL_is_init_finished(w->ssl_);
1320   args.GetReturnValue().Set(yes);
1321 }
1322
1323
1324 template <class Base>
1325 void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
1326   HandleScope scope(args.GetIsolate());
1327
1328   Base* w = Unwrap<Base>(args.This());
1329
1330   // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
1331   // peer certificate is questionable but it's compatible with what was
1332   // here before.
1333   long x509_verify_error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
1334   if (X509* peer_cert = SSL_get_peer_certificate(w->ssl_)) {
1335     X509_free(peer_cert);
1336     x509_verify_error = SSL_get_verify_result(w->ssl_);
1337   }
1338
1339   if (x509_verify_error == X509_V_OK)
1340     return args.GetReturnValue().SetNull();
1341
1342   // XXX(bnoordhuis) X509_verify_cert_error_string() is not actually thread-safe
1343   // in the presence of invalid error codes.  Probably academical but something
1344   // to keep in mind if/when node ever grows multi-isolate capabilities.
1345   const char* reason = X509_verify_cert_error_string(x509_verify_error);
1346   const char* code = reason;
1347 #define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
1348   switch (x509_verify_error) {
1349     CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
1350     CASE_X509_ERR(UNABLE_TO_GET_CRL)
1351     CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
1352     CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
1353     CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
1354     CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
1355     CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
1356     CASE_X509_ERR(CERT_NOT_YET_VALID)
1357     CASE_X509_ERR(CERT_HAS_EXPIRED)
1358     CASE_X509_ERR(CRL_NOT_YET_VALID)
1359     CASE_X509_ERR(CRL_HAS_EXPIRED)
1360     CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
1361     CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
1362     CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
1363     CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
1364     CASE_X509_ERR(OUT_OF_MEM)
1365     CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
1366     CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
1367     CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
1368     CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
1369     CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
1370     CASE_X509_ERR(CERT_REVOKED)
1371     CASE_X509_ERR(INVALID_CA)
1372     CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
1373     CASE_X509_ERR(INVALID_PURPOSE)
1374     CASE_X509_ERR(CERT_UNTRUSTED)
1375     CASE_X509_ERR(CERT_REJECTED)
1376   }
1377 #undef CASE_X509_ERR
1378
1379   Isolate* isolate = args.GetIsolate();
1380   Local<String> reason_string = OneByteString(isolate, reason);
1381   Local<Value> exception_value = Exception::Error(reason_string);
1382   Local<Object> exception_object = exception_value->ToObject();
1383   exception_object->Set(FIXED_ONE_BYTE_STRING(isolate, "code"),
1384                         OneByteString(isolate, code));
1385   args.GetReturnValue().Set(exception_object);
1386 }
1387
1388
1389 template <class Base>
1390 void SSLWrap<Base>::GetCurrentCipher(const FunctionCallbackInfo<Value>& args) {
1391   HandleScope scope(args.GetIsolate());
1392
1393   Base* w = Unwrap<Base>(args.This());
1394   Environment* env = w->ssl_env();
1395
1396   OPENSSL_CONST SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_);
1397   if (c == NULL)
1398     return;
1399
1400   Local<Object> info = Object::New(env->isolate());
1401   const char* cipher_name = SSL_CIPHER_get_name(c);
1402   info->Set(env->name_string(), OneByteString(args.GetIsolate(), cipher_name));
1403   const char* cipher_version = SSL_CIPHER_get_version(c);
1404   info->Set(env->version_string(),
1405             OneByteString(args.GetIsolate(), cipher_version));
1406   args.GetReturnValue().Set(info);
1407 }
1408
1409
1410 #ifdef OPENSSL_NPN_NEGOTIATED
1411 template <class Base>
1412 int SSLWrap<Base>::AdvertiseNextProtoCallback(SSL* s,
1413                                               const unsigned char** data,
1414                                               unsigned int* len,
1415                                               void* arg) {
1416   Base* w = static_cast<Base*>(arg);
1417   Environment* env = w->env();
1418   HandleScope handle_scope(env->isolate());
1419   Context::Scope context_scope(env->context());
1420
1421   if (w->npn_protos_.IsEmpty()) {
1422     // No initialization - no NPN protocols
1423     *data = reinterpret_cast<const unsigned char*>("");
1424     *len = 0;
1425   } else {
1426     Local<Object> obj = PersistentToLocal(env->isolate(), w->npn_protos_);
1427     *data = reinterpret_cast<const unsigned char*>(Buffer::Data(obj));
1428     *len = Buffer::Length(obj);
1429   }
1430
1431   return SSL_TLSEXT_ERR_OK;
1432 }
1433
1434
1435 template <class Base>
1436 int SSLWrap<Base>::SelectNextProtoCallback(SSL* s,
1437                                            unsigned char** out,
1438                                            unsigned char* outlen,
1439                                            const unsigned char* in,
1440                                            unsigned int inlen,
1441                                            void* arg) {
1442   Base* w = static_cast<Base*>(arg);
1443   Environment* env = w->env();
1444   HandleScope handle_scope(env->isolate());
1445   Context::Scope context_scope(env->context());
1446
1447   // Release old protocol handler if present
1448   w->selected_npn_proto_.Reset();
1449
1450   if (w->npn_protos_.IsEmpty()) {
1451     // We should at least select one protocol
1452     // If server is using NPN
1453     *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
1454     *outlen = 8;
1455
1456     // set status: unsupported
1457     w->selected_npn_proto_.Reset(env->isolate(), False(env->isolate()));
1458
1459     return SSL_TLSEXT_ERR_OK;
1460   }
1461
1462   Local<Object> obj = PersistentToLocal(env->isolate(), w->npn_protos_);
1463   const unsigned char* npn_protos =
1464       reinterpret_cast<const unsigned char*>(Buffer::Data(obj));
1465   size_t len = Buffer::Length(obj);
1466
1467   int status = SSL_select_next_proto(out, outlen, in, inlen, npn_protos, len);
1468   Handle<Value> result;
1469   switch (status) {
1470     case OPENSSL_NPN_UNSUPPORTED:
1471       result = Null(env->isolate());
1472       break;
1473     case OPENSSL_NPN_NEGOTIATED:
1474       result = OneByteString(env->isolate(), *out, *outlen);
1475       break;
1476     case OPENSSL_NPN_NO_OVERLAP:
1477       result = False(env->isolate());
1478       break;
1479     default:
1480       break;
1481   }
1482
1483   if (!result.IsEmpty())
1484     w->selected_npn_proto_.Reset(env->isolate(), result);
1485
1486   return SSL_TLSEXT_ERR_OK;
1487 }
1488
1489
1490 template <class Base>
1491 void SSLWrap<Base>::GetNegotiatedProto(
1492     const FunctionCallbackInfo<Value>& args) {
1493   HandleScope scope(args.GetIsolate());
1494
1495   Base* w = Unwrap<Base>(args.This());
1496
1497   if (w->is_client()) {
1498     if (w->selected_npn_proto_.IsEmpty() == false) {
1499       args.GetReturnValue().Set(w->selected_npn_proto_);
1500     }
1501     return;
1502   }
1503
1504   const unsigned char* npn_proto;
1505   unsigned int npn_proto_len;
1506
1507   SSL_get0_next_proto_negotiated(w->ssl_, &npn_proto, &npn_proto_len);
1508
1509   if (!npn_proto)
1510     return args.GetReturnValue().Set(false);
1511
1512   args.GetReturnValue().Set(
1513       OneByteString(args.GetIsolate(), npn_proto, npn_proto_len));
1514 }
1515
1516
1517 template <class Base>
1518 void SSLWrap<Base>::SetNPNProtocols(const FunctionCallbackInfo<Value>& args) {
1519   HandleScope scope(args.GetIsolate());
1520
1521   Base* w = Unwrap<Base>(args.This());
1522
1523   if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1524     return w->env()->ThrowTypeError("Must give a Buffer as first argument");
1525
1526   w->npn_protos_.Reset(args.GetIsolate(), args[0].As<Object>());
1527 }
1528 #endif  // OPENSSL_NPN_NEGOTIATED
1529
1530
1531 void Connection::OnClientHelloParseEnd(void* arg) {
1532   Connection* conn = static_cast<Connection*>(arg);
1533
1534   // Write all accumulated data
1535   int r = BIO_write(conn->bio_read_,
1536                     reinterpret_cast<char*>(conn->hello_data_),
1537                     conn->hello_offset_);
1538   conn->HandleBIOError(conn->bio_read_, "BIO_write", r);
1539   conn->SetShutdownFlags();
1540 }
1541
1542
1543 #ifdef SSL_PRINT_DEBUG
1544 # define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
1545 #else
1546 # define DEBUG_PRINT(...)
1547 #endif
1548
1549
1550 int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
1551   if (rv >= 0)
1552     return rv;
1553
1554   int retry = BIO_should_retry(bio);
1555   (void) retry;  // unused if !defined(SSL_PRINT_DEBUG)
1556
1557   if (BIO_should_write(bio)) {
1558     DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n",
1559                 ssl_,
1560                 func,
1561                 retry);
1562     return 0;
1563
1564   } else if (BIO_should_read(bio)) {
1565     DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
1566     return 0;
1567
1568   } else {
1569     char ssl_error_buf[512];
1570     ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
1571
1572     HandleScope scope(ssl_env()->isolate());
1573     Local<Value> exception =
1574         Exception::Error(OneByteString(ssl_env()->isolate(), ssl_error_buf));
1575     object()->Set(ssl_env()->error_string(), exception);
1576
1577     DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n",
1578                 ssl_,
1579                 func,
1580                 rv,
1581                 ssl_error_buf);
1582
1583     return rv;
1584   }
1585
1586   return 0;
1587 }
1588
1589
1590 int Connection::HandleSSLError(const char* func,
1591                                int rv,
1592                                ZeroStatus zs,
1593                                SyscallStatus ss) {
1594   ClearErrorOnReturn clear_error_on_return;
1595   (void) &clear_error_on_return;  // Silence unused variable warning.
1596
1597   if (rv > 0)
1598     return rv;
1599   if (rv == 0 && zs == kZeroIsNotAnError)
1600     return rv;
1601
1602   int err = SSL_get_error(ssl_, rv);
1603
1604   if (err == SSL_ERROR_NONE) {
1605     return 0;
1606
1607   } else if (err == SSL_ERROR_WANT_WRITE) {
1608     DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
1609     return 0;
1610
1611   } else if (err == SSL_ERROR_WANT_READ) {
1612     DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
1613     return 0;
1614
1615   } else if (err == SSL_ERROR_ZERO_RETURN) {
1616     HandleScope scope(ssl_env()->isolate());
1617
1618     Local<Value> exception =
1619         Exception::Error(ssl_env()->zero_return_string());
1620     object()->Set(ssl_env()->error_string(), exception);
1621     return rv;
1622
1623   } else if (err == SSL_ERROR_SYSCALL && ss == kIgnoreSyscall) {
1624     return 0;
1625
1626   } else {
1627     HandleScope scope(ssl_env()->isolate());
1628     BUF_MEM* mem;
1629     BIO *bio;
1630
1631     assert(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
1632
1633     // XXX We need to drain the error queue for this thread or else OpenSSL
1634     // has the possibility of blocking connections? This problem is not well
1635     // understood. And we should be somehow propagating these errors up
1636     // into JavaScript. There is no test which demonstrates this problem.
1637     // https://github.com/joyent/node/issues/1719
1638     bio = BIO_new(BIO_s_mem());
1639     if (bio != NULL) {
1640       ERR_print_errors(bio);
1641       BIO_get_mem_ptr(bio, &mem);
1642       Local<Value> exception = Exception::Error(
1643           OneByteString(ssl_env()->isolate(),
1644             mem->data,
1645             mem->length));
1646       object()->Set(ssl_env()->error_string(), exception);
1647       BIO_free_all(bio);
1648     }
1649
1650     return rv;
1651   }
1652
1653   return 0;
1654 }
1655
1656
1657 void Connection::ClearError() {
1658 #ifndef NDEBUG
1659   HandleScope scope(ssl_env()->isolate());
1660
1661   // We should clear the error in JS-land
1662   Local<String> error_key = ssl_env()->error_string();
1663   Local<Value> error = object()->Get(error_key);
1664   assert(error->BooleanValue() == false);
1665 #endif  // NDEBUG
1666 }
1667
1668
1669 void Connection::SetShutdownFlags() {
1670   HandleScope scope(ssl_env()->isolate());
1671
1672   int flags = SSL_get_shutdown(ssl_);
1673
1674   if (flags & SSL_SENT_SHUTDOWN) {
1675     Local<String> sent_shutdown_key = ssl_env()->sent_shutdown_string();
1676     object()->Set(sent_shutdown_key, True(ssl_env()->isolate()));
1677   }
1678
1679   if (flags & SSL_RECEIVED_SHUTDOWN) {
1680     Local<String> received_shutdown_key = ssl_env()->received_shutdown_string();
1681     object()->Set(received_shutdown_key, True(ssl_env()->isolate()));
1682   }
1683 }
1684
1685
1686 void Connection::NewSessionDoneCb() {
1687   HandleScope scope(env()->isolate());
1688
1689   MakeCallback(env()->onnewsessiondone_string(), 0, NULL);
1690 }
1691
1692
1693 void Connection::Initialize(Environment* env, Handle<Object> target) {
1694   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(),
1695                                                     Connection::New);
1696   t->InstanceTemplate()->SetInternalFieldCount(1);
1697   t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"));
1698
1699   NODE_SET_PROTOTYPE_METHOD(t, "encIn", Connection::EncIn);
1700   NODE_SET_PROTOTYPE_METHOD(t, "clearOut", Connection::ClearOut);
1701   NODE_SET_PROTOTYPE_METHOD(t, "clearIn", Connection::ClearIn);
1702   NODE_SET_PROTOTYPE_METHOD(t, "encOut", Connection::EncOut);
1703   NODE_SET_PROTOTYPE_METHOD(t, "clearPending", Connection::ClearPending);
1704   NODE_SET_PROTOTYPE_METHOD(t, "encPending", Connection::EncPending);
1705   NODE_SET_PROTOTYPE_METHOD(t, "start", Connection::Start);
1706   NODE_SET_PROTOTYPE_METHOD(t, "close", Connection::Close);
1707
1708   SSLWrap<Connection>::AddMethods(env, t);
1709
1710 #ifdef OPENSSL_NPN_NEGOTIATED
1711   NODE_SET_PROTOTYPE_METHOD(t,
1712                             "getNegotiatedProtocol",
1713                             Connection::GetNegotiatedProto);
1714   NODE_SET_PROTOTYPE_METHOD(t,
1715                             "setNPNProtocols",
1716                             Connection::SetNPNProtocols);
1717 #endif
1718
1719
1720 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1721   NODE_SET_PROTOTYPE_METHOD(t, "getServername", Connection::GetServername);
1722   NODE_SET_PROTOTYPE_METHOD(t, "setSNICallback",  Connection::SetSNICallback);
1723 #endif
1724
1725   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Connection"),
1726               t->GetFunction());
1727 }
1728
1729
1730 int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
1731   // Quoting SSL_set_verify(3ssl):
1732   //
1733   //   The VerifyCallback function is used to control the behaviour when
1734   //   the SSL_VERIFY_PEER flag is set. It must be supplied by the
1735   //   application and receives two arguments: preverify_ok indicates,
1736   //   whether the verification of the certificate in question was passed
1737   //   (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to
1738   //   the complete context used for the certificate chain verification.
1739   //
1740   //   The certificate chain is checked starting with the deepest nesting
1741   //   level (the root CA certificate) and worked upward to the peer's
1742   //   certificate.  At each level signatures and issuer attributes are
1743   //   checked.  Whenever a verification error is found, the error number is
1744   //   stored in x509_ctx and VerifyCallback is called with preverify_ok=0.
1745   //   By applying X509_CTX_store_* functions VerifyCallback can locate the
1746   //   certificate in question and perform additional steps (see EXAMPLES).
1747   //   If no error is found for a certificate, VerifyCallback is called
1748   //   with preverify_ok=1 before advancing to the next level.
1749   //
1750   //   The return value of VerifyCallback controls the strategy of the
1751   //   further verification process. If VerifyCallback returns 0, the
1752   //   verification process is immediately stopped with "verification
1753   //   failed" state. If SSL_VERIFY_PEER is set, a verification failure
1754   //   alert is sent to the peer and the TLS/SSL handshake is terminated. If
1755   //   VerifyCallback returns 1, the verification process is continued. If
1756   //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
1757   //   terminated with respect to verification failures and the connection
1758   //   will be established. The calling process can however retrieve the
1759   //   error code of the last verification error using
1760   //   SSL_get_verify_result(3) or by maintaining its own error storage
1761   //   managed by VerifyCallback.
1762   //
1763   //   If no VerifyCallback is specified, the default callback will be
1764   //   used.  Its return value is identical to preverify_ok, so that any
1765   //   verification failure will lead to a termination of the TLS/SSL
1766   //   handshake with an alert message, if SSL_VERIFY_PEER is set.
1767   //
1768   // Since we cannot perform I/O quickly enough in this callback, we ignore
1769   // all preverify_ok errors and let the handshake continue. It is
1770   // imparative that the user use Connection::VerifyError after the
1771   // 'secure' callback has been made.
1772   return 1;
1773 }
1774
1775
1776 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1777 int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
1778   Connection* conn = static_cast<Connection*>(SSL_get_app_data(s));
1779   Environment* env = conn->env();
1780   HandleScope scope(env->isolate());
1781
1782   const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1783
1784   if (servername) {
1785     conn->servername_.Reset(env->isolate(),
1786                             OneByteString(env->isolate(), servername));
1787
1788     // Call the SNI callback and use its return value as context
1789     if (!conn->sniObject_.IsEmpty()) {
1790       conn->sniContext_.Reset();
1791
1792       Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
1793       Local<Value> ret = conn->MakeCallback(env->onselect_string(), 1, &arg);
1794
1795       // If ret is SecureContext
1796       Local<FunctionTemplate> secure_context_constructor_template =
1797           env->secure_context_constructor_template();
1798       if (secure_context_constructor_template->HasInstance(ret)) {
1799         conn->sniContext_.Reset(env->isolate(), ret);
1800         SecureContext* sc = Unwrap<SecureContext>(ret.As<Object>());
1801         InitNPN(sc, conn);
1802         SSL_set_SSL_CTX(s, sc->ctx_);
1803       } else {
1804         return SSL_TLSEXT_ERR_NOACK;
1805       }
1806     }
1807   }
1808
1809   return SSL_TLSEXT_ERR_OK;
1810 }
1811 #endif
1812
1813 void Connection::New(const FunctionCallbackInfo<Value>& args) {
1814   Environment* env = Environment::GetCurrent(args.GetIsolate());
1815   HandleScope scope(env->isolate());
1816
1817   if (args.Length() < 1 || !args[0]->IsObject()) {
1818     env->ThrowError("First argument must be a crypto module Credentials");
1819     return;
1820   }
1821
1822   SecureContext* sc = Unwrap<SecureContext>(args[0]->ToObject());
1823
1824   bool is_server = args[1]->BooleanValue();
1825
1826   SSLWrap<Connection>::Kind kind =
1827       is_server ? SSLWrap<Connection>::kServer : SSLWrap<Connection>::kClient;
1828   Connection* conn = new Connection(env, args.This(), sc, kind);
1829   conn->ssl_ = SSL_new(sc->ctx_);
1830   conn->bio_read_ = NodeBIO::New();
1831   conn->bio_write_ = NodeBIO::New();
1832
1833   SSL_set_app_data(conn->ssl_, conn);
1834
1835   if (is_server)
1836     SSL_set_info_callback(conn->ssl_, SSLInfoCallback);
1837
1838   InitNPN(sc, conn);
1839
1840 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1841   if (is_server) {
1842     SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
1843   } else if (args[2]->IsString()) {
1844     const String::Utf8Value servername(args[2]);
1845     SSL_set_tlsext_host_name(conn->ssl_, *servername);
1846   }
1847 #endif
1848
1849   SSL_set_bio(conn->ssl_, conn->bio_read_, conn->bio_write_);
1850
1851 #ifdef SSL_MODE_RELEASE_BUFFERS
1852   long mode = SSL_get_mode(conn->ssl_);
1853   SSL_set_mode(conn->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
1854 #endif
1855
1856
1857   int verify_mode;
1858   if (is_server) {
1859     bool request_cert = args[2]->BooleanValue();
1860     if (!request_cert) {
1861       // Note reject_unauthorized ignored.
1862       verify_mode = SSL_VERIFY_NONE;
1863     } else {
1864       bool reject_unauthorized = args[3]->BooleanValue();
1865       verify_mode = SSL_VERIFY_PEER;
1866       if (reject_unauthorized)
1867         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1868     }
1869   } else {
1870     // Note request_cert and reject_unauthorized are ignored for clients.
1871     verify_mode = SSL_VERIFY_NONE;
1872   }
1873
1874
1875   // Always allow a connection. We'll reject in javascript.
1876   SSL_set_verify(conn->ssl_, verify_mode, VerifyCallback);
1877
1878   if (is_server) {
1879     SSL_set_accept_state(conn->ssl_);
1880   } else {
1881     SSL_set_connect_state(conn->ssl_);
1882   }
1883 }
1884
1885
1886 void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
1887   if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
1888     return;
1889
1890   // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
1891   // a non-const SSL* in OpenSSL <= 0.9.7e.
1892   SSL* ssl = const_cast<SSL*>(ssl_);
1893   Connection* conn = static_cast<Connection*>(SSL_get_app_data(ssl));
1894   Environment* env = conn->env();
1895   HandleScope handle_scope(env->isolate());
1896   Context::Scope context_scope(env->context());
1897
1898   if (where & SSL_CB_HANDSHAKE_START) {
1899     conn->MakeCallback(env->onhandshakestart_string(), 0, NULL);
1900   }
1901
1902   if (where & SSL_CB_HANDSHAKE_DONE) {
1903     conn->MakeCallback(env->onhandshakedone_string(), 0, NULL);
1904   }
1905 }
1906
1907
1908 void Connection::EncIn(const FunctionCallbackInfo<Value>& args) {
1909   HandleScope scope(args.GetIsolate());
1910
1911   Connection* conn = Unwrap<Connection>(args.This());
1912   Environment* env = conn->env();
1913
1914   if (args.Length() < 3) {
1915     return env->ThrowTypeError("Takes 3 parameters");
1916   }
1917
1918   if (!Buffer::HasInstance(args[0])) {
1919     return env->ThrowTypeError("Second argument should be a buffer");
1920   }
1921
1922   char* buffer_data = Buffer::Data(args[0]);
1923   size_t buffer_length = Buffer::Length(args[0]);
1924
1925   size_t off = args[1]->Int32Value();
1926   size_t len = args[2]->Int32Value();
1927
1928   if (!Buffer::IsWithinBounds(off, len, buffer_length))
1929     return env->ThrowError("off + len > buffer.length");
1930
1931   int bytes_written;
1932   char* data = buffer_data + off;
1933
1934   if (conn->is_server() && !conn->hello_parser_.IsEnded()) {
1935     // Just accumulate data, everything will be pushed to BIO later
1936     if (conn->hello_parser_.IsPaused()) {
1937       bytes_written = 0;
1938     } else {
1939       // Copy incoming data to the internal buffer
1940       // (which has a size of the biggest possible TLS frame)
1941       size_t available = sizeof(conn->hello_data_) - conn->hello_offset_;
1942       size_t copied = len < available ? len : available;
1943       memcpy(conn->hello_data_ + conn->hello_offset_, data, copied);
1944       conn->hello_offset_ += copied;
1945
1946       conn->hello_parser_.Parse(conn->hello_data_, conn->hello_offset_);
1947       bytes_written = copied;
1948     }
1949   } else {
1950     bytes_written = BIO_write(conn->bio_read_, data, len);
1951     conn->HandleBIOError(conn->bio_read_, "BIO_write", bytes_written);
1952     conn->SetShutdownFlags();
1953   }
1954
1955   args.GetReturnValue().Set(bytes_written);
1956 }
1957
1958
1959 void Connection::ClearOut(const FunctionCallbackInfo<Value>& args) {
1960   HandleScope scope(args.GetIsolate());
1961
1962   Connection* conn = Unwrap<Connection>(args.This());
1963   Environment* env = conn->env();
1964
1965   if (args.Length() < 3) {
1966     return env->ThrowTypeError("Takes 3 parameters");
1967   }
1968
1969   if (!Buffer::HasInstance(args[0])) {
1970     return env->ThrowTypeError("Second argument should be a buffer");
1971   }
1972
1973   char* buffer_data = Buffer::Data(args[0]);
1974   size_t buffer_length = Buffer::Length(args[0]);
1975
1976   size_t off = args[1]->Int32Value();
1977   size_t len = args[2]->Int32Value();
1978
1979   if (!Buffer::IsWithinBounds(off, len, buffer_length))
1980     return env->ThrowError("off + len > buffer.length");
1981
1982   if (!SSL_is_init_finished(conn->ssl_)) {
1983     int rv;
1984
1985     if (conn->is_server()) {
1986       rv = SSL_accept(conn->ssl_);
1987       conn->HandleSSLError("SSL_accept:ClearOut",
1988                            rv,
1989                            kZeroIsAnError,
1990                            kSyscallError);
1991     } else {
1992       rv = SSL_connect(conn->ssl_);
1993       conn->HandleSSLError("SSL_connect:ClearOut",
1994                            rv,
1995                            kZeroIsAnError,
1996                            kSyscallError);
1997     }
1998
1999     if (rv < 0) {
2000       return args.GetReturnValue().Set(rv);
2001     }
2002   }
2003
2004   int bytes_read = SSL_read(conn->ssl_, buffer_data + off, len);
2005   conn->HandleSSLError("SSL_read:ClearOut",
2006                        bytes_read,
2007                        kZeroIsNotAnError,
2008                        kSyscallError);
2009   conn->SetShutdownFlags();
2010
2011   args.GetReturnValue().Set(bytes_read);
2012 }
2013
2014
2015 void Connection::ClearPending(const FunctionCallbackInfo<Value>& args) {
2016   HandleScope scope(args.GetIsolate());
2017   Connection* conn = Unwrap<Connection>(args.This());
2018   int bytes_pending = BIO_pending(conn->bio_read_);
2019   args.GetReturnValue().Set(bytes_pending);
2020 }
2021
2022
2023 void Connection::EncPending(const FunctionCallbackInfo<Value>& args) {
2024   HandleScope scope(args.GetIsolate());
2025   Connection* conn = Unwrap<Connection>(args.This());
2026   int bytes_pending = BIO_pending(conn->bio_write_);
2027   args.GetReturnValue().Set(bytes_pending);
2028 }
2029
2030
2031 void Connection::EncOut(const FunctionCallbackInfo<Value>& args) {
2032   HandleScope scope(args.GetIsolate());
2033
2034   Connection* conn = Unwrap<Connection>(args.This());
2035   Environment* env = conn->env();
2036
2037   if (args.Length() < 3) {
2038     return env->ThrowTypeError("Takes 3 parameters");
2039   }
2040
2041   if (!Buffer::HasInstance(args[0])) {
2042     return env->ThrowTypeError("Second argument should be a buffer");
2043   }
2044
2045   char* buffer_data = Buffer::Data(args[0]);
2046   size_t buffer_length = Buffer::Length(args[0]);
2047
2048   size_t off = args[1]->Int32Value();
2049   size_t len = args[2]->Int32Value();
2050
2051   if (!Buffer::IsWithinBounds(off, len, buffer_length))
2052     return env->ThrowError("off + len > buffer.length");
2053
2054   int bytes_read = BIO_read(conn->bio_write_, buffer_data + off, len);
2055
2056   conn->HandleBIOError(conn->bio_write_, "BIO_read:EncOut", bytes_read);
2057   conn->SetShutdownFlags();
2058
2059   args.GetReturnValue().Set(bytes_read);
2060 }
2061
2062
2063 void Connection::ClearIn(const FunctionCallbackInfo<Value>& args) {
2064   HandleScope scope(args.GetIsolate());
2065
2066   Connection* conn = Unwrap<Connection>(args.This());
2067   Environment* env = conn->env();
2068
2069   if (args.Length() < 3) {
2070     return env->ThrowTypeError("Takes 3 parameters");
2071   }
2072
2073   if (!Buffer::HasInstance(args[0])) {
2074     return env->ThrowTypeError("Second argument should be a buffer");
2075   }
2076
2077   char* buffer_data = Buffer::Data(args[0]);
2078   size_t buffer_length = Buffer::Length(args[0]);
2079
2080   size_t off = args[1]->Int32Value();
2081   size_t len = args[2]->Int32Value();
2082
2083   if (!Buffer::IsWithinBounds(off, len, buffer_length))
2084     return env->ThrowError("off + len > buffer.length");
2085
2086   if (!SSL_is_init_finished(conn->ssl_)) {
2087     int rv;
2088     if (conn->is_server()) {
2089       rv = SSL_accept(conn->ssl_);
2090       conn->HandleSSLError("SSL_accept:ClearIn",
2091                            rv,
2092                            kZeroIsAnError,
2093                            kSyscallError);
2094     } else {
2095       rv = SSL_connect(conn->ssl_);
2096       conn->HandleSSLError("SSL_connect:ClearIn",
2097                            rv,
2098                            kZeroIsAnError,
2099                            kSyscallError);
2100     }
2101
2102     if (rv < 0) {
2103       return args.GetReturnValue().Set(rv);
2104     }
2105   }
2106
2107   int bytes_written = SSL_write(conn->ssl_, buffer_data + off, len);
2108
2109   conn->HandleSSLError("SSL_write:ClearIn",
2110                        bytes_written,
2111                        len == 0 ? kZeroIsNotAnError : kZeroIsAnError,
2112                        kSyscallError);
2113   conn->SetShutdownFlags();
2114
2115   args.GetReturnValue().Set(bytes_written);
2116 }
2117
2118
2119 void Connection::Start(const FunctionCallbackInfo<Value>& args) {
2120   HandleScope scope(args.GetIsolate());
2121
2122   Connection* conn = Unwrap<Connection>(args.This());
2123
2124   int rv = 0;
2125   if (!SSL_is_init_finished(conn->ssl_)) {
2126     if (conn->is_server()) {
2127       rv = SSL_accept(conn->ssl_);
2128       conn->HandleSSLError("SSL_accept:Start",
2129                            rv,
2130                            kZeroIsAnError,
2131                            kSyscallError);
2132     } else {
2133       rv = SSL_connect(conn->ssl_);
2134       conn->HandleSSLError("SSL_connect:Start",
2135                            rv,
2136                            kZeroIsAnError,
2137                            kSyscallError);
2138     }
2139   }
2140   args.GetReturnValue().Set(rv);
2141 }
2142
2143
2144 void Connection::Close(const FunctionCallbackInfo<Value>& args) {
2145   HandleScope scope(args.GetIsolate());
2146
2147   Connection* conn = Unwrap<Connection>(args.This());
2148
2149   if (conn->ssl_ != NULL) {
2150     SSL_free(conn->ssl_);
2151     conn->ssl_ = NULL;
2152   }
2153 }
2154
2155
2156 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2157 void Connection::GetServername(const FunctionCallbackInfo<Value>& args) {
2158   HandleScope scope(args.GetIsolate());
2159
2160   Connection* conn = Unwrap<Connection>(args.This());
2161
2162   if (conn->is_server() && !conn->servername_.IsEmpty()) {
2163     args.GetReturnValue().Set(conn->servername_);
2164   } else {
2165     args.GetReturnValue().Set(false);
2166   }
2167 }
2168
2169
2170 void Connection::SetSNICallback(const FunctionCallbackInfo<Value>& args) {
2171   HandleScope scope(args.GetIsolate());
2172
2173   Connection* conn = Unwrap<Connection>(args.This());
2174   Environment* env = conn->env();
2175
2176   if (args.Length() < 1 || !args[0]->IsFunction()) {
2177     return env->ThrowError("Must give a Function as first argument");
2178   }
2179
2180   Local<Object> obj = Object::New(env->isolate());
2181   obj->Set(FIXED_ONE_BYTE_STRING(args.GetIsolate(), "onselect"), args[0]);
2182   conn->sniObject_.Reset(args.GetIsolate(), obj);
2183 }
2184 #endif
2185
2186
2187 void CipherBase::Initialize(Environment* env, Handle<Object> target) {
2188   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
2189
2190   t->InstanceTemplate()->SetInternalFieldCount(1);
2191
2192   NODE_SET_PROTOTYPE_METHOD(t, "init", Init);
2193   NODE_SET_PROTOTYPE_METHOD(t, "initiv", InitIv);
2194   NODE_SET_PROTOTYPE_METHOD(t, "update", Update);
2195   NODE_SET_PROTOTYPE_METHOD(t, "final", Final);
2196   NODE_SET_PROTOTYPE_METHOD(t, "setAutoPadding", SetAutoPadding);
2197   NODE_SET_PROTOTYPE_METHOD(t, "getAuthTag", GetAuthTag);
2198   NODE_SET_PROTOTYPE_METHOD(t, "setAuthTag", SetAuthTag);
2199   NODE_SET_PROTOTYPE_METHOD(t, "setAAD", SetAAD);
2200
2201   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "CipherBase"),
2202               t->GetFunction());
2203 }
2204
2205
2206 void CipherBase::New(const FunctionCallbackInfo<Value>& args) {
2207   assert(args.IsConstructCall() == true);
2208   HandleScope handle_scope(args.GetIsolate());
2209   CipherKind kind = args[0]->IsTrue() ? kCipher : kDecipher;
2210   Environment* env = Environment::GetCurrent(args.GetIsolate());
2211   new CipherBase(env, args.This(), kind);
2212 }
2213
2214
2215 void CipherBase::Init(const char* cipher_type,
2216                       const char* key_buf,
2217                       int key_buf_len) {
2218   HandleScope scope(env()->isolate());
2219
2220   assert(cipher_ == NULL);
2221   cipher_ = EVP_get_cipherbyname(cipher_type);
2222   if (cipher_ == NULL) {
2223     return env()->ThrowError("Unknown cipher");
2224   }
2225
2226   unsigned char key[EVP_MAX_KEY_LENGTH];
2227   unsigned char iv[EVP_MAX_IV_LENGTH];
2228
2229   int key_len = EVP_BytesToKey(cipher_,
2230                                EVP_md5(),
2231                                NULL,
2232                                reinterpret_cast<const unsigned char*>(key_buf),
2233                                key_buf_len,
2234                                1,
2235                                key,
2236                                iv);
2237
2238   EVP_CIPHER_CTX_init(&ctx_);
2239   EVP_CipherInit_ex(&ctx_, cipher_, NULL, NULL, NULL, kind_ == kCipher);
2240   if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
2241     EVP_CIPHER_CTX_cleanup(&ctx_);
2242     return env()->ThrowError("Invalid key length");
2243   }
2244
2245   EVP_CipherInit_ex(&ctx_,
2246                     NULL,
2247                     NULL,
2248                     reinterpret_cast<unsigned char*>(key),
2249                     reinterpret_cast<unsigned char*>(iv),
2250                     kind_ == kCipher);
2251   initialised_ = true;
2252 }
2253
2254
2255 void CipherBase::Init(const FunctionCallbackInfo<Value>& args) {
2256   HandleScope scope(args.GetIsolate());
2257
2258   CipherBase* cipher = Unwrap<CipherBase>(args.This());
2259
2260   if (args.Length() < 2 ||
2261       !(args[0]->IsString() && Buffer::HasInstance(args[1]))) {
2262     return cipher->env()->ThrowError("Must give cipher-type, key");
2263   }
2264
2265   const String::Utf8Value cipher_type(args[0]);
2266   const char* key_buf = Buffer::Data(args[1]);
2267   ssize_t key_buf_len = Buffer::Length(args[1]);
2268   cipher->Init(*cipher_type, key_buf, key_buf_len);
2269 }
2270
2271
2272 void CipherBase::InitIv(const char* cipher_type,
2273                         const char* key,
2274                         int key_len,
2275                         const char* iv,
2276                         int iv_len) {
2277   HandleScope scope(env()->isolate());
2278
2279   cipher_ = EVP_get_cipherbyname(cipher_type);
2280   if (cipher_ == NULL) {
2281     return env()->ThrowError("Unknown cipher");
2282   }
2283
2284   /* OpenSSL versions up to 0.9.8l failed to return the correct
2285      iv_length (0) for ECB ciphers */
2286   if (EVP_CIPHER_iv_length(cipher_) != iv_len &&
2287       !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_ECB_MODE && iv_len == 0)) {
2288     return env()->ThrowError("Invalid IV length");
2289   }
2290   EVP_CIPHER_CTX_init(&ctx_);
2291   EVP_CipherInit_ex(&ctx_, cipher_, NULL, NULL, NULL, kind_ == kCipher);
2292   if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
2293     EVP_CIPHER_CTX_cleanup(&ctx_);
2294     return env()->ThrowError("Invalid key length");
2295   }
2296
2297   EVP_CipherInit_ex(&ctx_,
2298                     NULL,
2299                     NULL,
2300                     reinterpret_cast<const unsigned char*>(key),
2301                     reinterpret_cast<const unsigned char*>(iv),
2302                     kind_ == kCipher);
2303   initialised_ = true;
2304 }
2305
2306
2307 void CipherBase::InitIv(const FunctionCallbackInfo<Value>& args) {
2308   HandleScope scope(args.GetIsolate());
2309
2310   CipherBase* cipher = Unwrap<CipherBase>(args.This());
2311   Environment* env = cipher->env();
2312
2313   if (args.Length() < 3 || !args[0]->IsString()) {
2314     return env->ThrowError("Must give cipher-type, key, and iv as argument");
2315   }
2316
2317   ASSERT_IS_BUFFER(args[1]);
2318   ASSERT_IS_BUFFER(args[2]);
2319
2320   const String::Utf8Value cipher_type(args[0]);
2321   ssize_t key_len = Buffer::Length(args[1]);
2322   const char* key_buf = Buffer::Data(args[1]);
2323   ssize_t iv_len = Buffer::Length(args[2]);
2324   const char* iv_buf = Buffer::Data(args[2]);
2325   cipher->InitIv(*cipher_type, key_buf, key_len, iv_buf, iv_len);
2326 }
2327
2328
2329 bool CipherBase::IsAuthenticatedMode() const {
2330   // check if this cipher operates in an AEAD mode that we support.
2331   if (!cipher_)
2332     return false;
2333   int mode = EVP_CIPHER_mode(cipher_);
2334   return mode == EVP_CIPH_GCM_MODE;
2335 }
2336
2337
2338 bool CipherBase::GetAuthTag(char** out, unsigned int* out_len) const {
2339   // only callable after Final and if encrypting.
2340   if (initialised_ || kind_ != kCipher || !auth_tag_)
2341     return false;
2342   *out_len = auth_tag_len_;
2343   *out = new char[auth_tag_len_];
2344   memcpy(*out, auth_tag_, auth_tag_len_);
2345   return true;
2346 }
2347
2348
2349 void CipherBase::GetAuthTag(const FunctionCallbackInfo<Value>& args) {
2350   Environment* env = Environment::GetCurrent(args.GetIsolate());
2351   HandleScope handle_scope(args.GetIsolate());
2352   CipherBase* cipher = Unwrap<CipherBase>(args.This());
2353
2354   char* out = NULL;
2355   unsigned int out_len = 0;
2356
2357   if (cipher->GetAuthTag(&out, &out_len)) {
2358     Local<Object> buf = Buffer::Use(env, out, out_len);
2359     args.GetReturnValue().Set(buf);
2360   } else {
2361     env->ThrowError("Attempting to get auth tag in unsupported state");
2362   }
2363 }
2364
2365
2366 bool CipherBase::SetAuthTag(const char* data, unsigned int len) {
2367   if (!initialised_ || !IsAuthenticatedMode() || kind_ != kDecipher)
2368     return false;
2369   delete[] auth_tag_;
2370   auth_tag_len_ = len;
2371   auth_tag_ = new char[len];
2372   memcpy(auth_tag_, data, len);
2373   return true;
2374 }
2375
2376
2377 void CipherBase::SetAuthTag(const FunctionCallbackInfo<Value>& args) {
2378   HandleScope handle_scope(args.GetIsolate());
2379   Environment* env = Environment::GetCurrent(args.GetIsolate());
2380
2381   Local<Object> buf = args[0].As<Object>();
2382   if (!buf->IsObject() || !Buffer::HasInstance(buf))
2383     return env->ThrowTypeError("Argument must be a Buffer");
2384
2385   CipherBase* cipher = Unwrap<CipherBase>(args.This());
2386
2387   if (!cipher->SetAuthTag(Buffer::Data(buf), Buffer::Length(buf)))
2388     env->ThrowError("Attempting to set auth tag in unsupported state");
2389 }
2390
2391
2392 bool CipherBase::SetAAD(const char* data, unsigned int len) {
2393   if (!initialised_ || !IsAuthenticatedMode())
2394     return false;
2395   int outlen;
2396   if (!EVP_CipherUpdate(&ctx_,
2397                         NULL,
2398                         &outlen,
2399                         reinterpret_cast<const unsigned char*>(data),
2400                         len)) {
2401     ThrowCryptoTypeError(env(), ERR_get_error());
2402     return false;
2403   }
2404   return true;
2405 }
2406
2407
2408 void CipherBase::SetAAD(const FunctionCallbackInfo<Value>& args) {
2409   Environment* env = Environment::GetCurrent(args.GetIsolate());
2410   HandleScope handle_scope(env->isolate());
2411
2412   ASSERT_IS_BUFFER(args[0]);
2413
2414   CipherBase* cipher = Unwrap<CipherBase>(args.This());
2415
2416   if (!cipher->SetAAD(Buffer::Data(args[0]), Buffer::Length(args[0])))
2417     env->ThrowError("Attempting to set AAD in unsupported state");
2418 }
2419
2420
2421 bool CipherBase::Update(const char* data,
2422                         int len,
2423                         unsigned char** out,
2424                         int* out_len) {
2425   if (!initialised_)
2426     return 0;
2427
2428   // on first update:
2429   if (kind_ == kDecipher && IsAuthenticatedMode() && auth_tag_ != NULL) {
2430     EVP_CIPHER_CTX_ctrl(&ctx_,
2431                         EVP_CTRL_GCM_SET_TAG,
2432                         auth_tag_len_,
2433                         reinterpret_cast<unsigned char*>(auth_tag_));
2434     delete[] auth_tag_;
2435     auth_tag_ = NULL;
2436   }
2437
2438   *out_len = len + EVP_CIPHER_CTX_block_size(&ctx_);
2439   *out = new unsigned char[*out_len];
2440   return EVP_CipherUpdate(&ctx_,
2441                           *out,
2442                           out_len,
2443                           reinterpret_cast<const unsigned char*>(data),
2444                           len);
2445 }
2446
2447
2448 void CipherBase::Update(const FunctionCallbackInfo<Value>& args) {
2449   HandleScope handle_scope(args.GetIsolate());
2450   Environment* env = Environment::GetCurrent(args.GetIsolate());
2451
2452   CipherBase* cipher = Unwrap<CipherBase>(args.This());
2453
2454   ASSERT_IS_STRING_OR_BUFFER(args[0]);
2455
2456   unsigned char* out = NULL;
2457   bool r;
2458   int out_len = 0;
2459
2460   // Only copy the data if we have to, because it's a string
2461   if (args[0]->IsString()) {
2462     Local<String> string = args[0].As<String>();
2463     enum encoding encoding = ParseEncoding(env->isolate(), args[1], BINARY);
2464     if (!StringBytes::IsValidString(env->isolate(), string, encoding))
2465       return env->ThrowTypeError("Bad input string");
2466     size_t buflen = StringBytes::StorageSize(env->isolate(), string, encoding);
2467     char* buf = new char[buflen];
2468     size_t written = StringBytes::Write(env->isolate(),
2469                                         buf,
2470                                         buflen,
2471                                         string,
2472                                         encoding);
2473     r = cipher->Update(buf, written, &out, &out_len);
2474     delete[] buf;
2475   } else {
2476     char* buf = Buffer::Data(args[0]);
2477     size_t buflen = Buffer::Length(args[0]);
2478     r = cipher->Update(buf, buflen, &out, &out_len);
2479   }
2480
2481   if (!r) {
2482     delete[] out;
2483     return ThrowCryptoTypeError(env, ERR_get_error());
2484   }
2485
2486   Local<Object> buf = Buffer::New(env, reinterpret_cast<char*>(out), out_len);
2487   if (out)
2488     delete[] out;
2489
2490   args.GetReturnValue().Set(buf);
2491 }
2492
2493
2494 bool CipherBase::SetAutoPadding(bool auto_padding) {
2495   if (!initialised_)
2496     return false;
2497   return EVP_CIPHER_CTX_set_padding(&ctx_, auto_padding);
2498 }
2499
2500
2501 void CipherBase::SetAutoPadding(const FunctionCallbackInfo<Value>& args) {
2502   HandleScope scope(args.GetIsolate());
2503   CipherBase* cipher = Unwrap<CipherBase>(args.This());
2504   cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue());
2505 }
2506
2507
2508 bool CipherBase::Final(unsigned char** out, int *out_len) {
2509   if (!initialised_)
2510     return false;
2511
2512   *out = new unsigned char[EVP_CIPHER_CTX_block_size(&ctx_)];
2513   int r = EVP_CipherFinal_ex(&ctx_, *out, out_len);
2514
2515   if (r && kind_ == kCipher) {
2516     delete[] auth_tag_;
2517     auth_tag_ = NULL;
2518     if (IsAuthenticatedMode()) {
2519       auth_tag_len_ = EVP_GCM_TLS_TAG_LEN;  // use default tag length
2520       auth_tag_ = new char[auth_tag_len_];
2521       memset(auth_tag_, 0, auth_tag_len_);
2522       EVP_CIPHER_CTX_ctrl(&ctx_,
2523                           EVP_CTRL_GCM_GET_TAG,
2524                           auth_tag_len_,
2525                           reinterpret_cast<unsigned char*>(auth_tag_));
2526     }
2527   }
2528
2529   EVP_CIPHER_CTX_cleanup(&ctx_);
2530   initialised_ = false;
2531
2532   return r == 1;
2533 }
2534
2535
2536 void CipherBase::Final(const FunctionCallbackInfo<Value>& args) {
2537   HandleScope handle_scope(args.GetIsolate());
2538   Environment* env = Environment::GetCurrent(args.GetIsolate());
2539
2540   CipherBase* cipher = Unwrap<CipherBase>(args.This());
2541
2542   unsigned char* out_value = NULL;
2543   int out_len = -1;
2544   Local<Value> outString;
2545
2546   bool r = cipher->Final(&out_value, &out_len);
2547
2548   if (out_len <= 0 || !r) {
2549     delete[] out_value;
2550     out_value = NULL;
2551     out_len = 0;
2552     if (!r)
2553       return ThrowCryptoTypeError(env, ERR_get_error());
2554   }
2555
2556   args.GetReturnValue().Set(
2557       Buffer::New(env, reinterpret_cast<char*>(out_value), out_len));
2558 }
2559
2560
2561 void Hmac::Initialize(Environment* env, v8::Handle<v8::Object> target) {
2562   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
2563
2564   t->InstanceTemplate()->SetInternalFieldCount(1);
2565
2566   NODE_SET_PROTOTYPE_METHOD(t, "init", HmacInit);
2567   NODE_SET_PROTOTYPE_METHOD(t, "update", HmacUpdate);
2568   NODE_SET_PROTOTYPE_METHOD(t, "digest", HmacDigest);
2569
2570   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hmac"), t->GetFunction());
2571 }
2572
2573
2574 void Hmac::New(const FunctionCallbackInfo<Value>& args) {
2575   HandleScope handle_scope(args.GetIsolate());
2576   Environment* env = Environment::GetCurrent(args.GetIsolate());
2577   new Hmac(env, args.This());
2578 }
2579
2580
2581 void Hmac::HmacInit(const char* hash_type, const char* key, int key_len) {
2582   HandleScope scope(env()->isolate());
2583
2584   assert(md_ == NULL);
2585   md_ = EVP_get_digestbyname(hash_type);
2586   if (md_ == NULL) {
2587     return env()->ThrowError("Unknown message digest");
2588   }
2589   HMAC_CTX_init(&ctx_);
2590   if (key_len == 0) {
2591     HMAC_Init(&ctx_, "", 0, md_);
2592   } else {
2593     HMAC_Init(&ctx_, key, key_len, md_);
2594   }
2595   initialised_ = true;
2596 }
2597
2598
2599 void Hmac::HmacInit(const FunctionCallbackInfo<Value>& args) {
2600   HandleScope scope(args.GetIsolate());
2601
2602   Hmac* hmac = Unwrap<Hmac>(args.This());
2603   Environment* env = hmac->env();
2604
2605   if (args.Length() < 2 || !args[0]->IsString()) {
2606     return env->ThrowError("Must give hashtype string, key as arguments");
2607   }
2608
2609   ASSERT_IS_BUFFER(args[1]);
2610
2611   const String::Utf8Value hash_type(args[0]);
2612   const char* buffer_data = Buffer::Data(args[1]);
2613   size_t buffer_length = Buffer::Length(args[1]);
2614   hmac->HmacInit(*hash_type, buffer_data, buffer_length);
2615 }
2616
2617
2618 bool Hmac::HmacUpdate(const char* data, int len) {
2619   if (!initialised_)
2620     return false;
2621   HMAC_Update(&ctx_, reinterpret_cast<const unsigned char*>(data), len);
2622   return true;
2623 }
2624
2625
2626 void Hmac::HmacUpdate(const FunctionCallbackInfo<Value>& args) {
2627   Environment* env = Environment::GetCurrent(args.GetIsolate());
2628   HandleScope scope(env->isolate());
2629
2630   Hmac* hmac = Unwrap<Hmac>(args.This());
2631
2632   ASSERT_IS_STRING_OR_BUFFER(args[0]);
2633
2634   // Only copy the data if we have to, because it's a string
2635   bool r;
2636   if (args[0]->IsString()) {
2637     Local<String> string = args[0].As<String>();
2638     enum encoding encoding = ParseEncoding(env->isolate(), args[1], BINARY);
2639     if (!StringBytes::IsValidString(env->isolate(), string, encoding))
2640       return env->ThrowTypeError("Bad input string");
2641     size_t buflen = StringBytes::StorageSize(env->isolate(), string, encoding);
2642     char* buf = new char[buflen];
2643     size_t written = StringBytes::Write(env->isolate(),
2644                                         buf,
2645                                         buflen,
2646                                         string,
2647                                         encoding);
2648     r = hmac->HmacUpdate(buf, written);
2649     delete[] buf;
2650   } else {
2651     char* buf = Buffer::Data(args[0]);
2652     size_t buflen = Buffer::Length(args[0]);
2653     r = hmac->HmacUpdate(buf, buflen);
2654   }
2655
2656   if (!r) {
2657     return env->ThrowTypeError("HmacUpdate fail");
2658   }
2659 }
2660
2661
2662 bool Hmac::HmacDigest(unsigned char** md_value, unsigned int* md_len) {
2663   if (!initialised_)
2664     return false;
2665   *md_value = new unsigned char[EVP_MAX_MD_SIZE];
2666   HMAC_Final(&ctx_, *md_value, md_len);
2667   HMAC_CTX_cleanup(&ctx_);
2668   initialised_ = false;
2669   return true;
2670 }
2671
2672
2673 void Hmac::HmacDigest(const FunctionCallbackInfo<Value>& args) {
2674   Environment* env = Environment::GetCurrent(args.GetIsolate());
2675   HandleScope scope(env->isolate());
2676
2677   Hmac* hmac = Unwrap<Hmac>(args.This());
2678
2679   enum encoding encoding = BUFFER;
2680   if (args.Length() >= 1) {
2681     encoding = ParseEncoding(env->isolate(), args[0]->ToString(), BUFFER);
2682   }
2683
2684   unsigned char* md_value = NULL;
2685   unsigned int md_len = 0;
2686
2687   bool r = hmac->HmacDigest(&md_value, &md_len);
2688   if (!r) {
2689     md_value = NULL;
2690     md_len = 0;
2691   }
2692
2693   Local<Value> rc = StringBytes::Encode(env->isolate(),
2694                                         reinterpret_cast<const char*>(md_value),
2695                                         md_len,
2696                                         encoding);
2697   delete[] md_value;
2698   args.GetReturnValue().Set(rc);
2699 }
2700
2701
2702 void Hash::Initialize(Environment* env, v8::Handle<v8::Object> target) {
2703   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
2704
2705   t->InstanceTemplate()->SetInternalFieldCount(1);
2706
2707   NODE_SET_PROTOTYPE_METHOD(t, "update", HashUpdate);
2708   NODE_SET_PROTOTYPE_METHOD(t, "digest", HashDigest);
2709
2710   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Hash"), t->GetFunction());
2711 }
2712
2713
2714 void Hash::New(const FunctionCallbackInfo<Value>& args) {
2715   Environment* env = Environment::GetCurrent(args.GetIsolate());
2716   HandleScope scope(env->isolate());
2717
2718   if (args.Length() == 0 || !args[0]->IsString()) {
2719     return env->ThrowError("Must give hashtype string as argument");
2720   }
2721
2722   const String::Utf8Value hash_type(args[0]);
2723
2724   Hash* hash = new Hash(env, args.This());
2725   if (!hash->HashInit(*hash_type)) {
2726     return env->ThrowError("Digest method not supported");
2727   }
2728 }
2729
2730
2731 bool Hash::HashInit(const char* hash_type) {
2732   assert(md_ == NULL);
2733   md_ = EVP_get_digestbyname(hash_type);
2734   if (md_ == NULL)
2735     return false;
2736   EVP_MD_CTX_init(&mdctx_);
2737   EVP_DigestInit_ex(&mdctx_, md_, NULL);
2738   initialised_ = true;
2739   return true;
2740 }
2741
2742
2743 bool Hash::HashUpdate(const char* data, int len) {
2744   if (!initialised_)
2745     return false;
2746   EVP_DigestUpdate(&mdctx_, data, len);
2747   return true;
2748 }
2749
2750
2751 void Hash::HashUpdate(const FunctionCallbackInfo<Value>& args) {
2752   Environment* env = Environment::GetCurrent(args.GetIsolate());
2753   HandleScope scope(env->isolate());
2754
2755   Hash* hash = Unwrap<Hash>(args.This());
2756
2757   ASSERT_IS_STRING_OR_BUFFER(args[0]);
2758
2759   // Only copy the data if we have to, because it's a string
2760   bool r;
2761   if (args[0]->IsString()) {
2762     Local<String> string = args[0].As<String>();
2763     enum encoding encoding = ParseEncoding(env->isolate(), args[1], BINARY);
2764     if (!StringBytes::IsValidString(env->isolate(), string, encoding))
2765       return env->ThrowTypeError("Bad input string");
2766     size_t buflen = StringBytes::StorageSize(env->isolate(), string, encoding);
2767     char* buf = new char[buflen];
2768     size_t written = StringBytes::Write(env->isolate(),
2769                                         buf,
2770                                         buflen,
2771                                         string,
2772                                         encoding);
2773     r = hash->HashUpdate(buf, written);
2774     delete[] buf;
2775   } else {
2776     char* buf = Buffer::Data(args[0]);
2777     size_t buflen = Buffer::Length(args[0]);
2778     r = hash->HashUpdate(buf, buflen);
2779   }
2780
2781   if (!r) {
2782     return env->ThrowTypeError("HashUpdate fail");
2783   }
2784 }
2785
2786
2787 void Hash::HashDigest(const FunctionCallbackInfo<Value>& args) {
2788   Environment* env = Environment::GetCurrent(args.GetIsolate());
2789   HandleScope scope(env->isolate());
2790
2791   Hash* hash = Unwrap<Hash>(args.This());
2792
2793   if (!hash->initialised_) {
2794     return env->ThrowError("Not initialized");
2795   }
2796
2797   enum encoding encoding = BUFFER;
2798   if (args.Length() >= 1) {
2799     encoding = ParseEncoding(env->isolate(), args[0]->ToString(), BUFFER);
2800   }
2801
2802   unsigned char md_value[EVP_MAX_MD_SIZE];
2803   unsigned int md_len;
2804
2805   EVP_DigestFinal_ex(&hash->mdctx_, md_value, &md_len);
2806   EVP_MD_CTX_cleanup(&hash->mdctx_);
2807   hash->initialised_ = false;
2808
2809   Local<Value> rc = StringBytes::Encode(env->isolate(),
2810                                         reinterpret_cast<const char*>(md_value),
2811                                         md_len,
2812                                         encoding);
2813   args.GetReturnValue().Set(rc);
2814 }
2815
2816
2817 void SignBase::CheckThrow(SignBase::Error error) {
2818   HandleScope scope(env()->isolate());
2819
2820   switch (error) {
2821     case kSignUnknownDigest:
2822       return env()->ThrowError("Unknown message digest");
2823
2824     case kSignNotInitialised:
2825       return env()->ThrowError("Not initialised");
2826
2827     case kSignInit:
2828     case kSignUpdate:
2829     case kSignPrivateKey:
2830     case kSignPublicKey:
2831       {
2832         unsigned long err = ERR_get_error();
2833         if (err)
2834           return ThrowCryptoError(env(), err);
2835         switch (error) {
2836           case kSignInit:
2837             return env()->ThrowError("EVP_SignInit_ex failed");
2838           case kSignUpdate:
2839             return env()->ThrowError("EVP_SignUpdate failed");
2840           case kSignPrivateKey:
2841             return env()->ThrowError("PEM_read_bio_PrivateKey failed");
2842           case kSignPublicKey:
2843             return env()->ThrowError("PEM_read_bio_PUBKEY failed");
2844           default:
2845             abort();
2846         }
2847       }
2848
2849     case kSignOk:
2850       return;
2851   }
2852 }
2853
2854
2855
2856
2857 void Sign::Initialize(Environment* env, v8::Handle<v8::Object> target) {
2858   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
2859
2860   t->InstanceTemplate()->SetInternalFieldCount(1);
2861
2862   NODE_SET_PROTOTYPE_METHOD(t, "init", SignInit);
2863   NODE_SET_PROTOTYPE_METHOD(t, "update", SignUpdate);
2864   NODE_SET_PROTOTYPE_METHOD(t, "sign", SignFinal);
2865
2866   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Sign"), t->GetFunction());
2867 }
2868
2869
2870 void Sign::New(const FunctionCallbackInfo<Value>& args) {
2871   HandleScope handle_scope(args.GetIsolate());
2872   Environment* env = Environment::GetCurrent(args.GetIsolate());
2873   new Sign(env, args.This());
2874 }
2875
2876
2877 SignBase::Error Sign::SignInit(const char* sign_type) {
2878   assert(md_ == NULL);
2879   md_ = EVP_get_digestbyname(sign_type);
2880   if (!md_)
2881     return kSignUnknownDigest;
2882
2883   EVP_MD_CTX_init(&mdctx_);
2884   if (!EVP_SignInit_ex(&mdctx_, md_, NULL))
2885     return kSignInit;
2886   initialised_ = true;
2887
2888   return kSignOk;
2889 }
2890
2891
2892 void Sign::SignInit(const FunctionCallbackInfo<Value>& args) {
2893   HandleScope scope(args.GetIsolate());
2894
2895   Sign* sign = Unwrap<Sign>(args.This());
2896
2897   if (args.Length() == 0 || !args[0]->IsString()) {
2898     return sign->env()->ThrowError("Must give signtype string as argument");
2899   }
2900
2901   const String::Utf8Value sign_type(args[0]);
2902   sign->CheckThrow(sign->SignInit(*sign_type));
2903 }
2904
2905
2906 SignBase::Error Sign::SignUpdate(const char* data, int len) {
2907   if (!initialised_)
2908     return kSignNotInitialised;
2909   if (!EVP_SignUpdate(&mdctx_, data, len))
2910     return kSignUpdate;
2911   return kSignOk;
2912 }
2913
2914
2915 void Sign::SignUpdate(const FunctionCallbackInfo<Value>& args) {
2916   Environment* env = Environment::GetCurrent(args.GetIsolate());
2917   HandleScope scope(env->isolate());
2918
2919   Sign* sign = Unwrap<Sign>(args.This());
2920
2921   ASSERT_IS_STRING_OR_BUFFER(args[0]);
2922
2923   // Only copy the data if we have to, because it's a string
2924   Error err;
2925   if (args[0]->IsString()) {
2926     Local<String> string = args[0].As<String>();
2927     enum encoding encoding = ParseEncoding(env->isolate(), args[1], BINARY);
2928     if (!StringBytes::IsValidString(env->isolate(), string, encoding))
2929       return env->ThrowTypeError("Bad input string");
2930     size_t buflen = StringBytes::StorageSize(env->isolate(), string, encoding);
2931     char* buf = new char[buflen];
2932     size_t written = StringBytes::Write(env->isolate(),
2933                                         buf,
2934                                         buflen,
2935                                         string,
2936                                         encoding);
2937     err = sign->SignUpdate(buf, written);
2938     delete[] buf;
2939   } else {
2940     char* buf = Buffer::Data(args[0]);
2941     size_t buflen = Buffer::Length(args[0]);
2942     err = sign->SignUpdate(buf, buflen);
2943   }
2944
2945   sign->CheckThrow(err);
2946 }
2947
2948
2949 SignBase::Error Sign::SignFinal(const char* key_pem,
2950                                 int key_pem_len,
2951                                 const char* passphrase,
2952                                 unsigned char** sig,
2953                                 unsigned int *sig_len) {
2954   if (!initialised_)
2955     return kSignNotInitialised;
2956
2957   BIO* bp = NULL;
2958   EVP_PKEY* pkey = NULL;
2959   bool fatal = true;
2960
2961   bp = BIO_new(BIO_s_mem());
2962   if (bp == NULL)
2963     goto exit;
2964
2965   if (!BIO_write(bp, key_pem, key_pem_len))
2966     goto exit;
2967
2968   pkey = PEM_read_bio_PrivateKey(bp,
2969                                  NULL,
2970                                  CryptoPemCallback,
2971                                  const_cast<char*>(passphrase));
2972   if (pkey == NULL)
2973     goto exit;
2974
2975   if (EVP_SignFinal(&mdctx_, *sig, sig_len, pkey))
2976     fatal = false;
2977
2978   initialised_ = false;
2979
2980  exit:
2981   if (pkey != NULL)
2982     EVP_PKEY_free(pkey);
2983   if (bp != NULL)
2984     BIO_free_all(bp);
2985
2986   EVP_MD_CTX_cleanup(&mdctx_);
2987
2988   if (fatal)
2989     return kSignPrivateKey;
2990
2991   return kSignOk;
2992 }
2993
2994
2995 void Sign::SignFinal(const FunctionCallbackInfo<Value>& args) {
2996   Environment* env = Environment::GetCurrent(args.GetIsolate());
2997   HandleScope scope(env->isolate());
2998
2999   Sign* sign = Unwrap<Sign>(args.This());
3000
3001   unsigned char* md_value;
3002   unsigned int md_len;
3003
3004   unsigned int len = args.Length();
3005   enum encoding encoding = BUFFER;
3006   if (len >= 2 && args[1]->IsString()) {
3007     encoding = ParseEncoding(env->isolate(), args[1]->ToString(), BUFFER);
3008   }
3009
3010   String::Utf8Value passphrase(args[2]);
3011
3012   ASSERT_IS_BUFFER(args[0]);
3013   size_t buf_len = Buffer::Length(args[0]);
3014   char* buf = Buffer::Data(args[0]);
3015
3016   md_len = 8192;  // Maximum key size is 8192 bits
3017   md_value = new unsigned char[md_len];
3018
3019   Error err = sign->SignFinal(
3020       buf,
3021       buf_len,
3022       len >= 3 && !args[2]->IsNull() ? *passphrase : NULL,
3023       &md_value,
3024       &md_len);
3025   if (err != kSignOk) {
3026     delete[] md_value;
3027     md_value = NULL;
3028     md_len = 0;
3029     return sign->CheckThrow(err);
3030   }
3031
3032   Local<Value> rc = StringBytes::Encode(env->isolate(),
3033                                         reinterpret_cast<const char*>(md_value),
3034                                         md_len,
3035                                         encoding);
3036   delete[] md_value;
3037   args.GetReturnValue().Set(rc);
3038 }
3039
3040
3041 void Verify::Initialize(Environment* env, v8::Handle<v8::Object> target) {
3042   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
3043
3044   t->InstanceTemplate()->SetInternalFieldCount(1);
3045
3046   NODE_SET_PROTOTYPE_METHOD(t, "init", VerifyInit);
3047   NODE_SET_PROTOTYPE_METHOD(t, "update", VerifyUpdate);
3048   NODE_SET_PROTOTYPE_METHOD(t, "verify", VerifyFinal);
3049
3050   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Verify"),
3051               t->GetFunction());
3052 }
3053
3054
3055 void Verify::New(const FunctionCallbackInfo<Value>& args) {
3056   HandleScope handle_scope(args.GetIsolate());
3057   Environment* env = Environment::GetCurrent(args.GetIsolate());
3058   new Verify(env, args.This());
3059 }
3060
3061
3062 SignBase::Error Verify::VerifyInit(const char* verify_type) {
3063   assert(md_ == NULL);
3064   md_ = EVP_get_digestbyname(verify_type);
3065   if (md_ == NULL)
3066     return kSignUnknownDigest;
3067
3068   EVP_MD_CTX_init(&mdctx_);
3069   if (!EVP_VerifyInit_ex(&mdctx_, md_, NULL))
3070     return kSignInit;
3071   initialised_ = true;
3072
3073   return kSignOk;
3074 }
3075
3076
3077 void Verify::VerifyInit(const FunctionCallbackInfo<Value>& args) {
3078   HandleScope scope(args.GetIsolate());
3079
3080   Verify* verify = Unwrap<Verify>(args.This());
3081
3082   if (args.Length() == 0 || !args[0]->IsString()) {
3083     return verify->env()->ThrowError("Must give verifytype string as argument");
3084   }
3085
3086   const String::Utf8Value verify_type(args[0]);
3087   verify->CheckThrow(verify->VerifyInit(*verify_type));
3088 }
3089
3090
3091 SignBase::Error Verify::VerifyUpdate(const char* data, int len) {
3092   if (!initialised_)
3093     return kSignNotInitialised;
3094
3095   if (!EVP_VerifyUpdate(&mdctx_, data, len))
3096     return kSignUpdate;
3097
3098   return kSignOk;
3099 }
3100
3101
3102 void Verify::VerifyUpdate(const FunctionCallbackInfo<Value>& args) {
3103   Environment* env = Environment::GetCurrent(args.GetIsolate());
3104   HandleScope scope(env->isolate());
3105
3106   Verify* verify = Unwrap<Verify>(args.This());
3107
3108   ASSERT_IS_STRING_OR_BUFFER(args[0]);
3109
3110   // Only copy the data if we have to, because it's a string
3111   Error err;
3112   if (args[0]->IsString()) {
3113     Local<String> string = args[0].As<String>();
3114     enum encoding encoding = ParseEncoding(env->isolate(), args[1], BINARY);
3115     if (!StringBytes::IsValidString(env->isolate(), string, encoding))
3116       return env->ThrowTypeError("Bad input string");
3117     size_t buflen = StringBytes::StorageSize(env->isolate(), string, encoding);
3118     char* buf = new char[buflen];
3119     size_t written = StringBytes::Write(env->isolate(),
3120                                         buf,
3121                                         buflen,
3122                                         string,
3123                                         encoding);
3124     err = verify->VerifyUpdate(buf, written);
3125     delete[] buf;
3126   } else {
3127     char* buf = Buffer::Data(args[0]);
3128     size_t buflen = Buffer::Length(args[0]);
3129     err = verify->VerifyUpdate(buf, buflen);
3130   }
3131
3132   verify->CheckThrow(err);
3133 }
3134
3135
3136 SignBase::Error Verify::VerifyFinal(const char* key_pem,
3137                                     int key_pem_len,
3138                                     const char* sig,
3139                                     int siglen,
3140                                     bool* verify_result) {
3141   if (!initialised_)
3142     return kSignNotInitialised;
3143
3144   ClearErrorOnReturn clear_error_on_return;
3145   (void) &clear_error_on_return;  // Silence compiler warning.
3146
3147   EVP_PKEY* pkey = NULL;
3148   BIO* bp = NULL;
3149   X509* x509 = NULL;
3150   bool fatal = true;
3151   int r = 0;
3152
3153   bp = BIO_new(BIO_s_mem());
3154   if (bp == NULL)
3155     goto exit;
3156
3157   if (!BIO_write(bp, key_pem, key_pem_len))
3158     goto exit;
3159
3160   // Check if this is a PKCS#8 or RSA public key before trying as X.509.
3161   // Split this out into a separate function once we have more than one
3162   // consumer of public keys.
3163   if (strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
3164     pkey = PEM_read_bio_PUBKEY(bp, NULL, CryptoPemCallback, NULL);
3165     if (pkey == NULL)
3166       goto exit;
3167   } else if (strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
3168     RSA* rsa = PEM_read_bio_RSAPublicKey(bp, NULL, CryptoPemCallback, NULL);
3169     if (rsa) {
3170       pkey = EVP_PKEY_new();
3171       if (pkey)
3172         EVP_PKEY_set1_RSA(pkey, rsa);
3173       RSA_free(rsa);
3174     }
3175     if (pkey == NULL)
3176       goto exit;
3177   } else {
3178     // X.509 fallback
3179     x509 = PEM_read_bio_X509(bp, NULL, CryptoPemCallback, NULL);
3180     if (x509 == NULL)
3181       goto exit;
3182
3183     pkey = X509_get_pubkey(x509);
3184     if (pkey == NULL)
3185       goto exit;
3186   }
3187
3188   fatal = false;
3189   r = EVP_VerifyFinal(&mdctx_,
3190                       reinterpret_cast<const unsigned char*>(sig),
3191                       siglen,
3192                       pkey);
3193
3194  exit:
3195   if (pkey != NULL)
3196     EVP_PKEY_free(pkey);
3197   if (bp != NULL)
3198     BIO_free_all(bp);
3199   if (x509 != NULL)
3200     X509_free(x509);
3201
3202   EVP_MD_CTX_cleanup(&mdctx_);
3203   initialised_ = false;
3204
3205   if (fatal)
3206     return kSignPublicKey;
3207
3208   *verify_result = r == 1;
3209   return kSignOk;
3210 }
3211
3212
3213 void Verify::VerifyFinal(const FunctionCallbackInfo<Value>& args) {
3214   Environment* env = Environment::GetCurrent(args.GetIsolate());
3215   HandleScope scope(env->isolate());
3216
3217   Verify* verify = Unwrap<Verify>(args.This());
3218
3219   ASSERT_IS_BUFFER(args[0]);
3220   char* kbuf = Buffer::Data(args[0]);
3221   ssize_t klen = Buffer::Length(args[0]);
3222
3223   ASSERT_IS_STRING_OR_BUFFER(args[1]);
3224   // BINARY works for both buffers and binary strings.
3225   enum encoding encoding = BINARY;
3226   if (args.Length() >= 3) {
3227     encoding = ParseEncoding(env->isolate(), args[2]->ToString(), BINARY);
3228   }
3229
3230   ssize_t hlen = StringBytes::Size(env->isolate(), args[1], encoding);
3231
3232   // only copy if we need to, because it's a string.
3233   char* hbuf;
3234   if (args[1]->IsString()) {
3235     hbuf = new char[hlen];
3236     ssize_t hwritten = StringBytes::Write(env->isolate(),
3237                                           hbuf,
3238                                           hlen,
3239                                           args[1],
3240                                           encoding);
3241     assert(hwritten == hlen);
3242   } else {
3243     hbuf = Buffer::Data(args[1]);
3244   }
3245
3246   bool verify_result;
3247   Error err = verify->VerifyFinal(kbuf, klen, hbuf, hlen, &verify_result);
3248   if (args[1]->IsString())
3249     delete[] hbuf;
3250   if (err != kSignOk)
3251     return verify->CheckThrow(err);
3252   args.GetReturnValue().Set(verify_result);
3253 }
3254
3255
3256 void DiffieHellman::Initialize(Environment* env, Handle<Object> target) {
3257   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
3258
3259   static enum PropertyAttribute attributes =
3260       static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
3261
3262   t->InstanceTemplate()->SetInternalFieldCount(1);
3263
3264   NODE_SET_PROTOTYPE_METHOD(t, "generateKeys", GenerateKeys);
3265   NODE_SET_PROTOTYPE_METHOD(t, "computeSecret", ComputeSecret);
3266   NODE_SET_PROTOTYPE_METHOD(t, "getPrime", GetPrime);
3267   NODE_SET_PROTOTYPE_METHOD(t, "getGenerator", GetGenerator);
3268   NODE_SET_PROTOTYPE_METHOD(t, "getPublicKey", GetPublicKey);
3269   NODE_SET_PROTOTYPE_METHOD(t, "getPrivateKey", GetPrivateKey);
3270   NODE_SET_PROTOTYPE_METHOD(t, "setPublicKey", SetPublicKey);
3271   NODE_SET_PROTOTYPE_METHOD(t, "setPrivateKey", SetPrivateKey);
3272
3273   t->InstanceTemplate()->SetAccessor(env->verify_error_string(),
3274                                      DiffieHellman::VerifyErrorGetter,
3275                                      NULL,
3276                                      Handle<Value>(),
3277                                      v8::DEFAULT,
3278                                      attributes);
3279
3280   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellman"),
3281               t->GetFunction());
3282
3283   Local<FunctionTemplate> t2 = FunctionTemplate::New(env->isolate(),
3284                                                      DiffieHellmanGroup);
3285   t2->InstanceTemplate()->SetInternalFieldCount(1);
3286
3287   NODE_SET_PROTOTYPE_METHOD(t2, "generateKeys", GenerateKeys);
3288   NODE_SET_PROTOTYPE_METHOD(t2, "computeSecret", ComputeSecret);
3289   NODE_SET_PROTOTYPE_METHOD(t2, "getPrime", GetPrime);
3290   NODE_SET_PROTOTYPE_METHOD(t2, "getGenerator", GetGenerator);
3291   NODE_SET_PROTOTYPE_METHOD(t2, "getPublicKey", GetPublicKey);
3292   NODE_SET_PROTOTYPE_METHOD(t2, "getPrivateKey", GetPrivateKey);
3293
3294   t2->InstanceTemplate()->SetAccessor(env->verify_error_string(),
3295                                       DiffieHellman::VerifyErrorGetter,
3296                                       NULL,
3297                                       Handle<Value>(),
3298                                       v8::DEFAULT,
3299                                       attributes);
3300
3301   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellmanGroup"),
3302               t2->GetFunction());
3303 }
3304
3305
3306 bool DiffieHellman::Init(int primeLength, int g) {
3307   dh = DH_new();
3308   DH_generate_parameters_ex(dh, primeLength, g, 0);
3309   bool result = VerifyContext();
3310   if (!result)
3311     return false;
3312   initialised_ = true;
3313   return true;
3314 }
3315
3316
3317 bool DiffieHellman::Init(const char* p, int p_len, int g) {
3318   dh = DH_new();
3319   dh->p = BN_bin2bn(reinterpret_cast<const unsigned char*>(p), p_len, 0);
3320   dh->g = BN_new();
3321   if (!BN_set_word(dh->g, g))
3322     return false;
3323   bool result = VerifyContext();
3324   if (!result)
3325     return false;
3326   initialised_ = true;
3327   return true;
3328 }
3329
3330
3331 bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) {
3332   dh = DH_new();
3333   dh->p = BN_bin2bn(reinterpret_cast<const unsigned char*>(p), p_len, 0);
3334   dh->g = BN_bin2bn(reinterpret_cast<const unsigned char*>(g), g_len, 0);
3335   bool result = VerifyContext();
3336   if (!result)
3337     return false;
3338   initialised_ = true;
3339   return true;
3340 }
3341
3342
3343 void DiffieHellman::DiffieHellmanGroup(
3344     const FunctionCallbackInfo<Value>& args) {
3345   HandleScope scope(args.GetIsolate());
3346
3347   Environment* env = Environment::GetCurrent(args.GetIsolate());
3348   DiffieHellman* diffieHellman = new DiffieHellman(env, args.This());
3349
3350   if (args.Length() != 1 || !args[0]->IsString()) {
3351     return env->ThrowError("No group name given");
3352   }
3353
3354   bool initialized = false;
3355
3356   const String::Utf8Value group_name(args[0]);
3357   for (unsigned int i = 0; i < ARRAY_SIZE(modp_groups); ++i) {
3358     const modp_group* it = modp_groups + i;
3359
3360     if (strcasecmp(*group_name, it->name) != 0)
3361       continue;
3362
3363     initialized = diffieHellman->Init(it->prime,
3364                                       it->prime_size,
3365                                       it->gen,
3366                                       it->gen_size);
3367     if (!initialized)
3368       env->ThrowError("Initialization failed");
3369     return;
3370   }
3371
3372   env->ThrowError("Unknown group");
3373 }
3374
3375
3376 void DiffieHellman::New(const FunctionCallbackInfo<Value>& args) {
3377   HandleScope scope(args.GetIsolate());
3378
3379   Environment* env = Environment::GetCurrent(args.GetIsolate());
3380   DiffieHellman* diffieHellman =
3381       new DiffieHellman(env, args.This());
3382   bool initialized = false;
3383
3384   if (args.Length() == 2) {
3385     if (args[0]->IsInt32()) {
3386       if (args[1]->IsInt32()) {
3387         initialized = diffieHellman->Init(args[0]->Int32Value(),
3388                                           args[1]->Int32Value());
3389       }
3390     } else {
3391       if (args[1]->IsInt32()) {
3392         initialized = diffieHellman->Init(Buffer::Data(args[0]),
3393                                           Buffer::Length(args[0]),
3394                                           args[1]->Int32Value());
3395       } else {
3396         initialized = diffieHellman->Init(Buffer::Data(args[0]),
3397                                           Buffer::Length(args[0]),
3398                                           Buffer::Data(args[1]),
3399                                           Buffer::Length(args[1]));
3400       }
3401     }
3402   }
3403
3404   if (!initialized) {
3405     return env->ThrowError("Initialization failed");
3406   }
3407 }
3408
3409
3410 void DiffieHellman::GenerateKeys(const FunctionCallbackInfo<Value>& args) {
3411   Environment* env = Environment::GetCurrent(args.GetIsolate());
3412   HandleScope scope(env->isolate());
3413
3414   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3415
3416   if (!diffieHellman->initialised_) {
3417     return env->ThrowError("Not initialized");
3418   }
3419
3420   if (!DH_generate_key(diffieHellman->dh)) {
3421     return env->ThrowError("Key generation failed");
3422   }
3423
3424   int dataSize = BN_num_bytes(diffieHellman->dh->pub_key);
3425   char* data = new char[dataSize];
3426   BN_bn2bin(diffieHellman->dh->pub_key,
3427             reinterpret_cast<unsigned char*>(data));
3428
3429   args.GetReturnValue().Set(Encode(env->isolate(), data, dataSize, BUFFER));
3430   delete[] data;
3431 }
3432
3433
3434 void DiffieHellman::GetPrime(const FunctionCallbackInfo<Value>& args) {
3435   Environment* env = Environment::GetCurrent(args.GetIsolate());
3436   HandleScope scope(env->isolate());
3437
3438   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3439
3440   if (!diffieHellman->initialised_) {
3441     return env->ThrowError("Not initialized");
3442   }
3443
3444   int dataSize = BN_num_bytes(diffieHellman->dh->p);
3445   char* data = new char[dataSize];
3446   BN_bn2bin(diffieHellman->dh->p, reinterpret_cast<unsigned char*>(data));
3447
3448   args.GetReturnValue().Set(Encode(env->isolate(), data, dataSize, BUFFER));
3449   delete[] data;
3450 }
3451
3452
3453 void DiffieHellman::GetGenerator(const FunctionCallbackInfo<Value>& args) {
3454   Environment* env = Environment::GetCurrent(args.GetIsolate());
3455   HandleScope scope(env->isolate());
3456
3457   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3458
3459   if (!diffieHellman->initialised_) {
3460     return env->ThrowError("Not initialized");
3461   }
3462
3463   int dataSize = BN_num_bytes(diffieHellman->dh->g);
3464   char* data = new char[dataSize];
3465   BN_bn2bin(diffieHellman->dh->g, reinterpret_cast<unsigned char*>(data));
3466
3467   args.GetReturnValue().Set(Encode(env->isolate(), data, dataSize, BUFFER));
3468   delete[] data;
3469 }
3470
3471
3472 void DiffieHellman::GetPublicKey(const FunctionCallbackInfo<Value>& args) {
3473   Environment* env = Environment::GetCurrent(args.GetIsolate());
3474   HandleScope scope(env->isolate());
3475
3476   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3477
3478   if (!diffieHellman->initialised_) {
3479     return env->ThrowError("Not initialized");
3480   }
3481
3482   if (diffieHellman->dh->pub_key == NULL) {
3483     return env->ThrowError("No public key - did you forget to generate one?");
3484   }
3485
3486   int dataSize = BN_num_bytes(diffieHellman->dh->pub_key);
3487   char* data = new char[dataSize];
3488   BN_bn2bin(diffieHellman->dh->pub_key,
3489             reinterpret_cast<unsigned char*>(data));
3490
3491   args.GetReturnValue().Set(Encode(env->isolate(), data, dataSize, BUFFER));
3492   delete[] data;
3493 }
3494
3495
3496 void DiffieHellman::GetPrivateKey(const FunctionCallbackInfo<Value>& args) {
3497   Environment* env = Environment::GetCurrent(args.GetIsolate());
3498   HandleScope scope(env->isolate());
3499
3500   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3501
3502   if (!diffieHellman->initialised_) {
3503     return env->ThrowError("Not initialized");
3504   }
3505
3506   if (diffieHellman->dh->priv_key == NULL) {
3507     return env->ThrowError("No private key - did you forget to generate one?");
3508   }
3509
3510   int dataSize = BN_num_bytes(diffieHellman->dh->priv_key);
3511   char* data = new char[dataSize];
3512   BN_bn2bin(diffieHellman->dh->priv_key,
3513             reinterpret_cast<unsigned char*>(data));
3514
3515   args.GetReturnValue().Set(Encode(env->isolate(), data, dataSize, BUFFER));
3516   delete[] data;
3517 }
3518
3519
3520 void DiffieHellman::ComputeSecret(const FunctionCallbackInfo<Value>& args) {
3521   Environment* env = Environment::GetCurrent(args.GetIsolate());
3522   HandleScope scope(env->isolate());
3523
3524   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3525
3526   if (!diffieHellman->initialised_) {
3527     return env->ThrowError("Not initialized");
3528   }
3529
3530   ClearErrorOnReturn clear_error_on_return;
3531   (void) &clear_error_on_return;  // Silence compiler warning.
3532   BIGNUM* key = NULL;
3533
3534   if (args.Length() == 0) {
3535     return env->ThrowError("First argument must be other party's public key");
3536   } else {
3537     ASSERT_IS_BUFFER(args[0]);
3538     key = BN_bin2bn(
3539         reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3540         Buffer::Length(args[0]),
3541         0);
3542   }
3543
3544   int dataSize = DH_size(diffieHellman->dh);
3545   char* data = new char[dataSize];
3546
3547   int size = DH_compute_key(reinterpret_cast<unsigned char*>(data),
3548                             key,
3549                             diffieHellman->dh);
3550
3551   if (size == -1) {
3552     int checkResult;
3553     int checked;
3554
3555     checked = DH_check_pub_key(diffieHellman->dh, key, &checkResult);
3556     BN_free(key);
3557     delete[] data;
3558
3559     if (!checked) {
3560       return env->ThrowError("Invalid key");
3561     } else if (checkResult) {
3562       if (checkResult & DH_CHECK_PUBKEY_TOO_SMALL) {
3563         return env->ThrowError("Supplied key is too small");
3564       } else if (checkResult & DH_CHECK_PUBKEY_TOO_LARGE) {
3565         return env->ThrowError("Supplied key is too large");
3566       } else {
3567         return env->ThrowError("Invalid key");
3568       }
3569     } else {
3570       return env->ThrowError("Invalid key");
3571     }
3572   }
3573
3574   BN_free(key);
3575   assert(size >= 0);
3576
3577   // DH_size returns number of bytes in a prime number
3578   // DH_compute_key returns number of bytes in a remainder of exponent, which
3579   // may have less bytes than a prime number. Therefore add 0-padding to the
3580   // allocated buffer.
3581   if (size != dataSize) {
3582     assert(dataSize > size);
3583     memmove(data + dataSize - size, data, size);
3584     memset(data, 0, dataSize - size);
3585   }
3586
3587   args.GetReturnValue().Set(Encode(env->isolate(), data, dataSize, BUFFER));
3588   delete[] data;
3589 }
3590
3591
3592 void DiffieHellman::SetPublicKey(const FunctionCallbackInfo<Value>& args) {
3593   HandleScope scope(args.GetIsolate());
3594
3595   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3596   Environment* env = diffieHellman->env();
3597
3598   if (!diffieHellman->initialised_) {
3599     return env->ThrowError("Not initialized");
3600   }
3601
3602   if (args.Length() == 0) {
3603     return env->ThrowError("First argument must be public key");
3604   } else {
3605     ASSERT_IS_BUFFER(args[0]);
3606     diffieHellman->dh->pub_key = BN_bin2bn(
3607         reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3608         Buffer::Length(args[0]), 0);
3609   }
3610 }
3611
3612
3613 void DiffieHellman::SetPrivateKey(const FunctionCallbackInfo<Value>& args) {
3614   HandleScope scope(args.GetIsolate());
3615
3616   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3617   Environment* env = diffieHellman->env();
3618
3619   if (!diffieHellman->initialised_) {
3620     return env->ThrowError("Not initialized");
3621   }
3622
3623   if (args.Length() == 0) {
3624     return env->ThrowError("First argument must be private key");
3625   } else {
3626     ASSERT_IS_BUFFER(args[0]);
3627     diffieHellman->dh->priv_key = BN_bin2bn(
3628         reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3629         Buffer::Length(args[0]),
3630         0);
3631   }
3632 }
3633
3634
3635 void DiffieHellman::VerifyErrorGetter(Local<String> property,
3636                                       const PropertyCallbackInfo<Value>& args) {
3637   HandleScope scope(args.GetIsolate());
3638
3639   DiffieHellman* diffieHellman = Unwrap<DiffieHellman>(args.This());
3640
3641   if (!diffieHellman->initialised_)
3642     return diffieHellman->env()->ThrowError("Not initialized");
3643
3644   args.GetReturnValue().Set(diffieHellman->verifyError_);
3645 }
3646
3647
3648 bool DiffieHellman::VerifyContext() {
3649   int codes;
3650   if (!DH_check(dh, &codes))
3651     return false;
3652   verifyError_ = codes;
3653   return true;
3654 }
3655
3656
3657 class PBKDF2Request : public AsyncWrap {
3658  public:
3659   PBKDF2Request(Environment* env,
3660                 Local<Object> object,
3661                 const EVP_MD* digest,
3662                 ssize_t passlen,
3663                 char* pass,
3664                 ssize_t saltlen,
3665                 char* salt,
3666                 ssize_t iter,
3667                 ssize_t keylen)
3668       : AsyncWrap(env, object, AsyncWrap::PROVIDER_CRYPTO),
3669         digest_(digest),
3670         error_(0),
3671         passlen_(passlen),
3672         pass_(pass),
3673         saltlen_(saltlen),
3674         salt_(salt),
3675         keylen_(keylen),
3676         key_(static_cast<char*>(malloc(keylen))),
3677         iter_(iter) {
3678     if (key() == NULL)
3679       FatalError("node::PBKDF2Request()", "Out of Memory");
3680   }
3681
3682   ~PBKDF2Request() {
3683     persistent().Reset();
3684   }
3685
3686   uv_work_t* work_req() {
3687     return &work_req_;
3688   }
3689
3690   inline const EVP_MD* digest() const {
3691     return digest_;
3692   }
3693
3694   inline ssize_t passlen() const {
3695     return passlen_;
3696   }
3697
3698   inline char* pass() const {
3699     return pass_;
3700   }
3701
3702   inline ssize_t saltlen() const {
3703     return saltlen_;
3704   }
3705
3706   inline char* salt() const {
3707     return salt_;
3708   }
3709
3710   inline ssize_t keylen() const {
3711     return keylen_;
3712   }
3713
3714   inline char* key() const {
3715     return key_;
3716   }
3717
3718   inline ssize_t iter() const {
3719     return iter_;
3720   }
3721
3722   inline void release() {
3723     free(pass_);
3724     passlen_ = 0;
3725     free(salt_);
3726     saltlen_ = 0;
3727     free(key_);
3728     keylen_ = 0;
3729   }
3730
3731   inline int error() const {
3732     return error_;
3733   }
3734
3735   inline void set_error(int err) {
3736     error_ = err;
3737   }
3738
3739   // TODO(trevnorris): Make private and make work with CONTAINER_OF macro.
3740   uv_work_t work_req_;
3741
3742  private:
3743   const EVP_MD* digest_;
3744   int error_;
3745   ssize_t passlen_;
3746   char* pass_;
3747   ssize_t saltlen_;
3748   char* salt_;
3749   ssize_t keylen_;
3750   char* key_;
3751   ssize_t iter_;
3752 };
3753
3754
3755 void EIO_PBKDF2(PBKDF2Request* req) {
3756   req->set_error(PKCS5_PBKDF2_HMAC(
3757     req->pass(),
3758     req->passlen(),
3759     reinterpret_cast<unsigned char*>(req->salt()),
3760     req->saltlen(),
3761     req->iter(),
3762     req->digest(),
3763     req->keylen(),
3764     reinterpret_cast<unsigned char*>(req->key())));
3765   memset(req->pass(), 0, req->passlen());
3766   memset(req->salt(), 0, req->saltlen());
3767 }
3768
3769
3770 void EIO_PBKDF2(uv_work_t* work_req) {
3771   PBKDF2Request* req = CONTAINER_OF(work_req, PBKDF2Request, work_req_);
3772   EIO_PBKDF2(req);
3773 }
3774
3775
3776 void EIO_PBKDF2After(PBKDF2Request* req, Local<Value> argv[2]) {
3777   if (req->error()) {
3778     argv[0] = Undefined(req->env()->isolate());
3779     argv[1] = Encode(req->env()->isolate(), req->key(), req->keylen(), BUFFER);
3780     memset(req->key(), 0, req->keylen());
3781   } else {
3782     argv[0] = Exception::Error(req->env()->pbkdf2_error_string());
3783     argv[1] = Undefined(req->env()->isolate());
3784   }
3785 }
3786
3787
3788 void EIO_PBKDF2After(uv_work_t* work_req, int status) {
3789   assert(status == 0);
3790   PBKDF2Request* req = CONTAINER_OF(work_req, PBKDF2Request, work_req_);
3791   Environment* env = req->env();
3792   HandleScope handle_scope(env->isolate());
3793   Context::Scope context_scope(env->context());
3794   Local<Value> argv[2];
3795   EIO_PBKDF2After(req, argv);
3796   req->MakeCallback(env->ondone_string(), ARRAY_SIZE(argv), argv);
3797   req->release();
3798   delete req;
3799 }
3800
3801
3802 void PBKDF2(const FunctionCallbackInfo<Value>& args) {
3803   Environment* env = Environment::GetCurrent(args.GetIsolate());
3804   HandleScope scope(env->isolate());
3805
3806   const EVP_MD* digest = NULL;
3807   const char* type_error = NULL;
3808   char* pass = NULL;
3809   char* salt = NULL;
3810   ssize_t passlen = -1;
3811   ssize_t saltlen = -1;
3812   ssize_t keylen = -1;
3813   ssize_t pass_written = -1;
3814   ssize_t salt_written = -1;
3815   ssize_t iter = -1;
3816   PBKDF2Request* req = NULL;
3817   Local<Object> obj;
3818
3819   if (args.Length() != 5 && args.Length() != 6) {
3820     type_error = "Bad parameter";
3821     goto err;
3822   }
3823
3824   ASSERT_IS_BUFFER(args[0]);
3825   passlen = Buffer::Length(args[0]);
3826   if (passlen < 0) {
3827     type_error = "Bad password";
3828     goto err;
3829   }
3830
3831   pass = static_cast<char*>(malloc(passlen));
3832   if (pass == NULL) {
3833     FatalError("node::PBKDF2()", "Out of Memory");
3834   }
3835   pass_written = DecodeWrite(env->isolate(), pass, passlen, args[0], BINARY);
3836   assert(pass_written == passlen);
3837
3838   ASSERT_IS_BUFFER(args[1]);
3839   saltlen = Buffer::Length(args[1]);
3840   if (saltlen < 0) {
3841     type_error = "Bad salt";
3842     goto err;
3843   }
3844
3845   salt = static_cast<char*>(malloc(saltlen));
3846   if (salt == NULL) {
3847     FatalError("node::PBKDF2()", "Out of Memory");
3848   }
3849   salt_written = DecodeWrite(env->isolate(), salt, saltlen, args[1], BINARY);
3850   assert(salt_written == saltlen);
3851
3852   if (!args[2]->IsNumber()) {
3853     type_error = "Iterations not a number";
3854     goto err;
3855   }
3856
3857   iter = args[2]->Int32Value();
3858   if (iter < 0) {
3859     type_error = "Bad iterations";
3860     goto err;
3861   }
3862
3863   if (!args[3]->IsNumber()) {
3864     type_error = "Key length not a number";
3865     goto err;
3866   }
3867
3868   keylen = args[3]->Int32Value();
3869   if (keylen < 0) {
3870     type_error = "Bad key length";
3871     goto err;
3872   }
3873
3874   if (args[4]->IsString()) {
3875     String::Utf8Value digest_name(args[4]);
3876     digest = EVP_get_digestbyname(*digest_name);
3877     if (digest == NULL) {
3878       type_error = "Bad digest name";
3879       goto err;
3880     }
3881   }
3882
3883   if (digest == NULL) {
3884     digest = EVP_sha1();
3885   }
3886
3887   obj = Object::New(env->isolate());
3888   req = new PBKDF2Request(env,
3889                           obj,
3890                           digest,
3891                           passlen,
3892                           pass,
3893                           saltlen,
3894                           salt,
3895                           iter,
3896                           keylen);
3897
3898   if (args[5]->IsFunction()) {
3899     obj->Set(env->ondone_string(), args[5]);
3900     // XXX(trevnorris): This will need to go with the rest of domains.
3901     if (env->in_domain())
3902       obj->Set(env->domain_string(), env->domain_array()->Get(0));
3903     uv_queue_work(env->event_loop(),
3904                   req->work_req(),
3905                   EIO_PBKDF2,
3906                   EIO_PBKDF2After);
3907   } else {
3908     Local<Value> argv[2];
3909     EIO_PBKDF2(req);
3910     EIO_PBKDF2After(req, argv);
3911     if (argv[0]->IsObject())
3912       env->isolate()->ThrowException(argv[0]);
3913     else
3914       args.GetReturnValue().Set(argv[1]);
3915   }
3916   return;
3917
3918  err:
3919   free(salt);
3920   free(pass);
3921   return env->ThrowTypeError(type_error);
3922 }
3923
3924
3925 // Only instantiate within a valid HandleScope.
3926 class RandomBytesRequest : public AsyncWrap {
3927  public:
3928   RandomBytesRequest(Environment* env, Local<Object> object, size_t size)
3929       : AsyncWrap(env, object, AsyncWrap::PROVIDER_CRYPTO),
3930         error_(0),
3931         size_(size),
3932         data_(static_cast<char*>(malloc(size))) {
3933     if (data() == NULL)
3934       FatalError("node::RandomBytesRequest()", "Out of Memory");
3935   }
3936
3937   ~RandomBytesRequest() {
3938     persistent().Reset();
3939   }
3940
3941   uv_work_t* work_req() {
3942     return &work_req_;
3943   }
3944
3945   inline size_t size() const {
3946     return size_;
3947   }
3948
3949   inline char* data() const {
3950     return data_;
3951   }
3952
3953   inline void release() {
3954     free(data_);
3955     size_ = 0;
3956   }
3957
3958   inline void return_memory(char** d, size_t* len) {
3959     *d = data_;
3960     data_ = NULL;
3961     *len = size_;
3962     size_ = 0;
3963   }
3964
3965   inline unsigned long error() const {
3966     return error_;
3967   }
3968
3969   inline void set_error(unsigned long err) {
3970     error_ = err;
3971   }
3972
3973   // TODO(trevnorris): Make private and make work with CONTAINER_OF macro.
3974   uv_work_t work_req_;
3975
3976  private:
3977   unsigned long error_;
3978   size_t size_;
3979   char* data_;
3980 };
3981
3982
3983 template <bool pseudoRandom>
3984 void RandomBytesWork(uv_work_t* work_req) {
3985   RandomBytesRequest* req = CONTAINER_OF(work_req,
3986                                          RandomBytesRequest,
3987                                          work_req_);
3988   int r;
3989
3990   if (pseudoRandom == true) {
3991     r = RAND_pseudo_bytes(reinterpret_cast<unsigned char*>(req->data()),
3992                           req->size());
3993   } else {
3994     r = RAND_bytes(reinterpret_cast<unsigned char*>(req->data()), req->size());
3995   }
3996
3997   // RAND_bytes() returns 0 on error. RAND_pseudo_bytes() returns 0 when the
3998   // result is not cryptographically strong - but that's not an error.
3999   if (r == 0 && pseudoRandom == false) {
4000     req->set_error(ERR_get_error());
4001   } else if (r == -1) {
4002     req->set_error(static_cast<unsigned long>(-1));
4003   }
4004 }
4005
4006
4007 // don't call this function without a valid HandleScope
4008 void RandomBytesCheck(RandomBytesRequest* req, Local<Value> argv[2]) {
4009   if (req->error()) {
4010     char errmsg[256] = "Operation not supported";
4011
4012     if (req->error() != static_cast<unsigned long>(-1))
4013       ERR_error_string_n(req->error(), errmsg, sizeof errmsg);
4014
4015     argv[0] = Exception::Error(OneByteString(req->env()->isolate(), errmsg));
4016     argv[1] = Null(req->env()->isolate());
4017     req->release();
4018   } else {
4019     char* data = NULL;
4020     size_t size;
4021     req->return_memory(&data, &size);
4022     argv[0] = Null(req->env()->isolate());
4023     argv[1] = Buffer::Use(data, size);
4024   }
4025 }
4026
4027
4028 void RandomBytesAfter(uv_work_t* work_req, int status) {
4029   assert(status == 0);
4030   RandomBytesRequest* req = CONTAINER_OF(work_req,
4031                                          RandomBytesRequest,
4032                                          work_req_);
4033   Environment* env = req->env();
4034   HandleScope handle_scope(env->isolate());
4035   Context::Scope context_scope(env->context());
4036   Local<Value> argv[2];
4037   RandomBytesCheck(req, argv);
4038   req->MakeCallback(env->ondone_string(), ARRAY_SIZE(argv), argv);
4039   delete req;
4040 }
4041
4042
4043 template <bool pseudoRandom>
4044 void RandomBytes(const FunctionCallbackInfo<Value>& args) {
4045   HandleScope handle_scope(args.GetIsolate());
4046   Environment* env = Environment::GetCurrent(args.GetIsolate());
4047
4048   // maybe allow a buffer to write to? cuts down on object creation
4049   // when generating random data in a loop
4050   if (!args[0]->IsUint32()) {
4051     return env->ThrowTypeError("Argument #1 must be number > 0");
4052   }
4053
4054   const uint32_t size = args[0]->Uint32Value();
4055   if (size > Buffer::kMaxLength) {
4056     return env->ThrowTypeError("size > Buffer::kMaxLength");
4057   }
4058
4059   Local<Object> obj = Object::New(env->isolate());
4060   RandomBytesRequest* req = new RandomBytesRequest(env, obj, size);
4061
4062   if (args[1]->IsFunction()) {
4063     obj->Set(FIXED_ONE_BYTE_STRING(args.GetIsolate(), "ondone"), args[1]);
4064     // XXX(trevnorris): This will need to go with the rest of domains.
4065     if (env->in_domain())
4066       obj->Set(env->domain_string(), env->domain_array()->Get(0));
4067     uv_queue_work(env->event_loop(),
4068                   req->work_req(),
4069                   RandomBytesWork<pseudoRandom>,
4070                   RandomBytesAfter);
4071     args.GetReturnValue().Set(obj);
4072   } else {
4073     Local<Value> argv[2];
4074     RandomBytesWork<pseudoRandom>(req->work_req());
4075     RandomBytesCheck(req, argv);
4076     delete req;
4077
4078     if (!argv[0]->IsNull())
4079       env->isolate()->ThrowException(argv[0]);
4080     else
4081       args.GetReturnValue().Set(argv[1]);
4082   }
4083 }
4084
4085
4086 void GetSSLCiphers(const FunctionCallbackInfo<Value>& args) {
4087   Environment* env = Environment::GetCurrent(args.GetIsolate());
4088   HandleScope scope(env->isolate());
4089
4090   SSL_CTX* ctx = SSL_CTX_new(TLSv1_server_method());
4091   if (ctx == NULL) {
4092     return env->ThrowError("SSL_CTX_new() failed.");
4093   }
4094
4095   SSL* ssl = SSL_new(ctx);
4096   if (ssl == NULL) {
4097     SSL_CTX_free(ctx);
4098     return env->ThrowError("SSL_new() failed.");
4099   }
4100
4101   Local<Array> arr = Array::New(env->isolate());
4102   STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl);
4103
4104   for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
4105     SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
4106     arr->Set(i, OneByteString(args.GetIsolate(), SSL_CIPHER_get_name(cipher)));
4107   }
4108
4109   SSL_free(ssl);
4110   SSL_CTX_free(ctx);
4111
4112   args.GetReturnValue().Set(arr);
4113 }
4114
4115
4116 class CipherPushContext {
4117  public:
4118   explicit CipherPushContext(Environment* env)
4119       : arr(Array::New(env->isolate())),
4120         env_(env) {
4121   }
4122
4123   inline Environment* env() const { return env_; }
4124
4125   Local<Array> arr;
4126
4127  private:
4128   Environment* env_;
4129 };
4130
4131
4132 template <class TypeName>
4133 static void array_push_back(const TypeName* md,
4134                             const char* from,
4135                             const char* to,
4136                             void* arg) {
4137   CipherPushContext* ctx = static_cast<CipherPushContext*>(arg);
4138   ctx->arr->Set(ctx->arr->Length(), OneByteString(ctx->env()->isolate(), from));
4139 }
4140
4141
4142 void GetCiphers(const FunctionCallbackInfo<Value>& args) {
4143   Environment* env = Environment::GetCurrent(args.GetIsolate());
4144   HandleScope scope(env->isolate());
4145   CipherPushContext ctx(env);
4146   EVP_CIPHER_do_all_sorted(array_push_back<EVP_CIPHER>, &ctx);
4147   args.GetReturnValue().Set(ctx.arr);
4148 }
4149
4150
4151 void GetHashes(const FunctionCallbackInfo<Value>& args) {
4152   Environment* env = Environment::GetCurrent(args.GetIsolate());
4153   HandleScope scope(env->isolate());
4154   CipherPushContext ctx(env);
4155   EVP_MD_do_all_sorted(array_push_back<EVP_MD>, &ctx);
4156   args.GetReturnValue().Set(ctx.arr);
4157 }
4158
4159
4160 void Certificate::Initialize(Environment* env, Handle<Object> target) {
4161   HandleScope scope(env->isolate());
4162
4163   Local<FunctionTemplate> t = FunctionTemplate::New(env->isolate(), New);
4164
4165   t->InstanceTemplate()->SetInternalFieldCount(1);
4166
4167   NODE_SET_PROTOTYPE_METHOD(t, "verifySpkac", VerifySpkac);
4168   NODE_SET_PROTOTYPE_METHOD(t, "exportPublicKey", ExportPublicKey);
4169   NODE_SET_PROTOTYPE_METHOD(t, "exportChallenge", ExportChallenge);
4170
4171   target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Certificate"),
4172               t->GetFunction());
4173 }
4174
4175
4176 void Certificate::New(const FunctionCallbackInfo<Value>& args) {
4177   HandleScope handle_scope(args.GetIsolate());
4178   Environment* env = Environment::GetCurrent(args.GetIsolate());
4179   new Certificate(env, args.This());
4180 }
4181
4182
4183 bool Certificate::VerifySpkac(const char* data, unsigned int len) {
4184   bool i = 0;
4185   EVP_PKEY* pkey = NULL;
4186   NETSCAPE_SPKI* spki = NULL;
4187
4188   spki = NETSCAPE_SPKI_b64_decode(data, len);
4189   if (spki == NULL)
4190     goto exit;
4191
4192   pkey = X509_PUBKEY_get(spki->spkac->pubkey);
4193   if (pkey == NULL)
4194     goto exit;
4195
4196   i = NETSCAPE_SPKI_verify(spki, pkey) > 0;
4197
4198  exit:
4199   if (pkey != NULL)
4200     EVP_PKEY_free(pkey);
4201
4202   if (spki != NULL)
4203     NETSCAPE_SPKI_free(spki);
4204
4205   return i;
4206 }
4207
4208
4209 void Certificate::VerifySpkac(const FunctionCallbackInfo<Value>& args) {
4210   HandleScope scope(args.GetIsolate());
4211
4212   Certificate* certificate = Unwrap<Certificate>(args.This());
4213   Environment* env = certificate->env();
4214   bool i = false;
4215
4216   if (args.Length() < 1)
4217     return env->ThrowTypeError("Missing argument");
4218
4219   ASSERT_IS_BUFFER(args[0]);
4220
4221   size_t length = Buffer::Length(args[0]);
4222   if (length == 0)
4223     return args.GetReturnValue().Set(i);
4224
4225   char* data = Buffer::Data(args[0]);
4226   assert(data != NULL);
4227
4228   i = certificate->VerifySpkac(data, length) > 0;
4229
4230   args.GetReturnValue().Set(i);
4231 }
4232
4233
4234 const char* Certificate::ExportPublicKey(const char* data, int len) {
4235   char* buf = NULL;
4236   EVP_PKEY* pkey = NULL;
4237   NETSCAPE_SPKI* spki = NULL;
4238
4239   BIO* bio = BIO_new(BIO_s_mem());
4240   if (bio == NULL)
4241     goto exit;
4242
4243   spki = NETSCAPE_SPKI_b64_decode(data, len);
4244   if (spki == NULL)
4245     goto exit;
4246
4247   pkey = NETSCAPE_SPKI_get_pubkey(spki);
4248   if (pkey == NULL)
4249     goto exit;
4250
4251   if (PEM_write_bio_PUBKEY(bio, pkey) <= 0)
4252     goto exit;
4253
4254   BIO_write(bio, "\0", 1);
4255   BUF_MEM* ptr;
4256   BIO_get_mem_ptr(bio, &ptr);
4257
4258   buf = new char[ptr->length];
4259   memcpy(buf, ptr->data, ptr->length);
4260
4261  exit:
4262   if (pkey != NULL)
4263     EVP_PKEY_free(pkey);
4264
4265   if (spki != NULL)
4266     NETSCAPE_SPKI_free(spki);
4267
4268   if (bio != NULL)
4269     BIO_free_all(bio);
4270
4271   return buf;
4272 }
4273
4274
4275 void Certificate::ExportPublicKey(const FunctionCallbackInfo<Value>& args) {
4276   Environment* env = Environment::GetCurrent(args.GetIsolate());
4277   HandleScope scope(env->isolate());
4278
4279   Certificate* certificate = Unwrap<Certificate>(args.This());
4280
4281   if (args.Length() < 1)
4282     return env->ThrowTypeError("Missing argument");
4283
4284   ASSERT_IS_BUFFER(args[0]);
4285
4286   size_t length = Buffer::Length(args[0]);
4287   if (length == 0)
4288     return args.GetReturnValue().SetEmptyString();
4289
4290   char* data = Buffer::Data(args[0]);
4291   assert(data != NULL);
4292
4293   const char* pkey = certificate->ExportPublicKey(data, length);
4294   if (pkey == NULL)
4295     return args.GetReturnValue().SetEmptyString();
4296
4297   Local<Value> out = Encode(env->isolate(), pkey, strlen(pkey), BUFFER);
4298
4299   delete[] pkey;
4300
4301   args.GetReturnValue().Set(out);
4302 }
4303
4304
4305 const char* Certificate::ExportChallenge(const char* data, int len) {
4306   NETSCAPE_SPKI* sp = NULL;
4307
4308   sp = NETSCAPE_SPKI_b64_decode(data, len);
4309   if (sp == NULL)
4310     return NULL;
4311
4312   const char* buf = NULL;
4313   buf = reinterpret_cast<const char*>(ASN1_STRING_data(sp->spkac->challenge));
4314
4315   return buf;
4316 }
4317
4318
4319 void Certificate::ExportChallenge(const FunctionCallbackInfo<Value>& args) {
4320   Environment* env = Environment::GetCurrent(args.GetIsolate());
4321   HandleScope scope(env->isolate());
4322
4323   Certificate* crt = Unwrap<Certificate>(args.This());
4324
4325   if (args.Length() < 1)
4326     return env->ThrowTypeError("Missing argument");
4327
4328   ASSERT_IS_BUFFER(args[0]);
4329
4330   size_t len = Buffer::Length(args[0]);
4331   if (len == 0)
4332     return args.GetReturnValue().SetEmptyString();
4333
4334   char* data = Buffer::Data(args[0]);
4335   assert(data != NULL);
4336
4337   const char* cert = crt->ExportChallenge(data, len);
4338   if (cert == NULL)
4339     return args.GetReturnValue().SetEmptyString();
4340
4341   Local<Value> outString = Encode(env->isolate(), cert, strlen(cert), BUFFER);
4342
4343   delete[] cert;
4344
4345   args.GetReturnValue().Set(outString);
4346 }
4347
4348
4349 void InitCryptoOnce() {
4350   SSL_library_init();
4351   OpenSSL_add_all_algorithms();
4352   SSL_load_error_strings();
4353
4354   crypto_lock_init();
4355   CRYPTO_set_locking_callback(crypto_lock_cb);
4356   CRYPTO_THREADID_set_callback(crypto_threadid_cb);
4357
4358   // Turn off compression. Saves memory and protects against CRIME attacks.
4359 #if !defined(OPENSSL_NO_COMP)
4360 #if OPENSSL_VERSION_NUMBER < 0x00908000L
4361   STACK_OF(SSL_COMP)* comp_methods = SSL_COMP_get_compression_method();
4362 #else
4363   STACK_OF(SSL_COMP)* comp_methods = SSL_COMP_get_compression_methods();
4364 #endif
4365   sk_SSL_COMP_zero(comp_methods);
4366   assert(sk_SSL_COMP_num(comp_methods) == 0);
4367 #endif
4368
4369 #ifndef OPENSSL_NO_ENGINE
4370   ERR_load_ENGINE_strings();
4371   ENGINE_load_builtin_engines();
4372 #endif  // !OPENSSL_NO_ENGINE
4373 }
4374
4375
4376 #ifndef OPENSSL_NO_ENGINE
4377 void SetEngine(const FunctionCallbackInfo<Value>& args) {
4378   Environment* env = Environment::GetCurrent(args.GetIsolate());
4379   CHECK(args.Length() >= 2 && args[0]->IsString());
4380   unsigned int flags = args[1]->Uint32Value();
4381
4382   ClearErrorOnReturn clear_error_on_return;
4383   (void) &clear_error_on_return;  // Silence compiler warning.
4384
4385   const String::Utf8Value engine_id(args[0]);
4386   ENGINE* engine = ENGINE_by_id(*engine_id);
4387
4388   // Engine not found, try loading dynamically
4389   if (engine == NULL) {
4390     engine = ENGINE_by_id("dynamic");
4391     if (engine != NULL) {
4392       if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", *engine_id, 0) ||
4393           !ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0)) {
4394         ENGINE_free(engine);
4395         engine = NULL;
4396       }
4397     }
4398   }
4399
4400   if (engine == NULL) {
4401     int err = ERR_get_error();
4402     if (err == 0) {
4403       char tmp[1024];
4404       snprintf(tmp, sizeof(tmp), "Engine \"%s\" was not found", *engine_id);
4405       return env->ThrowError(tmp);
4406     } else {
4407       return ThrowCryptoError(env, err);
4408     }
4409   }
4410
4411   int r = ENGINE_set_default(engine, flags);
4412   ENGINE_free(engine);
4413   if (r == 0)
4414     return ThrowCryptoError(env, ERR_get_error());
4415 }
4416 #endif  // !OPENSSL_NO_ENGINE
4417
4418
4419 // FIXME(bnoordhuis) Handle global init correctly.
4420 void InitCrypto(Handle<Object> target,
4421                 Handle<Value> unused,
4422                 Handle<Context> context,
4423                 void* priv) {
4424   static uv_once_t init_once = UV_ONCE_INIT;
4425   uv_once(&init_once, InitCryptoOnce);
4426
4427   Environment* env = Environment::GetCurrent(context);
4428   SecureContext::Initialize(env, target);
4429   Connection::Initialize(env, target);
4430   CipherBase::Initialize(env, target);
4431   DiffieHellman::Initialize(env, target);
4432   Hmac::Initialize(env, target);
4433   Hash::Initialize(env, target);
4434   Sign::Initialize(env, target);
4435   Verify::Initialize(env, target);
4436   Certificate::Initialize(env, target);
4437
4438 #ifndef OPENSSL_NO_ENGINE
4439   NODE_SET_METHOD(target, "setEngine", SetEngine);
4440 #endif  // !OPENSSL_NO_ENGINE
4441   NODE_SET_METHOD(target, "PBKDF2", PBKDF2);
4442   NODE_SET_METHOD(target, "randomBytes", RandomBytes<false>);
4443   NODE_SET_METHOD(target, "pseudoRandomBytes", RandomBytes<true>);
4444   NODE_SET_METHOD(target, "getSSLCiphers", GetSSLCiphers);
4445   NODE_SET_METHOD(target, "getCiphers", GetCiphers);
4446   NODE_SET_METHOD(target, "getHashes", GetHashes);
4447 }
4448
4449 }  // namespace crypto
4450 }  // namespace node
4451
4452 NODE_MODULE_CONTEXT_AWARE_BUILTIN(crypto, node::crypto::InitCrypto)