certificate.js 26 KB

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