certificate.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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. }).catch(async (error) => {
  204. // Delete the certificate from the database if it was not created successfully
  205. await certificateModel
  206. .query()
  207. .deleteById(certificate.id);
  208. throw error;
  209. });
  210. } else {
  211. return certificate;
  212. }
  213. }).then((certificate) => {
  214. data.meta = _.assign({}, data.meta || {}, certificate.meta);
  215. // Add to audit log
  216. return internalAuditLog.add(access, {
  217. action: 'created',
  218. object_type: 'certificate',
  219. object_id: certificate.id,
  220. meta: data
  221. })
  222. .then(() => {
  223. return certificate;
  224. });
  225. });
  226. },
  227. /**
  228. * @param {Access} access
  229. * @param {Object} data
  230. * @param {Number} data.id
  231. * @param {String} [data.email]
  232. * @param {String} [data.name]
  233. * @return {Promise}
  234. */
  235. update: (access, data) => {
  236. return access.can('certificates:update', data.id)
  237. .then((/*access_data*/) => {
  238. return internalCertificate.get(access, {id: data.id});
  239. })
  240. .then((row) => {
  241. if (row.id !== data.id) {
  242. // Sanity check that something crazy hasn't happened
  243. throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  244. }
  245. return certificateModel
  246. .query()
  247. .omit(omissions())
  248. .patchAndFetchById(row.id, data)
  249. .then((saved_row) => {
  250. saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
  251. data.meta = internalCertificate.cleanMeta(data.meta);
  252. // Add row.nice_name for custom certs
  253. if (saved_row.provider === 'other') {
  254. data.nice_name = saved_row.nice_name;
  255. }
  256. // Add to audit log
  257. return internalAuditLog.add(access, {
  258. action: 'updated',
  259. object_type: 'certificate',
  260. object_id: row.id,
  261. meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
  262. })
  263. .then(() => {
  264. return _.omit(saved_row, omissions());
  265. });
  266. });
  267. });
  268. },
  269. /**
  270. * @param {Access} access
  271. * @param {Object} data
  272. * @param {Number} data.id
  273. * @param {Array} [data.expand]
  274. * @param {Array} [data.omit]
  275. * @return {Promise}
  276. */
  277. get: (access, data) => {
  278. if (typeof data === 'undefined') {
  279. data = {};
  280. }
  281. return access.can('certificates:get', data.id)
  282. .then((access_data) => {
  283. let query = certificateModel
  284. .query()
  285. .where('is_deleted', 0)
  286. .andWhere('id', data.id)
  287. .allowEager('[owner]')
  288. .first();
  289. if (access_data.permission_visibility !== 'all') {
  290. query.andWhere('owner_user_id', access.token.getUserId(1));
  291. }
  292. // Custom omissions
  293. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  294. query.omit(data.omit);
  295. }
  296. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  297. query.eager('[' + data.expand.join(', ') + ']');
  298. }
  299. return query;
  300. })
  301. .then((row) => {
  302. if (row) {
  303. return _.omit(row, omissions());
  304. } else {
  305. throw new error.ItemNotFoundError(data.id);
  306. }
  307. });
  308. },
  309. /**
  310. * @param {Access} access
  311. * @param {Object} data
  312. * @param {Number} data.id
  313. * @param {String} [data.reason]
  314. * @returns {Promise}
  315. */
  316. delete: (access, data) => {
  317. return access.can('certificates:delete', data.id)
  318. .then(() => {
  319. return internalCertificate.get(access, {id: data.id});
  320. })
  321. .then((row) => {
  322. if (!row) {
  323. throw new error.ItemNotFoundError(data.id);
  324. }
  325. return certificateModel
  326. .query()
  327. .where('id', row.id)
  328. .patch({
  329. is_deleted: 1
  330. })
  331. .then(() => {
  332. // Add to audit log
  333. row.meta = internalCertificate.cleanMeta(row.meta);
  334. return internalAuditLog.add(access, {
  335. action: 'deleted',
  336. object_type: 'certificate',
  337. object_id: row.id,
  338. meta: _.omit(row, omissions())
  339. });
  340. })
  341. .then(() => {
  342. if (row.provider === 'letsencrypt') {
  343. // Revoke the cert
  344. return internalCertificate.revokeLetsEncryptSsl(row);
  345. }
  346. });
  347. })
  348. .then(() => {
  349. return true;
  350. });
  351. },
  352. /**
  353. * All Certs
  354. *
  355. * @param {Access} access
  356. * @param {Array} [expand]
  357. * @param {String} [search_query]
  358. * @returns {Promise}
  359. */
  360. getAll: (access, expand, search_query) => {
  361. return access.can('certificates:list')
  362. .then((access_data) => {
  363. let query = certificateModel
  364. .query()
  365. .where('is_deleted', 0)
  366. .groupBy('id')
  367. .omit(['is_deleted'])
  368. .allowEager('[owner]')
  369. .orderBy('nice_name', 'ASC');
  370. if (access_data.permission_visibility !== 'all') {
  371. query.andWhere('owner_user_id', access.token.getUserId(1));
  372. }
  373. // Query is used for searching
  374. if (typeof search_query === 'string') {
  375. query.where(function () {
  376. this.where('name', 'like', '%' + search_query + '%');
  377. });
  378. }
  379. if (typeof expand !== 'undefined' && expand !== null) {
  380. query.eager('[' + expand.join(', ') + ']');
  381. }
  382. return query;
  383. });
  384. },
  385. /**
  386. * Report use
  387. *
  388. * @param {Number} user_id
  389. * @param {String} visibility
  390. * @returns {Promise}
  391. */
  392. getCount: (user_id, visibility) => {
  393. let query = certificateModel
  394. .query()
  395. .count('id as count')
  396. .where('is_deleted', 0);
  397. if (visibility !== 'all') {
  398. query.andWhere('owner_user_id', user_id);
  399. }
  400. return query.first()
  401. .then((row) => {
  402. return parseInt(row.count, 10);
  403. });
  404. },
  405. /**
  406. * @param {Object} certificate
  407. * @returns {Promise}
  408. */
  409. writeCustomCert: (certificate) => {
  410. if (debug_mode) {
  411. logger.info('Writing Custom Certificate:', certificate);
  412. }
  413. let dir = '/data/custom_ssl/npm-' + certificate.id;
  414. return new Promise((resolve, reject) => {
  415. if (certificate.provider === 'letsencrypt') {
  416. reject(new Error('Refusing to write letsencrypt certs here'));
  417. return;
  418. }
  419. let cert_data = certificate.meta.certificate;
  420. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  421. cert_data = cert_data + '\n' + certificate.meta.intermediate_certificate;
  422. }
  423. try {
  424. if (!fs.existsSync(dir)) {
  425. fs.mkdirSync(dir);
  426. }
  427. } catch (err) {
  428. reject(err);
  429. return;
  430. }
  431. fs.writeFile(dir + '/fullchain.pem', cert_data, function (err) {
  432. if (err) {
  433. reject(err);
  434. } else {
  435. resolve();
  436. }
  437. });
  438. })
  439. .then(() => {
  440. return new Promise((resolve, reject) => {
  441. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  442. if (err) {
  443. reject(err);
  444. } else {
  445. resolve();
  446. }
  447. });
  448. });
  449. });
  450. },
  451. /**
  452. * @param {Access} access
  453. * @param {Object} data
  454. * @param {Array} data.domain_names
  455. * @param {String} data.meta.letsencrypt_email
  456. * @param {Boolean} data.meta.letsencrypt_agree
  457. * @returns {Promise}
  458. */
  459. createQuickCertificate: (access, data) => {
  460. return internalCertificate.create(access, {
  461. provider: 'letsencrypt',
  462. domain_names: data.domain_names,
  463. meta: data.meta
  464. });
  465. },
  466. /**
  467. * Validates that the certs provided are good.
  468. * No access required here, nothing is changed or stored.
  469. *
  470. * @param {Object} data
  471. * @param {Object} data.files
  472. * @returns {Promise}
  473. */
  474. validate: (data) => {
  475. return new Promise((resolve) => {
  476. // Put file contents into an object
  477. let files = {};
  478. _.map(data.files, (file, name) => {
  479. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  480. files[name] = file.data.toString();
  481. }
  482. });
  483. resolve(files);
  484. })
  485. .then((files) => {
  486. // For each file, create a temp file and write the contents to it
  487. // Then test it depending on the file type
  488. let promises = [];
  489. _.map(files, (content, type) => {
  490. promises.push(new Promise((resolve) => {
  491. if (type === 'certificate_key') {
  492. resolve(internalCertificate.checkPrivateKey(content));
  493. } else {
  494. // this should handle `certificate` and intermediate certificate
  495. resolve(internalCertificate.getCertificateInfo(content, true));
  496. }
  497. }).then((res) => {
  498. return {[type]: res};
  499. }));
  500. });
  501. return Promise.all(promises)
  502. .then((files) => {
  503. let data = {};
  504. _.each(files, (file) => {
  505. data = _.assign({}, data, file);
  506. });
  507. return data;
  508. });
  509. });
  510. },
  511. /**
  512. * @param {Access} access
  513. * @param {Object} data
  514. * @param {Number} data.id
  515. * @param {Object} data.files
  516. * @returns {Promise}
  517. */
  518. upload: (access, data) => {
  519. return internalCertificate.get(access, {id: data.id})
  520. .then((row) => {
  521. if (row.provider !== 'other') {
  522. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  523. }
  524. return internalCertificate.validate(data)
  525. .then((validations) => {
  526. if (typeof validations.certificate === 'undefined') {
  527. throw new error.ValidationError('Certificate file was not provided');
  528. }
  529. _.map(data.files, (file, name) => {
  530. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  531. row.meta[name] = file.data.toString();
  532. }
  533. });
  534. // TODO: This uses a mysql only raw function that won't translate to postgres
  535. return internalCertificate.update(access, {
  536. id: data.id,
  537. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  538. domain_names: [validations.certificate.cn],
  539. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  540. })
  541. .then((certificate) => {
  542. console.log('ROWMETA:', row.meta);
  543. certificate.meta = row.meta;
  544. return internalCertificate.writeCustomCert(certificate);
  545. });
  546. })
  547. .then(() => {
  548. return _.pick(row.meta, internalCertificate.allowed_ssl_files);
  549. });
  550. });
  551. },
  552. /**
  553. * Uses the openssl command to validate the private key.
  554. * It will save the file to disk first, then run commands on it, then delete the file.
  555. *
  556. * @param {String} private_key This is the entire key contents as a string
  557. */
  558. checkPrivateKey: (private_key) => {
  559. return tempWrite(private_key, '/tmp')
  560. .then((filepath) => {
  561. return new Promise((resolve, reject) => {
  562. const failTimeout = setTimeout(() => {
  563. reject(new error.ValidationError('Result Validation Error: Validation timed out. This could be due to the key being passphrase-protected.'));
  564. }, 10000);
  565. utils
  566. .exec('openssl pkey -in ' + filepath + ' -check -noout 2>&1 ')
  567. .then((result) => {
  568. clearTimeout(failTimeout);
  569. if (!result.toLowerCase().includes('key is valid')) {
  570. reject(new error.ValidationError('Result Validation Error: ' + result));
  571. }
  572. fs.unlinkSync(filepath);
  573. resolve(true);
  574. })
  575. .catch((err) => {
  576. clearTimeout(failTimeout);
  577. fs.unlinkSync(filepath);
  578. reject(new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err));
  579. });
  580. });
  581. });
  582. },
  583. /**
  584. * Uses the openssl command to both validate and get info out of the certificate.
  585. * It will save the file to disk first, then run commands on it, then delete the file.
  586. *
  587. * @param {String} certificate This is the entire cert contents as a string
  588. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  589. */
  590. getCertificateInfo: (certificate, throw_expired) => {
  591. return tempWrite(certificate, '/tmp')
  592. .then((filepath) => {
  593. return internalCertificate.getCertificateInfoFromFile(filepath, throw_expired)
  594. .then((cert_data) => {
  595. fs.unlinkSync(filepath);
  596. return cert_data;
  597. }).catch((err) => {
  598. fs.unlinkSync(filepath);
  599. throw err;
  600. });
  601. });
  602. },
  603. /**
  604. * Uses the openssl command to both validate and get info out of the certificate.
  605. * It will save the file to disk first, then run commands on it, then delete the file.
  606. *
  607. * @param {String} certificate_file The file location on disk
  608. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  609. */
  610. getCertificateInfoFromFile: (certificate_file, throw_expired) => {
  611. let cert_data = {};
  612. return utils.exec('openssl x509 -in ' + certificate_file + ' -subject -noout')
  613. .then((result) => {
  614. // subject=CN = something.example.com
  615. let regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  616. let match = regex.exec(result);
  617. if (typeof match[1] === 'undefined') {
  618. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  619. }
  620. cert_data['cn'] = match[1];
  621. })
  622. .then(() => {
  623. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  624. })
  625. .then((result) => {
  626. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  627. let regex = /^(?:issuer=)?(.*)$/gim;
  628. let match = regex.exec(result);
  629. if (typeof match[1] === 'undefined') {
  630. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  631. }
  632. cert_data['issuer'] = match[1];
  633. })
  634. .then(() => {
  635. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  636. })
  637. .then((result) => {
  638. // notBefore=Jul 14 04:04:29 2018 GMT
  639. // notAfter=Oct 12 04:04:29 2018 GMT
  640. let valid_from = null;
  641. let valid_to = null;
  642. let lines = result.split('\n');
  643. lines.map(function (str) {
  644. let regex = /^(\S+)=(.*)$/gim;
  645. let match = regex.exec(str.trim());
  646. if (match && typeof match[2] !== 'undefined') {
  647. let date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  648. if (match[1].toLowerCase() === 'notbefore') {
  649. valid_from = date;
  650. } else if (match[1].toLowerCase() === 'notafter') {
  651. valid_to = date;
  652. }
  653. }
  654. });
  655. if (!valid_from || !valid_to) {
  656. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  657. }
  658. if (throw_expired && valid_to < parseInt(moment().format('X'), 10)) {
  659. throw new error.ValidationError('Certificate has expired');
  660. }
  661. cert_data['dates'] = {
  662. from: valid_from,
  663. to: valid_to
  664. };
  665. return cert_data;
  666. }).catch((err) => {
  667. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  668. });
  669. },
  670. /**
  671. * Cleans the ssl keys from the meta object and sets them to "true"
  672. *
  673. * @param {Object} meta
  674. * @param {Boolean} [remove]
  675. * @returns {Object}
  676. */
  677. cleanMeta: function (meta, remove) {
  678. internalCertificate.allowed_ssl_files.map((key) => {
  679. if (typeof meta[key] !== 'undefined' && meta[key]) {
  680. if (remove) {
  681. delete meta[key];
  682. } else {
  683. meta[key] = true;
  684. }
  685. }
  686. });
  687. return meta;
  688. },
  689. /**
  690. * @param {Object} certificate the certificate row
  691. * @returns {Promise}
  692. */
  693. requestLetsEncryptSsl: (certificate) => {
  694. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  695. let cmd = certbot_command + ' certonly --non-interactive ' +
  696. '--config "' + le_config + '" ' +
  697. '--cert-name "npm-' + certificate.id + '" ' +
  698. '--agree-tos ' +
  699. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  700. '--preferred-challenges "dns,http" ' +
  701. '--domains "' + certificate.domain_names.join(',') + '" ' +
  702. (le_staging ? '--staging' : '');
  703. if (debug_mode) {
  704. logger.info('Command:', cmd);
  705. }
  706. return utils.exec(cmd)
  707. .then((result) => {
  708. logger.success(result);
  709. return result;
  710. });
  711. },
  712. /**
  713. * @param {Object} certificate the certificate row
  714. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  715. * @param {String | null} credentials the content of this providers credentials file
  716. * @param {String} propagation_seconds the cloudflare api token
  717. * @returns {Promise}
  718. */
  719. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  720. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  721. if (!dns_plugin) {
  722. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  723. }
  724. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  725. const credentials_loc = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  726. const credentials_cmd = 'mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + certificate.meta.dns_provider_credentials.replace('\'', '\\\'') + '\' > \'' + credentials_loc + '\' && chmod 600 \'' + credentials_loc + '\'';
  727. const prepare_cmd = 'pip3 install ' + dns_plugin.package_name + '==' + dns_plugin.package_version + ' ' + dns_plugin.dependencies;
  728. // Whether the plugin has a --<name>-credentials argument
  729. const has_config_arg = certificate.meta.dns_provider !== 'route53';
  730. let main_cmd =
  731. certbot_command + ' certonly --non-interactive ' +
  732. '--cert-name "npm-' + certificate.id + '" ' +
  733. '--agree-tos ' +
  734. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  735. '--domains "' + certificate.domain_names.join(',') + '" ' +
  736. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  737. (
  738. has_config_arg
  739. ? '--' + dns_plugin.full_plugin_name + '-credentials "' + credentials_loc + '"'
  740. : ''
  741. ) +
  742. (
  743. certificate.meta.propagation_seconds !== undefined
  744. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  745. : ''
  746. ) +
  747. (le_staging ? ' --staging' : '');
  748. // Prepend the path to the credentials file as an environment variable
  749. if (certificate.meta.dns_provider === 'route53') {
  750. main_cmd = 'AWS_CONFIG_FILE=\'' + credentials_loc + '\' ' + main_cmd;
  751. }
  752. if (debug_mode) {
  753. logger.info('Command:', `${credentials_cmd} && ${prepare_cmd} && ${main_cmd}`);
  754. }
  755. return utils.exec(credentials_cmd)
  756. .then(() => {
  757. return utils.exec(prepare_cmd)
  758. .then(() => {
  759. return utils.exec(main_cmd)
  760. .then(async (result) => {
  761. logger.info(result);
  762. return result;
  763. });
  764. });
  765. }).catch(async (err) => {
  766. // Don't fail if file does not exist
  767. const delete_credentials_cmd = `rm -f '${credentials_loc}' || true`;
  768. await utils.exec(delete_credentials_cmd);
  769. throw err;
  770. });
  771. },
  772. /**
  773. * @param {Access} access
  774. * @param {Object} data
  775. * @param {Number} data.id
  776. * @returns {Promise}
  777. */
  778. renew: (access, data) => {
  779. return access.can('certificates:update', data)
  780. .then(() => {
  781. return internalCertificate.get(access, data);
  782. })
  783. .then((certificate) => {
  784. if (certificate.provider === 'letsencrypt') {
  785. let renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  786. return renewMethod(certificate)
  787. .then(() => {
  788. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  789. })
  790. .then((cert_info) => {
  791. return certificateModel
  792. .query()
  793. .patchAndFetchById(certificate.id, {
  794. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  795. });
  796. })
  797. .then((updated_certificate) => {
  798. // Add to audit log
  799. return internalAuditLog.add(access, {
  800. action: 'renewed',
  801. object_type: 'certificate',
  802. object_id: updated_certificate.id,
  803. meta: updated_certificate
  804. })
  805. .then(() => {
  806. return updated_certificate;
  807. });
  808. });
  809. } else {
  810. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  811. }
  812. });
  813. },
  814. /**
  815. * @param {Object} certificate the certificate row
  816. * @returns {Promise}
  817. */
  818. renewLetsEncryptSsl: (certificate) => {
  819. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  820. let cmd = certbot_command + ' renew --non-interactive ' +
  821. '--config "' + le_config + '" ' +
  822. '--cert-name "npm-' + certificate.id + '" ' +
  823. '--preferred-challenges "dns,http" ' +
  824. '--disable-hook-validation ' +
  825. (le_staging ? '--staging' : '');
  826. if (debug_mode) {
  827. logger.info('Command:', cmd);
  828. }
  829. return utils.exec(cmd)
  830. .then((result) => {
  831. logger.info(result);
  832. return result;
  833. });
  834. },
  835. /**
  836. * @param {Object} certificate the certificate row
  837. * @returns {Promise}
  838. */
  839. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  840. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  841. if (!dns_plugin) {
  842. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  843. }
  844. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  845. let main_cmd =
  846. certbot_command + ' renew --non-interactive ' +
  847. '--cert-name "npm-' + certificate.id + '" ' +
  848. '--disable-hook-validation' +
  849. (le_staging ? ' --staging' : '');
  850. // Prepend the path to the credentials file as an environment variable
  851. if (certificate.meta.dns_provider === 'route53') {
  852. const credentials_loc = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  853. main_cmd = 'AWS_CONFIG_FILE=\'' + credentials_loc + '\' ' + main_cmd;
  854. }
  855. if (debug_mode) {
  856. logger.info('Command:', main_cmd);
  857. }
  858. return utils.exec(main_cmd)
  859. .then(async (result) => {
  860. logger.info(result);
  861. return result;
  862. });
  863. },
  864. /**
  865. * @param {Object} certificate the certificate row
  866. * @param {Boolean} [throw_errors]
  867. * @returns {Promise}
  868. */
  869. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  870. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  871. const main_cmd = certbot_command + ' revoke --non-interactive ' +
  872. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  873. '--delete-after-revoke ' +
  874. (le_staging ? '--staging' : '');
  875. // Don't fail command if file does not exist
  876. const delete_credentials_cmd = `rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`;
  877. if (debug_mode) {
  878. logger.info('Command:', main_cmd + '; ' + delete_credentials_cmd);
  879. }
  880. return utils.exec(main_cmd)
  881. .then(async (result) => {
  882. await utils.exec(delete_credentials_cmd);
  883. logger.info(result);
  884. return result;
  885. })
  886. .catch((err) => {
  887. if (debug_mode) {
  888. logger.error(err.message);
  889. }
  890. if (throw_errors) {
  891. throw err;
  892. }
  893. });
  894. },
  895. /**
  896. * @param {Object} certificate
  897. * @returns {Boolean}
  898. */
  899. hasLetsEncryptSslCerts: (certificate) => {
  900. let le_path = '/etc/letsencrypt/live/npm-' + certificate.id;
  901. return fs.existsSync(le_path + '/fullchain.pem') && fs.existsSync(le_path + '/privkey.pem');
  902. },
  903. /**
  904. * @param {Object} in_use_result
  905. * @param {Number} in_use_result.total_count
  906. * @param {Array} in_use_result.proxy_hosts
  907. * @param {Array} in_use_result.redirection_hosts
  908. * @param {Array} in_use_result.dead_hosts
  909. */
  910. disableInUseHosts: (in_use_result) => {
  911. if (in_use_result.total_count) {
  912. let promises = [];
  913. if (in_use_result.proxy_hosts.length) {
  914. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  915. }
  916. if (in_use_result.redirection_hosts.length) {
  917. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  918. }
  919. if (in_use_result.dead_hosts.length) {
  920. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  921. }
  922. return Promise.all(promises);
  923. } else {
  924. return Promise.resolve();
  925. }
  926. },
  927. /**
  928. * @param {Object} in_use_result
  929. * @param {Number} in_use_result.total_count
  930. * @param {Array} in_use_result.proxy_hosts
  931. * @param {Array} in_use_result.redirection_hosts
  932. * @param {Array} in_use_result.dead_hosts
  933. */
  934. enableInUseHosts: (in_use_result) => {
  935. if (in_use_result.total_count) {
  936. let promises = [];
  937. if (in_use_result.proxy_hosts.length) {
  938. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  939. }
  940. if (in_use_result.redirection_hosts.length) {
  941. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  942. }
  943. if (in_use_result.dead_hosts.length) {
  944. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  945. }
  946. return Promise.all(promises);
  947. } else {
  948. return Promise.resolve();
  949. }
  950. }
  951. };
  952. module.exports = internalCertificate;