certificate.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. 'use strict';
  2. const fs = require('fs');
  3. const _ = require('lodash');
  4. const error = require('../lib/error');
  5. const certificateModel = require('../models/certificate');
  6. const internalAuditLog = require('./audit-log');
  7. const tempWrite = require('temp-write');
  8. const utils = require('../lib/utils');
  9. const moment = require('moment');
  10. function omissions () {
  11. return ['is_deleted'];
  12. }
  13. const internalCertificate = {
  14. allowed_ssl_files: ['certificate', 'certificate_key', 'intermediate_certificate'],
  15. /**
  16. * @param {Access} access
  17. * @param {Object} data
  18. * @returns {Promise}
  19. */
  20. create: (access, data) => {
  21. return access.can('certificates:create', data)
  22. .then(() => {
  23. data.owner_user_id = access.token.get('attrs').id;
  24. return certificateModel
  25. .query()
  26. .omit(omissions())
  27. .insertAndFetch(data);
  28. })
  29. .then(row => {
  30. data.meta = _.assign({}, data.meta || {}, row.meta);
  31. // Add to audit log
  32. return internalAuditLog.add(access, {
  33. action: 'created',
  34. object_type: 'certificate',
  35. object_id: row.id,
  36. meta: data
  37. })
  38. .then(() => {
  39. return row;
  40. });
  41. });
  42. },
  43. /**
  44. * @param {Access} access
  45. * @param {Object} data
  46. * @param {Integer} data.id
  47. * @param {String} [data.email]
  48. * @param {String} [data.name]
  49. * @return {Promise}
  50. */
  51. update: (access, data) => {
  52. return access.can('certificates:update', data.id)
  53. .then(access_data => {
  54. return internalCertificate.get(access, {id: data.id});
  55. })
  56. .then(row => {
  57. if (row.id !== data.id) {
  58. // Sanity check that something crazy hasn't happened
  59. throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  60. }
  61. return certificateModel
  62. .query()
  63. .omit(omissions())
  64. .patchAndFetchById(row.id, data)
  65. .debug()
  66. .then(saved_row => {
  67. saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
  68. data.meta = internalCertificate.cleanMeta(data.meta);
  69. // Add row.nice_name for custom certs
  70. if (saved_row.provider === 'other') {
  71. data.nice_name = saved_row.nice_name;
  72. }
  73. // Add to audit log
  74. return internalAuditLog.add(access, {
  75. action: 'updated',
  76. object_type: 'certificate',
  77. object_id: row.id,
  78. meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
  79. })
  80. .then(() => {
  81. return _.omit(saved_row, omissions());
  82. });
  83. });
  84. });
  85. },
  86. /**
  87. * @param {Access} access
  88. * @param {Object} data
  89. * @param {Integer} data.id
  90. * @param {Array} [data.expand]
  91. * @param {Array} [data.omit]
  92. * @return {Promise}
  93. */
  94. get: (access, data) => {
  95. if (typeof data === 'undefined') {
  96. data = {};
  97. }
  98. if (typeof data.id === 'undefined' || !data.id) {
  99. data.id = access.token.get('attrs').id;
  100. }
  101. return access.can('certificates:get', data.id)
  102. .then(access_data => {
  103. let query = certificateModel
  104. .query()
  105. .where('is_deleted', 0)
  106. .andWhere('id', data.id)
  107. .allowEager('[owner]')
  108. .first();
  109. if (access_data.permission_visibility !== 'all') {
  110. query.andWhere('owner_user_id', access.token.get('attrs').id);
  111. }
  112. // Custom omissions
  113. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  114. query.omit(data.omit);
  115. }
  116. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  117. query.eager('[' + data.expand.join(', ') + ']');
  118. }
  119. return query;
  120. })
  121. .then(row => {
  122. if (row) {
  123. return _.omit(row, omissions());
  124. } else {
  125. throw new error.ItemNotFoundError(data.id);
  126. }
  127. });
  128. },
  129. /**
  130. * @param {Access} access
  131. * @param {Object} data
  132. * @param {Integer} data.id
  133. * @param {String} [data.reason]
  134. * @returns {Promise}
  135. */
  136. delete: (access, data) => {
  137. return access.can('certificates:delete', data.id)
  138. .then(() => {
  139. return internalCertificate.get(access, {id: data.id});
  140. })
  141. .then(row => {
  142. if (!row) {
  143. throw new error.ItemNotFoundError(data.id);
  144. }
  145. return certificateModel
  146. .query()
  147. .where('id', row.id)
  148. .patch({
  149. is_deleted: 1
  150. })
  151. .then(() => {
  152. // Add to audit log
  153. row.meta = internalCertificate.cleanMeta(row.meta);
  154. return internalAuditLog.add(access, {
  155. action: 'deleted',
  156. object_type: 'certificate',
  157. object_id: row.id,
  158. meta: _.omit(row, omissions())
  159. });
  160. });
  161. })
  162. .then(() => {
  163. return true;
  164. });
  165. },
  166. /**
  167. * All Lists
  168. *
  169. * @param {Access} access
  170. * @param {Array} [expand]
  171. * @param {String} [search_query]
  172. * @returns {Promise}
  173. */
  174. getAll: (access, expand, search_query) => {
  175. return access.can('certificates:list')
  176. .then(access_data => {
  177. let query = certificateModel
  178. .query()
  179. .where('is_deleted', 0)
  180. .groupBy('id')
  181. .omit(['is_deleted'])
  182. .allowEager('[owner]')
  183. .orderBy('nice_name', 'ASC');
  184. if (access_data.permission_visibility !== 'all') {
  185. query.andWhere('owner_user_id', access.token.get('attrs').id);
  186. }
  187. // Query is used for searching
  188. if (typeof search_query === 'string') {
  189. query.where(function () {
  190. this.where('name', 'like', '%' + search_query + '%');
  191. });
  192. }
  193. if (typeof expand !== 'undefined' && expand !== null) {
  194. query.eager('[' + expand.join(', ') + ']');
  195. }
  196. return query;
  197. });
  198. },
  199. /**
  200. * Report use
  201. *
  202. * @param {Integer} user_id
  203. * @param {String} visibility
  204. * @returns {Promise}
  205. */
  206. getCount: (user_id, visibility) => {
  207. let query = certificateModel
  208. .query()
  209. .count('id as count')
  210. .where('is_deleted', 0);
  211. if (visibility !== 'all') {
  212. query.andWhere('owner_user_id', user_id);
  213. }
  214. return query.first()
  215. .then(row => {
  216. return parseInt(row.count, 10);
  217. });
  218. },
  219. /**
  220. * Validates that the certs provided are good.
  221. * No access required here, nothing is changed or stored.
  222. *
  223. * @param {Object} data
  224. * @param {Object} data.files
  225. * @returns {Promise}
  226. */
  227. validate: data => {
  228. return new Promise(resolve => {
  229. // Put file contents into an object
  230. let files = {};
  231. _.map(data.files, (file, name) => {
  232. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  233. files[name] = file.data.toString();
  234. }
  235. });
  236. resolve(files);
  237. })
  238. .then(files => {
  239. // For each file, create a temp file and write the contents to it
  240. // Then test it depending on the file type
  241. let promises = [];
  242. _.map(files, (content, type) => {
  243. promises.push(new Promise((resolve, reject) => {
  244. if (type === 'certificate_key') {
  245. resolve(internalCertificate.checkPrivateKey(content));
  246. } else {
  247. // this should handle `certificate` and intermediate certificate
  248. resolve(internalCertificate.getCertificateInfo(content, true));
  249. }
  250. }).then(res => {
  251. return {[type]: res};
  252. }));
  253. });
  254. return Promise.all(promises)
  255. .then(files => {
  256. let data = {};
  257. _.each(files, file => {
  258. data = _.assign({}, data, file);
  259. });
  260. return data;
  261. });
  262. });
  263. },
  264. /**
  265. * @param {Access} access
  266. * @param {Object} data
  267. * @param {Integer} data.id
  268. * @param {Object} data.files
  269. * @returns {Promise}
  270. */
  271. upload: (access, data) => {
  272. return internalCertificate.get(access, {id: data.id})
  273. .then(row => {
  274. if (row.provider !== 'other') {
  275. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  276. }
  277. return internalCertificate.validate(data)
  278. .then(validations => {
  279. if (typeof validations.certificate === 'undefined') {
  280. throw new error.ValidationError('Certificate file was not provided');
  281. }
  282. _.map(data.files, (file, name) => {
  283. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  284. row.meta[name] = file.data.toString();
  285. }
  286. });
  287. return internalCertificate.update(access, {
  288. id: data.id,
  289. expires_on: certificateModel.raw('FROM_UNIXTIME(' + validations.certificate.dates.to + ')'),
  290. domain_names: [validations.certificate.cn],
  291. meta: row.meta
  292. });
  293. })
  294. .then(() => {
  295. return _.pick(row.meta, internalCertificate.allowed_ssl_files);
  296. });
  297. });
  298. },
  299. /**
  300. * Uses the openssl command to validate the private key.
  301. * It will save the file to disk first, then run commands on it, then delete the file.
  302. *
  303. * @param {String} private_key This is the entire key contents as a string
  304. */
  305. checkPrivateKey: private_key => {
  306. return tempWrite(private_key, '/tmp')
  307. .then(filepath => {
  308. return utils.exec('openssl rsa -in ' + filepath + ' -check -noout')
  309. .then(result => {
  310. if (!result.toLowerCase().includes('key ok')) {
  311. throw new error.ValidationError(result);
  312. }
  313. fs.unlinkSync(filepath);
  314. return true;
  315. }).catch(err => {
  316. fs.unlinkSync(filepath);
  317. throw new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err);
  318. });
  319. });
  320. },
  321. /**
  322. * Uses the openssl command to both validate and get info out of the certificate.
  323. * It will save the file to disk first, then run commands on it, then delete the file.
  324. *
  325. * @param {String} certificate This is the entire cert contents as a string
  326. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  327. */
  328. getCertificateInfo: (certificate, throw_expired) => {
  329. return tempWrite(certificate, '/tmp')
  330. .then(filepath => {
  331. let cert_data = {};
  332. return utils.exec('openssl x509 -in ' + filepath + ' -subject -noout')
  333. .then(result => {
  334. // subject=CN = something.example.com
  335. let regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  336. let match = regex.exec(result);
  337. if (typeof match[1] === 'undefined') {
  338. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  339. }
  340. cert_data['cn'] = match[1];
  341. })
  342. .then(() => {
  343. return utils.exec('openssl x509 -in ' + filepath + ' -issuer -noout');
  344. })
  345. .then(result => {
  346. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  347. let regex = /^(?:issuer=)?(.*)$/gim;
  348. let match = regex.exec(result);
  349. if (typeof match[1] === 'undefined') {
  350. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  351. }
  352. cert_data['issuer'] = match[1];
  353. })
  354. .then(() => {
  355. return utils.exec('openssl x509 -in ' + filepath + ' -dates -noout');
  356. })
  357. .then(result => {
  358. // notBefore=Jul 14 04:04:29 2018 GMT
  359. // notAfter=Oct 12 04:04:29 2018 GMT
  360. let valid_from = null;
  361. let valid_to = null;
  362. let lines = result.split('\n');
  363. lines.map(function (str) {
  364. let regex = /^(\S+)=(.*)$/gim;
  365. let match = regex.exec(str.trim());
  366. if (match && typeof match[2] !== 'undefined') {
  367. let date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  368. if (match[1].toLowerCase() === 'notbefore') {
  369. valid_from = date;
  370. } else if (match[1].toLowerCase() === 'notafter') {
  371. valid_to = date;
  372. }
  373. }
  374. });
  375. if (!valid_from || !valid_to) {
  376. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  377. }
  378. if (throw_expired && valid_to < parseInt(moment().format('X'), 10)) {
  379. throw new error.ValidationError('Certificate has expired');
  380. }
  381. cert_data['dates'] = {
  382. from: valid_from,
  383. to: valid_to
  384. };
  385. })
  386. .then(() => {
  387. fs.unlinkSync(filepath);
  388. return cert_data;
  389. }).catch(err => {
  390. fs.unlinkSync(filepath);
  391. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  392. });
  393. });
  394. },
  395. /**
  396. * Cleans the ssl keys from the meta object and sets them to "true"
  397. *
  398. * @param {Object} meta
  399. * @param {Boolean} [remove]
  400. * @returns {Object}
  401. */
  402. cleanMeta: function (meta, remove) {
  403. internalCertificate.allowed_ssl_files.map(key => {
  404. if (typeof meta[key] !== 'undefined' && meta[key]) {
  405. if (remove) {
  406. delete meta[key];
  407. } else {
  408. meta[key] = true;
  409. }
  410. }
  411. });
  412. return meta;
  413. }
  414. };
  415. module.exports = internalCertificate;