Skip to content

Instantly share code, notes, and snippets.

@panarom
Last active August 1, 2017 21:52
Show Gist options
  • Save panarom/5c4b94062716abe8d6c0e5e6e6287d11 to your computer and use it in GitHub Desktop.
Save panarom/5c4b94062716abe8d6c0e5e6e6287d11 to your computer and use it in GitHub Desktop.
node server for signing spkac keygen requests with CA for generating client x509 TLS certificates
const http = require('http');
const execFile = require('child_process').execFileSync;
const qs = require('querystring');
const SPKAC = `SPKAC=
CN=Firstname Lastname
emailAddress=first.last@example.com
OU=orgUnit
organizationName=Organization
countryName=US
stateOrProvinceName=State
localityName=City
`;
var challenge = Math.floor(1e12*Math.random());
const FORM = `<form method="post">
<keygen name="pubkey" challenge="${challenge}">
<input type="submit" name="createcert" value="Generate">
</form>`;
var signKey = function(key) {
var spkacInstance = SPKAC.replace('SPKAC=', `SPKAC=${key}`);
var tmpSPKAC = execFile('mktemp');
require('fs').writeFileSync(tmpSPKAC, spkacInstance);
var tmpRes = execFile('mktemp');
try {
execFile('/usr/bin/openssl',
`ca -days 3650 -cert /path/to/CA.crt -keyfile /path/to/CA.key -utf8 -notext -batch -key _passphrase_for_CA_ -out ${tmpRes} -spkac ${tmpSPKAC}`.split(' '),
{/*cwd: '/path/to/certs/location/', //use this if openssl.cnf is misconfigured; rootless access; or other special circumstances */
input: spkacInstance}
);
} catch(e) {
console.log(e.stderr.toString());
}
return require('fs').readFileSync(tmpRes);
};
var writeResponse = function(res, body) {
res.writeHead(201, {'Content-Type': 'application/x-x509-user-cert'});
res.end(body);
}
var serverFunction = function(req, res) {
if(req.method=='GET') {
res.end(FORM);
} else {
var body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => writeResponse(res, signKey(qs.parse(body).pubkey.replace(/\s/g, ''))));
}
};
http.createServer(serverFunction).listen(10012);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment