Skip to content

Instantly share code, notes, and snippets.

@jamesdavidson
Last active February 19, 2019 06:34
Show Gist options
  • Save jamesdavidson/80fedc49b342fb4e6326b6282bfbdb93 to your computer and use it in GitHub Desktop.
Save jamesdavidson/80fedc49b342fb4e6326b6282bfbdb93 to your computer and use it in GitHub Desktop.
Open a TLS connection to a remote host on and verify its cert.
/* Open a TLS connection to a remote host and verify its cert.
* Usage: node tls_connect.js -connect thewest.com.au:443
*/
var tls = require('tls');
var i = process.argv.indexOf('-connect');
var connect = process.argv[1+i].split(':');
var servername = connect[0];
var port = Number(connect[1]);
if (0 < i && connect && servername && port) {
// Opening connection to `servername:port`...
} else {
console.error('-connect not set to servername:port');
process.exit(1);
}
var socket = tls.connect(
{host:servername, port:port, rejectUnauthorized:false, servername:servername},
function() {
var cert = socket.getPeerCertificate()
if (!cert) {
console.error('could not get peer certificate');
}
// Print out certificate information if -json option is set
if (0 < process.argv.indexOf('-json')) {
var c = {}
c['fingerprint'] = cert['fingerprint']
c['issuer'] = cert['issuer']
c['subject'] = cert['subject']
c['subjectaltname'] = cert['subjectaltname']
c['valid_from'] = cert['valid_from']
c['valid_to'] = cert['valid_to']
c['_meta'] = {
authorized: socket.authorized,
now: new Date().toISOString(),
servername: servername,
active: (new Date(cert.valid_from) < new Date() && new Date() < new Date(cert.valid_to))
}
console.log(JSON.stringify(c));
}
// fail if cert is soon to expire (in less days than -mindays option)
var i = process.argv.indexOf('-mindays');
var mindays = Number(process.argv[1+i]);
if (0 < i && mindays) {
var now = new Date();
var expiryDate = new Date(cert.valid_to);
var threshold = new Date(expiryDate - 24 * 60 * 60 * 1000 * mindays);
if (now > threshold) {
console.error('Cert for '+servername+' expires in less than '+mindays+' days.');
process.exit(1);
}
}
// exit with success code if cert validation succeeds
process.exit(socket.authorized ? 0 : 1);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment