Merge remote-tracking branch 'ry/v0.10'
[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_crypto.h"
23 #include "node_crypto_groups.h"
24 #include "v8.h"
25
26 #include "node.h"
27 #include "node_buffer.h"
28 #include "node_root_certs.h"
29
30 #include <string.h>
31 #ifdef _MSC_VER
32 #define strcasecmp _stricmp
33 #endif
34
35 #include <stdlib.h>
36 #include <errno.h>
37
38 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
39 # define OPENSSL_CONST const
40 #else
41 # define OPENSSL_CONST
42 #endif
43
44 #define ASSERT_IS_BUFFER(val) \
45   if (!Buffer::HasInstance(val)) { \
46     return ThrowException(Exception::TypeError(String::New("Not a buffer"))); \
47   }
48
49 static const char PUBLIC_KEY_PFX[] =  "-----BEGIN PUBLIC KEY-----";
50 static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
51 static const char PUBRSA_KEY_PFX[] =  "-----BEGIN RSA PUBLIC KEY-----";
52 static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
53 static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
54                                  | ASN1_STRFLGS_ESC_MSB
55                                  | XN_FLAG_SEP_MULTILINE
56                                  | XN_FLAG_FN_SN;
57
58 namespace node {
59 namespace crypto {
60
61 using namespace v8;
62
63 static Persistent<String> errno_symbol;
64 static Persistent<String> syscall_symbol;
65 static Persistent<String> subject_symbol;
66 static Persistent<String> subjectaltname_symbol;
67 static Persistent<String> modulus_symbol;
68 static Persistent<String> exponent_symbol;
69 static Persistent<String> issuer_symbol;
70 static Persistent<String> valid_from_symbol;
71 static Persistent<String> valid_to_symbol;
72 static Persistent<String> fingerprint_symbol;
73 static Persistent<String> name_symbol;
74 static Persistent<String> version_symbol;
75 static Persistent<String> ext_key_usage_symbol;
76 static Persistent<String> onhandshakestart_sym;
77 static Persistent<String> onhandshakedone_sym;
78 static Persistent<String> onclienthello_sym;
79 static Persistent<String> onnewsession_sym;
80 static Persistent<String> sessionid_sym;
81
82 static Persistent<FunctionTemplate> secure_context_constructor;
83
84 static uv_rwlock_t* locks;
85
86
87 static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
88   CRYPTO_THREADID_set_numeric(tid, uv_thread_self());
89 }
90
91
92 static void crypto_lock_init(void) {
93   int i, n;
94
95   n = CRYPTO_num_locks();
96   locks = new uv_rwlock_t[n];
97
98   for (i = 0; i < n; i++)
99     if (uv_rwlock_init(locks + i))
100       abort();
101 }
102
103
104 static void crypto_lock_cb(int mode, int n, const char* file, int line) {
105   assert((mode & CRYPTO_LOCK) || (mode & CRYPTO_UNLOCK));
106   assert((mode & CRYPTO_READ) || (mode & CRYPTO_WRITE));
107
108   if (mode & CRYPTO_LOCK) {
109     if (mode & CRYPTO_READ)
110       uv_rwlock_rdlock(locks + n);
111     else
112       uv_rwlock_wrlock(locks + n);
113   } else {
114     if (mode & CRYPTO_READ)
115       uv_rwlock_rdunlock(locks + n);
116     else
117       uv_rwlock_wrunlock(locks + n);
118   }
119 }
120
121
122 Handle<Value> ThrowCryptoErrorHelper(unsigned long err, bool is_type_error) {
123   HandleScope scope(node_isolate);
124   char errmsg[128];
125   ERR_error_string_n(err, errmsg, sizeof(errmsg));
126   return is_type_error ? ThrowTypeError(errmsg) : ThrowError(errmsg);
127 }
128
129
130 Handle<Value> ThrowCryptoError(unsigned long err) {
131   return ThrowCryptoErrorHelper(err, false);
132 }
133
134
135 Handle<Value> ThrowCryptoTypeError(unsigned long err) {
136   return ThrowCryptoErrorHelper(err, true);
137 }
138
139
140 void SecureContext::Initialize(Handle<Object> target) {
141   HandleScope scope(node_isolate);
142
143   Local<FunctionTemplate> t = FunctionTemplate::New(SecureContext::New);
144   secure_context_constructor = Persistent<FunctionTemplate>::New(node_isolate,
145                                                                  t);
146
147   t->InstanceTemplate()->SetInternalFieldCount(1);
148   t->SetClassName(String::NewSymbol("SecureContext"));
149
150   NODE_SET_PROTOTYPE_METHOD(t, "init", SecureContext::Init);
151   NODE_SET_PROTOTYPE_METHOD(t, "setKey", SecureContext::SetKey);
152   NODE_SET_PROTOTYPE_METHOD(t, "setCert", SecureContext::SetCert);
153   NODE_SET_PROTOTYPE_METHOD(t, "addCACert", SecureContext::AddCACert);
154   NODE_SET_PROTOTYPE_METHOD(t, "addCRL", SecureContext::AddCRL);
155   NODE_SET_PROTOTYPE_METHOD(t, "addRootCerts", SecureContext::AddRootCerts);
156   NODE_SET_PROTOTYPE_METHOD(t, "setCiphers", SecureContext::SetCiphers);
157   NODE_SET_PROTOTYPE_METHOD(t, "setOptions", SecureContext::SetOptions);
158   NODE_SET_PROTOTYPE_METHOD(t, "setSessionIdContext",
159                                SecureContext::SetSessionIdContext);
160   NODE_SET_PROTOTYPE_METHOD(t, "setSessionTimeout",
161                                SecureContext::SetSessionTimeout);
162   NODE_SET_PROTOTYPE_METHOD(t, "close", SecureContext::Close);
163   NODE_SET_PROTOTYPE_METHOD(t, "loadPKCS12", SecureContext::LoadPKCS12);
164
165   target->Set(String::NewSymbol("SecureContext"), t->GetFunction());
166 }
167
168
169 Handle<Value> SecureContext::New(const Arguments& args) {
170   HandleScope scope(node_isolate);
171   SecureContext *p = new SecureContext();
172   p->Wrap(args.Holder());
173   return args.This();
174 }
175
176
177 Handle<Value> SecureContext::Init(const Arguments& args) {
178   HandleScope scope(node_isolate);
179
180   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
181
182   OPENSSL_CONST SSL_METHOD *method = SSLv23_method();
183
184   if (args.Length() == 1 && args[0]->IsString()) {
185     String::Utf8Value sslmethod(args[0]);
186
187     if (strcmp(*sslmethod, "SSLv2_method") == 0) {
188 #ifndef OPENSSL_NO_SSL2
189       method = SSLv2_method();
190 #else
191       return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
192 #endif
193     } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
194 #ifndef OPENSSL_NO_SSL2
195       method = SSLv2_server_method();
196 #else
197       return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
198 #endif
199     } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
200 #ifndef OPENSSL_NO_SSL2
201       method = SSLv2_client_method();
202 #else
203       return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
204 #endif
205     } else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
206       method = SSLv3_method();
207     } else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
208       method = SSLv3_server_method();
209     } else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
210       method = SSLv3_client_method();
211     } else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
212       method = SSLv23_method();
213     } else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
214       method = SSLv23_server_method();
215     } else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
216       method = SSLv23_client_method();
217     } else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
218       method = TLSv1_method();
219     } else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
220       method = TLSv1_server_method();
221     } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
222       method = TLSv1_client_method();
223     } else {
224       return ThrowException(Exception::Error(String::New("Unknown method")));
225     }
226   }
227
228   sc->ctx_ = SSL_CTX_new(method);
229
230   // SSL session cache configuration
231   SSL_CTX_set_session_cache_mode(sc->ctx_,
232                                  SSL_SESS_CACHE_SERVER |
233                                  SSL_SESS_CACHE_NO_INTERNAL |
234                                  SSL_SESS_CACHE_NO_AUTO_CLEAR);
235   SSL_CTX_sess_set_get_cb(sc->ctx_, GetSessionCallback);
236   SSL_CTX_sess_set_new_cb(sc->ctx_, NewSessionCallback);
237
238   sc->ca_store_ = NULL;
239   return True(node_isolate);
240 }
241
242
243 SSL_SESSION* SecureContext::GetSessionCallback(SSL* s,
244                                                unsigned char* key,
245                                                int len,
246                                                int* copy) {
247   HandleScope scope(node_isolate);
248
249   Connection* p = static_cast<Connection*>(SSL_get_app_data(s));
250
251   *copy = 0;
252   SSL_SESSION* sess = p->next_sess_;
253   p->next_sess_ = NULL;
254
255   return sess;
256 }
257
258
259 void SessionDataFree(char* data, void* hint) {
260   delete[] data;
261 }
262
263
264 int SecureContext::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
265   HandleScope scope(node_isolate);
266
267   Connection* p = static_cast<Connection*>(SSL_get_app_data(s));
268
269   // Check if session is small enough to be stored
270   int size = i2d_SSL_SESSION(sess, NULL);
271   if (size > kMaxSessionSize) return 0;
272
273   // Serialize session
274   char* serialized = new char[size];
275   unsigned char* pserialized = reinterpret_cast<unsigned char*>(serialized);
276   memset(serialized, 0, size);
277   i2d_SSL_SESSION(sess, &pserialized);
278
279   Handle<Value> argv[2] = {
280     Buffer::New(reinterpret_cast<char*>(sess->session_id),
281                 sess->session_id_length)->handle_,
282     Buffer::New(serialized, size, SessionDataFree, NULL)->handle_
283   };
284
285   if (onnewsession_sym.IsEmpty()) {
286     onnewsession_sym = NODE_PSYMBOL("onnewsession");
287   }
288   MakeCallback(p->handle_, onnewsession_sym, ARRAY_SIZE(argv), argv);
289
290   return 0;
291 }
292
293
294 // Takes a string or buffer and loads it into a BIO.
295 // Caller responsible for BIO_free_all-ing the returned object.
296 static BIO* LoadBIO (Handle<Value> v) {
297   BIO *bio = BIO_new(BIO_s_mem());
298   if (!bio) return NULL;
299
300   HandleScope scope(node_isolate);
301
302   int r = -1;
303
304   if (v->IsString()) {
305     String::Utf8Value s(v);
306     r = BIO_write(bio, *s, s.length());
307   } else if (Buffer::HasInstance(v)) {
308     char* buffer_data = Buffer::Data(v);
309     size_t buffer_length = Buffer::Length(v);
310     r = BIO_write(bio, buffer_data, buffer_length);
311   }
312
313   if (r <= 0) {
314     BIO_free_all(bio);
315     return NULL;
316   }
317
318   return bio;
319 }
320
321
322 // Takes a string or buffer and loads it into an X509
323 // Caller responsible for X509_free-ing the returned object.
324 static X509* LoadX509 (Handle<Value> v) {
325   HandleScope scope(node_isolate); // necessary?
326
327   BIO *bio = LoadBIO(v);
328   if (!bio) return NULL;
329
330   X509 * x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
331   if (!x509) {
332     BIO_free_all(bio);
333     return NULL;
334   }
335
336   BIO_free_all(bio);
337   return x509;
338 }
339
340
341 Handle<Value> SecureContext::SetKey(const Arguments& args) {
342   HandleScope scope(node_isolate);
343
344   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
345
346   unsigned int len = args.Length();
347   if (len != 1 && len != 2) {
348     return ThrowException(Exception::TypeError(String::New("Bad parameter")));
349   }
350   if (len == 2 && !args[1]->IsString()) {
351     return ThrowException(Exception::TypeError(String::New("Bad parameter")));
352   }
353
354   BIO *bio = LoadBIO(args[0]);
355   if (!bio) return False(node_isolate);
356
357   String::Utf8Value passphrase(args[1]);
358
359   EVP_PKEY* key = PEM_read_bio_PrivateKey(bio, NULL, NULL,
360                                           len == 1 ? NULL : *passphrase);
361
362   if (!key) {
363     BIO_free_all(bio);
364     unsigned long err = ERR_get_error();
365     if (!err) {
366       return ThrowException(Exception::Error(
367           String::New("PEM_read_bio_PrivateKey")));
368     }
369     return ThrowCryptoError(err);
370   }
371
372   SSL_CTX_use_PrivateKey(sc->ctx_, key);
373   EVP_PKEY_free(key);
374   BIO_free_all(bio);
375
376   return True(node_isolate);
377 }
378
379
380 // Read a file that contains our certificate in "PEM" format,
381 // possibly followed by a sequence of CA certificates that should be
382 // sent to the peer in the Certificate message.
383 //
384 // Taken from OpenSSL - editted for style.
385 int SSL_CTX_use_certificate_chain(SSL_CTX *ctx, BIO *in) {
386   int ret = 0;
387   X509 *x = NULL;
388
389   x = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
390
391   if (x == NULL) {
392     SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
393     goto end;
394   }
395
396   ret = SSL_CTX_use_certificate(ctx, x);
397
398   if (ERR_peek_error() != 0) {
399     // Key/certificate mismatch doesn't imply ret==0 ...
400     ret = 0;
401   }
402
403   if (ret) {
404     // If we could set up our certificate, now proceed to
405     // the CA certificates.
406     X509 *ca;
407     int r;
408     unsigned long err;
409
410     if (ctx->extra_certs != NULL) {
411       sk_X509_pop_free(ctx->extra_certs, X509_free);
412       ctx->extra_certs = NULL;
413     }
414
415     while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
416       r = SSL_CTX_add_extra_chain_cert(ctx, ca);
417
418       if (!r) {
419         X509_free(ca);
420         ret = 0;
421         goto end;
422       }
423       // Note that we must not free r if it was successfully
424       // added to the chain (while we must free the main
425       // certificate, since its reference count is increased
426       // by SSL_CTX_use_certificate).
427     }
428
429     // When the while loop ends, it's usually just EOF.
430     err = ERR_peek_last_error();
431     if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
432         ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
433       ERR_clear_error();
434     } else  {
435       // some real error
436       ret = 0;
437     }
438   }
439
440 end:
441   if (x != NULL) X509_free(x);
442   return ret;
443 }
444
445
446 Handle<Value> SecureContext::SetCert(const Arguments& args) {
447   HandleScope scope(node_isolate);
448
449   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
450
451   if (args.Length() != 1) {
452     return ThrowException(Exception::TypeError(
453           String::New("Bad parameter")));
454   }
455
456   BIO* bio = LoadBIO(args[0]);
457   if (!bio) return False(node_isolate);
458
459   int rv = SSL_CTX_use_certificate_chain(sc->ctx_, bio);
460
461   BIO_free_all(bio);
462
463   if (!rv) {
464     unsigned long err = ERR_get_error();
465     if (!err) {
466       return ThrowException(Exception::Error(
467           String::New("SSL_CTX_use_certificate_chain")));
468     }
469     return ThrowCryptoError(err);
470   }
471
472   return True(node_isolate);
473 }
474
475
476 Handle<Value> SecureContext::AddCACert(const Arguments& args) {
477   bool newCAStore = false;
478   HandleScope scope(node_isolate);
479
480   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
481
482   if (args.Length() != 1) {
483     return ThrowException(Exception::TypeError(String::New("Bad parameter")));
484   }
485
486   if (!sc->ca_store_) {
487     sc->ca_store_ = X509_STORE_new();
488     newCAStore = true;
489   }
490
491   X509* x509 = LoadX509(args[0]);
492   if (!x509) return False(node_isolate);
493
494   X509_STORE_add_cert(sc->ca_store_, x509);
495   SSL_CTX_add_client_CA(sc->ctx_, x509);
496
497   X509_free(x509);
498
499   if (newCAStore) {
500     SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
501   }
502
503   return True(node_isolate);
504 }
505
506
507 Handle<Value> SecureContext::AddCRL(const Arguments& args) {
508   HandleScope scope(node_isolate);
509
510   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
511
512   if (args.Length() != 1) {
513     return ThrowException(Exception::TypeError(String::New("Bad parameter")));
514   }
515
516   BIO *bio = LoadBIO(args[0]);
517   if (!bio) return False(node_isolate);
518
519   X509_CRL *x509 = PEM_read_bio_X509_CRL(bio, NULL, NULL, NULL);
520
521   if (x509 == NULL) {
522     BIO_free_all(bio);
523     return False(node_isolate);
524   }
525
526   X509_STORE_add_crl(sc->ca_store_, x509);
527
528   X509_STORE_set_flags(sc->ca_store_, X509_V_FLAG_CRL_CHECK |
529                                       X509_V_FLAG_CRL_CHECK_ALL);
530
531   BIO_free_all(bio);
532   X509_CRL_free(x509);
533
534   return True(node_isolate);
535 }
536
537
538
539 Handle<Value> SecureContext::AddRootCerts(const Arguments& args) {
540   HandleScope scope(node_isolate);
541
542   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
543
544   assert(sc->ca_store_ == NULL);
545
546   if (!root_cert_store) {
547     root_cert_store = X509_STORE_new();
548
549     for (int i = 0; root_certs[i]; i++) {
550       BIO *bp = BIO_new(BIO_s_mem());
551
552       if (!BIO_write(bp, root_certs[i], strlen(root_certs[i]))) {
553         BIO_free_all(bp);
554         return False(node_isolate);
555       }
556
557       X509 *x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
558
559       if (x509 == NULL) {
560         BIO_free_all(bp);
561         return False(node_isolate);
562       }
563
564       X509_STORE_add_cert(root_cert_store, x509);
565
566       BIO_free_all(bp);
567       X509_free(x509);
568     }
569   }
570
571   sc->ca_store_ = root_cert_store;
572   SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
573
574   return True(node_isolate);
575 }
576
577
578 Handle<Value> SecureContext::SetCiphers(const Arguments& args) {
579   HandleScope scope(node_isolate);
580
581   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
582
583   if (args.Length() != 1 || !args[0]->IsString()) {
584     return ThrowException(Exception::TypeError(String::New("Bad parameter")));
585   }
586
587   String::Utf8Value ciphers(args[0]);
588   SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
589
590   return True(node_isolate);
591 }
592
593 Handle<Value> SecureContext::SetOptions(const Arguments& args) {
594   HandleScope scope(node_isolate);
595
596   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
597
598   if (args.Length() != 1 || !args[0]->IntegerValue()) {
599     return ThrowException(Exception::TypeError(String::New("Bad parameter")));
600   }
601
602   SSL_CTX_set_options(sc->ctx_, args[0]->IntegerValue());
603
604   return True(node_isolate);
605 }
606
607 Handle<Value> SecureContext::SetSessionIdContext(const Arguments& args) {
608   HandleScope scope(node_isolate);
609
610   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
611
612   if (args.Length() != 1 || !args[0]->IsString()) {
613     return ThrowException(Exception::TypeError(String::New("Bad parameter")));
614   }
615
616   String::Utf8Value sessionIdContext(args[0]);
617   const unsigned char* sid_ctx = (const unsigned char*) *sessionIdContext;
618   unsigned int sid_ctx_len = sessionIdContext.length();
619
620   int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
621   if (r != 1) {
622     Local<String> message;
623     BIO* bio;
624     BUF_MEM* mem;
625     if ((bio = BIO_new(BIO_s_mem()))) {
626       ERR_print_errors(bio);
627       BIO_get_mem_ptr(bio, &mem);
628       message = String::New(mem->data, mem->length);
629       BIO_free_all(bio);
630     } else {
631       message = String::New("SSL_CTX_set_session_id_context error");
632     }
633     return ThrowException(Exception::TypeError(message));
634   }
635
636   return True(node_isolate);
637 }
638
639 Handle<Value> SecureContext::SetSessionTimeout(const Arguments& args) {
640   HandleScope scope;
641
642   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
643
644   if (args.Length() != 1 || !args[0]->IsInt32()) {
645     return ThrowTypeError("Bad parameter");
646   }
647
648   int32_t sessionTimeout = args[0]->Int32Value();
649   SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
650
651   return True();
652 }
653
654 Handle<Value> SecureContext::Close(const Arguments& args) {
655   HandleScope scope(node_isolate);
656   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
657   sc->FreeCTXMem();
658   return False(node_isolate);
659 }
660
661 //Takes .pfx or .p12 and password in string or buffer format
662 Handle<Value> SecureContext::LoadPKCS12(const Arguments& args) {
663   HandleScope scope(node_isolate);
664
665   BIO* in = NULL;
666   PKCS12* p12 = NULL;
667   EVP_PKEY* pkey = NULL;
668   X509* cert = NULL;
669   STACK_OF(X509)* extraCerts = NULL;
670   char* pass = NULL;
671   bool ret = false;
672
673   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.Holder());
674
675   if (args.Length() < 1) {
676     return ThrowException(Exception::TypeError(
677           String::New("Bad parameter")));
678   }
679
680   in = LoadBIO(args[0]);
681   if (in == NULL) {
682     return ThrowException(Exception::Error(
683           String::New("Unable to load BIO")));
684   }
685
686   if (args.Length() >= 2) {
687     ASSERT_IS_BUFFER(args[1]);
688
689     int passlen = Buffer::Length(args[1]);
690     if (passlen < 0) {
691       BIO_free_all(in);
692       return ThrowException(Exception::TypeError(
693             String::New("Bad password")));
694     }
695     pass = new char[passlen + 1];
696     int pass_written = DecodeWrite(pass, passlen, args[1], BINARY);
697
698     assert(pass_written == passlen);
699     pass[passlen] = '\0';
700   }
701
702   if (d2i_PKCS12_bio(in, &p12) &&
703       PKCS12_parse(p12, pass, &pkey, &cert, &extraCerts) &&
704       SSL_CTX_use_certificate(sc->ctx_, cert) &&
705       SSL_CTX_use_PrivateKey(sc->ctx_, pkey))
706   {
707     // set extra certs
708     while (X509* x509 = sk_X509_pop(extraCerts)) {
709       if (!sc->ca_store_) {
710         sc->ca_store_ = X509_STORE_new();
711         SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
712       }
713
714       X509_STORE_add_cert(sc->ca_store_, x509);
715       SSL_CTX_add_client_CA(sc->ctx_, x509);
716     }
717
718     EVP_PKEY_free(pkey);
719     X509_free(cert);
720     sk_X509_free(extraCerts);
721
722     ret = true;
723   }
724
725   PKCS12_free(p12);
726   BIO_free_all(in);
727   delete[] pass;
728
729   if (!ret) {
730     unsigned long err = ERR_get_error();
731     const char* str = ERR_reason_error_string(err);
732     return ThrowException(Exception::Error(String::New(str)));
733   }
734
735   return True(node_isolate);
736 }
737
738
739 size_t ClientHelloParser::Write(const uint8_t* data, size_t len) {
740   HandleScope scope(node_isolate);
741
742   // Just accumulate data, everything will be pushed to BIO later
743   if (state_ == kPaused) return 0;
744
745   // Copy incoming data to the internal buffer
746   // (which has a size of the biggest possible TLS frame)
747   size_t available = sizeof(data_) - offset_;
748   size_t copied = len < available ? len : available;
749   memcpy(data_ + offset_, data, copied);
750   offset_ += copied;
751
752   // Vars for parsing hello
753   bool is_clienthello = false;
754   uint8_t session_size = -1;
755   uint8_t* session_id = NULL;
756   Local<Object> hello;
757   Handle<Value> argv[1];
758
759   switch (state_) {
760    case kWaiting:
761     // >= 5 bytes for header parsing
762     if (offset_ < 5) break;
763
764     if (data_[0] == kChangeCipherSpec || data_[0] == kAlert ||
765         data_[0] == kHandshake || data_[0] == kApplicationData) {
766       frame_len_ = (data_[3] << 8) + data_[4];
767       state_ = kTLSHeader;
768       body_offset_ = 5;
769     } else {
770       frame_len_ = (data_[0] << 8) + data_[1];
771       state_ = kSSLHeader;
772       if (*data_ & 0x40) {
773         // header with padding
774         body_offset_ = 3;
775       } else {
776         // without padding
777         body_offset_ = 2;
778       }
779     }
780
781     // Sanity check (too big frame, or too small)
782     if (frame_len_ >= sizeof(data_)) {
783       // Let OpenSSL handle it
784       Finish();
785       return copied;
786     }
787    case kTLSHeader:
788    case kSSLHeader:
789     // >= 5 + frame size bytes for frame parsing
790     if (offset_ < body_offset_ + frame_len_) break;
791
792     // Skip unsupported frames and gather some data from frame
793
794     // TODO: Check protocol version
795     if (data_[body_offset_] == kClientHello) {
796       is_clienthello = true;
797       uint8_t* body;
798       size_t session_offset;
799
800       if (state_ == kTLSHeader) {
801         // Skip frame header, hello header, protocol version and random data
802         session_offset = body_offset_ + 4 + 2 + 32;
803
804         if (session_offset + 1 < offset_) {
805           body = data_ + session_offset;
806           session_size = *body;
807           session_id = body + 1;
808         }
809       } else if (state_ == kSSLHeader) {
810         // Skip header, version
811         session_offset = body_offset_ + 3;
812
813         if (session_offset + 4 < offset_) {
814           body = data_ + session_offset;
815
816           int ciphers_size = (body[0] << 8) + body[1];
817
818           if (body + 4 + ciphers_size < data_ + offset_) {
819             session_size = (body[2] << 8) + body[3];
820             session_id = body + 4 + ciphers_size;
821           }
822         }
823       } else {
824         // Whoa? How did we get here?
825         abort();
826       }
827
828       // Check if we overflowed (do not reply with any private data)
829       if (session_id == NULL ||
830           session_size > 32 ||
831           session_id + session_size > data_ + offset_) {
832         Finish();
833         return copied;
834       }
835
836       // TODO: Parse other things?
837     }
838
839     // Not client hello - let OpenSSL handle it
840     if (!is_clienthello) {
841       Finish();
842       return copied;
843     }
844
845     // Parse frame, call javascript handler and
846     // move parser into the paused state
847     if (onclienthello_sym.IsEmpty()) {
848       onclienthello_sym = NODE_PSYMBOL("onclienthello");
849     }
850     if (sessionid_sym.IsEmpty()) {
851       sessionid_sym = NODE_PSYMBOL("sessionId");
852     }
853
854     state_ = kPaused;
855     hello = Object::New();
856     hello->Set(sessionid_sym,
857                Buffer::New(reinterpret_cast<char*>(session_id),
858                            session_size)->handle_);
859
860     argv[0] = hello;
861     MakeCallback(conn_->handle_, onclienthello_sym, 1, argv);
862     break;
863    case kEnded:
864    default:
865     break;
866   }
867
868   return copied;
869 }
870
871
872 void ClientHelloParser::Finish() {
873   assert(state_ != kEnded);
874   state_ = kEnded;
875
876   // Write all accumulated data
877   int r = BIO_write(conn_->bio_read_, reinterpret_cast<char*>(data_), offset_);
878   conn_->HandleBIOError(conn_->bio_read_, "BIO_write", r);
879   conn_->SetShutdownFlags();
880 }
881
882
883 #ifdef SSL_PRINT_DEBUG
884 # define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
885 #else
886 # define DEBUG_PRINT(...)
887 #endif
888
889
890 int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
891   if (rv >= 0) return rv;
892
893   int retry = BIO_should_retry(bio);
894   (void) retry; // unused if !defined(SSL_PRINT_DEBUG)
895
896   if (BIO_should_write(bio)) {
897     DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n", ssl_, func, retry);
898     return 0;
899
900   } else if (BIO_should_read(bio)) {
901     DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
902     return 0;
903
904   } else {
905    static char ssl_error_buf[512];
906     ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
907
908     HandleScope scope(node_isolate);
909     Local<Value> e = Exception::Error(String::New(ssl_error_buf));
910     handle_->Set(String::New("error"), e);
911
912     DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n", ssl_, func, rv, ssl_error_buf);
913
914     return rv;
915   }
916
917   return 0;
918 }
919
920
921 int Connection::HandleSSLError(const char* func, int rv, ZeroStatus zs) {
922   // Forcibly clear OpenSSL's error stack on return. This stops stale errors
923   // from popping up later in the lifecycle of the SSL connection where they
924   // would cause spurious failures. It's a rather blunt method, though.
925   // ERR_clear_error() isn't necessarily cheap either.
926   struct ClearErrorOnReturn {
927     ~ClearErrorOnReturn() { ERR_clear_error(); }
928   };
929   ClearErrorOnReturn clear_error_on_return;
930   (void) &clear_error_on_return;  // Silence unused variable warning.
931
932   if (rv > 0) return rv;
933   if ((rv == 0) && (zs == kZeroIsNotAnError)) return rv;
934
935   int err = SSL_get_error(ssl_, rv);
936
937   if (err == SSL_ERROR_NONE) {
938     return 0;
939
940   } else if (err == SSL_ERROR_WANT_WRITE) {
941     DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
942     return 0;
943
944   } else if (err == SSL_ERROR_WANT_READ) {
945     DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
946     return 0;
947
948   } else if (err == SSL_ERROR_ZERO_RETURN) {
949     handle_->Set(String::New("error"),
950                  Exception::Error(String::New("ZERO_RETURN")));
951     return rv;
952
953   } else {
954     HandleScope scope(node_isolate);
955     BUF_MEM* mem;
956     BIO *bio;
957
958     assert(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
959
960     // XXX We need to drain the error queue for this thread or else OpenSSL
961     // has the possibility of blocking connections? This problem is not well
962     // understood. And we should be somehow propagating these errors up
963     // into JavaScript. There is no test which demonstrates this problem.
964     // https://github.com/joyent/node/issues/1719
965     if ((bio = BIO_new(BIO_s_mem()))) {
966       ERR_print_errors(bio);
967       BIO_get_mem_ptr(bio, &mem);
968       Local<Value> e = Exception::Error(String::New(mem->data, mem->length));
969       handle_->Set(String::New("error"), e);
970       BIO_free_all(bio);
971     }
972
973     return rv;
974   }
975
976   return 0;
977 }
978
979
980 void Connection::ClearError() {
981 #ifndef NDEBUG
982   HandleScope scope(node_isolate);
983
984   // We should clear the error in JS-land
985   assert(handle_->Get(String::New("error"))->BooleanValue() == false);
986 #endif // NDEBUG
987 }
988
989
990 void Connection::SetShutdownFlags() {
991   HandleScope scope(node_isolate);
992
993   int flags = SSL_get_shutdown(ssl_);
994
995   if (flags & SSL_SENT_SHUTDOWN) {
996     handle_->Set(String::New("sentShutdown"), True(node_isolate));
997   }
998
999   if (flags & SSL_RECEIVED_SHUTDOWN) {
1000     handle_->Set(String::New("receivedShutdown"), True(node_isolate));
1001   }
1002 }
1003
1004
1005 void Connection::Initialize(Handle<Object> target) {
1006   HandleScope scope(node_isolate);
1007
1008   Local<FunctionTemplate> t = FunctionTemplate::New(Connection::New);
1009   t->InstanceTemplate()->SetInternalFieldCount(1);
1010   t->SetClassName(String::NewSymbol("Connection"));
1011
1012   NODE_SET_PROTOTYPE_METHOD(t, "encIn", Connection::EncIn);
1013   NODE_SET_PROTOTYPE_METHOD(t, "clearOut", Connection::ClearOut);
1014   NODE_SET_PROTOTYPE_METHOD(t, "clearIn", Connection::ClearIn);
1015   NODE_SET_PROTOTYPE_METHOD(t, "encOut", Connection::EncOut);
1016   NODE_SET_PROTOTYPE_METHOD(t, "clearPending", Connection::ClearPending);
1017   NODE_SET_PROTOTYPE_METHOD(t, "encPending", Connection::EncPending);
1018   NODE_SET_PROTOTYPE_METHOD(t, "getPeerCertificate", Connection::GetPeerCertificate);
1019   NODE_SET_PROTOTYPE_METHOD(t, "getSession", Connection::GetSession);
1020   NODE_SET_PROTOTYPE_METHOD(t, "setSession", Connection::SetSession);
1021   NODE_SET_PROTOTYPE_METHOD(t, "loadSession", Connection::LoadSession);
1022   NODE_SET_PROTOTYPE_METHOD(t, "isSessionReused", Connection::IsSessionReused);
1023   NODE_SET_PROTOTYPE_METHOD(t, "isInitFinished", Connection::IsInitFinished);
1024   NODE_SET_PROTOTYPE_METHOD(t, "verifyError", Connection::VerifyError);
1025   NODE_SET_PROTOTYPE_METHOD(t, "getCurrentCipher", Connection::GetCurrentCipher);
1026   NODE_SET_PROTOTYPE_METHOD(t, "start", Connection::Start);
1027   NODE_SET_PROTOTYPE_METHOD(t, "shutdown", Connection::Shutdown);
1028   NODE_SET_PROTOTYPE_METHOD(t, "receivedShutdown", Connection::ReceivedShutdown);
1029   NODE_SET_PROTOTYPE_METHOD(t, "close", Connection::Close);
1030
1031 #ifdef OPENSSL_NPN_NEGOTIATED
1032   NODE_SET_PROTOTYPE_METHOD(t, "getNegotiatedProtocol", Connection::GetNegotiatedProto);
1033   NODE_SET_PROTOTYPE_METHOD(t, "setNPNProtocols", Connection::SetNPNProtocols);
1034 #endif
1035
1036
1037 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1038   NODE_SET_PROTOTYPE_METHOD(t, "getServername", Connection::GetServername);
1039   NODE_SET_PROTOTYPE_METHOD(t, "setSNICallback",  Connection::SetSNICallback);
1040 #endif
1041
1042   target->Set(String::NewSymbol("Connection"), t->GetFunction());
1043 }
1044
1045
1046 static int VerifyCallback(int preverify_ok, X509_STORE_CTX *ctx) {
1047   // Quoting SSL_set_verify(3ssl):
1048   //
1049   //   The VerifyCallback function is used to control the behaviour when
1050   //   the SSL_VERIFY_PEER flag is set. It must be supplied by the
1051   //   application and receives two arguments: preverify_ok indicates,
1052   //   whether the verification of the certificate in question was passed
1053   //   (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to
1054   //   the complete context used for the certificate chain verification.
1055   //
1056   //   The certificate chain is checked starting with the deepest nesting
1057   //   level (the root CA certificate) and worked upward to the peer's
1058   //   certificate.  At each level signatures and issuer attributes are
1059   //   checked.  Whenever a verification error is found, the error number is
1060   //   stored in x509_ctx and VerifyCallback is called with preverify_ok=0.
1061   //   By applying X509_CTX_store_* functions VerifyCallback can locate the
1062   //   certificate in question and perform additional steps (see EXAMPLES).
1063   //   If no error is found for a certificate, VerifyCallback is called
1064   //   with preverify_ok=1 before advancing to the next level.
1065   //
1066   //   The return value of VerifyCallback controls the strategy of the
1067   //   further verification process. If VerifyCallback returns 0, the
1068   //   verification process is immediately stopped with "verification
1069   //   failed" state. If SSL_VERIFY_PEER is set, a verification failure
1070   //   alert is sent to the peer and the TLS/SSL handshake is terminated. If
1071   //   VerifyCallback returns 1, the verification process is continued. If
1072   //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
1073   //   terminated with respect to verification failures and the connection
1074   //   will be established. The calling process can however retrieve the
1075   //   error code of the last verification error using
1076   //   SSL_get_verify_result(3) or by maintaining its own error storage
1077   //   managed by VerifyCallback.
1078   //
1079   //   If no VerifyCallback is specified, the default callback will be
1080   //   used.  Its return value is identical to preverify_ok, so that any
1081   //   verification failure will lead to a termination of the TLS/SSL
1082   //   handshake with an alert message, if SSL_VERIFY_PEER is set.
1083   //
1084   // Since we cannot perform I/O quickly enough in this callback, we ignore
1085   // all preverify_ok errors and let the handshake continue. It is
1086   // imparative that the user use Connection::VerifyError after the
1087   // 'secure' callback has been made.
1088   return 1;
1089 }
1090
1091 #ifdef OPENSSL_NPN_NEGOTIATED
1092
1093 int Connection::AdvertiseNextProtoCallback_(SSL *s,
1094                                             const unsigned char** data,
1095                                             unsigned int *len,
1096                                             void *arg) {
1097
1098   Connection *p = static_cast<Connection*>(SSL_get_app_data(s));
1099
1100   if (p->npnProtos_.IsEmpty()) {
1101     // No initialization - no NPN protocols
1102     *data = reinterpret_cast<const unsigned char*>("");
1103     *len = 0;
1104   } else {
1105     *data = reinterpret_cast<const unsigned char*>(Buffer::Data(p->npnProtos_));
1106     *len = Buffer::Length(p->npnProtos_);
1107   }
1108
1109   return SSL_TLSEXT_ERR_OK;
1110 }
1111
1112 int Connection::SelectNextProtoCallback_(SSL *s,
1113                              unsigned char** out, unsigned char* outlen,
1114                              const unsigned char* in,
1115                              unsigned int inlen, void *arg) {
1116   Connection *p = static_cast<Connection*> SSL_get_app_data(s);
1117
1118   // Release old protocol handler if present
1119   if (!p->selectedNPNProto_.IsEmpty()) {
1120     p->selectedNPNProto_.Dispose(node_isolate);
1121   }
1122
1123   if (p->npnProtos_.IsEmpty()) {
1124     // We should at least select one protocol
1125     // If server is using NPN
1126     *out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
1127     *outlen = 8;
1128
1129     // set status unsupported
1130     p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
1131                                                   False(node_isolate));
1132
1133     return SSL_TLSEXT_ERR_OK;
1134   }
1135
1136   const unsigned char* npnProtos =
1137       reinterpret_cast<const unsigned char*>(Buffer::Data(p->npnProtos_));
1138
1139   int status = SSL_select_next_proto(out, outlen, in, inlen, npnProtos,
1140                                      Buffer::Length(p->npnProtos_));
1141
1142   switch (status) {
1143     case OPENSSL_NPN_UNSUPPORTED:
1144       p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
1145                                                     Null(node_isolate));
1146       break;
1147     case OPENSSL_NPN_NEGOTIATED:
1148       p->selectedNPNProto_ = Persistent<Value>::New(node_isolate, String::New(
1149                                  reinterpret_cast<const char*>(*out), *outlen
1150                              ));
1151       break;
1152     case OPENSSL_NPN_NO_OVERLAP:
1153       p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
1154                                                     False(node_isolate));
1155       break;
1156     default:
1157       break;
1158   }
1159
1160   return SSL_TLSEXT_ERR_OK;
1161 }
1162 #endif
1163
1164 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1165 int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
1166   HandleScope scope(node_isolate);
1167
1168   Connection *p = static_cast<Connection*> SSL_get_app_data(s);
1169
1170   const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1171
1172   if (servername) {
1173     if (!p->servername_.IsEmpty()) {
1174       p->servername_.Dispose(node_isolate);
1175     }
1176     p->servername_ = Persistent<String>::New(node_isolate,
1177                                              String::New(servername));
1178
1179     // Call the SNI callback and use its return value as context
1180     if (!p->sniObject_.IsEmpty()) {
1181       if (!p->sniContext_.IsEmpty()) {
1182         p->sniContext_.Dispose(node_isolate);
1183       }
1184
1185       // Get callback init args
1186       Local<Value> argv[1] = {*p->servername_};
1187
1188       // Call it
1189       Local<Value> ret = Local<Value>::New(node_isolate,
1190                                            MakeCallback(p->sniObject_,
1191                                                         "onselect",
1192                                                         ARRAY_SIZE(argv),
1193                                                         argv));
1194
1195       // If ret is SecureContext
1196       if (secure_context_constructor->HasInstance(ret)) {
1197         p->sniContext_ = Persistent<Value>::New(node_isolate, ret);
1198         SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(
1199                                 Local<Object>::Cast(ret));
1200         SSL_set_SSL_CTX(s, sc->ctx_);
1201       } else {
1202         return SSL_TLSEXT_ERR_NOACK;
1203       }
1204     }
1205   }
1206
1207   return SSL_TLSEXT_ERR_OK;
1208 }
1209 #endif
1210
1211 Handle<Value> Connection::New(const Arguments& args) {
1212   HandleScope scope(node_isolate);
1213
1214   Connection *p = new Connection();
1215   p->Wrap(args.Holder());
1216
1217   if (args.Length() < 1 || !args[0]->IsObject()) {
1218     return ThrowException(Exception::Error(String::New(
1219       "First argument must be a crypto module Credentials")));
1220   }
1221
1222   SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args[0]->ToObject());
1223
1224   bool is_server = args[1]->BooleanValue();
1225
1226   p->ssl_ = SSL_new(sc->ctx_);
1227   p->bio_read_ = BIO_new(BIO_s_mem());
1228   p->bio_write_ = BIO_new(BIO_s_mem());
1229
1230   SSL_set_app_data(p->ssl_, p);
1231
1232   if (is_server) SSL_set_info_callback(p->ssl_, SSLInfoCallback);
1233
1234 #ifdef OPENSSL_NPN_NEGOTIATED
1235   if (is_server) {
1236     // Server should advertise NPN protocols
1237     SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
1238                                           AdvertiseNextProtoCallback_,
1239                                           NULL);
1240   } else {
1241     // Client should select protocol from advertised
1242     // If server supports NPN
1243     SSL_CTX_set_next_proto_select_cb(sc->ctx_,
1244                                      SelectNextProtoCallback_,
1245                                      NULL);
1246   }
1247 #endif
1248
1249 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
1250   if (is_server) {
1251     SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
1252   } else {
1253     String::Utf8Value servername(args[2]);
1254     SSL_set_tlsext_host_name(p->ssl_, *servername);
1255   }
1256 #endif
1257
1258   SSL_set_bio(p->ssl_, p->bio_read_, p->bio_write_);
1259
1260 #ifdef SSL_MODE_RELEASE_BUFFERS
1261   long mode = SSL_get_mode(p->ssl_);
1262   SSL_set_mode(p->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
1263 #endif
1264
1265
1266   int verify_mode;
1267   if (is_server) {
1268     bool request_cert = args[2]->BooleanValue();
1269     if (!request_cert) {
1270       // Note reject_unauthorized ignored.
1271       verify_mode = SSL_VERIFY_NONE;
1272     } else {
1273       bool reject_unauthorized = args[3]->BooleanValue();
1274       verify_mode = SSL_VERIFY_PEER;
1275       if (reject_unauthorized) verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1276     }
1277   } else {
1278     // Note request_cert and reject_unauthorized are ignored for clients.
1279     verify_mode = SSL_VERIFY_NONE;
1280   }
1281
1282
1283   // Always allow a connection. We'll reject in javascript.
1284   SSL_set_verify(p->ssl_, verify_mode, VerifyCallback);
1285
1286   if ((p->is_server_ = is_server)) {
1287     SSL_set_accept_state(p->ssl_);
1288   } else {
1289     SSL_set_connect_state(p->ssl_);
1290   }
1291
1292   return args.This();
1293 }
1294
1295
1296 void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
1297   // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
1298   // a non-const SSL* in OpenSSL <= 0.9.7e.
1299   SSL* ssl = const_cast<SSL*>(ssl_);
1300   if (where & SSL_CB_HANDSHAKE_START) {
1301     HandleScope scope(node_isolate);
1302     Connection* c = static_cast<Connection*>(SSL_get_app_data(ssl));
1303     if (onhandshakestart_sym.IsEmpty()) {
1304       onhandshakestart_sym = NODE_PSYMBOL("onhandshakestart");
1305     }
1306     MakeCallback(c->handle_, onhandshakestart_sym, 0, NULL);
1307   }
1308   if (where & SSL_CB_HANDSHAKE_DONE) {
1309     HandleScope scope(node_isolate);
1310     Connection* c = static_cast<Connection*>(SSL_get_app_data(ssl));
1311     if (onhandshakedone_sym.IsEmpty()) {
1312       onhandshakedone_sym = NODE_PSYMBOL("onhandshakedone");
1313     }
1314     MakeCallback(c->handle_, onhandshakedone_sym, 0, NULL);
1315   }
1316 }
1317
1318
1319 Handle<Value> Connection::EncIn(const Arguments& args) {
1320   HandleScope scope(node_isolate);
1321
1322   Connection *ss = Connection::Unwrap(args);
1323
1324   if (args.Length() < 3) {
1325     return ThrowException(Exception::TypeError(
1326           String::New("Takes 3 parameters")));
1327   }
1328
1329   if (!Buffer::HasInstance(args[0])) {
1330     return ThrowException(Exception::TypeError(
1331           String::New("Second argument should be a buffer")));
1332   }
1333
1334   char* buffer_data = Buffer::Data(args[0]);
1335   size_t buffer_length = Buffer::Length(args[0]);
1336
1337   size_t off = args[1]->Int32Value();
1338   size_t len = args[2]->Int32Value();
1339   if (off + len > buffer_length) {
1340     return ThrowException(Exception::Error(
1341           String::New("off + len > buffer.length")));
1342   }
1343
1344   int bytes_written;
1345   char* data = buffer_data + off;
1346
1347   if (ss->is_server_ && !ss->hello_parser_.ended()) {
1348     bytes_written = ss->hello_parser_.Write(reinterpret_cast<uint8_t*>(data),
1349                                             len);
1350   } else {
1351     bytes_written = BIO_write(ss->bio_read_, data, len);
1352     ss->HandleBIOError(ss->bio_read_, "BIO_write", bytes_written);
1353     ss->SetShutdownFlags();
1354   }
1355
1356   return scope.Close(Integer::New(bytes_written, node_isolate));
1357 }
1358
1359
1360 Handle<Value> Connection::ClearOut(const Arguments& args) {
1361   HandleScope scope(node_isolate);
1362
1363   Connection *ss = Connection::Unwrap(args);
1364
1365   if (args.Length() < 3) {
1366     return ThrowException(Exception::TypeError(
1367           String::New("Takes 3 parameters")));
1368   }
1369
1370   if (!Buffer::HasInstance(args[0])) {
1371     return ThrowException(Exception::TypeError(
1372           String::New("Second argument should be a buffer")));
1373   }
1374
1375   char* buffer_data = Buffer::Data(args[0]);
1376   size_t buffer_length = Buffer::Length(args[0]);
1377
1378   size_t off = args[1]->Int32Value();
1379   size_t len = args[2]->Int32Value();
1380   if (off + len > buffer_length) {
1381     return ThrowException(Exception::Error(
1382           String::New("off + len > buffer.length")));
1383   }
1384
1385   if (!SSL_is_init_finished(ss->ssl_)) {
1386     int rv;
1387
1388     if (ss->is_server_) {
1389       rv = SSL_accept(ss->ssl_);
1390       ss->HandleSSLError("SSL_accept:ClearOut", rv, kZeroIsAnError);
1391     } else {
1392       rv = SSL_connect(ss->ssl_);
1393       ss->HandleSSLError("SSL_connect:ClearOut", rv, kZeroIsAnError);
1394     }
1395
1396     if (rv < 0) return scope.Close(Integer::New(rv, node_isolate));
1397   }
1398
1399   int bytes_read = SSL_read(ss->ssl_, buffer_data + off, len);
1400   ss->HandleSSLError("SSL_read:ClearOut", bytes_read, kZeroIsNotAnError);
1401   ss->SetShutdownFlags();
1402
1403   return scope.Close(Integer::New(bytes_read, node_isolate));
1404 }
1405
1406
1407 Handle<Value> Connection::ClearPending(const Arguments& args) {
1408   HandleScope scope(node_isolate);
1409
1410   Connection *ss = Connection::Unwrap(args);
1411
1412   int bytes_pending = BIO_pending(ss->bio_read_);
1413   return scope.Close(Integer::New(bytes_pending, node_isolate));
1414 }
1415
1416
1417 Handle<Value> Connection::EncPending(const Arguments& args) {
1418   HandleScope scope(node_isolate);
1419
1420   Connection *ss = Connection::Unwrap(args);
1421
1422   int bytes_pending = BIO_pending(ss->bio_write_);
1423   return scope.Close(Integer::New(bytes_pending, node_isolate));
1424 }
1425
1426
1427 Handle<Value> Connection::EncOut(const Arguments& args) {
1428   HandleScope scope(node_isolate);
1429
1430   Connection *ss = Connection::Unwrap(args);
1431
1432   if (args.Length() < 3) {
1433     return ThrowException(Exception::TypeError(
1434           String::New("Takes 3 parameters")));
1435   }
1436
1437   if (!Buffer::HasInstance(args[0])) {
1438     return ThrowException(Exception::TypeError(
1439           String::New("Second argument should be a buffer")));
1440   }
1441
1442   char* buffer_data = Buffer::Data(args[0]);
1443   size_t buffer_length = Buffer::Length(args[0]);
1444
1445   size_t off = args[1]->Int32Value();
1446   size_t len = args[2]->Int32Value();
1447   if (off + len > buffer_length) {
1448     return ThrowException(Exception::Error(
1449           String::New("off + len > buffer.length")));
1450   }
1451
1452   int bytes_read = BIO_read(ss->bio_write_, buffer_data + off, len);
1453
1454   ss->HandleBIOError(ss->bio_write_, "BIO_read:EncOut", bytes_read);
1455   ss->SetShutdownFlags();
1456
1457   return scope.Close(Integer::New(bytes_read, node_isolate));
1458 }
1459
1460
1461 Handle<Value> Connection::ClearIn(const Arguments& args) {
1462   HandleScope scope(node_isolate);
1463
1464   Connection *ss = Connection::Unwrap(args);
1465
1466   if (args.Length() < 3) {
1467     return ThrowException(Exception::TypeError(
1468           String::New("Takes 3 parameters")));
1469   }
1470
1471   if (!Buffer::HasInstance(args[0])) {
1472     return ThrowException(Exception::TypeError(
1473           String::New("Second argument should be a buffer")));
1474   }
1475
1476   char* buffer_data = Buffer::Data(args[0]);
1477   size_t buffer_length = Buffer::Length(args[0]);
1478
1479   size_t off = args[1]->Int32Value();
1480   size_t len = args[2]->Int32Value();
1481   if (off + len > buffer_length) {
1482     return ThrowException(Exception::Error(
1483           String::New("off + len > buffer.length")));
1484   }
1485
1486   if (!SSL_is_init_finished(ss->ssl_)) {
1487     int rv;
1488     if (ss->is_server_) {
1489       rv = SSL_accept(ss->ssl_);
1490       ss->HandleSSLError("SSL_accept:ClearIn", rv, kZeroIsAnError);
1491     } else {
1492       rv = SSL_connect(ss->ssl_);
1493       ss->HandleSSLError("SSL_connect:ClearIn", rv, kZeroIsAnError);
1494     }
1495
1496     if (rv < 0) return scope.Close(Integer::New(rv, node_isolate));
1497   }
1498
1499   int bytes_written = SSL_write(ss->ssl_, buffer_data + off, len);
1500
1501   ss->HandleSSLError("SSL_write:ClearIn", bytes_written, kZeroIsAnError);
1502   ss->SetShutdownFlags();
1503
1504   return scope.Close(Integer::New(bytes_written, node_isolate));
1505 }
1506
1507
1508 Handle<Value> Connection::GetPeerCertificate(const Arguments& args) {
1509   HandleScope scope(node_isolate);
1510
1511   Connection *ss = Connection::Unwrap(args);
1512
1513   if (ss->ssl_ == NULL) return Undefined(node_isolate);
1514   Local<Object> info = Object::New();
1515   X509* peer_cert = SSL_get_peer_certificate(ss->ssl_);
1516   if (peer_cert != NULL) {
1517     BIO* bio = BIO_new(BIO_s_mem());
1518     BUF_MEM* mem;
1519     if (X509_NAME_print_ex(bio, X509_get_subject_name(peer_cert), 0,
1520                            X509_NAME_FLAGS) > 0) {
1521       BIO_get_mem_ptr(bio, &mem);
1522       info->Set(subject_symbol, String::New(mem->data, mem->length));
1523     }
1524     (void) BIO_reset(bio);
1525
1526     if (X509_NAME_print_ex(bio, X509_get_issuer_name(peer_cert), 0,
1527                            X509_NAME_FLAGS) > 0) {
1528       BIO_get_mem_ptr(bio, &mem);
1529       info->Set(issuer_symbol, String::New(mem->data, mem->length));
1530     }
1531     (void) BIO_reset(bio);
1532
1533     int index = X509_get_ext_by_NID(peer_cert, NID_subject_alt_name, -1);
1534     if (index >= 0) {
1535       X509_EXTENSION* ext;
1536       int rv;
1537
1538       ext = X509_get_ext(peer_cert, index);
1539       assert(ext != NULL);
1540
1541       rv = X509V3_EXT_print(bio, ext, 0, 0);
1542       assert(rv == 1);
1543
1544       BIO_get_mem_ptr(bio, &mem);
1545       info->Set(subjectaltname_symbol, String::New(mem->data, mem->length));
1546
1547       (void) BIO_reset(bio);
1548     }
1549
1550     EVP_PKEY *pkey = NULL;
1551     RSA *rsa = NULL;
1552     if( NULL != (pkey = X509_get_pubkey(peer_cert))
1553         && NULL != (rsa = EVP_PKEY_get1_RSA(pkey)) ) {
1554         BN_print(bio, rsa->n);
1555         BIO_get_mem_ptr(bio, &mem);
1556         info->Set(modulus_symbol, String::New(mem->data, mem->length) );
1557         (void) BIO_reset(bio);
1558
1559         BN_print(bio, rsa->e);
1560         BIO_get_mem_ptr(bio, &mem);
1561         info->Set(exponent_symbol, String::New(mem->data, mem->length) );
1562         (void) BIO_reset(bio);
1563     }
1564
1565     if (pkey != NULL) {
1566       EVP_PKEY_free(pkey);
1567       pkey = NULL;
1568     }
1569     if (rsa != NULL) {
1570       RSA_free(rsa);
1571       rsa = NULL;
1572     }
1573
1574     ASN1_TIME_print(bio, X509_get_notBefore(peer_cert));
1575     BIO_get_mem_ptr(bio, &mem);
1576     info->Set(valid_from_symbol, String::New(mem->data, mem->length));
1577     (void) BIO_reset(bio);
1578
1579     ASN1_TIME_print(bio, X509_get_notAfter(peer_cert));
1580     BIO_get_mem_ptr(bio, &mem);
1581     info->Set(valid_to_symbol, String::New(mem->data, mem->length));
1582     BIO_free_all(bio);
1583
1584     unsigned int md_size, i;
1585     unsigned char md[EVP_MAX_MD_SIZE];
1586     if (X509_digest(peer_cert, EVP_sha1(), md, &md_size)) {
1587       const char hex[] = "0123456789ABCDEF";
1588       char fingerprint[EVP_MAX_MD_SIZE * 3];
1589
1590       for (i=0; i<md_size; i++) {
1591         fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
1592         fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
1593         fingerprint[(3*i)+2] = ':';
1594       }
1595
1596       if (md_size > 0) {
1597         fingerprint[(3*(md_size-1))+2] = '\0';
1598       }
1599       else {
1600         fingerprint[0] = '\0';
1601       }
1602
1603       info->Set(fingerprint_symbol, String::New(fingerprint));
1604     }
1605
1606     STACK_OF(ASN1_OBJECT) *eku = (STACK_OF(ASN1_OBJECT) *)X509_get_ext_d2i(
1607         peer_cert, NID_ext_key_usage, NULL, NULL);
1608     if (eku != NULL) {
1609       Local<Array> ext_key_usage = Array::New();
1610       char buf[256];
1611
1612       for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
1613         memset(buf, 0, sizeof(buf));
1614         OBJ_obj2txt(buf, sizeof(buf) - 1, sk_ASN1_OBJECT_value(eku, i), 1);
1615         ext_key_usage->Set(Integer::New(i, node_isolate), String::New(buf));
1616       }
1617
1618       sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
1619       info->Set(ext_key_usage_symbol, ext_key_usage);
1620     }
1621
1622     X509_free(peer_cert);
1623   }
1624   return scope.Close(info);
1625 }
1626
1627 Handle<Value> Connection::GetSession(const Arguments& args) {
1628   HandleScope scope(node_isolate);
1629
1630   Connection *ss = Connection::Unwrap(args);
1631
1632   if (ss->ssl_ == NULL) return Undefined(node_isolate);
1633
1634   SSL_SESSION* sess = SSL_get_session(ss->ssl_);
1635   if (!sess) return Undefined(node_isolate);
1636
1637   int slen = i2d_SSL_SESSION(sess, NULL);
1638   assert(slen > 0);
1639
1640   if (slen > 0) {
1641     unsigned char* sbuf = new unsigned char[slen];
1642     unsigned char* p = sbuf;
1643     i2d_SSL_SESSION(sess, &p);
1644     Local<Value> s = Encode(sbuf, slen, BINARY);
1645     delete[] sbuf;
1646     return scope.Close(s);
1647   }
1648
1649   return Null(node_isolate);
1650 }
1651
1652 Handle<Value> Connection::SetSession(const Arguments& args) {
1653   HandleScope scope(node_isolate);
1654
1655   Connection *ss = Connection::Unwrap(args);
1656
1657   if (args.Length() < 1 ||
1658       (!args[0]->IsString() && !Buffer::HasInstance(args[0]))) {
1659     Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
1660     return ThrowException(exception);
1661   }
1662
1663   ASSERT_IS_BUFFER(args[0]);
1664   ssize_t slen = Buffer::Length(args[0]);
1665
1666   if (slen < 0) {
1667     Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
1668     return ThrowException(exception);
1669   }
1670
1671   char* sbuf = new char[slen];
1672
1673   ssize_t wlen = DecodeWrite(sbuf, slen, args[0], BINARY);
1674   assert(wlen == slen);
1675
1676   const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
1677   SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, wlen);
1678
1679   delete [] sbuf;
1680
1681   if (!sess)
1682     return Undefined(node_isolate);
1683
1684   int r = SSL_set_session(ss->ssl_, sess);
1685   SSL_SESSION_free(sess);
1686
1687   if (!r) {
1688     Local<String> eStr = String::New("SSL_set_session error");
1689     return ThrowException(Exception::Error(eStr));
1690   }
1691
1692   return True(node_isolate);
1693 }
1694
1695 Handle<Value> Connection::LoadSession(const Arguments& args) {
1696   HandleScope scope(node_isolate);
1697
1698   Connection *ss = Connection::Unwrap(args);
1699
1700   if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1701     ssize_t slen = Buffer::Length(args[0].As<Object>());
1702     char* sbuf = Buffer::Data(args[0].As<Object>());
1703
1704     const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
1705     SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, slen);
1706
1707     // Setup next session and move hello to the BIO buffer
1708     if (ss->next_sess_ != NULL) {
1709       SSL_SESSION_free(ss->next_sess_);
1710     }
1711     ss->next_sess_ = sess;
1712   }
1713
1714   ss->hello_parser_.Finish();
1715
1716   return True(node_isolate);
1717 }
1718
1719 Handle<Value> Connection::IsSessionReused(const Arguments& args) {
1720   HandleScope scope(node_isolate);
1721
1722   Connection *ss = Connection::Unwrap(args);
1723
1724   if (ss->ssl_ == NULL || SSL_session_reused(ss->ssl_) == false) {
1725     return False(node_isolate);
1726   }
1727
1728   return True(node_isolate);
1729 }
1730
1731
1732 Handle<Value> Connection::Start(const Arguments& args) {
1733   HandleScope scope(node_isolate);
1734
1735   Connection *ss = Connection::Unwrap(args);
1736
1737   if (!SSL_is_init_finished(ss->ssl_)) {
1738     int rv;
1739     if (ss->is_server_) {
1740       rv = SSL_accept(ss->ssl_);
1741       ss->HandleSSLError("SSL_accept:Start", rv, kZeroIsAnError);
1742     } else {
1743       rv = SSL_connect(ss->ssl_);
1744       ss->HandleSSLError("SSL_connect:Start", rv, kZeroIsAnError);
1745     }
1746
1747     return scope.Close(Integer::New(rv, node_isolate));
1748   }
1749
1750   return scope.Close(Integer::New(0, node_isolate));
1751 }
1752
1753
1754 Handle<Value> Connection::Shutdown(const Arguments& args) {
1755   HandleScope scope(node_isolate);
1756
1757   Connection *ss = Connection::Unwrap(args);
1758
1759   if (ss->ssl_ == NULL) return False(node_isolate);
1760   int rv = SSL_shutdown(ss->ssl_);
1761   ss->HandleSSLError("SSL_shutdown", rv, kZeroIsNotAnError);
1762   ss->SetShutdownFlags();
1763
1764   return scope.Close(Integer::New(rv, node_isolate));
1765 }
1766
1767
1768 Handle<Value> Connection::ReceivedShutdown(const Arguments& args) {
1769   HandleScope scope(node_isolate);
1770
1771   Connection *ss = Connection::Unwrap(args);
1772
1773   if (ss->ssl_ == NULL) return False(node_isolate);
1774   int r = SSL_get_shutdown(ss->ssl_);
1775
1776   if (r & SSL_RECEIVED_SHUTDOWN) return True(node_isolate);
1777
1778   return False(node_isolate);
1779 }
1780
1781
1782 Handle<Value> Connection::IsInitFinished(const Arguments& args) {
1783   HandleScope scope(node_isolate);
1784
1785   Connection *ss = Connection::Unwrap(args);
1786
1787   if (ss->ssl_ == NULL || SSL_is_init_finished(ss->ssl_) == false) {
1788     return False(node_isolate);
1789   }
1790
1791   return True(node_isolate);
1792 }
1793
1794
1795 Handle<Value> Connection::VerifyError(const Arguments& args) {
1796   HandleScope scope(node_isolate);
1797
1798   Connection *ss = Connection::Unwrap(args);
1799
1800   if (ss->ssl_ == NULL) return Null(node_isolate);
1801
1802
1803   // XXX Do this check in JS land?
1804   X509* peer_cert = SSL_get_peer_certificate(ss->ssl_);
1805   if (peer_cert == NULL) {
1806     // We requested a certificate and they did not send us one.
1807     // Definitely an error.
1808     // XXX is this the right error message?
1809     return scope.Close(Exception::Error(
1810           String::New("UNABLE_TO_GET_ISSUER_CERT")));
1811   }
1812   X509_free(peer_cert);
1813
1814
1815   long x509_verify_error = SSL_get_verify_result(ss->ssl_);
1816
1817   Local<String> s;
1818
1819   switch (x509_verify_error) {
1820     case X509_V_OK:
1821       return Null(node_isolate);
1822
1823     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1824       s = String::New("UNABLE_TO_GET_ISSUER_CERT");
1825       break;
1826
1827     case X509_V_ERR_UNABLE_TO_GET_CRL:
1828       s = String::New("UNABLE_TO_GET_CRL");
1829       break;
1830
1831     case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1832       s = String::New("UNABLE_TO_DECRYPT_CERT_SIGNATURE");
1833       break;
1834
1835     case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1836       s = String::New("UNABLE_TO_DECRYPT_CRL_SIGNATURE");
1837       break;
1838
1839     case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1840       s = String::New("UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY");
1841       break;
1842
1843     case X509_V_ERR_CERT_SIGNATURE_FAILURE:
1844       s = String::New("CERT_SIGNATURE_FAILURE");
1845       break;
1846
1847     case X509_V_ERR_CRL_SIGNATURE_FAILURE:
1848       s = String::New("CRL_SIGNATURE_FAILURE");
1849       break;
1850
1851     case X509_V_ERR_CERT_NOT_YET_VALID:
1852       s = String::New("CERT_NOT_YET_VALID");
1853       break;
1854
1855     case X509_V_ERR_CERT_HAS_EXPIRED:
1856       s = String::New("CERT_HAS_EXPIRED");
1857       break;
1858
1859     case X509_V_ERR_CRL_NOT_YET_VALID:
1860       s = String::New("CRL_NOT_YET_VALID");
1861       break;
1862
1863     case X509_V_ERR_CRL_HAS_EXPIRED:
1864       s = String::New("CRL_HAS_EXPIRED");
1865       break;
1866
1867     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1868       s = String::New("ERROR_IN_CERT_NOT_BEFORE_FIELD");
1869       break;
1870
1871     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1872       s = String::New("ERROR_IN_CERT_NOT_AFTER_FIELD");
1873       break;
1874
1875     case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1876       s = String::New("ERROR_IN_CRL_LAST_UPDATE_FIELD");
1877       break;
1878
1879     case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1880       s = String::New("ERROR_IN_CRL_NEXT_UPDATE_FIELD");
1881       break;
1882
1883     case X509_V_ERR_OUT_OF_MEM:
1884       s = String::New("OUT_OF_MEM");
1885       break;
1886
1887     case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1888       s = String::New("DEPTH_ZERO_SELF_SIGNED_CERT");
1889       break;
1890
1891     case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1892       s = String::New("SELF_SIGNED_CERT_IN_CHAIN");
1893       break;
1894
1895     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1896       s = String::New("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
1897       break;
1898
1899     case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1900       s = String::New("UNABLE_TO_VERIFY_LEAF_SIGNATURE");
1901       break;
1902
1903     case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1904       s = String::New("CERT_CHAIN_TOO_LONG");
1905       break;
1906
1907     case X509_V_ERR_CERT_REVOKED:
1908       s = String::New("CERT_REVOKED");
1909       break;
1910
1911     case X509_V_ERR_INVALID_CA:
1912       s = String::New("INVALID_CA");
1913       break;
1914
1915     case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1916       s = String::New("PATH_LENGTH_EXCEEDED");
1917       break;
1918
1919     case X509_V_ERR_INVALID_PURPOSE:
1920       s = String::New("INVALID_PURPOSE");
1921       break;
1922
1923     case X509_V_ERR_CERT_UNTRUSTED:
1924       s = String::New("CERT_UNTRUSTED");
1925       break;
1926
1927     case X509_V_ERR_CERT_REJECTED:
1928       s = String::New("CERT_REJECTED");
1929       break;
1930
1931     default:
1932       s = String::New(X509_verify_cert_error_string(x509_verify_error));
1933       break;
1934   }
1935
1936   return scope.Close(Exception::Error(s));
1937 }
1938
1939
1940 Handle<Value> Connection::GetCurrentCipher(const Arguments& args) {
1941   HandleScope scope(node_isolate);
1942
1943   Connection *ss = Connection::Unwrap(args);
1944
1945   OPENSSL_CONST SSL_CIPHER *c;
1946
1947   if ( ss->ssl_ == NULL ) return Undefined(node_isolate);
1948   c = SSL_get_current_cipher(ss->ssl_);
1949   if ( c == NULL ) return Undefined(node_isolate);
1950   Local<Object> info = Object::New();
1951   const char* cipher_name = SSL_CIPHER_get_name(c);
1952   info->Set(name_symbol, String::New(cipher_name));
1953   const char* cipher_version = SSL_CIPHER_get_version(c);
1954   info->Set(version_symbol, String::New(cipher_version));
1955   return scope.Close(info);
1956 }
1957
1958 Handle<Value> Connection::Close(const Arguments& args) {
1959   HandleScope scope(node_isolate);
1960
1961   Connection *ss = Connection::Unwrap(args);
1962
1963   if (ss->ssl_ != NULL) {
1964     SSL_free(ss->ssl_);
1965     ss->ssl_ = NULL;
1966   }
1967   return True(node_isolate);
1968 }
1969
1970 #ifdef OPENSSL_NPN_NEGOTIATED
1971 Handle<Value> Connection::GetNegotiatedProto(const Arguments& args) {
1972   HandleScope scope(node_isolate);
1973
1974   Connection *ss = Connection::Unwrap(args);
1975
1976   if (ss->is_server_) {
1977     const unsigned char* npn_proto;
1978     unsigned int npn_proto_len;
1979
1980     SSL_get0_next_proto_negotiated(ss->ssl_, &npn_proto, &npn_proto_len);
1981
1982     if (!npn_proto) {
1983       return False(node_isolate);
1984     }
1985
1986     return String::New((const char*) npn_proto, npn_proto_len);
1987   } else {
1988     return ss->selectedNPNProto_;
1989   }
1990 }
1991
1992 Handle<Value> Connection::SetNPNProtocols(const Arguments& args) {
1993   HandleScope scope(node_isolate);
1994
1995   Connection *ss = Connection::Unwrap(args);
1996
1997   if (args.Length() < 1 || !Buffer::HasInstance(args[0])) {
1998     return ThrowException(Exception::Error(String::New(
1999            "Must give a Buffer as first argument")));
2000   }
2001
2002   // Release old handle
2003   if (!ss->npnProtos_.IsEmpty()) {
2004     ss->npnProtos_.Dispose(node_isolate);
2005   }
2006   ss->npnProtos_ = Persistent<Object>::New(node_isolate, args[0]->ToObject());
2007
2008   return True(node_isolate);
2009 };
2010 #endif
2011
2012 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2013 Handle<Value> Connection::GetServername(const Arguments& args) {
2014   HandleScope scope(node_isolate);
2015
2016   Connection *ss = Connection::Unwrap(args);
2017
2018   if (ss->is_server_ && !ss->servername_.IsEmpty()) {
2019     return ss->servername_;
2020   } else {
2021     return False(node_isolate);
2022   }
2023 }
2024
2025 Handle<Value> Connection::SetSNICallback(const Arguments& args) {
2026   HandleScope scope(node_isolate);
2027
2028   Connection *ss = Connection::Unwrap(args);
2029
2030   if (args.Length() < 1 || !args[0]->IsFunction()) {
2031     return ThrowException(Exception::Error(String::New(
2032            "Must give a Function as first argument")));
2033   }
2034
2035   // Release old handle
2036   if (!ss->sniObject_.IsEmpty()) {
2037     ss->sniObject_.Dispose(node_isolate);
2038   }
2039   ss->sniObject_ = Persistent<Object>::New(node_isolate, Object::New());
2040   ss->sniObject_->Set(String::New("onselect"), args[0]);
2041
2042   return True(node_isolate);
2043 }
2044 #endif
2045
2046
2047 void CipherBase::Initialize(Handle<Object> target) {
2048   HandleScope scope(node_isolate);
2049
2050   Local<FunctionTemplate> t = FunctionTemplate::New(New);
2051
2052   t->InstanceTemplate()->SetInternalFieldCount(1);
2053
2054   NODE_SET_PROTOTYPE_METHOD(t, "init", Init);
2055   NODE_SET_PROTOTYPE_METHOD(t, "initiv", InitIv);
2056   NODE_SET_PROTOTYPE_METHOD(t, "update", Update);
2057   NODE_SET_PROTOTYPE_METHOD(t, "final", Final);
2058   NODE_SET_PROTOTYPE_METHOD(t, "setAutoPadding", SetAutoPadding);
2059
2060   target->Set(String::NewSymbol("CipherBase"), t->GetFunction());
2061 }
2062
2063
2064 Handle<Value> CipherBase::New(const Arguments& args) {
2065   HandleScope scope(node_isolate);
2066
2067   CipherBase* cipher = new CipherBase(args[0]->IsTrue() ? kCipher : kDecipher);
2068   cipher->Wrap(args.This());
2069   return args.This();
2070 }
2071
2072
2073 Handle<Value> CipherBase::Init(char* cipher_type,
2074                                char* key_buf,
2075                                int key_buf_len) {
2076   HandleScope scope(node_isolate);
2077
2078   assert(cipher_ == NULL);
2079   cipher_ = EVP_get_cipherbyname(cipher_type);
2080   if (cipher_ == NULL) {
2081     return ThrowError("Unknown cipher");
2082   }
2083
2084   unsigned char key[EVP_MAX_KEY_LENGTH];
2085   unsigned char iv[EVP_MAX_IV_LENGTH];
2086
2087   int key_len = EVP_BytesToKey(cipher_,
2088                                EVP_md5(),
2089                                NULL,
2090                                reinterpret_cast<unsigned char*>(key_buf),
2091                                key_buf_len,
2092                                1,
2093                                key,
2094                                iv);
2095
2096   EVP_CIPHER_CTX_init(&ctx_);
2097   EVP_CipherInit_ex(&ctx_, cipher_, NULL, NULL, NULL, kind_ == kCipher);
2098   if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
2099     EVP_CIPHER_CTX_cleanup(&ctx_);
2100     return ThrowError("Invalid key length");
2101   }
2102
2103   EVP_CipherInit_ex(&ctx_,
2104                     NULL,
2105                     NULL,
2106                     reinterpret_cast<unsigned char*>(key),
2107                     reinterpret_cast<unsigned char*>(iv),
2108                     kind_ == kCipher);
2109   initialised_ = true;
2110   return Null(node_isolate);
2111 }
2112
2113
2114 Handle<Value> CipherBase::Init(const Arguments& args) {
2115   HandleScope scope(node_isolate);
2116
2117   CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2118
2119   if (args.Length() < 2 ||
2120       !(args[0]->IsString() && Buffer::HasInstance(args[1]))) {
2121     return ThrowError("Must give cipher-type, key");
2122   }
2123
2124   String::Utf8Value cipher_type(args[0]);
2125   char* key_buf = Buffer::Data(args[1]);
2126   ssize_t key_buf_len = Buffer::Length(args[1]);
2127
2128   Handle<Value> ret = cipher->Init(*cipher_type, key_buf, key_buf_len);
2129
2130   if (ret->IsNull()) {
2131     return args.This();
2132   } else {
2133     // Exception
2134     return scope.Close(ret);
2135   }
2136 }
2137
2138
2139 Handle<Value> CipherBase::InitIv(char* cipher_type,
2140                                  char* key,
2141                                  int key_len,
2142                                  char* iv,
2143                                  int iv_len) {
2144   HandleScope scope(node_isolate);
2145
2146   cipher_ = EVP_get_cipherbyname(cipher_type);
2147   if (cipher_ == NULL) {
2148     return ThrowError("Unknown cipher");
2149   }
2150
2151   /* OpenSSL versions up to 0.9.8l failed to return the correct
2152      iv_length (0) for ECB ciphers */
2153   if (EVP_CIPHER_iv_length(cipher_) != iv_len &&
2154       !(EVP_CIPHER_mode(cipher_) == EVP_CIPH_ECB_MODE && iv_len == 0)) {
2155     return ThrowError("Invalid IV length");
2156   }
2157   EVP_CIPHER_CTX_init(&ctx_);
2158   EVP_CipherInit_ex(&ctx_, cipher_, NULL, NULL, NULL, kind_ == kCipher);
2159   if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
2160     EVP_CIPHER_CTX_cleanup(&ctx_);
2161     return ThrowError("Invalid key length");
2162   }
2163
2164   EVP_CipherInit_ex(&ctx_,
2165                     NULL,
2166                     NULL,
2167                     reinterpret_cast<unsigned char*>(key),
2168                     reinterpret_cast<unsigned char*>(iv),
2169                     kind_ == kCipher);
2170   initialised_ = true;
2171   return Null(node_isolate);
2172 }
2173
2174
2175 Handle<Value> CipherBase::InitIv(const Arguments& args) {
2176   HandleScope scope(node_isolate);
2177
2178   CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2179
2180   if (args.Length() < 3 || !args[0]->IsString()) {
2181     return ThrowError("Must give cipher-type, key, and iv as argument");
2182   }
2183
2184   ASSERT_IS_BUFFER(args[1]);
2185   ASSERT_IS_BUFFER(args[2]);
2186
2187   String::Utf8Value cipher_type(args[0]);
2188   ssize_t key_len = Buffer::Length(args[1]);
2189   char* key_buf = Buffer::Data(args[1]);
2190   ssize_t iv_len = Buffer::Length(args[2]);
2191   char* iv_buf = Buffer::Data(args[2]);
2192
2193   Handle<Value> ret = cipher->InitIv(*cipher_type,
2194                                      key_buf,
2195                                      key_len,
2196                                      iv_buf,
2197                                      iv_len);
2198
2199   if (ret->IsNull()) {
2200     return args.This();
2201   } else {
2202     // Exception
2203     return scope.Close(ret);
2204   }
2205 }
2206
2207
2208 bool CipherBase::Update(char* data,
2209                         int len,
2210                         unsigned char** out,
2211                         int* out_len) {
2212   if (!initialised_) return 0;
2213   *out_len = len + EVP_CIPHER_CTX_block_size(&ctx_);
2214   *out = new unsigned char[*out_len];
2215   return EVP_CipherUpdate(&ctx_,
2216                           *out,
2217                           out_len,
2218                           reinterpret_cast<unsigned char*>(data),
2219                           len);
2220 }
2221
2222
2223 Handle<Value> CipherBase::Update(const Arguments& args) {
2224   HandleScope scope(node_isolate);
2225
2226   CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2227
2228   ASSERT_IS_BUFFER(args[0]);
2229
2230   unsigned char* out = NULL;
2231   bool r;
2232   int out_len = 0;
2233   char* buffer_data = Buffer::Data(args[0]);
2234   size_t buffer_length = Buffer::Length(args[0]);
2235
2236   r = cipher->Update(buffer_data, buffer_length, &out, &out_len);
2237
2238   if (!r) {
2239     delete[] out;
2240     return ThrowCryptoTypeError(ERR_get_error());
2241   }
2242
2243   Buffer* buf = Buffer::New(reinterpret_cast<char*>(out), out_len);
2244
2245   return scope.Close(buf->handle_);
2246 }
2247
2248
2249 bool CipherBase::SetAutoPadding(bool auto_padding) {
2250   if (!initialised_) return false;
2251   return EVP_CIPHER_CTX_set_padding(&ctx_, auto_padding);
2252 }
2253
2254
2255 Handle<Value> CipherBase::SetAutoPadding(const Arguments& args) {
2256   HandleScope scope(node_isolate);
2257
2258   CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2259
2260   cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue());
2261
2262   return Undefined(node_isolate);
2263 }
2264
2265
2266 bool CipherBase::Final(unsigned char** out, int *out_len) {
2267   if (!initialised_) return false;
2268
2269   *out = new unsigned char[EVP_CIPHER_CTX_block_size(&ctx_)];
2270   bool r = EVP_CipherFinal_ex(&ctx_, *out, out_len);
2271   EVP_CIPHER_CTX_cleanup(&ctx_);
2272   initialised_ = false;
2273
2274   return r;
2275 }
2276
2277
2278 Handle<Value> CipherBase::Final(const Arguments& args) {
2279   HandleScope scope(node_isolate);
2280
2281   CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
2282
2283   unsigned char* out_value = NULL;
2284   int out_len = -1;
2285   Local<Value> outString;
2286
2287   bool r = cipher->Final(&out_value, &out_len);
2288
2289   if (out_len <= 0 || !r) {
2290     delete[] out_value;
2291     out_value = NULL;
2292     out_len = 0;
2293     if (!r) return ThrowCryptoTypeError(ERR_get_error());
2294   }
2295
2296   Buffer* buf = Buffer::New(reinterpret_cast<char*>(out_value), out_len);
2297
2298   return scope.Close(buf->handle_);
2299 }
2300
2301
2302 void Hmac::Initialize(v8::Handle<v8::Object> target) {
2303   HandleScope scope(node_isolate);
2304
2305   Local<FunctionTemplate> t = FunctionTemplate::New(New);
2306
2307   t->InstanceTemplate()->SetInternalFieldCount(1);
2308
2309   NODE_SET_PROTOTYPE_METHOD(t, "init", HmacInit);
2310   NODE_SET_PROTOTYPE_METHOD(t, "update", HmacUpdate);
2311   NODE_SET_PROTOTYPE_METHOD(t, "digest", HmacDigest);
2312
2313   target->Set(String::NewSymbol("Hmac"), t->GetFunction());
2314 }
2315
2316
2317 Handle<Value> Hmac::New(const Arguments& args) {
2318   HandleScope scope(node_isolate);
2319
2320   Hmac* hmac = new Hmac();
2321   hmac->Wrap(args.This());
2322   return args.This();
2323 }
2324
2325
2326 Handle<Value> Hmac::HmacInit(char* hashType, char* key, int key_len) {
2327   HandleScope scope(node_isolate);
2328
2329   assert(md_ == NULL);
2330   md_ = EVP_get_digestbyname(hashType);
2331   if (md_ == NULL) {
2332     return ThrowError("Unknown message digest");
2333   }
2334   HMAC_CTX_init(&ctx_);
2335   if (key_len == 0) {
2336     HMAC_Init(&ctx_, "", 0, md_);
2337   } else {
2338     HMAC_Init(&ctx_, key, key_len, md_);
2339   }
2340   initialised_ = true;
2341
2342   return Null(node_isolate);
2343 }
2344
2345
2346 Handle<Value> Hmac::HmacInit(const Arguments& args) {
2347   HandleScope scope(node_isolate);
2348
2349   Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
2350
2351   if (args.Length() < 2 || !args[0]->IsString()) {
2352     return ThrowError("Must give hashtype string, key as arguments");
2353   }
2354
2355   ASSERT_IS_BUFFER(args[1]);
2356
2357   String::Utf8Value hashType(args[0]);
2358
2359   char* buffer_data = Buffer::Data(args[1]);
2360   size_t buffer_length = Buffer::Length(args[1]);
2361
2362   Handle<Value> ret = hmac->HmacInit(*hashType, buffer_data, buffer_length);
2363
2364   if (ret->IsNull()) {
2365     return args.This();
2366   } else {
2367     // Exception
2368     return ret;
2369   }
2370 }
2371
2372
2373 bool Hmac::HmacUpdate(char* data, int len) {
2374   if (!initialised_) return false;
2375   HMAC_Update(&ctx_, reinterpret_cast<unsigned char*>(data), len);
2376   return true;
2377 }
2378
2379
2380 Handle<Value> Hmac::HmacUpdate(const Arguments& args) {
2381   HandleScope scope(node_isolate);
2382
2383   Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
2384
2385   ASSERT_IS_BUFFER(args[0]);
2386
2387   bool r;
2388
2389   char* buffer_data = Buffer::Data(args[0]);
2390   size_t buffer_length = Buffer::Length(args[0]);
2391
2392   r = hmac->HmacUpdate(buffer_data, buffer_length);
2393
2394   if (!r) {
2395     return ThrowTypeError("HmacUpdate fail");
2396   }
2397
2398   return args.This();
2399 }
2400
2401
2402 bool Hmac::HmacDigest(unsigned char** md_value, unsigned int* md_len) {
2403   if (!initialised_) return false;
2404   *md_value = new unsigned char[EVP_MAX_MD_SIZE];
2405   HMAC_Final(&ctx_, *md_value, md_len);
2406   HMAC_CTX_cleanup(&ctx_);
2407   initialised_ = false;
2408   return true;
2409 }
2410
2411
2412 Handle<Value> Hmac::HmacDigest(const Arguments& args) {
2413   HandleScope scope(node_isolate);
2414
2415   Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
2416
2417   unsigned char* md_value = NULL;
2418   unsigned int md_len = 0;
2419   Local<Value> outString;
2420
2421   bool r = hmac->HmacDigest(&md_value, &md_len);
2422   if (!r) {
2423     md_value = NULL;
2424     md_len = 0;
2425   }
2426
2427   Buffer* buf = Buffer::New(reinterpret_cast<char*>(md_value), md_len);
2428
2429   return scope.Close(buf->handle_);
2430 }
2431
2432
2433 void Hash::Initialize(v8::Handle<v8::Object> target) {
2434   HandleScope scope(node_isolate);
2435
2436   Local<FunctionTemplate> t = FunctionTemplate::New(New);
2437
2438   t->InstanceTemplate()->SetInternalFieldCount(1);
2439
2440   NODE_SET_PROTOTYPE_METHOD(t, "update", HashUpdate);
2441   NODE_SET_PROTOTYPE_METHOD(t, "digest", HashDigest);
2442
2443   target->Set(String::NewSymbol("Hash"), t->GetFunction());
2444 }
2445
2446
2447 Handle<Value> Hash::New(const Arguments& args) {
2448   HandleScope scope(node_isolate);
2449
2450   if (args.Length() == 0 || !args[0]->IsString()) {
2451     return ThrowError("Must give hashtype string as argument");
2452   }
2453
2454   String::Utf8Value hashType(args[0]);
2455
2456   Hash* hash = new Hash();
2457   if (!hash->HashInit(*hashType)) {
2458     delete hash;
2459     return ThrowError("Digest method not supported");
2460   }
2461
2462   hash->Wrap(args.This());
2463   return args.This();
2464 }
2465
2466
2467 bool Hash::HashInit(const char* hashType) {
2468   assert(md_ == NULL);
2469   md_ = EVP_get_digestbyname(hashType);
2470   if (md_ == NULL) return false;
2471   EVP_MD_CTX_init(&mdctx_);
2472   EVP_DigestInit_ex(&mdctx_, md_, NULL);
2473   initialised_ = true;
2474   return true;
2475 }
2476
2477
2478 bool Hash::HashUpdate(char* data, int len) {
2479   if (!initialised_) return false;
2480   EVP_DigestUpdate(&mdctx_, data, len);
2481   return true;
2482 }
2483
2484
2485 Handle<Value> Hash::HashUpdate(const Arguments& args) {
2486   HandleScope scope(node_isolate);
2487
2488   Hash* hash = ObjectWrap::Unwrap<Hash>(args.This());
2489
2490   ASSERT_IS_BUFFER(args[0]);
2491
2492   bool r;
2493
2494   char* buffer_data = Buffer::Data(args[0]);
2495   size_t buffer_length = Buffer::Length(args[0]);
2496   r = hash->HashUpdate(buffer_data, buffer_length);
2497
2498   if (!r) {
2499     return ThrowTypeError("HashUpdate fail");
2500   }
2501
2502   return args.This();
2503 }
2504
2505
2506 Handle<Value> Hash::HashDigest(const Arguments& args) {
2507   HandleScope scope(node_isolate);
2508
2509   Hash* hash = ObjectWrap::Unwrap<Hash>(args.This());
2510
2511   if (!hash->initialised_) {
2512     return ThrowError("Not initialized");
2513   }
2514
2515   unsigned char md_value[EVP_MAX_MD_SIZE];
2516   unsigned int md_len;
2517
2518   EVP_DigestFinal_ex(&hash->mdctx_, md_value, &md_len);
2519   EVP_MD_CTX_cleanup(&hash->mdctx_);
2520   hash->initialised_ = false;
2521
2522   Buffer* buf = Buffer::New(reinterpret_cast<char*>(md_value), md_len);
2523
2524   return scope.Close(buf->handle_);
2525 }
2526
2527
2528 void Sign::Initialize(v8::Handle<v8::Object> target) {
2529   HandleScope scope(node_isolate);
2530
2531   Local<FunctionTemplate> t = FunctionTemplate::New(New);
2532
2533   t->InstanceTemplate()->SetInternalFieldCount(1);
2534
2535   NODE_SET_PROTOTYPE_METHOD(t, "init", SignInit);
2536   NODE_SET_PROTOTYPE_METHOD(t, "update", SignUpdate);
2537   NODE_SET_PROTOTYPE_METHOD(t, "sign", SignFinal);
2538
2539   target->Set(String::NewSymbol("Sign"), t->GetFunction());
2540 }
2541
2542
2543 Handle<Value> Sign::New(const Arguments& args) {
2544   HandleScope scope(node_isolate);
2545
2546   Sign* sign = new Sign();
2547   sign->Wrap(args.This());
2548
2549   return args.This();
2550 }
2551
2552
2553 Handle<Value> Sign::SignInit(const char* sign_type) {
2554   HandleScope scope(node_isolate);
2555
2556   assert(md_ == NULL);
2557   md_ = EVP_get_digestbyname(sign_type);
2558   if (!md_) {
2559     return ThrowError("Uknown message digest");
2560   }
2561   EVP_MD_CTX_init(&mdctx_);
2562   EVP_SignInit_ex(&mdctx_, md_, NULL);
2563   initialised_ = true;
2564   return Null(node_isolate);
2565 }
2566
2567
2568 Handle<Value> Sign::SignInit(const Arguments& args) {
2569   HandleScope scope(node_isolate);
2570
2571   Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
2572
2573   if (args.Length() == 0 || !args[0]->IsString()) {
2574     return ThrowError("Must give signtype string as argument");
2575   }
2576
2577   String::Utf8Value sign_type(args[0]);
2578
2579   Handle<Value> ret = sign->SignInit(*sign_type);
2580
2581   if (ret->IsNull()) {
2582     return args.This();
2583   } else {
2584     // Exception
2585     return scope.Close(ret);
2586   }
2587 }
2588
2589
2590 bool Sign::SignUpdate(char* data, int len) {
2591   if (!initialised_) return false;
2592   EVP_SignUpdate(&mdctx_, data, len);
2593   return true;
2594 }
2595
2596
2597 Handle<Value> Sign::SignUpdate(const Arguments& args) {
2598   HandleScope scope(node_isolate);
2599
2600   Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
2601
2602   ASSERT_IS_BUFFER(args[0]);
2603
2604   bool r;
2605
2606   char* buffer_data = Buffer::Data(args[0]);
2607   size_t buffer_length = Buffer::Length(args[0]);
2608
2609   r = sign->SignUpdate(buffer_data, buffer_length);
2610
2611   if (!r) {
2612     return ThrowTypeError("SignUpdate fail");
2613   }
2614
2615   return args.This();
2616 }
2617
2618
2619 bool Sign::SignFinal(unsigned char** md_value,
2620                      unsigned int *md_len,
2621                      char* key_pem,
2622                      int key_pem_len) {
2623   if (!initialised_) return false;
2624
2625   BIO* bp = NULL;
2626   EVP_PKEY* pkey = NULL;
2627   bp = BIO_new(BIO_s_mem());
2628   if (!BIO_write(bp, key_pem, key_pem_len)) return false;
2629
2630   pkey = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL);
2631   if (pkey == NULL) return 0;
2632
2633   EVP_SignFinal(&mdctx_, *md_value, md_len, pkey);
2634   EVP_MD_CTX_cleanup(&mdctx_);
2635   initialised_ = false;
2636   EVP_PKEY_free(pkey);
2637   BIO_free_all(bp);
2638   return true;
2639 }
2640
2641
2642 Handle<Value> Sign::SignFinal(const Arguments& args) {
2643   HandleScope scope(node_isolate);
2644
2645   Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
2646
2647   unsigned char* md_value;
2648   unsigned int md_len;
2649   Local<Value> outString;
2650
2651   md_len = 8192; // Maximum key size is 8192 bits
2652   md_value = new unsigned char[md_len];
2653
2654   ASSERT_IS_BUFFER(args[0]);
2655   ssize_t len = Buffer::Length(args[0]);
2656   char* buf = Buffer::Data(args[0]);
2657
2658   bool r = sign->SignFinal(&md_value, &md_len, buf, len);
2659   if (!r) {
2660     delete[] md_value;
2661     md_value = NULL;
2662     md_len = 0;
2663   }
2664
2665   Buffer* ret = Buffer::New(reinterpret_cast<char*>(md_value), md_len);
2666   delete[] md_value;
2667
2668   return scope.Close(ret->handle_);
2669 }
2670
2671
2672 void Verify::Initialize(v8::Handle<v8::Object> target) {
2673   HandleScope scope(node_isolate);
2674
2675   Local<FunctionTemplate> t = FunctionTemplate::New(New);
2676
2677   t->InstanceTemplate()->SetInternalFieldCount(1);
2678
2679   NODE_SET_PROTOTYPE_METHOD(t, "init", VerifyInit);
2680   NODE_SET_PROTOTYPE_METHOD(t, "update", VerifyUpdate);
2681   NODE_SET_PROTOTYPE_METHOD(t, "verify", VerifyFinal);
2682
2683   target->Set(String::NewSymbol("Verify"), t->GetFunction());
2684 }
2685
2686
2687 Handle<Value> Verify::New(const Arguments& args) {
2688   HandleScope scope(node_isolate);
2689
2690   Verify* verify = new Verify();
2691   verify->Wrap(args.This());
2692
2693   return args.This();
2694 }
2695
2696
2697 Handle<Value> Verify::VerifyInit(const char* verify_type) {
2698   HandleScope scope(node_isolate);
2699
2700   assert(md_ == NULL);
2701   md_ = EVP_get_digestbyname(verify_type);
2702   if (md_ == NULL) {
2703     return ThrowError("Unknown message digest");
2704   }
2705
2706   EVP_MD_CTX_init(&mdctx_);
2707   EVP_VerifyInit_ex(&mdctx_, md_, NULL);
2708   initialised_ = true;
2709
2710   return Null(node_isolate);
2711 }
2712
2713
2714 Handle<Value> Verify::VerifyInit(const Arguments& args) {
2715   HandleScope scope(node_isolate);
2716
2717   Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
2718
2719   if (args.Length() == 0 || !args[0]->IsString()) {
2720     return ThrowError("Must give verifytype string as argument");
2721   }
2722
2723   String::Utf8Value verify_type(args[0]);
2724
2725   Handle<Value> ret = verify->VerifyInit(*verify_type);
2726
2727   if (ret->IsNull()) {
2728     return args.This();
2729   } else {
2730     // Exception
2731     return scope.Close(ret);
2732   }
2733 }
2734
2735
2736 bool Verify::VerifyUpdate(char* data, int len) {
2737   if (!initialised_) return false;
2738   EVP_VerifyUpdate(&mdctx_, data, len);
2739   return true;
2740 }
2741
2742
2743 Handle<Value> Verify::VerifyUpdate(const Arguments& args) {
2744   HandleScope scope(node_isolate);
2745
2746   Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
2747
2748   ASSERT_IS_BUFFER(args[0]);
2749
2750   bool r;
2751
2752   char* buffer_data = Buffer::Data(args[0]);
2753   size_t buffer_length = Buffer::Length(args[0]);
2754
2755   r = verify->VerifyUpdate(buffer_data, buffer_length);
2756
2757   if (!r) {
2758     return ThrowTypeError("VerifyUpdate fail");
2759   }
2760
2761   return args.This();
2762 }
2763
2764
2765 Handle<Value> Verify::VerifyFinal(char* key_pem,
2766                                   int key_pem_len,
2767                                   unsigned char* sig,
2768                                   int siglen) {
2769   HandleScope scope(node_isolate);
2770
2771   if (!initialised_) {
2772     return ThrowError("Verify not initalised");
2773   }
2774
2775   EVP_PKEY* pkey = NULL;
2776   BIO* bp = NULL;
2777   X509* x509 = NULL;
2778   bool fatal = true;
2779   int r;
2780
2781   bp = BIO_new(BIO_s_mem());
2782   if (bp == NULL)
2783     goto exit;
2784
2785   if (!BIO_write(bp, key_pem, key_pem_len))
2786     goto exit;
2787
2788   // Check if this is a PKCS#8 or RSA public key before trying as X.509.
2789   // Split this out into a separate function once we have more than one
2790   // consumer of public keys.
2791   if (strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
2792     pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL);
2793     if (pkey == NULL)
2794       goto exit;
2795   } else if (strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
2796     RSA* rsa = PEM_read_bio_RSAPublicKey(bp, NULL, NULL, NULL);
2797     if (rsa) {
2798       pkey = EVP_PKEY_new();
2799       if (pkey) EVP_PKEY_set1_RSA(pkey, rsa);
2800       RSA_free(rsa);
2801     }
2802     if (pkey == NULL)
2803       goto exit;
2804   } else {
2805     // X.509 fallback
2806     x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
2807     if (x509 == NULL)
2808       goto exit;
2809
2810     pkey = X509_get_pubkey(x509);
2811     if (pkey == NULL)
2812       goto exit;
2813   }
2814
2815   fatal = false;
2816   r = EVP_VerifyFinal(&mdctx_, sig, siglen, pkey);
2817
2818 exit:
2819   if (pkey != NULL)
2820     EVP_PKEY_free(pkey);
2821   if (bp != NULL)
2822     BIO_free_all(bp);
2823   if (x509 != NULL)
2824     X509_free(x509);
2825
2826   EVP_MD_CTX_cleanup(&mdctx_);
2827   initialised_ = false;
2828
2829   if (fatal) {
2830     unsigned long err = ERR_get_error();
2831     return ThrowCryptoError(err);
2832   }
2833
2834   return scope.Close(r ? True() : False(node_isolate));
2835 }
2836
2837
2838 Handle<Value> Verify::VerifyFinal(const Arguments& args) {
2839   HandleScope scope(node_isolate);
2840
2841   Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
2842
2843   ASSERT_IS_BUFFER(args[0]);
2844   char* kbuf = Buffer::Data(args[0]);
2845   ssize_t klen = Buffer::Length(args[0]);
2846
2847   ASSERT_IS_BUFFER(args[1]);
2848   unsigned char* hbuf = reinterpret_cast<unsigned char*>(Buffer::Data(args[1]));
2849   ssize_t hlen = Buffer::Length(args[1]);
2850
2851   return scope.Close(verify->VerifyFinal(kbuf, klen, hbuf, hlen));
2852 }
2853
2854
2855 void DiffieHellman::Initialize(v8::Handle<v8::Object> target) {
2856   HandleScope scope(node_isolate);
2857
2858   Local<FunctionTemplate> t = FunctionTemplate::New(New);
2859
2860   t->InstanceTemplate()->SetInternalFieldCount(1);
2861
2862   NODE_SET_PROTOTYPE_METHOD(t, "generateKeys", GenerateKeys);
2863   NODE_SET_PROTOTYPE_METHOD(t, "computeSecret", ComputeSecret);
2864   NODE_SET_PROTOTYPE_METHOD(t, "getPrime", GetPrime);
2865   NODE_SET_PROTOTYPE_METHOD(t, "getGenerator", GetGenerator);
2866   NODE_SET_PROTOTYPE_METHOD(t, "getPublicKey", GetPublicKey);
2867   NODE_SET_PROTOTYPE_METHOD(t, "getPrivateKey", GetPrivateKey);
2868   NODE_SET_PROTOTYPE_METHOD(t, "setPublicKey", SetPublicKey);
2869   NODE_SET_PROTOTYPE_METHOD(t, "setPrivateKey", SetPrivateKey);
2870
2871   target->Set(String::NewSymbol("DiffieHellman"), t->GetFunction());
2872
2873   Local<FunctionTemplate> t2 = FunctionTemplate::New(DiffieHellmanGroup);
2874   t2->InstanceTemplate()->SetInternalFieldCount(1);
2875
2876   NODE_SET_PROTOTYPE_METHOD(t2, "generateKeys", GenerateKeys);
2877   NODE_SET_PROTOTYPE_METHOD(t2, "computeSecret", ComputeSecret);
2878   NODE_SET_PROTOTYPE_METHOD(t2, "getPrime", GetPrime);
2879   NODE_SET_PROTOTYPE_METHOD(t2, "getGenerator", GetGenerator);
2880   NODE_SET_PROTOTYPE_METHOD(t2, "getPublicKey", GetPublicKey);
2881   NODE_SET_PROTOTYPE_METHOD(t2, "getPrivateKey", GetPrivateKey);
2882
2883   target->Set(String::NewSymbol("DiffieHellmanGroup"), t2->GetFunction());
2884 }
2885
2886
2887 bool DiffieHellman::Init(int primeLength) {
2888   dh = DH_new();
2889   DH_generate_parameters_ex(dh, primeLength, DH_GENERATOR_2, 0);
2890   bool result = VerifyContext();
2891   if (!result) return false;
2892   initialised_ = true;
2893   return true;
2894 }
2895
2896
2897 bool DiffieHellman::Init(unsigned char* p, int p_len) {
2898   dh = DH_new();
2899   dh->p = BN_bin2bn(p, p_len, 0);
2900   dh->g = BN_new();
2901   if (!BN_set_word(dh->g, 2)) return false;
2902   bool result = VerifyContext();
2903   if (!result) return false;
2904   initialised_ = true;
2905   return true;
2906 }
2907
2908
2909 bool DiffieHellman::Init(unsigned char* p,
2910                          int p_len,
2911                          unsigned char* g,
2912                          int g_len) {
2913   dh = DH_new();
2914   dh->p = BN_bin2bn(p, p_len, 0);
2915   dh->g = BN_bin2bn(g, g_len, 0);
2916   initialised_ = true;
2917   return true;
2918 }
2919
2920
2921 Handle<Value> DiffieHellman::DiffieHellmanGroup(const Arguments& args) {
2922   HandleScope scope(node_isolate);
2923
2924   DiffieHellman* diffieHellman = new DiffieHellman();
2925
2926   if (args.Length() != 1 || !args[0]->IsString()) {
2927     return ThrowError("No group name given");
2928   }
2929
2930   String::Utf8Value group_name(args[0]);
2931
2932   modp_group* it = modp_groups;
2933
2934   while(it->name != NULL) {
2935     if (!strcasecmp(*group_name, it->name))
2936       break;
2937     it++;
2938   }
2939
2940   if (it->name != NULL) {
2941     diffieHellman->Init(it->prime,
2942                         it->prime_size,
2943                         it->gen,
2944                         it->gen_size);
2945   } else {
2946     return ThrowError("Unknown group");
2947   }
2948
2949   diffieHellman->Wrap(args.This());
2950
2951   return args.This();
2952 }
2953
2954
2955 Handle<Value> DiffieHellman::New(const Arguments& args) {
2956   HandleScope scope(node_isolate);
2957
2958   DiffieHellman* diffieHellman = new DiffieHellman();
2959   bool initialized = false;
2960
2961   if (args.Length() > 0) {
2962     if (args[0]->IsInt32()) {
2963       initialized = diffieHellman->Init(args[0]->Int32Value());
2964     } else {
2965       initialized = diffieHellman->Init(
2966               reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
2967               Buffer::Length(args[0]));
2968     }
2969   }
2970
2971   if (!initialized) {
2972     return ThrowError("Initialization failed");
2973   }
2974
2975   diffieHellman->Wrap(args.This());
2976
2977   return args.This();
2978 }
2979
2980
2981 Handle<Value> DiffieHellman::GenerateKeys(const Arguments& args) {
2982   HandleScope scope(node_isolate);
2983
2984   DiffieHellman* diffieHellman =
2985       ObjectWrap::Unwrap<DiffieHellman>(args.This());
2986
2987   if (!diffieHellman->initialised_) {
2988     return ThrowError("Not initialized");
2989   }
2990
2991   if (!DH_generate_key(diffieHellman->dh)) {
2992     return ThrowError("Key generation failed");
2993   }
2994
2995   Local<Value> outString;
2996
2997   int dataSize = BN_num_bytes(diffieHellman->dh->pub_key);
2998   char* data = new char[dataSize];
2999   BN_bn2bin(diffieHellman->dh->pub_key,
3000             reinterpret_cast<unsigned char*>(data));
3001
3002   outString = Encode(data, dataSize, BUFFER);
3003   delete[] data;
3004
3005   return scope.Close(outString);
3006 }
3007
3008
3009 Handle<Value> DiffieHellman::GetPrime(const Arguments& args) {
3010   HandleScope scope(node_isolate);
3011
3012   DiffieHellman* diffieHellman =
3013       ObjectWrap::Unwrap<DiffieHellman>(args.This());
3014
3015   if (!diffieHellman->initialised_) {
3016     return ThrowError("Not initialized");
3017   }
3018
3019   int dataSize = BN_num_bytes(diffieHellman->dh->p);
3020   char* data = new char[dataSize];
3021   BN_bn2bin(diffieHellman->dh->p, reinterpret_cast<unsigned char*>(data));
3022
3023   Local<Value> outString;
3024
3025   outString = Encode(data, dataSize, BUFFER);
3026
3027   delete[] data;
3028
3029   return scope.Close(outString);
3030 }
3031
3032
3033 Handle<Value> DiffieHellman::GetGenerator(const Arguments& args) {
3034   HandleScope scope(node_isolate);
3035
3036   DiffieHellman* diffieHellman =
3037       ObjectWrap::Unwrap<DiffieHellman>(args.This());
3038
3039   if (!diffieHellman->initialised_) {
3040     return ThrowError("Not initialized");
3041   }
3042
3043   int dataSize = BN_num_bytes(diffieHellman->dh->g);
3044   char* data = new char[dataSize];
3045   BN_bn2bin(diffieHellman->dh->g, reinterpret_cast<unsigned char*>(data));
3046
3047   Local<Value> outString;
3048
3049   outString = Encode(data, dataSize, BUFFER);
3050
3051   delete[] data;
3052
3053   return scope.Close(outString);
3054 }
3055
3056
3057 Handle<Value> DiffieHellman::GetPublicKey(const Arguments& args) {
3058   HandleScope scope(node_isolate);
3059
3060   DiffieHellman* diffieHellman =
3061       ObjectWrap::Unwrap<DiffieHellman>(args.This());
3062
3063   if (!diffieHellman->initialised_) {
3064     return ThrowError("Not initialized");
3065   }
3066
3067   if (diffieHellman->dh->pub_key == NULL) {
3068     return ThrowError("No public key - did you forget to generate one?");
3069   }
3070
3071   int dataSize = BN_num_bytes(diffieHellman->dh->pub_key);
3072   char* data = new char[dataSize];
3073   BN_bn2bin(diffieHellman->dh->pub_key,
3074             reinterpret_cast<unsigned char*>(data));
3075
3076   Local<Value> outString;
3077
3078   outString = Encode(data, dataSize, BUFFER);
3079
3080   delete[] data;
3081
3082   return scope.Close(outString);
3083 }
3084
3085
3086 Handle<Value> DiffieHellman::GetPrivateKey(const Arguments& args) {
3087   HandleScope scope(node_isolate);
3088
3089   DiffieHellman* diffieHellman =
3090       ObjectWrap::Unwrap<DiffieHellman>(args.This());
3091
3092   if (!diffieHellman->initialised_) {
3093     return ThrowError("Not initialized");
3094   }
3095
3096   if (diffieHellman->dh->priv_key == NULL) {
3097     return ThrowError("No private key - did you forget to generate one?");
3098   }
3099
3100   int dataSize = BN_num_bytes(diffieHellman->dh->priv_key);
3101   char* data = new char[dataSize];
3102   BN_bn2bin(diffieHellman->dh->priv_key,
3103             reinterpret_cast<unsigned char*>(data));
3104
3105   Local<Value> outString;
3106
3107   outString = Encode(data, dataSize, BUFFER);
3108
3109   delete[] data;
3110
3111   return scope.Close(outString);
3112 }
3113
3114
3115 Handle<Value> DiffieHellman::ComputeSecret(const Arguments& args) {
3116   HandleScope scope(node_isolate);
3117
3118   DiffieHellman* diffieHellman =
3119       ObjectWrap::Unwrap<DiffieHellman>(args.This());
3120
3121   if (!diffieHellman->initialised_) {
3122     return ThrowError("Not initialized");
3123   }
3124
3125   BIGNUM* key = NULL;
3126
3127   if (args.Length() == 0) {
3128     return ThrowError("First argument must be other party's public key");
3129   } else {
3130     ASSERT_IS_BUFFER(args[0]);
3131     key = BN_bin2bn(
3132         reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3133         Buffer::Length(args[0]),
3134         0);
3135   }
3136
3137   int dataSize = DH_size(diffieHellman->dh);
3138   char* data = new char[dataSize];
3139
3140   int size = DH_compute_key(reinterpret_cast<unsigned char*>(data),
3141                             key,
3142                             diffieHellman->dh);
3143
3144   if (size == -1) {
3145     int checkResult;
3146     int checked;
3147
3148     checked = DH_check_pub_key(diffieHellman->dh, key, &checkResult);
3149     BN_free(key);
3150     delete[] data;
3151
3152     if (!checked) {
3153       return ThrowError("Invalid key");
3154     } else if (checkResult) {
3155       if (checkResult & DH_CHECK_PUBKEY_TOO_SMALL) {
3156         return ThrowError("Supplied key is too small");
3157       } else if (checkResult & DH_CHECK_PUBKEY_TOO_LARGE) {
3158         return ThrowError("Supplied key is too large");
3159       } else {
3160         return ThrowError("Invalid key");
3161       }
3162     } else {
3163       return ThrowError("Invalid key");
3164     }
3165   }
3166
3167   BN_free(key);
3168   assert(size >= 0);
3169
3170   // DH_size returns number of bytes in a prime number
3171   // DH_compute_key returns number of bytes in a remainder of exponent, which
3172   // may have less bytes than a prime number. Therefore add 0-padding to the
3173   // allocated buffer.
3174   if (size != dataSize) {
3175     assert(dataSize > size);
3176     memset(data + size, 0, dataSize - size);
3177   }
3178
3179   Local<Value> outString;
3180
3181   outString = Encode(data, dataSize, BUFFER);
3182
3183   delete[] data;
3184   return scope.Close(outString);
3185 }
3186
3187
3188 Handle<Value> DiffieHellman::SetPublicKey(const Arguments& args) {
3189   HandleScope scope(node_isolate);
3190
3191   DiffieHellman* diffieHellman =
3192       ObjectWrap::Unwrap<DiffieHellman>(args.This());
3193
3194   if (!diffieHellman->initialised_) {
3195     return ThrowError("Not initialized");
3196   }
3197
3198   if (args.Length() == 0) {
3199     return ThrowError("First argument must be public key");
3200   } else {
3201     ASSERT_IS_BUFFER(args[0]);
3202     diffieHellman->dh->pub_key = BN_bin2bn(
3203         reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3204         Buffer::Length(args[0]), 0);
3205   }
3206
3207   return args.This();
3208 }
3209
3210
3211 Handle<Value> DiffieHellman::SetPrivateKey(const Arguments& args) {
3212   HandleScope scope(node_isolate);
3213
3214   DiffieHellman* diffieHellman =
3215       ObjectWrap::Unwrap<DiffieHellman>(args.This());
3216
3217   if (!diffieHellman->initialised_) {
3218     return ThrowError("Not initialized");
3219   }
3220
3221   if (args.Length() == 0) {
3222     return ThrowError("First argument must be private key");
3223   } else {
3224     ASSERT_IS_BUFFER(args[0]);
3225     diffieHellman->dh->priv_key = BN_bin2bn(
3226         reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
3227         Buffer::Length(args[0]),
3228         0);
3229   }
3230
3231   return args.This();
3232 }
3233
3234
3235 bool DiffieHellman::VerifyContext() {
3236   int codes;
3237   if (!DH_check(dh, &codes)) return false;
3238   if (codes & DH_CHECK_P_NOT_SAFE_PRIME) return false;
3239   if (codes & DH_CHECK_P_NOT_PRIME) return false;
3240   if (codes & DH_UNABLE_TO_CHECK_GENERATOR) return false;
3241   if (codes & DH_NOT_SUITABLE_GENERATOR) return false;
3242   return true;
3243 }
3244
3245
3246 struct pbkdf2_req {
3247   uv_work_t work_req;
3248   int err;
3249   char* pass;
3250   size_t passlen;
3251   char* salt;
3252   size_t saltlen;
3253   size_t iter;
3254   char* key;
3255   size_t keylen;
3256   Persistent<Object> obj;
3257 };
3258
3259
3260 void EIO_PBKDF2(pbkdf2_req* req) {
3261   req->err = PKCS5_PBKDF2_HMAC_SHA1(
3262     req->pass,
3263     req->passlen,
3264     (unsigned char*)req->salt,
3265     req->saltlen,
3266     req->iter,
3267     req->keylen,
3268     (unsigned char*)req->key);
3269   memset(req->pass, 0, req->passlen);
3270   memset(req->salt, 0, req->saltlen);
3271 }
3272
3273
3274 void EIO_PBKDF2(uv_work_t* work_req) {
3275   pbkdf2_req* req = container_of(work_req, pbkdf2_req, work_req);
3276   EIO_PBKDF2(req);
3277 }
3278
3279
3280 void EIO_PBKDF2After(pbkdf2_req* req, Local<Value> argv[2]) {
3281   if (req->err) {
3282     argv[0] = Local<Value>::New(node_isolate, Undefined(node_isolate));
3283     argv[1] = Encode(req->key, req->keylen, BUFFER);
3284     memset(req->key, 0, req->keylen);
3285   } else {
3286     argv[0] = Exception::Error(String::New("PBKDF2 error"));
3287     argv[1] = Local<Value>::New(node_isolate, Undefined(node_isolate));
3288   }
3289
3290   delete[] req->pass;
3291   delete[] req->salt;
3292   delete[] req->key;
3293   delete req;
3294 }
3295
3296
3297 void EIO_PBKDF2After(uv_work_t* work_req, int status) {
3298   assert(status == 0);
3299   pbkdf2_req* req = container_of(work_req, pbkdf2_req, work_req);
3300   HandleScope scope(node_isolate);
3301   Local<Value> argv[2];
3302   Persistent<Object> obj = req->obj;
3303   EIO_PBKDF2After(req, argv);
3304   MakeCallback(obj, "ondone", ARRAY_SIZE(argv), argv);
3305   obj.Dispose(node_isolate);
3306 }
3307
3308
3309 Handle<Value> PBKDF2(const Arguments& args) {
3310   HandleScope scope(node_isolate);
3311
3312   const char* type_error = NULL;
3313   char* pass = NULL;
3314   char* salt = NULL;
3315   ssize_t passlen = -1;
3316   ssize_t saltlen = -1;
3317   ssize_t keylen = -1;
3318   ssize_t pass_written = -1;
3319   ssize_t salt_written = -1;
3320   ssize_t iter = -1;
3321   pbkdf2_req* req = NULL;
3322
3323   if (args.Length() != 4 && args.Length() != 5) {
3324     type_error = "Bad parameter";
3325     goto err;
3326   }
3327
3328   ASSERT_IS_BUFFER(args[0]);
3329   passlen = Buffer::Length(args[0]);
3330   if (passlen < 0) {
3331     type_error = "Bad password";
3332     goto err;
3333   }
3334
3335   pass = new char[passlen];
3336   pass_written = DecodeWrite(pass, passlen, args[0], BINARY);
3337   assert(pass_written == passlen);
3338
3339   ASSERT_IS_BUFFER(args[1]);
3340   saltlen = Buffer::Length(args[1]);
3341   if (saltlen < 0) {
3342     type_error = "Bad salt";
3343     goto err;
3344   }
3345
3346   salt = new char[saltlen];
3347   salt_written = DecodeWrite(salt, saltlen, args[1], BINARY);
3348   assert(salt_written == saltlen);
3349
3350   if (!args[2]->IsNumber()) {
3351     type_error = "Iterations not a number";
3352     goto err;
3353   }
3354
3355   iter = args[2]->Int32Value();
3356   if (iter < 0) {
3357     type_error = "Bad iterations";
3358     goto err;
3359   }
3360
3361   if (!args[3]->IsNumber()) {
3362     type_error = "Key length not a number";
3363     goto err;
3364   }
3365
3366   keylen = args[3]->Int32Value();
3367   if (keylen < 0) {
3368     type_error = "Bad key length";
3369     goto err;
3370   }
3371
3372   req = new pbkdf2_req;
3373   req->err = 0;
3374   req->pass = pass;
3375   req->passlen = passlen;
3376   req->salt = salt;
3377   req->saltlen = saltlen;
3378   req->iter = iter;
3379   req->key = new char[keylen];
3380   req->keylen = keylen;
3381
3382   if (args[4]->IsFunction()) {
3383     req->obj = Persistent<Object>::New(node_isolate, Object::New());
3384     req->obj->Set(String::New("ondone"), args[4]);
3385     uv_queue_work(uv_default_loop(),
3386                   &req->work_req,
3387                   EIO_PBKDF2,
3388                   EIO_PBKDF2After);
3389     return Undefined(node_isolate);
3390   } else {
3391     Local<Value> argv[2];
3392     EIO_PBKDF2(req);
3393     EIO_PBKDF2After(req, argv);
3394     if (argv[0]->IsObject()) return ThrowException(argv[0]);
3395     return scope.Close(argv[1]);
3396   }
3397
3398 err:
3399   delete[] salt;
3400   delete[] pass;
3401   return ThrowException(Exception::TypeError(String::New(type_error)));
3402 }
3403
3404
3405 struct RandomBytesRequest {
3406   ~RandomBytesRequest();
3407   Persistent<Object> obj_;
3408   unsigned long error_; // openssl error code or zero
3409   uv_work_t work_req_;
3410   size_t size_;
3411   char* data_;
3412 };
3413
3414
3415 RandomBytesRequest::~RandomBytesRequest() {
3416   if (obj_.IsEmpty()) return;
3417   obj_.Dispose(node_isolate);
3418   obj_.Clear();
3419 }
3420
3421
3422 void RandomBytesFree(char* data, void* hint) {
3423   delete[] data;
3424 }
3425
3426
3427 template <bool pseudoRandom>
3428 void RandomBytesWork(uv_work_t* work_req) {
3429   RandomBytesRequest* req = container_of(work_req,
3430                                          RandomBytesRequest,
3431                                          work_req_);
3432   int r;
3433
3434   if (pseudoRandom == true) {
3435     r = RAND_pseudo_bytes(reinterpret_cast<unsigned char*>(req->data_),
3436                           req->size_);
3437   } else {
3438     r = RAND_bytes(reinterpret_cast<unsigned char*>(req->data_), req->size_);
3439   }
3440
3441   // RAND_bytes() returns 0 on error. RAND_pseudo_bytes() returns 0 when the
3442   // result is not cryptographically strong - but that's not an error.
3443   if (r == 0 && pseudoRandom == false) {
3444     req->error_ = ERR_get_error();
3445   } else if (r == -1) {
3446     req->error_ = static_cast<unsigned long>(-1);
3447   }
3448 }
3449
3450
3451 // don't call this function without a valid HandleScope
3452 void RandomBytesCheck(RandomBytesRequest* req, Local<Value> argv[2]) {
3453   if (req->error_) {
3454     char errmsg[256] = "Operation not supported";
3455
3456     if (req->error_ != (unsigned long) -1)
3457       ERR_error_string_n(req->error_, errmsg, sizeof errmsg);
3458
3459     argv[0] = Exception::Error(String::New(errmsg));
3460     argv[1] = Local<Value>::New(node_isolate, Null(node_isolate));
3461   }
3462   else {
3463     // avoids the malloc + memcpy
3464     Buffer* buffer = Buffer::New(req->data_, req->size_, RandomBytesFree, NULL);
3465     argv[0] = Local<Value>::New(node_isolate, Null(node_isolate));
3466     argv[1] = Local<Object>::New(node_isolate, buffer->handle_);
3467   }
3468 }
3469
3470
3471 void RandomBytesAfter(uv_work_t* work_req, int status) {
3472   assert(status == 0);
3473   RandomBytesRequest* req = container_of(work_req,
3474                                          RandomBytesRequest,
3475                                          work_req_);
3476   HandleScope scope(node_isolate);
3477   Local<Value> argv[2];
3478   RandomBytesCheck(req, argv);
3479   MakeCallback(req->obj_, "ondone", ARRAY_SIZE(argv), argv);
3480   delete req;
3481 }
3482
3483
3484 template <bool pseudoRandom>
3485 Handle<Value> RandomBytes(const Arguments& args) {
3486   HandleScope scope(node_isolate);
3487
3488   // maybe allow a buffer to write to? cuts down on object creation
3489   // when generating random data in a loop
3490   if (!args[0]->IsUint32()) {
3491     return ThrowTypeError("Argument #1 must be number > 0");
3492   }
3493
3494   const uint32_t size = args[0]->Uint32Value();
3495   if (size > Buffer::kMaxLength) {
3496     return ThrowTypeError("size > Buffer::kMaxLength");
3497   }
3498
3499   RandomBytesRequest* req = new RandomBytesRequest();
3500   req->error_ = 0;
3501   req->data_ = new char[size];
3502   req->size_ = size;
3503
3504   if (args[1]->IsFunction()) {
3505     req->obj_ = Persistent<Object>::New(node_isolate, Object::New());
3506     req->obj_->Set(String::New("ondone"), args[1]);
3507
3508     uv_queue_work(uv_default_loop(),
3509                   &req->work_req_,
3510                   RandomBytesWork<pseudoRandom>,
3511                   RandomBytesAfter);
3512
3513     return req->obj_;
3514   }
3515   else {
3516     Local<Value> argv[2];
3517     RandomBytesWork<pseudoRandom>(&req->work_req_);
3518     RandomBytesCheck(req, argv);
3519     delete req;
3520
3521     if (!argv[0]->IsNull())
3522       return ThrowException(argv[0]);
3523     else
3524       return argv[1];
3525   }
3526 }
3527
3528
3529 Handle<Value> GetSSLCiphers(const Arguments& args) {
3530   HandleScope scope(node_isolate);
3531
3532   SSL_CTX* ctx = SSL_CTX_new(TLSv1_server_method());
3533   if (ctx == NULL) {
3534     return ThrowError("SSL_CTX_new() failed.");
3535   }
3536
3537   SSL* ssl = SSL_new(ctx);
3538   if (ssl == NULL) {
3539     SSL_CTX_free(ctx);
3540     return ThrowError("SSL_new() failed.");
3541   }
3542
3543   Local<Array> arr = Array::New();
3544   STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl);
3545
3546   for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
3547     SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
3548     arr->Set(i, String::New(SSL_CIPHER_get_name(cipher)));
3549   }
3550
3551   SSL_free(ssl);
3552   SSL_CTX_free(ctx);
3553
3554   return scope.Close(arr);
3555 }
3556
3557
3558 template <class TypeName>
3559 static void array_push_back(const TypeName* md,
3560                             const char* from,
3561                             const char* to,
3562                             void* arg) {
3563   Local<Array>& arr = *static_cast<Local<Array>*>(arg);
3564   arr->Set(arr->Length(), String::New(from));
3565 }
3566
3567
3568 Handle<Value> GetCiphers(const Arguments& args) {
3569   HandleScope scope;
3570   Local<Array> arr = Array::New();
3571   EVP_CIPHER_do_all_sorted(array_push_back<EVP_CIPHER>, &arr);
3572   return scope.Close(arr);
3573 }
3574
3575
3576 Handle<Value> GetHashes(const Arguments& args) {
3577   HandleScope scope(node_isolate);
3578   Local<Array> arr = Array::New();
3579   EVP_MD_do_all_sorted(array_push_back<EVP_MD>, &arr);
3580   return scope.Close(arr);
3581 }
3582
3583
3584 void InitCrypto(Handle<Object> target) {
3585   HandleScope scope(node_isolate);
3586
3587   SSL_library_init();
3588   OpenSSL_add_all_algorithms();
3589   OpenSSL_add_all_digests();
3590   SSL_load_error_strings();
3591   ERR_load_crypto_strings();
3592
3593   crypto_lock_init();
3594   CRYPTO_set_locking_callback(crypto_lock_cb);
3595   CRYPTO_THREADID_set_callback(crypto_threadid_cb);
3596
3597   // Turn off compression. Saves memory - do it in userland.
3598 #if !defined(OPENSSL_NO_COMP)
3599   STACK_OF(SSL_COMP)* comp_methods =
3600 #if OPENSSL_VERSION_NUMBER < 0x00908000L
3601     SSL_COMP_get_compression_method()
3602 #else
3603     SSL_COMP_get_compression_methods()
3604 #endif
3605   ;
3606   sk_SSL_COMP_zero(comp_methods);
3607   assert(sk_SSL_COMP_num(comp_methods) == 0);
3608 #endif
3609
3610   SecureContext::Initialize(target);
3611   Connection::Initialize(target);
3612   CipherBase::Initialize(target);
3613   DiffieHellman::Initialize(target);
3614   Hmac::Initialize(target);
3615   Hash::Initialize(target);
3616   Sign::Initialize(target);
3617   Verify::Initialize(target);
3618
3619   NODE_SET_METHOD(target, "PBKDF2", PBKDF2);
3620   NODE_SET_METHOD(target, "randomBytes", RandomBytes<false>);
3621   NODE_SET_METHOD(target, "pseudoRandomBytes", RandomBytes<true>);
3622   NODE_SET_METHOD(target, "getSSLCiphers", GetSSLCiphers);
3623   NODE_SET_METHOD(target, "getCiphers", GetCiphers);
3624   NODE_SET_METHOD(target, "getHashes", GetHashes);
3625
3626   subject_symbol    = NODE_PSYMBOL("subject");
3627   issuer_symbol     = NODE_PSYMBOL("issuer");
3628   valid_from_symbol = NODE_PSYMBOL("valid_from");
3629   valid_to_symbol   = NODE_PSYMBOL("valid_to");
3630   subjectaltname_symbol = NODE_PSYMBOL("subjectaltname");
3631   modulus_symbol        = NODE_PSYMBOL("modulus");
3632   exponent_symbol       = NODE_PSYMBOL("exponent");
3633   fingerprint_symbol   = NODE_PSYMBOL("fingerprint");
3634   name_symbol       = NODE_PSYMBOL("name");
3635   version_symbol    = NODE_PSYMBOL("version");
3636   ext_key_usage_symbol = NODE_PSYMBOL("ext_key_usage");
3637 }
3638
3639 }  // namespace crypto
3640 }  // namespace node
3641
3642 NODE_MODULE(node_crypto, node::crypto::InitCrypto)