certificate.js 37 KB

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