certificate.js 38 KB

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