certificate.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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: certificateModel.raw('FROM_UNIXTIME(' + cert_info.dates.to + ')')
  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: certificateModel.raw('FROM_UNIXTIME(' + cert_info.dates.to + ')')
  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: certificateModel.raw('FROM_UNIXTIME(' + validations.certificate.dates.to + ')'),
  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. '--webroot ' +
  686. '--domains "' + certificate.domain_names.join(',') + '" ' +
  687. (le_staging ? '--staging' : '');
  688. if (debug_mode) {
  689. logger.info('Command:', cmd);
  690. }
  691. return utils.exec(cmd)
  692. .then((result) => {
  693. logger.success(result);
  694. return result;
  695. });
  696. },
  697. /**
  698. * @param {Object} certificate the certificate row
  699. * @param {String} apiToken the cloudflare api token
  700. * @returns {Promise}
  701. */
  702. requestLetsEncryptCloudFlareDnsSsl: (certificate, apiToken) => {
  703. logger.info('Requesting Let\'sEncrypt certificates via Cloudflare DNS for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  704. let tokenLoc = '~/cloudflare-token';
  705. let storeKey = 'echo "dns_cloudflare_api_token = ' + apiToken + '" > ' + tokenLoc;
  706. let cmd =
  707. storeKey + " && " +
  708. certbot_command + ' certonly --non-interactive ' +
  709. '--cert-name "npm-' + certificate.id + '" ' +
  710. '--agree-tos ' +
  711. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  712. '--domains "' + certificate.domain_names.join(',') + '" ' +
  713. '--dns-cloudflare --dns-cloudflare-credentials ' + tokenLoc +
  714. (le_staging ? ' --staging' : '')
  715. + ' && rm ' + tokenLoc;
  716. if (debug_mode) {
  717. logger.info('Command:', cmd);
  718. }
  719. return utils.exec(cmd).then((result) => {
  720. logger.info(result);
  721. return result;
  722. });
  723. },
  724. /**
  725. * @param {Access} access
  726. * @param {Object} data
  727. * @param {Number} data.id
  728. * @returns {Promise}
  729. */
  730. renew: (access, data) => {
  731. return access.can('certificates:update', data)
  732. .then(() => {
  733. return internalCertificate.get(access, data);
  734. })
  735. .then((certificate) => {
  736. if (certificate.provider === 'letsencrypt') {
  737. return internalCertificate.renewLetsEncryptSsl(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: certificateModel.raw('FROM_UNIXTIME(' + cert_info.dates.to + ')')
  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. * @param {Boolean} [throw_errors]
  789. * @returns {Promise}
  790. */
  791. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  792. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  793. let cmd = certbot_command + ' revoke --non-interactive ' +
  794. '--config "' + le_config + '" ' +
  795. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  796. '--delete-after-revoke ' +
  797. (le_staging ? '--staging' : '');
  798. if (debug_mode) {
  799. logger.info('Command:', cmd);
  800. }
  801. return utils.exec(cmd)
  802. .then((result) => {
  803. if (debug_mode) {
  804. logger.info('Command:', cmd);
  805. }
  806. logger.info(result);
  807. return result;
  808. })
  809. .catch((err) => {
  810. if (debug_mode) {
  811. logger.error(err.message);
  812. }
  813. if (throw_errors) {
  814. throw err;
  815. }
  816. });
  817. },
  818. /**
  819. * @param {Object} certificate
  820. * @returns {Boolean}
  821. */
  822. hasLetsEncryptSslCerts: (certificate) => {
  823. let le_path = '/etc/letsencrypt/live/npm-' + certificate.id;
  824. return fs.existsSync(le_path + '/fullchain.pem') && fs.existsSync(le_path + '/privkey.pem');
  825. },
  826. /**
  827. * @param {Object} in_use_result
  828. * @param {Number} in_use_result.total_count
  829. * @param {Array} in_use_result.proxy_hosts
  830. * @param {Array} in_use_result.redirection_hosts
  831. * @param {Array} in_use_result.dead_hosts
  832. */
  833. disableInUseHosts: (in_use_result) => {
  834. if (in_use_result.total_count) {
  835. let promises = [];
  836. if (in_use_result.proxy_hosts.length) {
  837. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  838. }
  839. if (in_use_result.redirection_hosts.length) {
  840. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  841. }
  842. if (in_use_result.dead_hosts.length) {
  843. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  844. }
  845. return Promise.all(promises);
  846. } else {
  847. return Promise.resolve();
  848. }
  849. },
  850. /**
  851. * @param {Object} in_use_result
  852. * @param {Number} in_use_result.total_count
  853. * @param {Array} in_use_result.proxy_hosts
  854. * @param {Array} in_use_result.redirection_hosts
  855. * @param {Array} in_use_result.dead_hosts
  856. */
  857. enableInUseHosts: (in_use_result) => {
  858. if (in_use_result.total_count) {
  859. let promises = [];
  860. if (in_use_result.proxy_hosts.length) {
  861. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  862. }
  863. if (in_use_result.redirection_hosts.length) {
  864. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  865. }
  866. if (in_use_result.dead_hosts.length) {
  867. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  868. }
  869. return Promise.all(promises);
  870. } else {
  871. return Promise.resolve();
  872. }
  873. }
  874. };
  875. module.exports = internalCertificate;