Skip to content

Commit 550c263

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 PR-URL: #1464 Reviewed-By: Shigeki Ohtsu <[email protected]>
1 parent 30b7349 commit 550c263

23 files changed

+438
-95
lines changed

lib/_tls_wrap.js

+23-26
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
}
@@ -333,15 +327,18 @@ TLSSocket.prototype._init = function(socket, wrap) {
333327
ssl.onhandshakestart = onhandshakestart.bind(this);
334328
ssl.onhandshakedone = onhandshakedone.bind(this);
335329
ssl.onclienthello = onclienthello.bind(this);
330+
ssl.oncertcb = oncertcb.bind(this);
336331
ssl.onnewsession = onnewsession.bind(this);
337332
ssl.lastHandshakeTime = 0;
338333
ssl.handshakes = 0;
339334

340-
if (this.server &&
341-
(listenerCount(this.server, 'resumeSession') > 0 ||
342-
listenerCount(this.server, 'newSession') > 0 ||
343-
listenerCount(this.server, 'OCSPRequest') > 0)) {
344-
ssl.enableSessionCallbacks();
335+
if (this.server) {
336+
if (listenerCount(this.server, 'resumeSession') > 0 ||
337+
listenerCount(this.server, 'newSession') > 0) {
338+
ssl.enableSessionCallbacks();
339+
}
340+
if (listenerCount(this.server, 'OCSPRequest') > 0)
341+
ssl.enableCertCb();
345342
}
346343
} else {
347344
ssl.onhandshakestart = function() {};
@@ -382,7 +379,7 @@ TLSSocket.prototype._init = function(socket, wrap) {
382379
options.server._contexts.length)) {
383380
assert(typeof options.SNICallback === 'function');
384381
this._SNICallback = options.SNICallback;
385-
ssl.enableHelloParser();
382+
ssl.enableCertCb();
386383
}
387384

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

src/env.h

+1
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

+129-3
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,8 @@ template int SSLWrap<TLSWrap>::SelectNextProtoCallback(
132132
#endif
133133
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
134134
template void SSLWrap<TLSWrap>::DestroySSL();
135+
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
136+
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
135137

136138

137139
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
@@ -511,7 +513,8 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
511513
}
512514

513515
while ((ca = PEM_read_bio_X509(in, nullptr, CryptoPemCallback, nullptr))) {
514-
r = SSL_CTX_add_extra_chain_cert(ctx, ca);
516+
// NOTE: Increments reference count on `ca`
517+
r = SSL_CTX_add1_chain_cert(ctx, ca);
515518

516519
if (!r) {
517520
X509_free(ca);
@@ -987,6 +990,7 @@ void SSLWrap<Base>::AddMethods(Environment* env, Handle<FunctionTemplate> t) {
987990
env->SetProtoMethod(t, "verifyError", VerifyError);
988991
env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher);
989992
env->SetProtoMethod(t, "endParser", EndParser);
993+
env->SetProtoMethod(t, "certCbDone", CertCbDone);
990994
env->SetProtoMethod(t, "renegotiate", Renegotiate);
991995
env->SetProtoMethod(t, "shutdownSSL", Shutdown);
992996
env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket);
@@ -1869,6 +1873,122 @@ int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
18691873
#endif // NODE__HAVE_TLSEXT_STATUS_CB
18701874

18711875

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

2098+
} else if (err == SSL_ERROR_WANT_X509_LOOKUP) {
2099+
DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func);
2100+
return 0;
2101+
19782102
} else if (err == SSL_ERROR_ZERO_RETURN) {
19792103
HandleScope scope(ssl_env()->isolate());
19802104

@@ -2140,7 +2264,7 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
21402264

21412265
// Call the SNI callback and use its return value as context
21422266
if (!conn->sniObject_.IsEmpty()) {
2143-
conn->sniContext_.Reset();
2267+
conn->sni_context_.Reset();
21442268

21452269
Local<Value> arg = PersistentToLocal(env->isolate(), conn->servername_);
21462270
Local<Value> ret = conn->MakeCallback(env->onselect_string(), 1, &arg);
@@ -2149,7 +2273,7 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
21492273
Local<FunctionTemplate> secure_context_constructor_template =
21502274
env->secure_context_constructor_template();
21512275
if (secure_context_constructor_template->HasInstance(ret)) {
2152-
conn->sniContext_.Reset(env->isolate(), ret);
2276+
conn->sni_context_.Reset(env->isolate(), ret);
21532277
SecureContext* sc = Unwrap<SecureContext>(ret.As<Object>());
21542278
InitNPN(sc);
21552279
SSL_set_SSL_CTX(s, sc->ctx_);
@@ -2188,6 +2312,8 @@ void Connection::New(const FunctionCallbackInfo<Value>& args) {
21882312

21892313
InitNPN(sc);
21902314

2315+
SSL_set_cert_cb(conn->ssl_, SSLWrap<Connection>::SSLCertCallback, conn);
2316+
21912317
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
21922318
if (is_server) {
21932319
SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);

src/node_crypto.h

+23-3
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,10 @@ class SSLWrap {
143143
kind_(kind),
144144
next_sess_(nullptr),
145145
session_callbacks_(false),
146-
new_session_wait_(false) {
146+
new_session_wait_(false),
147+
cert_cb_(nullptr),
148+
cert_cb_arg_(nullptr),
149+
cert_cb_running_(false) {
147150
ssl_ = SSL_new(sc->ctx_);
148151
env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
149152
CHECK_NE(ssl_, nullptr);
@@ -160,6 +163,9 @@ class SSLWrap {
160163
npn_protos_.Reset();
161164
selected_npn_proto_.Reset();
162165
#endif
166+
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
167+
sni_context_.Reset();
168+
#endif
163169
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
164170
ocsp_response_.Reset();
165171
#endif // NODE__HAVE_TLSEXT_STATUS_CB
@@ -170,8 +176,11 @@ class SSLWrap {
170176
inline bool is_server() const { return kind_ == kServer; }
171177
inline bool is_client() const { return kind_ == kClient; }
172178
inline bool is_waiting_new_session() const { return new_session_wait_; }
179+
inline bool is_waiting_cert_cb() const { return cert_cb_ != nullptr; }
173180

174181
protected:
182+
typedef void (*CertCb)(void* arg);
183+
175184
// Size allocated by OpenSSL: one for SSL structure, one for SSL3_STATE and
176185
// some for buffers.
177186
// NOTE: Actually it is much more than this
@@ -199,6 +208,7 @@ class SSLWrap {
199208
static void VerifyError(const v8::FunctionCallbackInfo<v8::Value>& args);
200209
static void GetCurrentCipher(const v8::FunctionCallbackInfo<v8::Value>& args);
201210
static void EndParser(const v8::FunctionCallbackInfo<v8::Value>& args);
211+
static void CertCbDone(const v8::FunctionCallbackInfo<v8::Value>& args);
202212
static void Renegotiate(const v8::FunctionCallbackInfo<v8::Value>& args);
203213
static void Shutdown(const v8::FunctionCallbackInfo<v8::Value>& args);
204214
static void GetTLSTicket(const v8::FunctionCallbackInfo<v8::Value>& args);
@@ -227,10 +237,12 @@ class SSLWrap {
227237
void* arg);
228238
#endif // OPENSSL_NPN_NEGOTIATED
229239
static int TLSExtStatusCallback(SSL* s, void* arg);
240+
static int SSLCertCallback(SSL* s, void* arg);
230241
static void SSLGetter(v8::Local<v8::String> property,
231242
const v8::PropertyCallbackInfo<v8::Value>& info);
232243

233244
void DestroySSL();
245+
void WaitForCertCb(CertCb cb, void* arg);
234246

235247
inline Environment* ssl_env() const {
236248
return env_;
@@ -242,6 +254,12 @@ class SSLWrap {
242254
SSL* ssl_;
243255
bool session_callbacks_;
244256
bool new_session_wait_;
257+
258+
// SSL_set_cert_cb
259+
CertCb cert_cb_;
260+
void* cert_cb_arg_;
261+
bool cert_cb_running_;
262+
245263
ClientHelloParser hello_parser_;
246264

247265
#ifdef NODE__HAVE_TLSEXT_STATUS_CB
@@ -253,6 +271,10 @@ class SSLWrap {
253271
v8::Persistent<v8::Value> selected_npn_proto_;
254272
#endif // OPENSSL_NPN_NEGOTIATED
255273

274+
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
275+
v8::Persistent<v8::Value> sni_context_;
276+
#endif
277+
256278
friend class SecureContext;
257279
};
258280

@@ -264,7 +286,6 @@ class Connection : public SSLWrap<Connection>, public AsyncWrap {
264286
~Connection() override {
265287
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
266288
sniObject_.Reset();
267-
sniContext_.Reset();
268289
servername_.Reset();
269290
#endif
270291
}
@@ -279,7 +300,6 @@ class Connection : public SSLWrap<Connection>, public AsyncWrap {
279300

280301
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
281302
v8::Persistent<v8::Object> sniObject_;
282-
v8::Persistent<v8::Value> sniContext_;
283303
v8::Persistent<v8::String> servername_;
284304
#endif
285305

0 commit comments

Comments
 (0)