1'use strict';
2const common = require('../common');
3if (!common.hasCrypto)
4  common.skip('missing crypto');
5
6const { TestTLSSocket, ccs } = require('../common/tls');
7const fixtures = require('../common/fixtures');
8const https = require('https');
9
10// Regression test for an use-after-free bug in the TLS implementation that
11// would occur when `SSL_write()` failed.
12// Refs: https://github.com/nodejs-private/security/issues/189
13
14const server_key = fixtures.readKey('agent1-key.pem');
15const server_cert = fixtures.readKey('agent1-cert.pem');
16
17const opts = {
18  key: server_key,
19  cert: server_cert,
20  ciphers: 'ALL@SECLEVEL=0'
21};
22
23const server = https.createServer(opts, (req, res) => {
24  res.write('hello');
25}).listen(0, common.mustCall(() => {
26  const client = new TestTLSSocket(server_cert);
27
28  client.connect({
29    host: 'localhost',
30    port: server.address().port
31  }, common.mustCall(() => {
32    const ch = client.createClientHello();
33    client.write(ch);
34  }));
35
36  client.once('data', common.mustCall((buf) => {
37    let remaining = buf;
38    do {
39      remaining = client.parseTLSFrame(remaining);
40    } while (remaining.length > 0);
41
42    const cke = client.createClientKeyExchange();
43    const finished = client.createFinished();
44    const ill = client.createIllegalHandshake();
45    const frames = Buffer.concat([
46      cke,
47      ccs,
48      client.encrypt(finished),
49      client.encrypt(ill),
50    ]);
51    client.write(frames, common.mustCall(() => {
52      client.end();
53      server.close();
54    }));
55  }));
56}));
57