certificate.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. const _ = require('lodash');
  2. const fs = require('fs');
  3. const https = require('https');
  4. const tempWrite = require('temp-write');
  5. const moment = require('moment');
  6. const archiver = require('archiver');
  7. const path = require('path');
  8. const { isArray } = require('lodash');
  9. const logger = require('../logger').ssl;
  10. const config = require('../lib/config');
  11. const error = require('../lib/error');
  12. const utils = require('../lib/utils');
  13. const certbot = require('../lib/certbot');
  14. const certificateModel = require('../models/certificate');
  15. const tokenModel = require('../models/token');
  16. const dnsPlugins = require('../global/certbot-dns-plugins.json');
  17. const internalAuditLog = require('./audit-log');
  18. const internalNginx = require('./nginx');
  19. const internalHost = require('./host');
  20. const letsencryptStaging = config.useLetsencryptStaging();
  21. const letsencryptConfig = '/etc/letsencrypt.ini';
  22. const certbotCommand = 'certbot';
  23. function omissions() {
  24. return ['is_deleted', 'owner.is_deleted'];
  25. }
  26. const internalCertificate = {
  27. allowedSslFiles: ['certificate', 'certificate_key', 'intermediate_certificate'],
  28. intervalTimeout: 1000 * 60 * 60, // 1 hour
  29. interval: null,
  30. intervalProcessing: false,
  31. renewBeforeExpirationBy: [30, 'days'],
  32. initTimer: () => {
  33. logger.info('Let\'s Encrypt Renewal Timer initialized');
  34. internalCertificate.interval = setInterval(internalCertificate.processExpiringHosts, internalCertificate.intervalTimeout);
  35. // And do this now as well
  36. internalCertificate.processExpiringHosts();
  37. },
  38. /**
  39. * Triggered by a timer, this will check for expiring hosts and renew their ssl certs if required
  40. */
  41. processExpiringHosts: () => {
  42. if (!internalCertificate.intervalProcessing) {
  43. internalCertificate.intervalProcessing = true;
  44. logger.info('Renewing SSL certs expiring within ' + internalCertificate.renewBeforeExpirationBy[0] + ' ' + internalCertificate.renewBeforeExpirationBy[1] + ' ...');
  45. const expirationThreshold = moment().add(internalCertificate.renewBeforeExpirationBy[0], internalCertificate.renewBeforeExpirationBy[1]).format('YYYY-MM-DD HH:mm:ss');
  46. // Fetch all the letsencrypt certs from the db that will expire within the configured threshold
  47. certificateModel
  48. .query()
  49. .where('is_deleted', 0)
  50. .andWhere('provider', 'letsencrypt')
  51. .andWhere('expires_on', '<', expirationThreshold)
  52. .then((certificates) => {
  53. if (!certificates || !certificates.length) {
  54. return null;
  55. }
  56. /**
  57. * Renews must be run sequentially or we'll get an error 'Another
  58. * instance of Certbot is already running.'
  59. */
  60. let sequence = Promise.resolve();
  61. certificates.forEach(function (certificate) {
  62. sequence = sequence.then(() =>
  63. internalCertificate
  64. .renew(
  65. {
  66. can: () =>
  67. Promise.resolve({
  68. permission_visibility: 'all',
  69. }),
  70. token: new tokenModel(),
  71. },
  72. { id: certificate.id },
  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 sequence;
  81. })
  82. .then(() => {
  83. logger.info('Completed SSL cert renew process');
  84. internalCertificate.intervalProcessing = false;
  85. })
  86. .catch((err) => {
  87. logger.error(err);
  88. internalCertificate.intervalProcessing = false;
  89. });
  90. }
  91. },
  92. /**
  93. * @param {Access} access
  94. * @param {Object} data
  95. * @returns {Promise}
  96. */
  97. create: (access, data) => {
  98. return access.can('certificates:create', data)
  99. .then(() => {
  100. data.owner_user_id = access.token.getUserId(1);
  101. if (data.provider === 'letsencrypt') {
  102. data.nice_name = data.domain_names.join(', ');
  103. }
  104. return certificateModel
  105. .query()
  106. .insertAndFetch(data)
  107. .then(utils.omitRow(omissions()));
  108. })
  109. .then((certificate) => {
  110. if (certificate.provider === 'letsencrypt') {
  111. // Request a new Cert from LE. Let the fun begin.
  112. // 1. Find out any hosts that are using any of the hostnames in this cert
  113. // 2. Disable them in nginx temporarily
  114. // 3. Generate the LE config
  115. // 4. Request cert
  116. // 5. Remove LE config
  117. // 6. Re-instate previously disabled hosts
  118. // 1. Find out any hosts that are using any of the hostnames in this cert
  119. return internalHost.getHostsWithDomains(certificate.domain_names)
  120. .then((in_use_result) => {
  121. // 2. Disable them in nginx temporarily
  122. return internalCertificate.disableInUseHosts(in_use_result)
  123. .then(() => {
  124. return in_use_result;
  125. });
  126. })
  127. .then((in_use_result) => {
  128. // With DNS challenge no config is needed, so skip 3 and 5.
  129. if (certificate.meta.dns_challenge) {
  130. return internalNginx.reload().then(() => {
  131. // 4. Request cert
  132. return internalCertificate.requestLetsEncryptSslWithDnsChallenge(certificate);
  133. })
  134. .then(internalNginx.reload)
  135. .then(() => {
  136. // 6. Re-instate previously disabled hosts
  137. return internalCertificate.enableInUseHosts(in_use_result);
  138. })
  139. .then(() => {
  140. return certificate;
  141. })
  142. .catch((err) => {
  143. // In the event of failure, revert things and throw err back
  144. return internalCertificate.enableInUseHosts(in_use_result)
  145. .then(internalNginx.reload)
  146. .then(() => {
  147. throw err;
  148. });
  149. });
  150. } else {
  151. // 3. Generate the LE config
  152. return internalNginx.generateLetsEncryptRequestConfig(certificate)
  153. .then(internalNginx.reload)
  154. .then(async() => await new Promise((r) => setTimeout(r, 5000)))
  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. .patchAndFetchById(row.id, data)
  247. .then(utils.omitRow(omissions()))
  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 saved_row;
  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. .allowGraph('[owner]')
  287. .first();
  288. if (access_data.permission_visibility !== 'all') {
  289. query.andWhere('owner_user_id', access.token.getUserId(1));
  290. }
  291. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  292. query.withGraphFetched('[' + data.expand.join(', ') + ']');
  293. }
  294. return query.then(utils.omitRow(omissions()));
  295. })
  296. .then((row) => {
  297. if (!row || !row.id) {
  298. throw new error.ItemNotFoundError(data.id);
  299. }
  300. // Custom omissions
  301. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  302. row = _.omit(row, data.omit);
  303. }
  304. return row;
  305. });
  306. },
  307. /**
  308. * @param {Access} access
  309. * @param {Object} data
  310. * @param {Number} data.id
  311. * @returns {Promise}
  312. */
  313. download: (access, data) => {
  314. return new Promise((resolve, reject) => {
  315. access.can('certificates:get', data)
  316. .then(() => {
  317. return internalCertificate.get(access, data);
  318. })
  319. .then((certificate) => {
  320. if (certificate.provider === 'letsencrypt') {
  321. const zipDirectory = '/etc/letsencrypt/live/npm-' + data.id;
  322. if (!fs.existsSync(zipDirectory)) {
  323. throw new error.ItemNotFoundError('Certificate ' + certificate.nice_name + ' does not exists');
  324. }
  325. let certFiles = fs.readdirSync(zipDirectory)
  326. .filter((fn) => fn.endsWith('.pem'))
  327. .map((fn) => fs.realpathSync(path.join(zipDirectory, fn)));
  328. const downloadName = 'npm-' + data.id + '-' + `${Date.now()}.zip`;
  329. const opName = '/tmp/' + downloadName;
  330. internalCertificate.zipFiles(certFiles, opName)
  331. .then(() => {
  332. logger.debug('zip completed : ', opName);
  333. const resp = {
  334. fileName: opName
  335. };
  336. resolve(resp);
  337. }).catch((err) => reject(err));
  338. } else {
  339. throw new error.ValidationError('Only Let\'sEncrypt certificates can be downloaded');
  340. }
  341. }).catch((err) => reject(err));
  342. });
  343. },
  344. /**
  345. * @param {String} source
  346. * @param {String} out
  347. * @returns {Promise}
  348. */
  349. zipFiles(source, out) {
  350. const archive = archiver('zip', { zlib: { level: 9 } });
  351. const stream = fs.createWriteStream(out);
  352. return new Promise((resolve, reject) => {
  353. source
  354. .map((fl) => {
  355. let fileName = path.basename(fl);
  356. logger.debug(fl, 'added to certificate zip');
  357. archive.file(fl, { name: fileName });
  358. });
  359. archive
  360. .on('error', (err) => reject(err))
  361. .pipe(stream);
  362. stream.on('close', () => resolve());
  363. archive.finalize();
  364. });
  365. },
  366. /**
  367. * @param {Access} access
  368. * @param {Object} data
  369. * @param {Number} data.id
  370. * @param {String} [data.reason]
  371. * @returns {Promise}
  372. */
  373. delete: (access, data) => {
  374. return access.can('certificates:delete', data.id)
  375. .then(() => {
  376. return internalCertificate.get(access, {id: data.id});
  377. })
  378. .then((row) => {
  379. if (!row || !row.id) {
  380. throw new error.ItemNotFoundError(data.id);
  381. }
  382. return certificateModel
  383. .query()
  384. .where('id', row.id)
  385. .patch({
  386. is_deleted: 1
  387. })
  388. .then(() => {
  389. // Add to audit log
  390. row.meta = internalCertificate.cleanMeta(row.meta);
  391. return internalAuditLog.add(access, {
  392. action: 'deleted',
  393. object_type: 'certificate',
  394. object_id: row.id,
  395. meta: _.omit(row, omissions())
  396. });
  397. })
  398. .then(() => {
  399. if (row.provider === 'letsencrypt') {
  400. // Revoke the cert
  401. return internalCertificate.revokeLetsEncryptSsl(row);
  402. }
  403. });
  404. })
  405. .then(() => {
  406. return true;
  407. });
  408. },
  409. /**
  410. * All Certs
  411. *
  412. * @param {Access} access
  413. * @param {Array} [expand]
  414. * @param {String} [search_query]
  415. * @returns {Promise}
  416. */
  417. getAll: (access, expand, search_query) => {
  418. return access.can('certificates:list')
  419. .then((access_data) => {
  420. let query = certificateModel
  421. .query()
  422. .where('is_deleted', 0)
  423. .groupBy('id')
  424. .allowGraph('[owner]')
  425. .orderBy('nice_name', 'ASC');
  426. if (access_data.permission_visibility !== 'all') {
  427. query.andWhere('owner_user_id', access.token.getUserId(1));
  428. }
  429. // Query is used for searching
  430. if (typeof search_query === 'string') {
  431. query.where(function () {
  432. this.where('nice_name', 'like', '%' + search_query + '%');
  433. });
  434. }
  435. if (typeof expand !== 'undefined' && expand !== null) {
  436. query.withGraphFetched('[' + expand.join(', ') + ']');
  437. }
  438. return query.then(utils.omitRows(omissions()));
  439. });
  440. },
  441. /**
  442. * Report use
  443. *
  444. * @param {Number} user_id
  445. * @param {String} visibility
  446. * @returns {Promise}
  447. */
  448. getCount: (user_id, visibility) => {
  449. let query = certificateModel
  450. .query()
  451. .count('id as count')
  452. .where('is_deleted', 0);
  453. if (visibility !== 'all') {
  454. query.andWhere('owner_user_id', user_id);
  455. }
  456. return query.first()
  457. .then((row) => {
  458. return parseInt(row.count, 10);
  459. });
  460. },
  461. /**
  462. * @param {Object} certificate
  463. * @returns {Promise}
  464. */
  465. writeCustomCert: (certificate) => {
  466. logger.info('Writing Custom Certificate:', certificate);
  467. const dir = '/data/custom_ssl/npm-' + certificate.id;
  468. return new Promise((resolve, reject) => {
  469. if (certificate.provider === 'letsencrypt') {
  470. reject(new Error('Refusing to write letsencrypt certs here'));
  471. return;
  472. }
  473. let certData = certificate.meta.certificate;
  474. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  475. certData = certData + '\n' + certificate.meta.intermediate_certificate;
  476. }
  477. try {
  478. if (!fs.existsSync(dir)) {
  479. fs.mkdirSync(dir);
  480. }
  481. } catch (err) {
  482. reject(err);
  483. return;
  484. }
  485. fs.writeFile(dir + '/fullchain.pem', certData, function (err) {
  486. if (err) {
  487. reject(err);
  488. } else {
  489. resolve();
  490. }
  491. });
  492. })
  493. .then(() => {
  494. return new Promise((resolve, reject) => {
  495. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  496. if (err) {
  497. reject(err);
  498. } else {
  499. resolve();
  500. }
  501. });
  502. });
  503. });
  504. },
  505. /**
  506. * @param {Access} access
  507. * @param {Object} data
  508. * @param {Array} data.domain_names
  509. * @param {String} data.meta.letsencrypt_email
  510. * @param {Boolean} data.meta.letsencrypt_agree
  511. * @returns {Promise}
  512. */
  513. createQuickCertificate: (access, data) => {
  514. return internalCertificate.create(access, {
  515. provider: 'letsencrypt',
  516. domain_names: data.domain_names,
  517. meta: data.meta
  518. });
  519. },
  520. /**
  521. * Validates that the certs provided are good.
  522. * No access required here, nothing is changed or stored.
  523. *
  524. * @param {Object} data
  525. * @param {Object} data.files
  526. * @returns {Promise}
  527. */
  528. validate: (data) => {
  529. return new Promise((resolve) => {
  530. // Put file contents into an object
  531. let files = {};
  532. _.map(data.files, (file, name) => {
  533. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  534. files[name] = file.data.toString();
  535. }
  536. });
  537. resolve(files);
  538. })
  539. .then((files) => {
  540. // For each file, create a temp file and write the contents to it
  541. // Then test it depending on the file type
  542. let promises = [];
  543. _.map(files, (content, type) => {
  544. promises.push(new Promise((resolve) => {
  545. if (type === 'certificate_key') {
  546. resolve(internalCertificate.checkPrivateKey(content));
  547. } else {
  548. // this should handle `certificate` and intermediate certificate
  549. resolve(internalCertificate.getCertificateInfo(content, true));
  550. }
  551. }).then((res) => {
  552. return {[type]: res};
  553. }));
  554. });
  555. return Promise.all(promises)
  556. .then((files) => {
  557. let data = {};
  558. _.each(files, (file) => {
  559. data = _.assign({}, data, file);
  560. });
  561. return data;
  562. });
  563. });
  564. },
  565. /**
  566. * @param {Access} access
  567. * @param {Object} data
  568. * @param {Number} data.id
  569. * @param {Object} data.files
  570. * @returns {Promise}
  571. */
  572. upload: (access, data) => {
  573. return internalCertificate.get(access, {id: data.id})
  574. .then((row) => {
  575. if (row.provider !== 'other') {
  576. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  577. }
  578. return internalCertificate.validate(data)
  579. .then((validations) => {
  580. if (typeof validations.certificate === 'undefined') {
  581. throw new error.ValidationError('Certificate file was not provided');
  582. }
  583. _.map(data.files, (file, name) => {
  584. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  585. row.meta[name] = file.data.toString();
  586. }
  587. });
  588. // TODO: This uses a mysql only raw function that won't translate to postgres
  589. return internalCertificate.update(access, {
  590. id: data.id,
  591. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  592. domain_names: [validations.certificate.cn],
  593. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  594. })
  595. .then((certificate) => {
  596. certificate.meta = row.meta;
  597. return internalCertificate.writeCustomCert(certificate);
  598. });
  599. })
  600. .then(() => {
  601. return _.pick(row.meta, internalCertificate.allowedSslFiles);
  602. });
  603. });
  604. },
  605. /**
  606. * Uses the openssl command to validate the private key.
  607. * It will save the file to disk first, then run commands on it, then delete the file.
  608. *
  609. * @param {String} private_key This is the entire key contents as a string
  610. */
  611. checkPrivateKey: (private_key) => {
  612. return tempWrite(private_key, '/tmp')
  613. .then((filepath) => {
  614. return new Promise((resolve, reject) => {
  615. const failTimeout = setTimeout(() => {
  616. reject(new error.ValidationError('Result Validation Error: Validation timed out. This could be due to the key being passphrase-protected.'));
  617. }, 10000);
  618. utils
  619. .exec('openssl pkey -in ' + filepath + ' -check -noout 2>&1 ')
  620. .then((result) => {
  621. clearTimeout(failTimeout);
  622. if (!result.toLowerCase().includes('key is valid')) {
  623. reject(new error.ValidationError('Result Validation Error: ' + result));
  624. }
  625. fs.unlinkSync(filepath);
  626. resolve(true);
  627. })
  628. .catch((err) => {
  629. clearTimeout(failTimeout);
  630. fs.unlinkSync(filepath);
  631. reject(new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err));
  632. });
  633. });
  634. });
  635. },
  636. /**
  637. * Uses the openssl command to both validate and get info out of the certificate.
  638. * It will save the file to disk first, then run commands on it, then delete the file.
  639. *
  640. * @param {String} certificate This is the entire cert contents as a string
  641. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  642. */
  643. getCertificateInfo: (certificate, throw_expired) => {
  644. return tempWrite(certificate, '/tmp')
  645. .then((filepath) => {
  646. return internalCertificate.getCertificateInfoFromFile(filepath, throw_expired)
  647. .then((certData) => {
  648. fs.unlinkSync(filepath);
  649. return certData;
  650. }).catch((err) => {
  651. fs.unlinkSync(filepath);
  652. throw err;
  653. });
  654. });
  655. },
  656. /**
  657. * Uses the openssl command to both validate and get info out of the certificate.
  658. * It will save the file to disk first, then run commands on it, then delete the file.
  659. *
  660. * @param {String} certificate_file The file location on disk
  661. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  662. */
  663. getCertificateInfoFromFile: (certificate_file, throw_expired) => {
  664. let certData = {};
  665. return utils.exec('openssl x509 -in ' + certificate_file + ' -subject -noout')
  666. .then((result) => {
  667. // subject=CN = something.example.com
  668. const regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  669. const match = regex.exec(result);
  670. if (typeof match[1] === 'undefined') {
  671. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  672. }
  673. certData['cn'] = match[1];
  674. })
  675. .then(() => {
  676. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  677. })
  678. .then((result) => {
  679. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  680. const regex = /^(?:issuer=)?(.*)$/gim;
  681. const match = regex.exec(result);
  682. if (typeof match[1] === 'undefined') {
  683. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  684. }
  685. certData['issuer'] = match[1];
  686. })
  687. .then(() => {
  688. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  689. })
  690. .then((result) => {
  691. // notBefore=Jul 14 04:04:29 2018 GMT
  692. // notAfter=Oct 12 04:04:29 2018 GMT
  693. let validFrom = null;
  694. let validTo = null;
  695. const lines = result.split('\n');
  696. lines.map(function (str) {
  697. const regex = /^(\S+)=(.*)$/gim;
  698. const match = regex.exec(str.trim());
  699. if (match && typeof match[2] !== 'undefined') {
  700. const date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  701. if (match[1].toLowerCase() === 'notbefore') {
  702. validFrom = date;
  703. } else if (match[1].toLowerCase() === 'notafter') {
  704. validTo = date;
  705. }
  706. }
  707. });
  708. if (!validFrom || !validTo) {
  709. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  710. }
  711. if (throw_expired && validTo < parseInt(moment().format('X'), 10)) {
  712. throw new error.ValidationError('Certificate has expired');
  713. }
  714. certData['dates'] = {
  715. from: validFrom,
  716. to: validTo
  717. };
  718. return certData;
  719. }).catch((err) => {
  720. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  721. });
  722. },
  723. /**
  724. * Cleans the ssl keys from the meta object and sets them to "true"
  725. *
  726. * @param {Object} meta
  727. * @param {Boolean} [remove]
  728. * @returns {Object}
  729. */
  730. cleanMeta: function (meta, remove) {
  731. internalCertificate.allowedSslFiles.map((key) => {
  732. if (typeof meta[key] !== 'undefined' && meta[key]) {
  733. if (remove) {
  734. delete meta[key];
  735. } else {
  736. meta[key] = true;
  737. }
  738. }
  739. });
  740. return meta;
  741. },
  742. /**
  743. * Request a certificate using the http challenge
  744. * @param {Object} certificate the certificate row
  745. * @returns {Promise}
  746. */
  747. requestLetsEncryptSsl: (certificate) => {
  748. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  749. const cmd = certbotCommand + ' certonly ' +
  750. '--config "' + letsencryptConfig + '" ' +
  751. '--work-dir "/tmp/letsencrypt-lib" ' +
  752. '--logs-dir "/tmp/letsencrypt-log" ' +
  753. '--cert-name "npm-' + certificate.id + '" ' +
  754. '--agree-tos ' +
  755. '--authenticator webroot ' +
  756. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  757. '--preferred-challenges "dns,http" ' +
  758. '--domains "' + certificate.domain_names.join(',') + '" ' +
  759. (letsencryptStaging ? '--staging' : '');
  760. logger.info('Command:', cmd);
  761. return utils.exec(cmd)
  762. .then((result) => {
  763. logger.success(result);
  764. return result;
  765. });
  766. },
  767. /**
  768. * @param {Object} certificate the certificate row
  769. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.json`)
  770. * @param {String | null} credentials the content of this providers credentials file
  771. * @param {String} propagation_seconds
  772. * @returns {Promise}
  773. */
  774. requestLetsEncryptSslWithDnsChallenge: async (certificate) => {
  775. await certbot.installPlugin(certificate.meta.dns_provider);
  776. const dnsPlugin = dnsPlugins[certificate.meta.dns_provider];
  777. logger.info(`Requesting Let'sEncrypt certificates via ${dnsPlugin.name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  778. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  779. fs.mkdirSync('/etc/letsencrypt/credentials', { recursive: true });
  780. fs.writeFileSync(credentialsLocation, certificate.meta.dns_provider_credentials, {mode: 0o600});
  781. // Whether the plugin has a --<name>-credentials argument
  782. const hasConfigArg = certificate.meta.dns_provider !== 'route53';
  783. let mainCmd = certbotCommand + ' certonly ' +
  784. '--config "' + letsencryptConfig + '" ' +
  785. '--work-dir "/tmp/letsencrypt-lib" ' +
  786. '--logs-dir "/tmp/letsencrypt-log" ' +
  787. '--cert-name "npm-' + certificate.id + '" ' +
  788. '--agree-tos ' +
  789. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  790. '--domains "' + certificate.domain_names.join(',') + '" ' +
  791. '--authenticator ' + dnsPlugin.full_plugin_name + ' ' +
  792. (
  793. hasConfigArg
  794. ? '--' + dnsPlugin.full_plugin_name + '-credentials "' + credentialsLocation + '"'
  795. : ''
  796. ) +
  797. (
  798. certificate.meta.propagation_seconds !== undefined
  799. ? ' --' + dnsPlugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  800. : ''
  801. ) +
  802. (letsencryptStaging ? ' --staging' : '');
  803. // Prepend the path to the credentials file as an environment variable
  804. if (certificate.meta.dns_provider === 'route53') {
  805. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  806. }
  807. if (certificate.meta.dns_provider === 'duckdns') {
  808. mainCmd = mainCmd + ' --dns-duckdns-no-txt-restore';
  809. }
  810. logger.info('Command:', mainCmd);
  811. try {
  812. const result = await utils.exec(mainCmd);
  813. logger.info(result);
  814. return result;
  815. } catch (err) {
  816. // Don't fail if file does not exist, so no need for action in the callback
  817. fs.unlink(credentialsLocation, () => {});
  818. throw err;
  819. }
  820. },
  821. /**
  822. * @param {Access} access
  823. * @param {Object} data
  824. * @param {Number} data.id
  825. * @returns {Promise}
  826. */
  827. renew: (access, data) => {
  828. return access.can('certificates:update', data)
  829. .then(() => {
  830. return internalCertificate.get(access, data);
  831. })
  832. .then((certificate) => {
  833. if (certificate.provider === 'letsencrypt') {
  834. const renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  835. return renewMethod(certificate)
  836. .then(() => {
  837. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  838. })
  839. .then((cert_info) => {
  840. return certificateModel
  841. .query()
  842. .patchAndFetchById(certificate.id, {
  843. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  844. });
  845. })
  846. .then((updated_certificate) => {
  847. // Add to audit log
  848. return internalAuditLog.add(access, {
  849. action: 'renewed',
  850. object_type: 'certificate',
  851. object_id: updated_certificate.id,
  852. meta: updated_certificate
  853. })
  854. .then(() => {
  855. return updated_certificate;
  856. });
  857. });
  858. } else {
  859. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  860. }
  861. });
  862. },
  863. /**
  864. * @param {Object} certificate the certificate row
  865. * @returns {Promise}
  866. */
  867. renewLetsEncryptSsl: (certificate) => {
  868. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  869. const cmd = certbotCommand + ' renew --force-renewal ' +
  870. '--config "' + letsencryptConfig + '" ' +
  871. '--work-dir "/tmp/letsencrypt-lib" ' +
  872. '--logs-dir "/tmp/letsencrypt-log" ' +
  873. '--cert-name "npm-' + certificate.id + '" ' +
  874. '--preferred-challenges "dns,http" ' +
  875. '--no-random-sleep-on-renew ' +
  876. '--disable-hook-validation ' +
  877. (letsencryptStaging ? '--staging' : '');
  878. logger.info('Command:', cmd);
  879. return utils.exec(cmd)
  880. .then((result) => {
  881. logger.info(result);
  882. return result;
  883. });
  884. },
  885. /**
  886. * @param {Object} certificate the certificate row
  887. * @returns {Promise}
  888. */
  889. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  890. const dnsPlugin = dnsPlugins[certificate.meta.dns_provider];
  891. if (!dnsPlugin) {
  892. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  893. }
  894. logger.info(`Renewing Let'sEncrypt certificates via ${dnsPlugin.name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  895. let mainCmd = certbotCommand + ' renew --force-renewal ' +
  896. '--config "' + letsencryptConfig + '" ' +
  897. '--work-dir "/tmp/letsencrypt-lib" ' +
  898. '--logs-dir "/tmp/letsencrypt-log" ' +
  899. '--cert-name "npm-' + certificate.id + '" ' +
  900. '--disable-hook-validation ' +
  901. '--no-random-sleep-on-renew ' +
  902. (letsencryptStaging ? ' --staging' : '');
  903. // Prepend the path to the credentials file as an environment variable
  904. if (certificate.meta.dns_provider === 'route53') {
  905. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  906. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  907. }
  908. logger.info('Command:', mainCmd);
  909. return utils.exec(mainCmd)
  910. .then(async (result) => {
  911. logger.info(result);
  912. return result;
  913. });
  914. },
  915. /**
  916. * @param {Object} certificate the certificate row
  917. * @param {Boolean} [throw_errors]
  918. * @returns {Promise}
  919. */
  920. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  921. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  922. const mainCmd = certbotCommand + ' revoke ' +
  923. '--config "' + letsencryptConfig + '" ' +
  924. '--work-dir "/tmp/letsencrypt-lib" ' +
  925. '--logs-dir "/tmp/letsencrypt-log" ' +
  926. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  927. '--delete-after-revoke ' +
  928. (letsencryptStaging ? '--staging' : '');
  929. // Don't fail command if file does not exist
  930. const delete_credentialsCmd = `rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`;
  931. logger.info('Command:', mainCmd + '; ' + delete_credentialsCmd);
  932. return utils.exec(mainCmd)
  933. .then(async (result) => {
  934. await utils.exec(delete_credentialsCmd);
  935. logger.info(result);
  936. return result;
  937. })
  938. .catch((err) => {
  939. logger.error(err.message);
  940. if (throw_errors) {
  941. throw err;
  942. }
  943. });
  944. },
  945. /**
  946. * @param {Object} certificate
  947. * @returns {Boolean}
  948. */
  949. hasLetsEncryptSslCerts: (certificate) => {
  950. const letsencryptPath = '/etc/letsencrypt/live/npm-' + certificate.id;
  951. return fs.existsSync(letsencryptPath + '/fullchain.pem') && fs.existsSync(letsencryptPath + '/privkey.pem');
  952. },
  953. /**
  954. * @param {Object} in_use_result
  955. * @param {Number} in_use_result.total_count
  956. * @param {Array} in_use_result.proxy_hosts
  957. * @param {Array} in_use_result.redirection_hosts
  958. * @param {Array} in_use_result.dead_hosts
  959. */
  960. disableInUseHosts: (in_use_result) => {
  961. if (in_use_result.total_count) {
  962. let promises = [];
  963. if (in_use_result.proxy_hosts.length) {
  964. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  965. }
  966. if (in_use_result.redirection_hosts.length) {
  967. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  968. }
  969. if (in_use_result.dead_hosts.length) {
  970. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  971. }
  972. return Promise.all(promises);
  973. } else {
  974. return Promise.resolve();
  975. }
  976. },
  977. /**
  978. * @param {Object} in_use_result
  979. * @param {Number} in_use_result.total_count
  980. * @param {Array} in_use_result.proxy_hosts
  981. * @param {Array} in_use_result.redirection_hosts
  982. * @param {Array} in_use_result.dead_hosts
  983. */
  984. enableInUseHosts: (in_use_result) => {
  985. if (in_use_result.total_count) {
  986. let promises = [];
  987. if (in_use_result.proxy_hosts.length) {
  988. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  989. }
  990. if (in_use_result.redirection_hosts.length) {
  991. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  992. }
  993. if (in_use_result.dead_hosts.length) {
  994. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  995. }
  996. return Promise.all(promises);
  997. } else {
  998. return Promise.resolve();
  999. }
  1000. },
  1001. testHttpsChallenge: async (access, domains) => {
  1002. await access.can('certificates:list');
  1003. if (!isArray(domains)) {
  1004. throw new error.InternalValidationError('Domains must be an array of strings');
  1005. }
  1006. if (domains.length === 0) {
  1007. throw new error.InternalValidationError('No domains provided');
  1008. }
  1009. // Create a test challenge file
  1010. const testChallengeDir = '/data/letsencrypt-acme-challenge/.well-known/acme-challenge';
  1011. const testChallengeFile = testChallengeDir + '/test-challenge';
  1012. fs.mkdirSync(testChallengeDir, {recursive: true});
  1013. fs.writeFileSync(testChallengeFile, 'Success', {encoding: 'utf8'});
  1014. async function performTestForDomain (domain) {
  1015. logger.info('Testing http challenge for ' + domain);
  1016. const url = `http://${domain}/.well-known/acme-challenge/test-challenge`;
  1017. const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`;
  1018. const options = {
  1019. method: 'POST',
  1020. headers: {
  1021. 'User-Agent': 'Mozilla/5.0',
  1022. 'Content-Type': 'application/x-www-form-urlencoded',
  1023. 'Content-Length': Buffer.byteLength(formBody)
  1024. }
  1025. };
  1026. const result = await new Promise((resolve) => {
  1027. const req = https.request('https://www.site24x7.com/tools/restapi-tester', options, function (res) {
  1028. let responseBody = '';
  1029. res.on('data', (chunk) => responseBody = responseBody + chunk);
  1030. res.on('end', function () {
  1031. try {
  1032. const parsedBody = JSON.parse(responseBody + '');
  1033. if (res.statusCode !== 200) {
  1034. logger.warn(`Failed to test HTTP challenge for domain ${domain} because HTTP status code ${res.statusCode} was returned: ${parsedBody.message}`);
  1035. resolve(undefined);
  1036. } else {
  1037. resolve(parsedBody);
  1038. }
  1039. } catch (err) {
  1040. if (res.statusCode !== 200) {
  1041. logger.warn(`Failed to test HTTP challenge for domain ${domain} because HTTP status code ${res.statusCode} was returned`);
  1042. } else {
  1043. logger.warn(`Failed to test HTTP challenge for domain ${domain} because response failed to be parsed: ${err.message}`);
  1044. }
  1045. resolve(undefined);
  1046. }
  1047. });
  1048. });
  1049. // Make sure to write the request body.
  1050. req.write(formBody);
  1051. req.end();
  1052. req.on('error', function (e) { logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e);
  1053. resolve(undefined); });
  1054. });
  1055. if (!result) {
  1056. // Some error occurred while trying to get the data
  1057. return 'failed';
  1058. } else if (result.error) {
  1059. logger.info(`HTTP challenge test failed for domain ${domain} because error was returned: ${result.error.msg}`);
  1060. return `other:${result.error.msg}`;
  1061. } else if (`${result.responsecode}` === '200' && result.htmlresponse === 'Success') {
  1062. // Server exists and has responded with the correct data
  1063. return 'ok';
  1064. } else if (`${result.responsecode}` === '200') {
  1065. // Server exists but has responded with wrong data
  1066. logger.info(`HTTP challenge test failed for domain ${domain} because of invalid returned data:`, result.htmlresponse);
  1067. return 'wrong-data';
  1068. } else if (`${result.responsecode}` === '404') {
  1069. // Server exists but responded with a 404
  1070. logger.info(`HTTP challenge test failed for domain ${domain} because code 404 was returned`);
  1071. return '404';
  1072. } else if (`${result.responsecode}` === '0' || (typeof result.reason === 'string' && result.reason.toLowerCase() === 'host unavailable')) {
  1073. // Server does not exist at domain
  1074. logger.info(`HTTP challenge test failed for domain ${domain} the host was not found`);
  1075. return 'no-host';
  1076. } else {
  1077. // Other errors
  1078. logger.info(`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`);
  1079. return `other:${result.responsecode}`;
  1080. }
  1081. }
  1082. const results = {};
  1083. for (const domain of domains){
  1084. results[domain] = await performTestForDomain(domain);
  1085. }
  1086. // Remove the test challenge file
  1087. fs.unlinkSync(testChallengeFile);
  1088. return results;
  1089. }
  1090. };
  1091. module.exports = internalCertificate;