Skip to content

Commit 52ec001

Browse files
committed
tls: use SSL_set_cert_cb for async SNI/OCSP
Do not enable ClientHello parser for async SNI/OCSP. Use new OpenSSL-1.0.2's API `SSL_set_cert_cb` to pause the handshake process and load the cert/OCSP response asynchronously. Hopefuly this will make whole async SNI/OCSP process much faster and will eventually let us remove the ClientHello parser itself (which is currently used only for async session, see #1462 for the discussion of removing it). NOTE: Ported our code to `SSL_CTX_add1_chain_cert` to use `SSL_CTX_get0_chain_certs` in `CertCbDone`. Test provided for this feature. Fix: #1423
1 parent 2f6986e commit 52ec001

23 files changed

+439
-95
lines changed

lib/_tls_wrap.js

Lines changed: 23 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -141,29 +141,23 @@ function onclienthello(hello) {
141141
if (err)
142142
return self.destroy(err);
143143

144-
// Servername came from SSL session
145-
// NOTE: TLS Session ticket doesn't include servername information
146-
//
147-
// Another note, From RFC3546:
148-
//
149-
// If, on the other hand, the older
150-
// session is resumed, then the server MUST ignore extensions appearing
151-
// in the client hello, and send a server hello containing no
152-
// extensions; in this case the extension functionality negotiated
153-
// during the original session initiation is applied to the resumed
154-
// session.
155-
//
156-
// Therefore we should account session loading when dealing with servername
157-
var servername = session && session.servername || hello.servername;
158-
loadSNI(self, servername, function(err, ctx) {
144+
self._handle.endParser();
145+
});
146+
}
147+
148+
149+
function oncertcb(info) {
150+
var self = this;
151+
var servername = info.servername;
152+
153+
loadSNI(self, servername, function(err, ctx) {
154+
if (err)
155+
return self.destroy(err);
156+
requestOCSP(self, info, ctx, function(err) {
159157
if (err)
160158
return self.destroy(err);
161-
requestOCSP(self, hello, ctx, function(err) {
162-
if (err)
163-
return self.destroy(err);
164159

165-
self._handle.endParser();
166-
});
160+
self._handle.certCbDone();
167161
});
168162
});
169163
}
@@ -325,15 +319,18 @@ TLSSocket.prototype._init = function(socket, wrap) {
325319
ssl.onhandshakestart = onhandshakestart.bind(this);
326320
ssl.onhandshakedone = onhandshakedone.bind(this);
327321
ssl.onclienthello = onclienthello.bind(this);
322+
ssl.oncertcb = oncertcb.bind(this);
328323
ssl.onnewsession = onnewsession.bind(this);
329324
ssl.lastHandshakeTime = 0;
330325
ssl.handshakes = 0;
331326

332-
if (this.server &&
333-
(listenerCount(this.server, 'resumeSession') > 0 ||
334-
listenerCount(this.server, 'newSession') > 0 ||
335-
listenerCount(this.server, 'OCSPRequest') > 0)) {
336-
ssl.enableSessionCallbacks();
327+
if (this.server) {
328+
if (listenerCount(this.server, 'resumeSession') > 0 ||
329+
listenerCount(this.server, 'newSession') > 0) {
330+
ssl.enableSessionCallbacks();
331+
}
332+
if (listenerCount(this.server, 'OCSPRequest') > 0)
333+
ssl.enableCertCb();
337334
}
338335
} else {
339336
ssl.onhandshakestart = function() {};
@@ -374,7 +371,7 @@ TLSSocket.prototype._init = function(socket, wrap) {
374371
options.server._contexts.length)) {
375372
assert(typeof options.SNICallback === 'function');
376373
this._SNICallback = options.SNICallback;
377-
ssl.enableHelloParser();
374+
ssl.enableCertCb();
378375
}
379376

380377
if (process.features.tls_npn && options.NPNProtocols)

src/env.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ namespace node {
5555
V(bytes_parsed_string, "bytesParsed") \
5656
V(callback_string, "callback") \
5757
V(change_string, "change") \
58+
V(oncertcb_string, "oncertcb") \
5859
V(onclose_string, "_onclose") \
5960
V(code_string, "code") \
6061
V(compare_string, "compare") \

src/node_crypto.cc

Lines changed: 129 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ template int SSLWrap<TLSWrap>::SelectNextProtoCallback(
131131
void* arg);
132132
#endif
133133
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
134+
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
135+
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
134136

135137

136138
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
@@ -509,7 +511,8 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
509511
}
510512

511513
while ((ca = PEM_read_bio_X509(in, nullptr, CryptoPemCallback, nullptr))) {
512-
r = SSL_CTX_add_extra_chain_cert(ctx, ca);
514+
// NOTE: Increments reference count on `ca`
515+
r = SSL_CTX_add1_chain_cert(ctx, ca);
513516

514517
if (!r) {
515518
X509_free(ca);
@@ -978,6 +981,7 @@ void SSLWrap<Base>::AddMethods(Environment* env, Handle<FunctionTemplate> t) {
978981
env->SetProtoMethod(t, "verifyError", VerifyError);
979982
env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
980983
env->SetProtoMethod(t, "endParser", EndParser);
984+
env->SetProtoMethod(t, "certCbDone", CertCbDone);
981985
env->SetProtoMethod(t, "renegotiate", Renegotiate);
982986
env->SetProtoMethod(t, "shutdownSSL", Shutdown);
983987
env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket);
@@ -1860,6 +1864,122 @@ int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
18601864
#endif // NODE__HAVE_TLSEXT_STATUS_CB
18611865

18621866

1867+
template <class Base>
1868+
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
1869+
cert_cb_ = cb;
1870+
cert_cb_arg_ = arg;
1871+
}
1872+
1873+
1874+
template <class Base>
1875+
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
1876+
Base* w = static_cast<Base*>(SSL_get_app_data(s));
1877+
1878+
if (!w->is_server())
1879+
return 1;
1880+
1881+
if (!w->is_waiting_cert_cb())
1882+
return 1;
1883+
1884+
if (w->cert_cb_running_)
1885+
return -1;
1886+
1887+
Environment* env = w->env();
1888+
HandleScope handle_scope(env->isolate());
1889+
Context::Scope context_scope(env->context());
1890+
w->cert_cb_running_ = true;
1891+
1892+
Local<Object> info = Object::New(env->isolate());
1893+
1894+
SSL_SESSION* sess = SSL_get_session(s);
1895+
if (sess != nullptr) {
1896+
if (sess->tlsext_hostname == nullptr) {
1897+
info->Set(env->servername_string(), String::Empty(env->isolate()));
1898+
} else {
1899+
Local<String> servername = OneByteString(env->isolate(),
1900+
sess->tlsext_hostname,
1901+
strlen(sess->tlsext_hostname));
1902+
info->Set(env->servername_string(), servername);
1903+
}
1904+
info->Set(env->tls_ticket_string(),
1905+
Boolean::New(env->isolate(), sess->tlsext_ticklen != 0));
1906+
}
1907+
bool ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp;
1908+
info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp));
1909+
1910+
Local<Value> argv[] = { info };
1911+
w->MakeCallback(env->oncertcb_string(), ARRAY_SIZE(argv), argv);
1912+
1913+
if (!w->cert_cb_running_)
1914+
return 1;
1915+
1916+
// Performing async action, wait...
1917+
return -1;
1918+
}
1919+
1920+
1921+
template <class Base>
1922+
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
1923+
Base* w = Unwrap<Base>(args.Holder());
1924+
Environment* env = w->env();
1925+
1926+
CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
1927+
1928+
Local<Object> object = w->object();
1929+
Local<Value> ctx = object->Get(env->sni_context_string());
1930+
Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1931+
1932+
// Not an object, probably undefined or null
1933+
if (!ctx->IsObject())
1934+
goto fire_cb;
1935+
1936+
if (cons->HasInstance(ctx)) {
1937+
SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1938+
w->sni_context_.Reset();
1939+
w->sni_context_.Reset(env->isolate(), ctx);
1940+
1941+
int rv;
1942+
1943+
// NOTE: reference count is not increased by this API methods
1944+
X509* x509 = SSL_CTX_get0_certificate(sc->ctx_);
1945+
EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_);
1946+
STACK_OF(X509)* chain;
1947+
1948+
rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain);
1949+
if (rv)
1950+
rv = SSL_use_certificate(w->ssl_, x509);
1951+
if (rv)
1952+
rv = SSL_use_PrivateKey(w->ssl_, pkey);
1953+
if (rv && chain != nullptr)
1954+
rv = SSL_set1_chain(w->ssl_, chain);
1955+
if (!rv) {
1956+
unsigned long err = ERR_get_error();
1957+
if (!err)
1958+
return env->ThrowError("CertCbDone");
1959+
return ThrowCryptoError(env, err);
1960+
}
1961+
} else {
1962+
// Failure: incorrect SNI context object
1963+
Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1964+
w->MakeCallback(env->onerror_string(), 1, &err);
1965+
return;
1966+
}
1967+
1968+
fire_cb:
1969+
CertCb cb;
1970+
void* arg;
1971+
1972+
cb = w->cert_cb_;
1973+
arg = w->cert_cb_arg_;
1974+
1975+
w->cert_cb_running_ = false;
1976+
w->cert_cb_ = nullptr;
1977+
w->cert_cb_arg_ = nullptr;
1978+
1979+
cb(arg);
1980+
}
1981+
1982+
18631983
template <class Base>
18641984
void SSLWrap<Base>::SSLGetter(Local<String> property,
18651985
const PropertyCallbackInfo<Value>& info) {
@@ -1955,6 +2075,10 @@ int Connection::HandleSSLError(const char* func,
19552075
DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
19562076
return 0;
19572077

2078+
} else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2079+
DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2080+
return 0;
2081+
19582082
} else if (err == SSL_ERROR_ZERO_RETURN) {
19592083
HandleScope scope(ssl_env()->isolate());
19602084

@@ -2120,7 +2244,7 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
21202244

21212245
// Call the SNI callback and use its return value as context
21222246
if (!conn->sniObject_.IsEmpty()) {
2123-
conn->sniContext_.Reset();
2247+
conn->sni_context_.Reset();
21242248

21252249
Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
21262250
Local<Value> ret = conn->MakeCallback(env->onselect_string(), 1, &arg);
@@ -2129,7 +2253,7 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
21292253
Local<FunctionTemplate> secure_context_constructor_template =
21302254
env->secure_context_constructor_template();
21312255
if (secure_context_constructor_template->HasInstance(ret)) {
2132-
conn->sniContext_.Reset(env->isolate(), ret);
2256+
conn->sni_context_.Reset(env->isolate(), ret);
21332257
SecureContext* sc = Unwrap<SecureContext>(ret.As<Object>());
21342258
InitNPN(sc);
21352259
SSL_set_SSL_CTX(s, sc->ctx_);
@@ -2168,6 +2292,8 @@ void Connection::New(const FunctionCallbackInfo<Value>& args) {
21682292

21692293
InitNPN(sc);
21702294

2295+
SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
2296+
21712297
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
21722298
if (is_server) {
21732299
SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);

src/node_crypto.h

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,10 @@ class SSLWrap {
138138
kind_(kind),
139139
next_sess_(nullptr),
140140
session_callbacks_(false),
141-
new_session_wait_(false) {
141+
new_session_wait_(false),
142+
cert_cb_(nullptr),
143+
cert_cb_arg_(nullptr),
144+
cert_cb_running_(false) {
142145
ssl_ = SSL_new(sc->ctx_);
143146
CHECK_NE(ssl_, nullptr);
144147
}
@@ -157,6 +160,9 @@ class SSLWrap {
157160
npn_protos_.Reset();
158161
selected_npn_proto_.Reset();
159162
#endif
163+
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
164+
sni_context_.Reset();
165+
#endif
160166
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
161167
ocsp_response_.Reset();
162168
#endif // NODE__HAVE_TLSEXT_STATUS_CB
@@ -167,8 +173,11 @@ class SSLWrap {
167173
inline bool is_server() const { return kind_ == kServer; }
168174
inline bool is_client() const { return kind_ == kClient; }
169175
inline bool is_waiting_new_session() const { return new_session_wait_; }
176+
inline bool is_waiting_cert_cb() const { return cert_cb_ != nullptr; }
170177

171178
protected:
179+
typedef void (*CertCb)(void* arg);
180+
172181
static void InitNPN(SecureContext* sc);
173182
static void AddMethods(Environment* env, v8::Handle<v8::FunctionTemplate> t);
174183

@@ -190,6 +199,7 @@ class SSLWrap {
190199
static void VerifyError(const v8::FunctionCallbackInfo<v8::Value>& args);
191200
static void GetCurrentCipher(const v8::FunctionCallbackInfo<v8::Value>& args);
192201
static void EndParser(const v8::FunctionCallbackInfo<v8::Value>& args);
202+
static void CertCbDone(const v8::FunctionCallbackInfo<v8::Value>& args);
193203
static void Renegotiate(const v8::FunctionCallbackInfo<v8::Value>& args);
194204
static void Shutdown(const v8::FunctionCallbackInfo<v8::Value>& args);
195205
static void GetTLSTicket(const v8::FunctionCallbackInfo<v8::Value>& args);
@@ -218,9 +228,12 @@ class SSLWrap {
218228
void* arg);
219229
#endif // OPENSSL_NPN_NEGOTIATED
220230
static int TLSExtStatusCallback(SSL* s, void* arg);
231+
static int SSLCertCallback(SSL* s, void* arg);
221232
static void SSLGetter(v8::Local<v8::String> property,
222233
const v8::PropertyCallbackInfo<v8::Value>& info);
223234

235+
void WaitForCertCb(CertCb cb, void* arg);
236+
224237
inline Environment* ssl_env() const {
225238
return env_;
226239
}
@@ -231,6 +244,12 @@ class SSLWrap {
231244
SSL* ssl_;
232245
bool session_callbacks_;
233246
bool new_session_wait_;
247+
248+
// SSL_set_cert_cb
249+
CertCb cert_cb_;
250+
void* cert_cb_arg_;
251+
bool cert_cb_running_;
252+
234253
ClientHelloParser hello_parser_;
235254

236255
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
@@ -242,6 +261,10 @@ class SSLWrap {
242261
v8::Persistent<v8::Value> selected_npn_proto_;
243262
#endif // OPENSSL_NPN_NEGOTIATED
244263

264+
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
265+
v8::Persistent<v8::Value> sni_context_;
266+
#endif
267+
245268
friend class SecureContext;
246269
};
247270

@@ -253,7 +276,6 @@ class Connection : public SSLWrap<Connection>, public AsyncWrap {
253276
~Connection() override {
254277
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
255278
sniObject_.Reset();
256-
sniContext_.Reset();
257279
servername_.Reset();
258280
#endif
259281
}
@@ -268,7 +290,6 @@ class Connection : public SSLWrap<Connection>, public AsyncWrap {
268290

269291
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
270292
v8::Persistent<v8::Object> sniObject_;
271-
v8::Persistent<v8::Value> sniContext_;
272293
v8::Persistent<v8::String> servername_;
273294
#endif
274295

0 commit comments

Comments
 (0)