certificate.js 31 KB

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