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