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