Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] tls: add server.sessionTimeout getter and setter. #34006

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions doc/api/tls.md
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,20 @@ Existing or currently pending server connections will use the previous keys.

See [Session Resumption][] for more information.

### `server.getSessionTimeout()`

* Returns: {number} The number of seconds after which a TLS session
created by the server will no longer be resumable.

Returns the session timeout in seconds.

### `server.setSessionTimeout(sessionTimeout)`

* `sessionTimeout` {number} The number of seconds after which a TLS session
created by the server will no longer be resumable.

Sets the session timeout.
TODO (changed dynamically/for further connections?)
## Class: `tls.TLSSocket`
<!-- YAML
added: v0.11.4
Expand Down
7 changes: 7 additions & 0 deletions lib/_tls_wrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -1356,6 +1356,13 @@ Server.prototype._setServerData = function(data) {
this.setTicketKeys(Buffer.from(data.ticketKeys, 'hex'));
};

Server.prototype.getSessionTimeout = function getSessionTimeout() {
return this._sharedCreds.context.getSessionTimeout();
};

Server.prototype.setSessionTimeout = function setSessionTimeout(sessionTimeout) {
this._sharedCreds.context.setSessionTimeout(sessionTimeout);
};

Server.prototype.getTicketKeys = function getTicketKeys() {
return this._sharedCreds.context.getTicketKeys();
Expand Down
10 changes: 10 additions & 0 deletions src/node_crypto.cc
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ void SecureContext::Initialize(Environment* env, Local<Object> target) {
env->SetProtoMethod(t, "getMinProto", GetMinProto);
env->SetProtoMethod(t, "setOptions", SetOptions);
env->SetProtoMethod(t, "setSessionIdContext", SetSessionIdContext);
env->SetProtoMethod(t, "getSessionTimeout", GetSessionTimeout);
env->SetProtoMethod(t, "setSessionTimeout", SetSessionTimeout);
env->SetProtoMethod(t, "close", Close);
env->SetProtoMethod(t, "loadPKCS12", LoadPKCS12);
Expand Down Expand Up @@ -1374,6 +1375,15 @@ void SecureContext::SetSessionIdContext(
args.GetIsolate()->ThrowException(Exception::TypeError(message));
}

void SecureContext::GetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc;
ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());

CHECK_EQ(args.Length(), 0);

long sessionTimeout = SSL_CTX_get_timeout(sc->ctx_.get());
args.GetReturnValue().Set(static_cast<uint32_t>(sessionTimeout));
Comment on lines +1384 to +1385
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recognize the same style issue exists in SetSessionTimeout() but...

Suggested change
long sessionTimeout = SSL_CTX_get_timeout(sc->ctx_.get());
args.GetReturnValue().Set(static_cast<uint32_t>(sessionTimeout));
long session_timeout = SSL_CTX_get_timeout(sc->ctx_.get());
args.GetReturnValue().Set(static_cast<uint32_t>(session_timeout));

(and I'm going to guess the first line needs a // NOLINT(runtime/int) to shut up cpplint)

}

void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
SecureContext* sc;
Expand Down
2 changes: 2 additions & 0 deletions src/node_crypto.h
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ class SecureContext final : public BaseObject {
static void SetOptions(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetSessionIdContext(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetSessionTimeout(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetSessionTimeout(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetMinProto(const v8::FunctionCallbackInfo<v8::Value>& args);
Expand Down
152 changes: 152 additions & 0 deletions test/parallel/test-tls-session-timeout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

Comment on lines +1 to +21
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

(not necessary in new test files)

'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const fixtures = require('../common/fixtures');
const assert = require('assert');
const tls = require('tls');
const { spawn } = require('child_process');

if (!common.opensslCli)
common.skip('node compiled without OpenSSL CLI.');


// WARNING!
// This is only a POC test.
// Unfortunately, it is useless because with '-no_tickets' option not enabled,
// 'newSession' and 'resumeSession' event callbacks are not called.
doTest();

function doTest() {
const key = fixtures.readKey('rsa_private.pem');
const cert = fixtures.readKey('rsa_cert.crt');
const options = {
key,
cert,
ca: [cert],
requestCert: true,
rejectUnauthorized: false,
secureProtocol: 'TLS_method',
};
let session;

let newSessions = 0;
let resumedSessions = 0;

const server = tls.createServer(options, function(cleartext) {
cleartext.on('error', function(er) {
// We're ok with getting ECONNRESET in this test, but it's
// timing-dependent, and thus unreliable. Any other errors
// are just failures, though.
if (er.code !== 'ECONNRESET')
throw er;
});
cleartext.end('');
});

server.on('newSession', function(id, data, cb) {
++newSessions;

setImmediate(() => {
session = { id, data };
cb();
});
});

server.on('resumeSession', function(id, callback) {
++resumedSessions;
assert.ok(session);
assert.strictEqual(session.id.toString('hex'), id.toString('hex'));

setImmediate(() => {
callback(null, session.data);
});
});

server.listen(0, function() {
const args = [
's_client',
'-tls1',
'-connect', `localhost:${this.address().port}`,
'-servername', 'ohgod',
'-key', fixtures.path('keys/rsa_private.pem'),
'-cert', fixtures.path('keys/rsa_cert.crt'),
'-no_ticket'
];

function spawnClient(cb) {
const client = spawn(common.opensslCli, args, {
stdio: [ 0, 1, 'pipe' ]
});
let err = '';
client.stderr.setEncoding('utf8');
client.stderr.on('data', function(chunk) {
err += chunk;
});

client.on('exit', common.mustCall(function(code, signal) {
if (code !== 0) {
// If SmartOS and connection refused, then retry. See
// https://github.com/nodejs/node/issues/2663.
if (common.isSunOS && err.includes('Connection refused')) {
requestCount = 0;
spawnClient();
return;
}
assert.fail(`code: ${code}, signal: ${signal}, output: ${err}`);
}
assert.strictEqual(code, 0);

setImmediate(cb);
}));
}

spawnClient(() => {
// Make the first connection. A new session should be estabilished.
// newSessions: 0 -> 1
// resumedSessions: 0
spawnClient(() => {
// Make the second connection. A session should be resumed.
// newSessions: 1
// resumedSessions: 0 -> 1
// Set session timeout to 1 second,
server.setSessionTimeout(1);
assert.strictEqual(server.getSessionTimeout(), 1);
// After 2 seconds, session should time out.
// newSessions: 1 -> 2
// resumedSessions: 1
setTimeout(function () {
spawnClient(() => {
server.close();
});
}, 2);
});
});
});

process.on('exit', function() {
// assert.strictEqual(resumedSessions, 1);
// assert.strictEqual(newSessions, 2);
});
};