1'use strict';
2const common = require('../common');
3if (!common.hasCrypto)
4  common.skip('missing crypto');
5const fixtures = require('../common/fixtures');
6
7const assert = require('assert');
8const { X509Certificate } = require('crypto');
9const tls = require('tls');
10
11const key = fixtures.readKey('agent2-key.pem');
12const cert = fixtures.readKey('agent2-cert.pem');
13
14// TODO(@sam-github) test works with TLS1.3, rework test to add
15//   'ECDH' with 'TLS_AES_128_GCM_SHA256',
16
17function loadDHParam(n) {
18  return fixtures.readKey(`dh${n}.pem`);
19}
20
21function test(size, type, name, cipher) {
22  assert(cipher);
23
24  const options = {
25    key: key,
26    cert: cert,
27    ciphers: cipher,
28    maxVersion: 'TLSv1.2',
29  };
30
31  if (name) options.ecdhCurve = name;
32
33  if (type === 'DH') {
34    if (size === 'auto') {
35      options.dhparam = 'auto';
36      // The DHE parameters selected by OpenSSL depend on the strength of the
37      // certificate's key. For this test, we can assume that the modulus length
38      // of the certificate's key is equal to the size of the DHE parameter, but
39      // that is really only true for a few modulus lengths.
40      ({
41        publicKey: { asymmetricKeyDetails: { modulusLength: size } }
42      } = new X509Certificate(cert));
43    } else {
44      options.dhparam = loadDHParam(size);
45    }
46  }
47
48  const server = tls.createServer(options, common.mustCall((conn) => {
49    assert.strictEqual(conn.getEphemeralKeyInfo(), null);
50    conn.end();
51  }));
52
53  server.on('close', common.mustSucceed());
54
55  server.listen(0, common.mustCall(() => {
56    const client = tls.connect({
57      port: server.address().port,
58      rejectUnauthorized: false
59    }, common.mustCall(function() {
60      const ekeyinfo = client.getEphemeralKeyInfo();
61      assert.strictEqual(ekeyinfo.type, type);
62      assert.strictEqual(ekeyinfo.size, size);
63      assert.strictEqual(ekeyinfo.name, name);
64      server.close();
65    }));
66    client.on('secureConnect', common.mustCall());
67  }));
68}
69
70test(undefined, undefined, undefined, 'AES128-SHA256');
71test('auto', 'DH', undefined, 'DHE-RSA-AES128-GCM-SHA256');
72test(1024, 'DH', undefined, 'DHE-RSA-AES128-GCM-SHA256');
73test(2048, 'DH', undefined, 'DHE-RSA-AES128-GCM-SHA256');
74test(256, 'ECDH', 'prime256v1', 'ECDHE-RSA-AES128-GCM-SHA256');
75test(521, 'ECDH', 'secp521r1', 'ECDHE-RSA-AES128-GCM-SHA256');
76test(253, 'ECDH', 'X25519', 'ECDHE-RSA-AES128-GCM-SHA256');
77test(448, 'ECDH', 'X448', 'ECDHE-RSA-AES128-GCM-SHA256');
78