certificate.js 31 KB

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