certificate.js 37 KB

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