Certificates polish

This commit is contained in:
Jamie Curnow
2018-08-13 19:50:28 +10:00
parent c8592503e3
commit 065727fba2
15 changed files with 563 additions and 256 deletions

View File

@ -5,9 +5,9 @@ const _ = require('lodash');
const error = require('../lib/error');
const certificateModel = require('../models/certificate');
const internalAuditLog = require('./audit-log');
const internalHost = require('./host');
const tempWrite = require('temp-write');
const utils = require('../lib/utils');
const moment = require('moment');
function omissions () {
return ['is_deleted'];
@ -15,6 +15,8 @@ function omissions () {
const internalCertificate = {
allowed_ssl_files: ['certificate', 'certificate_key', 'intermediate_certificate'],
/**
* @param {Access} access
* @param {Object} data
@ -57,8 +59,39 @@ const internalCertificate = {
update: (access, data) => {
return access.can('certificates:update', data.id)
.then(access_data => {
// TODO
return {};
return internalCertificate.get(access, {id: data.id});
})
.then(row => {
if (row.id !== data.id) {
// Sanity check that something crazy hasn't happened
throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
}
return certificateModel
.query()
.omit(omissions())
.patchAndFetchById(row.id, data)
.debug()
.then(saved_row => {
saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
data.meta = internalCertificate.cleanMeta(data.meta);
// Add row.nice_name for custom certs
if (saved_row.provider === 'other') {
data.nice_name = saved_row.nice_name;
}
// Add to audit log
return internalAuditLog.add(access, {
action: 'updated',
object_type: 'certificate',
object_id: row.id,
meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
})
.then(() => {
return _.omit(saved_row, omissions());
});
});
});
},
@ -113,10 +146,10 @@ const internalCertificate = {
},
/**
* @param {Access} access
* @param {Object} data
* @param {Integer} data.id
* @param {String} [data.reason]
* @param {Access} access
* @param {Object} data
* @param {Integer} data.id
* @param {String} [data.reason]
* @returns {Promise}
*/
delete: (access, data) => {
@ -134,6 +167,17 @@ const internalCertificate = {
.where('id', row.id)
.patch({
is_deleted: 1
})
.then(() => {
// Add to audit log
row.meta = internalCertificate.cleanMeta(row.meta);
return internalAuditLog.add(access, {
action: 'deleted',
object_type: 'certificate',
object_id: row.id,
meta: _.omit(row, omissions())
});
});
})
.then(() => {
@ -204,19 +248,18 @@ const internalCertificate = {
/**
* Validates that the certs provided are good.
* This is probably a horrible way to do this.
* No access required here, nothing is changed or stored.
*
* @param {Access} access
* @param {Object} data
* @param {Object} data.files
* @returns {Promise}
*/
validate: (access, data) => {
validate: data => {
return new Promise(resolve => {
// Put file contents into an object
let files = {};
_.map(data.files, (file, name) => {
if (internalHost.allowed_ssl_files.indexOf(name) !== -1) {
if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
files[name] = file.data.toString();
}
});
@ -228,56 +271,26 @@ const internalCertificate = {
// Then test it depending on the file type
let promises = [];
_.map(files, (content, type) => {
promises.push(tempWrite(content, '/tmp')
.then(filepath => {
if (type === 'certificate_key') {
return utils.exec('openssl rsa -in ' + filepath + ' -check')
.then(result => {
return {tmp: filepath, result: result.split("\n").shift()};
}).catch(err => {
return {tmp: filepath, result: false, err: new error.ValidationError('Certificate Key is not valid')};
});
} else if (type === 'certificate') {
return utils.exec('openssl x509 -in ' + filepath + ' -text -noout')
.then(result => {
return {tmp: filepath, result: result};
}).catch(err => {
return {tmp: filepath, result: false, err: new error.ValidationError('Certificate is not valid')};
});
} else {
return {tmp: filepath, result: false};
}
})
.then(file_result => {
// Remove temp files
fs.unlinkSync(file_result.tmp);
delete file_result.tmp;
return {[type]: file_result};
})
);
promises.push(new Promise((resolve, reject) => {
if (type === 'certificate_key') {
resolve(internalCertificate.checkPrivateKey(content));
} else {
// this should handle `certificate` and intermediate certificate
resolve(internalCertificate.getCertificateInfo(content, true));
}
}).then(res => {
return {[type]: res};
}));
});
// With the results, delete the temp files for security mainly.
// If there was an error with any of them, wait until we've done the deleting
// before throwing it.
return Promise.all(promises)
.then(files => {
let data = {};
let err = null;
_.each(files, file => {
data = _.assign({}, data, file);
if (typeof file.err !== 'undefined' && file.err) {
err = file.err;
}
});
if (err) {
throw err;
}
return data;
});
});
@ -297,28 +310,159 @@ const internalCertificate = {
throw new error.ValidationError('Cannot upload certificates for this type of provider');
}
_.map(data.files, (file, name) => {
if (internalHost.allowed_ssl_files.indexOf(name) !== -1) {
row.meta[name] = file.data.toString();
}
});
return internalCertificate.validate(data)
.then(validations => {
if (typeof validations.certificate === 'undefined') {
throw new error.ValidationError('Certificate file was not provided');
}
return internalCertificate.update(access, {
id: data.id,
meta: row.meta
});
})
.then(row => {
return internalAuditLog.add(access, {
action: 'updated',
object_type: 'certificate',
object_id: row.id,
meta: data
})
_.map(data.files, (file, name) => {
if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
row.meta[name] = file.data.toString();
}
});
return internalCertificate.update(access, {
id: data.id,
expires_on: certificateModel.raw('FROM_UNIXTIME(' + validations.certificate.dates.to + ')'),
domain_names: [validations.certificate.cn],
meta: row.meta
});
})
.then(() => {
return _.pick(row.meta, internalHost.allowed_ssl_files);
return _.pick(row.meta, internalCertificate.allowed_ssl_files);
});
});
},
/**
* Uses the openssl command to validate the private key.
* It will save the file to disk first, then run commands on it, then delete the file.
*
* @param {String} private_key This is the entire key contents as a string
*/
checkPrivateKey: private_key => {
return tempWrite(private_key, '/tmp')
.then(filepath => {
return utils.exec('openssl rsa -in ' + filepath + ' -check -noout')
.then(result => {
if (!result.toLowerCase().includes('key ok')) {
throw new error.ValidationError(result);
}
fs.unlinkSync(filepath);
return true;
}).catch(err => {
fs.unlinkSync(filepath);
throw new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err);
});
});
},
/**
* Uses the openssl command to both validate and get info out of the certificate.
* It will save the file to disk first, then run commands on it, then delete the file.
*
* @param {String} certificate This is the entire cert contents as a string
* @param {Boolean} [throw_expired] Throw when the certificate is out of date
*/
getCertificateInfo: (certificate, throw_expired) => {
return tempWrite(certificate, '/tmp')
.then(filepath => {
let cert_data = {};
return utils.exec('openssl x509 -in ' + filepath + ' -subject -noout')
.then(result => {
// subject=CN = something.example.com
let regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
let match = regex.exec(result);
if (typeof match[1] === 'undefined') {
throw new error.ValidationError('Could not determine subject from certificate: ' + result);
}
cert_data['cn'] = match[1];
})
.then(() => {
return utils.exec('openssl x509 -in ' + filepath + ' -issuer -noout');
})
.then(result => {
// issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
let regex = /^(?:issuer=)?(.*)$/gim;
let match = regex.exec(result);
if (typeof match[1] === 'undefined') {
throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
}
cert_data['issuer'] = match[1];
})
.then(() => {
return utils.exec('openssl x509 -in ' + filepath + ' -dates -noout');
})
.then(result => {
// notBefore=Jul 14 04:04:29 2018 GMT
// notAfter=Oct 12 04:04:29 2018 GMT
let valid_from = null;
let valid_to = null;
let lines = result.split('\n');
lines.map(function (str) {
let regex = /^(\S+)=(.*)$/gim;
let match = regex.exec(str.trim());
if (match && typeof match[2] !== 'undefined') {
let date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
if (match[1].toLowerCase() === 'notbefore') {
valid_from = date;
} else if (match[1].toLowerCase() === 'notafter') {
valid_to = date;
}
}
});
if (!valid_from || !valid_to) {
throw new error.ValidationError('Could not determine dates from certificate: ' + result);
}
if (throw_expired && valid_to < parseInt(moment().format('X'), 10)) {
throw new error.ValidationError('Certificate has expired');
}
cert_data['dates'] = {
from: valid_from,
to: valid_to
};
})
.then(() => {
fs.unlinkSync(filepath);
return cert_data;
}).catch(err => {
fs.unlinkSync(filepath);
throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
});
});
},
/**
* Cleans the ssl keys from the meta object and sets them to "true"
*
* @param {Object} meta
* @param {Boolean} [remove]
* @returns {Object}
*/
cleanMeta: function (meta, remove) {
internalCertificate.allowed_ssl_files.map(key => {
if (typeof meta[key] !== 'undefined' && meta[key]) {
if (remove) {
delete meta[key];
} else {
meta[key] = true;
}
}
});
return meta;
}
};

View File

@ -1,15 +1,11 @@
'use strict';
const _ = require('lodash');
const error = require('../lib/error');
const proxyHostModel = require('../models/proxy_host');
const redirectionHostModel = require('../models/redirection_host');
const deadHostModel = require('../models/dead_host');
const internalHost = {
allowed_ssl_files: ['certificate', 'certificate_key', 'intermediate_certificate'],
/**
* Internal use only, checks to see if the domain is already taken by any other record
*
@ -66,21 +62,6 @@ const internalHost = {
});
},
/**
* Cleans the ssl keys from the meta object and sets them to "true"
*
* @param {Object} meta
* @returns {*}
*/
cleanMeta: function (meta) {
internalHost.allowed_ssl_files.map(key => {
if (typeof meta[key] !== 'undefined' && meta[key]) {
meta[key] = true;
}
});
return meta;
},
/**
* Private call only
*

View File

@ -203,7 +203,7 @@ router
res.status(400)
.send({error: 'No files were uploaded'});
} else {
internalCertificate.validate(res.locals.access, {
internalCertificate.validate({
files: req.files
})
.then(result => {