certificate.js 27 KB

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