1'use strict';
2const common = require('../common');
3if (!common.hasCrypto)
4  common.skip('missing crypto');
5
6const assert = require('assert');
7const tls = require('tls');
8const fixtures = require('../common/fixtures');
9
10const key = fixtures.readKey('agent2-key.pem');
11const cert = fixtures.readKey('agent2-cert.pem');
12
13let nsuccess = 0;
14let nerror = 0;
15
16function loadDHParam(n) {
17  return fixtures.readKey(`dh${n}.pem`);
18}
19
20function test(size, err, next) {
21  const options = {
22    key: key,
23    cert: cert,
24    dhparam: loadDHParam(size),
25    ciphers: 'DHE-RSA-AES128-GCM-SHA256'
26  };
27
28  const server = tls.createServer(options, function(conn) {
29    conn.end();
30  });
31
32  server.on('close', function(isException) {
33    assert(!isException);
34    if (next) next();
35  });
36
37  server.listen(0, function() {
38    // Client set minimum DH parameter size to 2048 bits so that
39    // it fails when it make a connection to the tls server where
40    // dhparams is 1024 bits
41    const client = tls.connect({
42      minDHSize: 2048,
43      port: this.address().port,
44      rejectUnauthorized: false,
45      maxVersion: 'TLSv1.2',
46    }, function() {
47      nsuccess++;
48      server.close();
49    });
50    if (err) {
51      client.on('error', function(e) {
52        nerror++;
53        assert.strictEqual(e.code, 'ERR_TLS_DH_PARAM_SIZE');
54        server.close();
55      });
56    }
57  });
58}
59
60// A client connection fails with an error when a client has an
61// 2048 bits minDHSize option and a server has 1024 bits dhparam
62function testDHE1024() {
63  test(1024, true, testDHE2048);
64}
65
66// A client connection successes when a client has an
67// 2048 bits minDHSize option and a server has 2048 bits dhparam
68function testDHE2048() {
69  test(2048, false, null);
70}
71
72testDHE1024();
73
74assert.throws(() => test(512, true, common.mustNotCall()),
75              /DH parameter is less than 1024 bits/);
76
77let errMessage = /minDHSize is not a positive number/;
78[0, -1, -Infinity, NaN].forEach((minDHSize) => {
79  assert.throws(() => tls.connect({ minDHSize }),
80                errMessage);
81});
82
83errMessage = /minDHSize is not a number/;
84[true, false, null, undefined, {}, [], '', '1'].forEach((minDHSize) => {
85  assert.throws(() => tls.connect({ minDHSize }), errMessage);
86});
87
88process.on('exit', function() {
89  assert.strictEqual(nsuccess, 1);
90  assert.strictEqual(nerror, 1);
91});
92