1'use strict'; 2const common = require('../common'); 3 4if (!common.hasCrypto) 5 common.skip('missing crypto'); 6 7if (!common.opensslCli) 8 common.skip('node compiled without OpenSSL CLI'); 9 10const assert = require('assert'); 11const net = require('net'); 12const tls = require('tls'); 13const fixtures = require('../common/fixtures'); 14 15let clientClosed = false; 16let errorReceived = false; 17function canCloseServer() { 18 return clientClosed && errorReceived; 19} 20 21function loadPEM(n) { 22 return fixtures.readKey(`${n}.pem`, 'utf-8'); 23} 24 25const opts = { 26 key: loadPEM('agent2-key'), 27 cert: loadPEM('agent2-cert') 28}; 29 30const max_iter = 20; 31let iter = 0; 32 33const errorHandler = common.mustCall((err) => { 34 assert.strictEqual(err.code, 'ERR_SSL_WRONG_VERSION_NUMBER'); 35 assert.strictEqual(err.library, 'SSL routines'); 36 if (!common.hasOpenSSL3) assert.strictEqual(err.function, 'ssl3_get_record'); 37 assert.strictEqual(err.reason, 'wrong version number'); 38 errorReceived = true; 39 if (canCloseServer()) 40 server.close(); 41}); 42const server = tls.createServer(opts, common.mustCall(function(s) { 43 s.pipe(s); 44 s.on('error', errorHandler); 45}, 2)); 46 47server.listen(0, common.mustCall(function() { 48 sendClient(); 49})); 50 51server.on('tlsClientError', common.mustNotCall()); 52 53server.on('error', common.mustNotCall()); 54 55function sendClient() { 56 const client = tls.connect(server.address().port, { 57 rejectUnauthorized: false 58 }); 59 client.on('data', common.mustCall(function() { 60 if (iter++ === 2) sendBADTLSRecord(); 61 if (iter < max_iter) { 62 client.write('a'); 63 return; 64 } 65 client.end(); 66 }, max_iter)); 67 client.write('a', common.mustCall()); 68 client.on('error', common.mustNotCall()); 69 client.on('close', common.mustCall(function() { 70 clientClosed = true; 71 if (canCloseServer()) 72 server.close(); 73 })); 74} 75 76 77function sendBADTLSRecord() { 78 const BAD_RECORD = Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); 79 const socket = net.connect(server.address().port); 80 const client = tls.connect({ 81 socket: socket, 82 rejectUnauthorized: false 83 }, common.mustCall(function() { 84 client.write('x'); 85 client.on('data', (data) => { 86 socket.end(BAD_RECORD); 87 }); 88 })); 89 client.on('error', common.mustCall((err) => { 90 assert.strictEqual(err.code, 'ERR_SSL_TLSV1_ALERT_PROTOCOL_VERSION'); 91 assert.strictEqual(err.library, 'SSL routines'); 92 if (!common.hasOpenSSL3) 93 assert.strictEqual(err.function, 'ssl3_read_bytes'); 94 assert.strictEqual(err.reason, 'tlsv1 alert protocol version'); 95 })); 96} 97