• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3
4if (!common.hasCrypto)
5  common.skip('missing crypto');
6
7const assert = require('assert');
8const tls = require('tls');
9
10const CIPHERS = 'PSK+HIGH:TLS_AES_128_GCM_SHA256';
11const USERS = {
12  UserA: Buffer.allocUnsafe(128),
13  UserB: Buffer.from('82072606b502b0f4025e90eb75fe137d', 'hex'),
14};
15const TEST_DATA = 'x';
16
17const serverOptions = {
18  ciphers: CIPHERS,
19  pskCallback(socket, id) {
20    assert.ok(socket instanceof tls.TLSSocket);
21    assert.ok(typeof id === 'string');
22    return USERS[id];
23  },
24};
25
26function test(secret, opts, error) {
27  const cb = !error ?
28    common.mustCall((c) => { c.pipe(c); }) :
29    common.mustNotCall();
30  const server = tls.createServer(serverOptions, cb);
31  server.listen(0, common.mustCall(() => {
32    const options = {
33      port: server.address().port,
34      ciphers: CIPHERS,
35      checkServerIdentity: () => {},
36      pskCallback: common.mustCall(() => secret),
37      ...opts,
38    };
39
40    if (!error) {
41      const client = tls.connect(options, common.mustCall(() => {
42        client.end(TEST_DATA);
43
44        client.on('data', common.mustCall((data) => {
45          assert.strictEqual(data.toString(), TEST_DATA);
46        }));
47        client.on('close', common.mustCall(() => server.close()));
48      }));
49    } else {
50      const client = tls.connect(options, common.mustNotCall());
51      client.on('error', common.mustCall((err) => {
52        assert.strictEqual(err.code, error);
53        server.close();
54      }));
55    }
56  }));
57}
58
59test({ psk: USERS.UserA, identity: 'UserA' });
60test({ psk: USERS.UserA, identity: 'UserA' }, { maxVersion: 'TLSv1.2' });
61test({ psk: USERS.UserA, identity: 'UserA' }, { minVersion: 'TLSv1.3' });
62test({ psk: USERS.UserB, identity: 'UserB' });
63test({ psk: USERS.UserB, identity: 'UserB' }, { minVersion: 'TLSv1.3' });
64// Unrecognized user should fail handshake
65test({ psk: USERS.UserB, identity: 'UserC' }, {},
66     'ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE');
67// Recognized user but incorrect secret should fail handshake
68test({ psk: USERS.UserA, identity: 'UserB' }, {},
69     'ERR_SSL_SSLV3_ALERT_ILLEGAL_PARAMETER');
70test({ psk: USERS.UserB, identity: 'UserB' });
71