certificate.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. const fs = require('fs');
  2. const _ = require('lodash');
  3. const logger = require('../logger').ssl;
  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. const debug_mode = process.env.NODE_ENV !== 'production' || !!process.env.DEBUG;
  11. const le_staging = process.env.NODE_ENV !== 'production';
  12. const internalNginx = require('./nginx');
  13. const internalHost = require('./host');
  14. const certbot_command = '/usr/bin/certbot';
  15. const le_config = '/etc/letsencrypt.ini';
  16. function omissions() {
  17. return ['is_deleted'];
  18. }
  19. const internalCertificate = {
  20. allowed_ssl_files: ['certificate', 'certificate_key', 'intermediate_certificate'],
  21. interval_timeout: 1000 * 60 * 60, // 1 hour
  22. interval: null,
  23. interval_processing: false,
  24. initTimer: () => {
  25. logger.info('Let\'s Encrypt Renewal Timer initialized');
  26. internalCertificate.interval = setInterval(internalCertificate.processExpiringHosts, internalCertificate.interval_timeout);
  27. // And do this now as well
  28. internalCertificate.processExpiringHosts();
  29. },
  30. /**
  31. * Triggered by a timer, this will check for expiring hosts and renew their ssl certs if required
  32. */
  33. processExpiringHosts: () => {
  34. if (!internalCertificate.interval_processing) {
  35. internalCertificate.interval_processing = true;
  36. logger.info('Renewing SSL certs close to expiry...');
  37. let cmd = certbot_command + ' renew --non-interactive --quiet ' +
  38. '--config "' + le_config + '" ' +
  39. '--preferred-challenges "dns,http" ' +
  40. '--disable-hook-validation ' +
  41. (le_staging ? '--staging' : '');
  42. return utils.exec(cmd)
  43. .then((result) => {
  44. if (result) {
  45. logger.info('Renew Result: ' + result);
  46. }
  47. return internalNginx.reload()
  48. .then(() => {
  49. logger.info('Renew Complete');
  50. return result;
  51. });
  52. })
  53. .then(() => {
  54. // Now go and fetch all the letsencrypt certs from the db and query the files and update expiry times
  55. return certificateModel
  56. .query()
  57. .where('is_deleted', 0)
  58. .andWhere('provider', 'letsencrypt')
  59. .then((certificates) => {
  60. if (certificates && certificates.length) {
  61. let promises = [];
  62. certificates.map(function (certificate) {
  63. promises.push(
  64. internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  65. .then((cert_info) => {
  66. return certificateModel
  67. .query()
  68. .where('id', certificate.id)
  69. .andWhere('provider', 'letsencrypt')
  70. .patch({
  71. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  72. });
  73. })
  74. .catch((err) => {
  75. // Don't want to stop the train here, just log the error
  76. logger.error(err.message);
  77. })
  78. );
  79. });
  80. return Promise.all(promises);
  81. }
  82. });
  83. })
  84. .then(() => {
  85. internalCertificate.interval_processing = false;
  86. })
  87. .catch((err) => {
  88. logger.error(err);
  89. internalCertificate.interval_processing = false;
  90. });
  91. }
  92. },
  93. /**
  94. * @param {Access} access
  95. * @param {Object} data
  96. * @returns {Promise}
  97. */
  98. create: (access, data) => {
  99. return access.can('certificates:create', data)
  100. .then(() => {
  101. data.owner_user_id = access.token.getUserId(1);
  102. if (data.provider === 'letsencrypt') {
  103. data.nice_name = data.domain_names.sort().join(', ');
  104. }
  105. return certificateModel
  106. .query()
  107. .omit(omissions())
  108. .insertAndFetch(data);
  109. })
  110. .then((certificate) => {
  111. if (certificate.provider === 'letsencrypt') {
  112. // Request a new Cert from LE. Let the fun begin.
  113. // 1. Find out any hosts that are using any of the hostnames in this cert
  114. // 2. Disable them in nginx temporarily
  115. // 3. Generate the LE config
  116. // 4. Request cert
  117. // 5. Remove LE config
  118. // 6. Re-instate previously disabled hosts
  119. // 1. Find out any hosts that are using any of the hostnames in this cert
  120. return internalHost.getHostsWithDomains(certificate.domain_names)
  121. .then((in_use_result) => {
  122. // 2. Disable them in nginx temporarily
  123. return internalCertificate.disableInUseHosts(in_use_result)
  124. .then(() => {
  125. return in_use_result;
  126. });
  127. })
  128. .then((in_use_result) => {
  129. // Is CloudFlare, no config needed, so skip 3 and 5.
  130. if (data.meta.cloudflare_use) {
  131. return internalNginx.reload().then(() => {
  132. // 4. Request cert
  133. return internalCertificate.requestLetsEncryptCloudFlareDnsSsl(certificate, data.meta.cloudflare_token);
  134. })
  135. .then(internalNginx.reload)
  136. .then(() => {
  137. // 6. Re-instate previously disabled hosts
  138. return internalCertificate.enableInUseHosts(in_use_result);
  139. })
  140. .then(() => {
  141. return certificate;
  142. })
  143. .catch((err) => {
  144. // In the event of failure, revert things and throw err back
  145. return internalCertificate.enableInUseHosts(in_use_result)
  146. .then(internalNginx.reload)
  147. .then(() => {
  148. throw err;
  149. });
  150. });
  151. } else {
  152. // 3. Generate the LE config
  153. return internalNginx.generateLetsEncryptRequestConfig(certificate)
  154. .then(internalNginx.reload)
  155. .then(() => {
  156. // 4. Request cert
  157. return internalCertificate.requestLetsEncryptSsl(certificate);
  158. })
  159. .then(() => {
  160. // 5. Remove LE config
  161. return internalNginx.deleteLetsEncryptRequestConfig(certificate);
  162. })
  163. .then(internalNginx.reload)
  164. .then(() => {
  165. // 6. Re-instate previously disabled hosts
  166. return internalCertificate.enableInUseHosts(in_use_result);
  167. })
  168. .then(() => {
  169. return certificate;
  170. })
  171. .catch((err) => {
  172. // In the event of failure, revert things and throw err back
  173. return internalNginx.deleteLetsEncryptRequestConfig(certificate)
  174. .then(() => {
  175. return internalCertificate.enableInUseHosts(in_use_result);
  176. })
  177. .then(internalNginx.reload)
  178. .then(() => {
  179. throw err;
  180. });
  181. });
  182. }
  183. })
  184. .then(() => {
  185. // At this point, the letsencrypt cert should exist on disk.
  186. // Lets get the expiry date from the file and update the row silently
  187. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  188. .then((cert_info) => {
  189. return certificateModel
  190. .query()
  191. .patchAndFetchById(certificate.id, {
  192. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  193. })
  194. .then((saved_row) => {
  195. // Add cert data for audit log
  196. saved_row.meta = _.assign({}, saved_row.meta, {
  197. letsencrypt_certificate: cert_info
  198. });
  199. return saved_row;
  200. });
  201. });
  202. });
  203. } else {
  204. return certificate;
  205. }
  206. }).then((certificate) => {
  207. data.meta = _.assign({}, data.meta || {}, certificate.meta);
  208. // Add to audit log
  209. return internalAuditLog.add(access, {
  210. action: 'created',
  211. object_type: 'certificate',
  212. object_id: certificate.id,
  213. meta: data
  214. })
  215. .then(() => {
  216. return certificate;
  217. });
  218. });
  219. },
  220. /**
  221. * @param {Access} access
  222. * @param {Object} data
  223. * @param {Number} data.id
  224. * @param {String} [data.email]
  225. * @param {String} [data.name]
  226. * @return {Promise}
  227. */
  228. update: (access, data) => {
  229. return access.can('certificates:update', data.id)
  230. .then((/*access_data*/) => {
  231. return internalCertificate.get(access, {id: data.id});
  232. })
  233. .then((row) => {
  234. if (row.id !== data.id) {
  235. // Sanity check that something crazy hasn't happened
  236. throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  237. }
  238. return certificateModel
  239. .query()
  240. .omit(omissions())
  241. .patchAndFetchById(row.id, data)
  242. .then((saved_row) => {
  243. saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
  244. data.meta = internalCertificate.cleanMeta(data.meta);
  245. // Add row.nice_name for custom certs
  246. if (saved_row.provider === 'other') {
  247. data.nice_name = saved_row.nice_name;
  248. }
  249. // Add to audit log
  250. return internalAuditLog.add(access, {
  251. action: 'updated',
  252. object_type: 'certificate',
  253. object_id: row.id,
  254. meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
  255. })
  256. .then(() => {
  257. return _.omit(saved_row, omissions());
  258. });
  259. });
  260. });
  261. },
  262. /**
  263. * @param {Access} access
  264. * @param {Object} data
  265. * @param {Number} data.id
  266. * @param {Array} [data.expand]
  267. * @param {Array} [data.omit]
  268. * @return {Promise}
  269. */
  270. get: (access, data) => {
  271. if (typeof data === 'undefined') {
  272. data = {};
  273. }
  274. return access.can('certificates:get', data.id)
  275. .then((access_data) => {
  276. let query = certificateModel
  277. .query()
  278. .where('is_deleted', 0)
  279. .andWhere('id', data.id)
  280. .allowEager('[owner]')
  281. .first();
  282. if (access_data.permission_visibility !== 'all') {
  283. query.andWhere('owner_user_id', access.token.getUserId(1));
  284. }
  285. // Custom omissions
  286. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  287. query.omit(data.omit);
  288. }
  289. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  290. query.eager('[' + data.expand.join(', ') + ']');
  291. }
  292. return query;
  293. })
  294. .then((row) => {
  295. if (row) {
  296. return _.omit(row, omissions());
  297. } else {
  298. throw new error.ItemNotFoundError(data.id);
  299. }
  300. });
  301. },
  302. /**
  303. * @param {Access} access
  304. * @param {Object} data
  305. * @param {Number} data.id
  306. * @param {String} [data.reason]
  307. * @returns {Promise}
  308. */
  309. delete: (access, data) => {
  310. return access.can('certificates:delete', data.id)
  311. .then(() => {
  312. return internalCertificate.get(access, {id: data.id});
  313. })
  314. .then((row) => {
  315. if (!row) {
  316. throw new error.ItemNotFoundError(data.id);
  317. }
  318. return certificateModel
  319. .query()
  320. .where('id', row.id)
  321. .patch({
  322. is_deleted: 1
  323. })
  324. .then(() => {
  325. // Add to audit log
  326. row.meta = internalCertificate.cleanMeta(row.meta);
  327. return internalAuditLog.add(access, {
  328. action: 'deleted',
  329. object_type: 'certificate',
  330. object_id: row.id,
  331. meta: _.omit(row, omissions())
  332. });
  333. })
  334. .then(() => {
  335. if (row.provider === 'letsencrypt') {
  336. // Revoke the cert
  337. return internalCertificate.revokeLetsEncryptSsl(row);
  338. }
  339. });
  340. })
  341. .then(() => {
  342. return true;
  343. });
  344. },
  345. /**
  346. * All Certs
  347. *
  348. * @param {Access} access
  349. * @param {Array} [expand]
  350. * @param {String} [search_query]
  351. * @returns {Promise}
  352. */
  353. getAll: (access, expand, search_query) => {
  354. return access.can('certificates:list')
  355. .then((access_data) => {
  356. let query = certificateModel
  357. .query()
  358. .where('is_deleted', 0)
  359. .groupBy('id')
  360. .omit(['is_deleted'])
  361. .allowEager('[owner]')
  362. .orderBy('nice_name', 'ASC');
  363. if (access_data.permission_visibility !== 'all') {
  364. query.andWhere('owner_user_id', access.token.getUserId(1));
  365. }
  366. // Query is used for searching
  367. if (typeof search_query === 'string') {
  368. query.where(function () {
  369. this.where('name', 'like', '%' + search_query + '%');
  370. });
  371. }
  372. if (typeof expand !== 'undefined' && expand !== null) {
  373. query.eager('[' + expand.join(', ') + ']');
  374. }
  375. return query;
  376. });
  377. },
  378. /**
  379. * Report use
  380. *
  381. * @param {Number} user_id
  382. * @param {String} visibility
  383. * @returns {Promise}
  384. */
  385. getCount: (user_id, visibility) => {
  386. let query = certificateModel
  387. .query()
  388. .count('id as count')
  389. .where('is_deleted', 0);
  390. if (visibility !== 'all') {
  391. query.andWhere('owner_user_id', user_id);
  392. }
  393. return query.first()
  394. .then((row) => {
  395. return parseInt(row.count, 10);
  396. });
  397. },
  398. /**
  399. * @param {Object} certificate
  400. * @returns {Promise}
  401. */
  402. writeCustomCert: (certificate) => {
  403. if (debug_mode) {
  404. logger.info('Writing Custom Certificate:', certificate);
  405. }
  406. let dir = '/data/custom_ssl/npm-' + certificate.id;
  407. return new Promise((resolve, reject) => {
  408. if (certificate.provider === 'letsencrypt') {
  409. reject(new Error('Refusing to write letsencrypt certs here'));
  410. return;
  411. }
  412. let cert_data = certificate.meta.certificate;
  413. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  414. cert_data = cert_data + '\n' + certificate.meta.intermediate_certificate;
  415. }
  416. try {
  417. if (!fs.existsSync(dir)) {
  418. fs.mkdirSync(dir);
  419. }
  420. } catch (err) {
  421. reject(err);
  422. return;
  423. }
  424. fs.writeFile(dir + '/fullchain.pem', cert_data, function (err) {
  425. if (err) {
  426. reject(err);
  427. } else {
  428. resolve();
  429. }
  430. });
  431. })
  432. .then(() => {
  433. return new Promise((resolve, reject) => {
  434. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  435. if (err) {
  436. reject(err);
  437. } else {
  438. resolve();
  439. }
  440. });
  441. });
  442. });
  443. },
  444. /**
  445. * @param {Access} access
  446. * @param {Object} data
  447. * @param {Array} data.domain_names
  448. * @param {String} data.meta.letsencrypt_email
  449. * @param {Boolean} data.meta.letsencrypt_agree
  450. * @returns {Promise}
  451. */
  452. createQuickCertificate: (access, data) => {
  453. return internalCertificate.create(access, {
  454. provider: 'letsencrypt',
  455. domain_names: data.domain_names,
  456. meta: data.meta
  457. });
  458. },
  459. /**
  460. * Validates that the certs provided are good.
  461. * No access required here, nothing is changed or stored.
  462. *
  463. * @param {Object} data
  464. * @param {Object} data.files
  465. * @returns {Promise}
  466. */
  467. validate: (data) => {
  468. return new Promise((resolve) => {
  469. // Put file contents into an object
  470. let files = {};
  471. _.map(data.files, (file, name) => {
  472. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  473. files[name] = file.data.toString();
  474. }
  475. });
  476. resolve(files);
  477. })
  478. .then((files) => {
  479. // For each file, create a temp file and write the contents to it
  480. // Then test it depending on the file type
  481. let promises = [];
  482. _.map(files, (content, type) => {
  483. promises.push(new Promise((resolve) => {
  484. if (type === 'certificate_key') {
  485. resolve(internalCertificate.checkPrivateKey(content));
  486. } else {
  487. // this should handle `certificate` and intermediate certificate
  488. resolve(internalCertificate.getCertificateInfo(content, true));
  489. }
  490. }).then((res) => {
  491. return {[type]: res};
  492. }));
  493. });
  494. return Promise.all(promises)
  495. .then((files) => {
  496. let data = {};
  497. _.each(files, (file) => {
  498. data = _.assign({}, data, file);
  499. });
  500. return data;
  501. });
  502. });
  503. },
  504. /**
  505. * @param {Access} access
  506. * @param {Object} data
  507. * @param {Number} data.id
  508. * @param {Object} data.files
  509. * @returns {Promise}
  510. */
  511. upload: (access, data) => {
  512. return internalCertificate.get(access, {id: data.id})
  513. .then((row) => {
  514. if (row.provider !== 'other') {
  515. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  516. }
  517. return internalCertificate.validate(data)
  518. .then((validations) => {
  519. if (typeof validations.certificate === 'undefined') {
  520. throw new error.ValidationError('Certificate file was not provided');
  521. }
  522. _.map(data.files, (file, name) => {
  523. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  524. row.meta[name] = file.data.toString();
  525. }
  526. });
  527. // TODO: This uses a mysql only raw function that won't translate to postgres
  528. return internalCertificate.update(access, {
  529. id: data.id,
  530. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  531. domain_names: [validations.certificate.cn],
  532. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  533. })
  534. .then((certificate) => {
  535. console.log('ROWMETA:', row.meta);
  536. certificate.meta = row.meta;
  537. return internalCertificate.writeCustomCert(certificate);
  538. });
  539. })
  540. .then(() => {
  541. return _.pick(row.meta, internalCertificate.allowed_ssl_files);
  542. });
  543. });
  544. },
  545. /**
  546. * Uses the openssl command to validate the private key.
  547. * It will save the file to disk first, then run commands on it, then delete the file.
  548. *
  549. * @param {String} private_key This is the entire key contents as a string
  550. */
  551. checkPrivateKey: (private_key) => {
  552. return tempWrite(private_key, '/tmp')
  553. .then((filepath) => {
  554. return utils.exec('openssl rsa -in ' + filepath + ' -check -noout')
  555. .then((result) => {
  556. if (!result.toLowerCase().includes('key ok')) {
  557. throw new error.ValidationError(result);
  558. }
  559. fs.unlinkSync(filepath);
  560. return true;
  561. }).catch((err) => {
  562. fs.unlinkSync(filepath);
  563. throw new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err);
  564. });
  565. });
  566. },
  567. /**
  568. * Uses the openssl command to both validate and get info out of the certificate.
  569. * It will save the file to disk first, then run commands on it, then delete the file.
  570. *
  571. * @param {String} certificate This is the entire cert contents as a string
  572. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  573. */
  574. getCertificateInfo: (certificate, throw_expired) => {
  575. return tempWrite(certificate, '/tmp')
  576. .then((filepath) => {
  577. return internalCertificate.getCertificateInfoFromFile(filepath, throw_expired)
  578. .then((cert_data) => {
  579. fs.unlinkSync(filepath);
  580. return cert_data;
  581. }).catch((err) => {
  582. fs.unlinkSync(filepath);
  583. throw err;
  584. });
  585. });
  586. },
  587. /**
  588. * Uses the openssl command to both validate and get info out of the certificate.
  589. * It will save the file to disk first, then run commands on it, then delete the file.
  590. *
  591. * @param {String} certificate_file The file location on disk
  592. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  593. */
  594. getCertificateInfoFromFile: (certificate_file, throw_expired) => {
  595. let cert_data = {};
  596. return utils.exec('openssl x509 -in ' + certificate_file + ' -subject -noout')
  597. .then((result) => {
  598. // subject=CN = something.example.com
  599. let regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  600. let match = regex.exec(result);
  601. if (typeof match[1] === 'undefined') {
  602. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  603. }
  604. cert_data['cn'] = match[1];
  605. })
  606. .then(() => {
  607. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  608. })
  609. .then((result) => {
  610. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  611. let regex = /^(?:issuer=)?(.*)$/gim;
  612. let match = regex.exec(result);
  613. if (typeof match[1] === 'undefined') {
  614. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  615. }
  616. cert_data['issuer'] = match[1];
  617. })
  618. .then(() => {
  619. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  620. })
  621. .then((result) => {
  622. // notBefore=Jul 14 04:04:29 2018 GMT
  623. // notAfter=Oct 12 04:04:29 2018 GMT
  624. let valid_from = null;
  625. let valid_to = null;
  626. let lines = result.split('\n');
  627. lines.map(function (str) {
  628. let regex = /^(\S+)=(.*)$/gim;
  629. let match = regex.exec(str.trim());
  630. if (match && typeof match[2] !== 'undefined') {
  631. let date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  632. if (match[1].toLowerCase() === 'notbefore') {
  633. valid_from = date;
  634. } else if (match[1].toLowerCase() === 'notafter') {
  635. valid_to = date;
  636. }
  637. }
  638. });
  639. if (!valid_from || !valid_to) {
  640. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  641. }
  642. if (throw_expired && valid_to < parseInt(moment().format('X'), 10)) {
  643. throw new error.ValidationError('Certificate has expired');
  644. }
  645. cert_data['dates'] = {
  646. from: valid_from,
  647. to: valid_to
  648. };
  649. return cert_data;
  650. }).catch((err) => {
  651. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  652. });
  653. },
  654. /**
  655. * Cleans the ssl keys from the meta object and sets them to "true"
  656. *
  657. * @param {Object} meta
  658. * @param {Boolean} [remove]
  659. * @returns {Object}
  660. */
  661. cleanMeta: function (meta, remove) {
  662. internalCertificate.allowed_ssl_files.map((key) => {
  663. if (typeof meta[key] !== 'undefined' && meta[key]) {
  664. if (remove) {
  665. delete meta[key];
  666. } else {
  667. meta[key] = true;
  668. }
  669. }
  670. });
  671. return meta;
  672. },
  673. /**
  674. * @param {Object} certificate the certificate row
  675. * @returns {Promise}
  676. */
  677. requestLetsEncryptSsl: (certificate) => {
  678. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  679. let cmd = certbot_command + ' certonly --non-interactive ' +
  680. '--config "' + le_config + '" ' +
  681. '--cert-name "npm-' + certificate.id + '" ' +
  682. '--agree-tos ' +
  683. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  684. '--preferred-challenges "dns,http" ' +
  685. '--domains "' + certificate.domain_names.join(',') + '" ' +
  686. (le_staging ? '--staging' : '');
  687. if (debug_mode) {
  688. logger.info('Command:', cmd);
  689. }
  690. return utils.exec(cmd)
  691. .then((result) => {
  692. logger.success(result);
  693. return result;
  694. });
  695. },
  696. /**
  697. * @param {Object} certificate the certificate row
  698. * @param {String} apiToken the cloudflare api token
  699. * @returns {Promise}
  700. */
  701. requestLetsEncryptCloudFlareDnsSsl: (certificate, apiToken) => {
  702. logger.info('Requesting Let\'sEncrypt certificates via Cloudflare DNS for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  703. let tokenLoc = '~/cloudflare-token';
  704. let storeKey = 'echo "dns_cloudflare_api_token = ' + apiToken + '" > ' + tokenLoc;
  705. let cmd =
  706. storeKey + ' && ' +
  707. certbot_command + ' certonly --non-interactive ' +
  708. '--cert-name "npm-' + certificate.id + '" ' +
  709. '--agree-tos ' +
  710. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  711. '--domains "' + certificate.domain_names.join(',') + '" ' +
  712. '--dns-cloudflare --dns-cloudflare-credentials ' + tokenLoc +
  713. (le_staging ? ' --staging' : '')
  714. + ' && rm ' + tokenLoc;
  715. if (debug_mode) {
  716. logger.info('Command:', cmd);
  717. }
  718. return utils.exec(cmd).then((result) => {
  719. logger.info(result);
  720. return result;
  721. });
  722. },
  723. /**
  724. * @param {Access} access
  725. * @param {Object} data
  726. * @param {Number} data.id
  727. * @returns {Promise}
  728. */
  729. renew: (access, data) => {
  730. return access.can('certificates:update', data)
  731. .then(() => {
  732. return internalCertificate.get(access, data);
  733. })
  734. .then((certificate) => {
  735. if (certificate.provider === 'letsencrypt') {
  736. let renewMethod = certificate.meta.cloudflare_use ? internalCertificate.renewLetsEncryptCloudFlareSsl : internalCertificate.renewLetsEncryptSsl;
  737. return renewMethod(certificate)
  738. .then(() => {
  739. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  740. })
  741. .then((cert_info) => {
  742. return certificateModel
  743. .query()
  744. .patchAndFetchById(certificate.id, {
  745. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  746. });
  747. })
  748. .then((updated_certificate) => {
  749. // Add to audit log
  750. return internalAuditLog.add(access, {
  751. action: 'renewed',
  752. object_type: 'certificate',
  753. object_id: updated_certificate.id,
  754. meta: updated_certificate
  755. })
  756. .then(() => {
  757. return updated_certificate;
  758. });
  759. });
  760. } else {
  761. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  762. }
  763. });
  764. },
  765. /**
  766. * @param {Object} certificate the certificate row
  767. * @returns {Promise}
  768. */
  769. renewLetsEncryptSsl: (certificate) => {
  770. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  771. let cmd = certbot_command + ' renew --non-interactive ' +
  772. '--config "' + le_config + '" ' +
  773. '--cert-name "npm-' + certificate.id + '" ' +
  774. '--preferred-challenges "dns,http" ' +
  775. '--disable-hook-validation ' +
  776. (le_staging ? '--staging' : '');
  777. if (debug_mode) {
  778. logger.info('Command:', cmd);
  779. }
  780. return utils.exec(cmd)
  781. .then((result) => {
  782. logger.info(result);
  783. return result;
  784. });
  785. },
  786. /**
  787. * @param {Object} certificate the certificate row
  788. * @returns {Promise}
  789. */
  790. renewLetsEncryptCloudFlareSsl: (certificate) => {
  791. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  792. let cmd = certbot_command + ' renew --non-interactive ' +
  793. '--cert-name "npm-' + certificate.id + '" ' +
  794. '--disable-hook-validation ' +
  795. (le_staging ? '--staging' : '');
  796. if (debug_mode) {
  797. logger.info('Command:', cmd);
  798. }
  799. return utils.exec(cmd)
  800. .then((result) => {
  801. logger.info(result);
  802. return result;
  803. });
  804. },
  805. /**
  806. * @param {Object} certificate the certificate row
  807. * @param {Boolean} [throw_errors]
  808. * @returns {Promise}
  809. */
  810. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  811. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  812. let cmd = certbot_command + ' revoke --non-interactive ' +
  813. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  814. '--delete-after-revoke ' +
  815. (le_staging ? '--staging' : '');
  816. if (debug_mode) {
  817. logger.info('Command:', cmd);
  818. }
  819. return utils.exec(cmd)
  820. .then((result) => {
  821. if (debug_mode) {
  822. logger.info('Command:', cmd);
  823. }
  824. logger.info(result);
  825. return result;
  826. })
  827. .catch((err) => {
  828. if (debug_mode) {
  829. logger.error(err.message);
  830. }
  831. if (throw_errors) {
  832. throw err;
  833. }
  834. });
  835. },
  836. /**
  837. * @param {Object} certificate
  838. * @returns {Boolean}
  839. */
  840. hasLetsEncryptSslCerts: (certificate) => {
  841. let le_path = '/etc/letsencrypt/live/npm-' + certificate.id;
  842. return fs.existsSync(le_path + '/fullchain.pem') && fs.existsSync(le_path + '/privkey.pem');
  843. },
  844. /**
  845. * @param {Object} in_use_result
  846. * @param {Number} in_use_result.total_count
  847. * @param {Array} in_use_result.proxy_hosts
  848. * @param {Array} in_use_result.redirection_hosts
  849. * @param {Array} in_use_result.dead_hosts
  850. */
  851. disableInUseHosts: (in_use_result) => {
  852. if (in_use_result.total_count) {
  853. let promises = [];
  854. if (in_use_result.proxy_hosts.length) {
  855. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  856. }
  857. if (in_use_result.redirection_hosts.length) {
  858. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  859. }
  860. if (in_use_result.dead_hosts.length) {
  861. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  862. }
  863. return Promise.all(promises);
  864. } else {
  865. return Promise.resolve();
  866. }
  867. },
  868. /**
  869. * @param {Object} in_use_result
  870. * @param {Number} in_use_result.total_count
  871. * @param {Array} in_use_result.proxy_hosts
  872. * @param {Array} in_use_result.redirection_hosts
  873. * @param {Array} in_use_result.dead_hosts
  874. */
  875. enableInUseHosts: (in_use_result) => {
  876. if (in_use_result.total_count) {
  877. let promises = [];
  878. if (in_use_result.proxy_hosts.length) {
  879. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  880. }
  881. if (in_use_result.redirection_hosts.length) {
  882. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  883. }
  884. if (in_use_result.dead_hosts.length) {
  885. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  886. }
  887. return Promise.all(promises);
  888. } else {
  889. return Promise.resolve();
  890. }
  891. }
  892. };
  893. module.exports = internalCertificate;