certificate.js 28 KB

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