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 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(async() => await new Promise((r) => setTimeout(r, 5000)))
  160. .then(() => {
  161. // 4. Request cert
  162. return internalCertificate.requestLetsEncryptSsl(certificate);
  163. })
  164. .then(() => {
  165. // 5. Remove LE config
  166. return internalNginx.deleteLetsEncryptRequestConfig(certificate);
  167. })
  168. .then(internalNginx.reload)
  169. .then(() => {
  170. // 6. Re-instate previously disabled hosts
  171. return internalCertificate.enableInUseHosts(in_use_result);
  172. })
  173. .then(() => {
  174. return certificate;
  175. })
  176. .catch((err) => {
  177. // In the event of failure, revert things and throw err back
  178. return internalNginx.deleteLetsEncryptRequestConfig(certificate)
  179. .then(() => {
  180. return internalCertificate.enableInUseHosts(in_use_result);
  181. })
  182. .then(internalNginx.reload)
  183. .then(() => {
  184. throw err;
  185. });
  186. });
  187. }
  188. })
  189. .then(() => {
  190. // At this point, the letsencrypt cert should exist on disk.
  191. // Lets get the expiry date from the file and update the row silently
  192. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  193. .then((cert_info) => {
  194. return certificateModel
  195. .query()
  196. .patchAndFetchById(certificate.id, {
  197. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  198. })
  199. .then((saved_row) => {
  200. // Add cert data for audit log
  201. saved_row.meta = _.assign({}, saved_row.meta, {
  202. letsencrypt_certificate: cert_info
  203. });
  204. return saved_row;
  205. });
  206. });
  207. }).catch(async (error) => {
  208. // Delete the certificate from the database if it was not created successfully
  209. await certificateModel
  210. .query()
  211. .deleteById(certificate.id);
  212. throw error;
  213. });
  214. } else {
  215. return certificate;
  216. }
  217. }).then((certificate) => {
  218. data.meta = _.assign({}, data.meta || {}, certificate.meta);
  219. // Add to audit log
  220. return internalAuditLog.add(access, {
  221. action: 'created',
  222. object_type: 'certificate',
  223. object_id: certificate.id,
  224. meta: data
  225. })
  226. .then(() => {
  227. return certificate;
  228. });
  229. });
  230. },
  231. /**
  232. * @param {Access} access
  233. * @param {Object} data
  234. * @param {Number} data.id
  235. * @param {String} [data.email]
  236. * @param {String} [data.name]
  237. * @return {Promise}
  238. */
  239. update: (access, data) => {
  240. return access.can('certificates:update', data.id)
  241. .then((/*access_data*/) => {
  242. return internalCertificate.get(access, {id: data.id});
  243. })
  244. .then((row) => {
  245. if (row.id !== data.id) {
  246. // Sanity check that something crazy hasn't happened
  247. throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  248. }
  249. return certificateModel
  250. .query()
  251. .omit(omissions())
  252. .patchAndFetchById(row.id, data)
  253. .then((saved_row) => {
  254. saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
  255. data.meta = internalCertificate.cleanMeta(data.meta);
  256. // Add row.nice_name for custom certs
  257. if (saved_row.provider === 'other') {
  258. data.nice_name = saved_row.nice_name;
  259. }
  260. // Add to audit log
  261. return internalAuditLog.add(access, {
  262. action: 'updated',
  263. object_type: 'certificate',
  264. object_id: row.id,
  265. meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
  266. })
  267. .then(() => {
  268. return _.omit(saved_row, omissions());
  269. });
  270. });
  271. });
  272. },
  273. /**
  274. * @param {Access} access
  275. * @param {Object} data
  276. * @param {Number} data.id
  277. * @param {Array} [data.expand]
  278. * @param {Array} [data.omit]
  279. * @return {Promise}
  280. */
  281. get: (access, data) => {
  282. if (typeof data === 'undefined') {
  283. data = {};
  284. }
  285. return access.can('certificates:get', data.id)
  286. .then((access_data) => {
  287. let query = certificateModel
  288. .query()
  289. .where('is_deleted', 0)
  290. .andWhere('id', data.id)
  291. .allowEager('[owner]')
  292. .first();
  293. if (access_data.permission_visibility !== 'all') {
  294. query.andWhere('owner_user_id', access.token.getUserId(1));
  295. }
  296. // Custom omissions
  297. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  298. query.omit(data.omit);
  299. }
  300. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  301. query.eager('[' + data.expand.join(', ') + ']');
  302. }
  303. return query;
  304. })
  305. .then((row) => {
  306. if (row) {
  307. return _.omit(row, omissions());
  308. } else {
  309. throw new error.ItemNotFoundError(data.id);
  310. }
  311. });
  312. },
  313. /**
  314. * @param {Access} access
  315. * @param {Object} data
  316. * @param {Number} data.id
  317. * @returns {Promise}
  318. */
  319. download: (access, data) => {
  320. return new Promise((resolve, reject) => {
  321. access.can('certificates:get', data)
  322. .then(() => {
  323. return internalCertificate.get(access, data);
  324. })
  325. .then((certificate) => {
  326. if (certificate.provider === 'letsencrypt') {
  327. const zipDirectory = '/etc/letsencrypt/live/npm-' + data.id;
  328. if (!fs.existsSync(zipDirectory)) {
  329. throw new error.ItemNotFoundError('Certificate ' + certificate.nice_name + ' does not exists');
  330. }
  331. let certFiles = fs.readdirSync(zipDirectory)
  332. .filter((fn) => fn.endsWith('.pem'))
  333. .map((fn) => fs.realpathSync(path.join(zipDirectory, fn)));
  334. const downloadName = 'npm-' + data.id + '-' + `${Date.now()}.zip`;
  335. const opName = '/tmp/' + downloadName;
  336. internalCertificate.zipFiles(certFiles, opName)
  337. .then(() => {
  338. logger.debug('zip completed : ', opName);
  339. const resp = {
  340. fileName: opName
  341. };
  342. resolve(resp);
  343. }).catch((err) => reject(err));
  344. } else {
  345. throw new error.ValidationError('Only Let\'sEncrypt certificates can be downloaded');
  346. }
  347. }).catch((err) => reject(err));
  348. });
  349. },
  350. /**
  351. * @param {String} source
  352. * @param {String} out
  353. * @returns {Promise}
  354. */
  355. zipFiles(source, out) {
  356. const archive = archiver('zip', { zlib: { level: 9 } });
  357. const stream = fs.createWriteStream(out);
  358. return new Promise((resolve, reject) => {
  359. source
  360. .map((fl) => {
  361. let fileName = path.basename(fl);
  362. logger.debug(fl, 'added to certificate zip');
  363. archive.file(fl, { name: fileName });
  364. });
  365. archive
  366. .on('error', (err) => reject(err))
  367. .pipe(stream);
  368. stream.on('close', () => resolve());
  369. archive.finalize();
  370. });
  371. },
  372. /**
  373. * @param {Access} access
  374. * @param {Object} data
  375. * @param {Number} data.id
  376. * @param {String} [data.reason]
  377. * @returns {Promise}
  378. */
  379. delete: (access, data) => {
  380. return access.can('certificates:delete', data.id)
  381. .then(() => {
  382. return internalCertificate.get(access, {id: data.id});
  383. })
  384. .then((row) => {
  385. if (!row) {
  386. throw new error.ItemNotFoundError(data.id);
  387. }
  388. return certificateModel
  389. .query()
  390. .where('id', row.id)
  391. .patch({
  392. is_deleted: 1
  393. })
  394. .then(() => {
  395. // Add to audit log
  396. row.meta = internalCertificate.cleanMeta(row.meta);
  397. return internalAuditLog.add(access, {
  398. action: 'deleted',
  399. object_type: 'certificate',
  400. object_id: row.id,
  401. meta: _.omit(row, omissions())
  402. });
  403. })
  404. .then(() => {
  405. if (row.provider === 'letsencrypt') {
  406. // Revoke the cert
  407. return internalCertificate.revokeLetsEncryptSsl(row);
  408. }
  409. });
  410. })
  411. .then(() => {
  412. return true;
  413. });
  414. },
  415. /**
  416. * All Certs
  417. *
  418. * @param {Access} access
  419. * @param {Array} [expand]
  420. * @param {String} [search_query]
  421. * @returns {Promise}
  422. */
  423. getAll: (access, expand, search_query) => {
  424. return access.can('certificates:list')
  425. .then((access_data) => {
  426. let query = certificateModel
  427. .query()
  428. .where('is_deleted', 0)
  429. .groupBy('id')
  430. .omit(['is_deleted'])
  431. .allowEager('[owner]')
  432. .orderBy('nice_name', 'ASC');
  433. if (access_data.permission_visibility !== 'all') {
  434. query.andWhere('owner_user_id', access.token.getUserId(1));
  435. }
  436. // Query is used for searching
  437. if (typeof search_query === 'string') {
  438. query.where(function () {
  439. this.where('nice_name', 'like', '%' + search_query + '%');
  440. });
  441. }
  442. if (typeof expand !== 'undefined' && expand !== null) {
  443. query.eager('[' + expand.join(', ') + ']');
  444. }
  445. return query;
  446. });
  447. },
  448. /**
  449. * Report use
  450. *
  451. * @param {Number} user_id
  452. * @param {String} visibility
  453. * @returns {Promise}
  454. */
  455. getCount: (user_id, visibility) => {
  456. let query = certificateModel
  457. .query()
  458. .count('id as count')
  459. .where('is_deleted', 0);
  460. if (visibility !== 'all') {
  461. query.andWhere('owner_user_id', user_id);
  462. }
  463. return query.first()
  464. .then((row) => {
  465. return parseInt(row.count, 10);
  466. });
  467. },
  468. /**
  469. * @param {Object} certificate
  470. * @returns {Promise}
  471. */
  472. writeCustomCert: (certificate) => {
  473. logger.info('Writing Custom Certificate:', certificate);
  474. const dir = '/data/custom_ssl/npm-' + certificate.id;
  475. return new Promise((resolve, reject) => {
  476. if (certificate.provider === 'letsencrypt') {
  477. reject(new Error('Refusing to write letsencrypt certs here'));
  478. return;
  479. }
  480. let certData = certificate.meta.certificate;
  481. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  482. certData = certData + '\n' + certificate.meta.intermediate_certificate;
  483. }
  484. try {
  485. if (!fs.existsSync(dir)) {
  486. fs.mkdirSync(dir);
  487. }
  488. } catch (err) {
  489. reject(err);
  490. return;
  491. }
  492. fs.writeFile(dir + '/fullchain.pem', certData, function (err) {
  493. if (err) {
  494. reject(err);
  495. } else {
  496. resolve();
  497. }
  498. });
  499. })
  500. .then(() => {
  501. return new Promise((resolve, reject) => {
  502. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  503. if (err) {
  504. reject(err);
  505. } else {
  506. resolve();
  507. }
  508. });
  509. });
  510. });
  511. },
  512. /**
  513. * @param {Access} access
  514. * @param {Object} data
  515. * @param {Array} data.domain_names
  516. * @param {String} data.meta.letsencrypt_email
  517. * @param {Boolean} data.meta.letsencrypt_agree
  518. * @returns {Promise}
  519. */
  520. createQuickCertificate: (access, data) => {
  521. return internalCertificate.create(access, {
  522. provider: 'letsencrypt',
  523. domain_names: data.domain_names,
  524. meta: data.meta
  525. });
  526. },
  527. /**
  528. * Validates that the certs provided are good.
  529. * No access required here, nothing is changed or stored.
  530. *
  531. * @param {Object} data
  532. * @param {Object} data.files
  533. * @returns {Promise}
  534. */
  535. validate: (data) => {
  536. return new Promise((resolve) => {
  537. // Put file contents into an object
  538. let files = {};
  539. _.map(data.files, (file, name) => {
  540. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  541. files[name] = file.data.toString();
  542. }
  543. });
  544. resolve(files);
  545. })
  546. .then((files) => {
  547. // For each file, create a temp file and write the contents to it
  548. // Then test it depending on the file type
  549. let promises = [];
  550. _.map(files, (content, type) => {
  551. promises.push(new Promise((resolve) => {
  552. if (type === 'certificate_key') {
  553. resolve(internalCertificate.checkPrivateKey(content));
  554. } else {
  555. // this should handle `certificate` and intermediate certificate
  556. resolve(internalCertificate.getCertificateInfo(content, true));
  557. }
  558. }).then((res) => {
  559. return {[type]: res};
  560. }));
  561. });
  562. return Promise.all(promises)
  563. .then((files) => {
  564. let data = {};
  565. _.each(files, (file) => {
  566. data = _.assign({}, data, file);
  567. });
  568. return data;
  569. });
  570. });
  571. },
  572. /**
  573. * @param {Access} access
  574. * @param {Object} data
  575. * @param {Number} data.id
  576. * @param {Object} data.files
  577. * @returns {Promise}
  578. */
  579. upload: (access, data) => {
  580. return internalCertificate.get(access, {id: data.id})
  581. .then((row) => {
  582. if (row.provider !== 'other') {
  583. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  584. }
  585. return internalCertificate.validate(data)
  586. .then((validations) => {
  587. if (typeof validations.certificate === 'undefined') {
  588. throw new error.ValidationError('Certificate file was not provided');
  589. }
  590. _.map(data.files, (file, name) => {
  591. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  592. row.meta[name] = file.data.toString();
  593. }
  594. });
  595. // TODO: This uses a mysql only raw function that won't translate to postgres
  596. return internalCertificate.update(access, {
  597. id: data.id,
  598. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  599. domain_names: [validations.certificate.cn],
  600. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  601. })
  602. .then((certificate) => {
  603. console.log('ROWMETA:', row.meta);
  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. '--cert-name "npm-' + certificate.id + '" ' +
  760. '--agree-tos ' +
  761. '--authenticator webroot ' +
  762. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  763. '--preferred-challenges "dns,http" ' +
  764. '--domains "' + certificate.domain_names.join(',') + '" ' +
  765. (letsencryptStaging ? '--staging' : '');
  766. logger.info('Command:', cmd);
  767. return utils.exec(cmd)
  768. .then((result) => {
  769. logger.success(result);
  770. return result;
  771. });
  772. },
  773. /**
  774. * @param {Object} certificate the certificate row
  775. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  776. * @param {String | null} credentials the content of this providers credentials file
  777. * @param {String} propagation_seconds the cloudflare api token
  778. * @returns {Promise}
  779. */
  780. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  781. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  782. if (!dns_plugin) {
  783. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  784. }
  785. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  786. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  787. // Escape single quotes and backslashes
  788. const escapedCredentials = certificate.meta.dns_provider_credentials.replaceAll('\'', '\\\'').replaceAll('\\', '\\\\');
  789. const credentialsCmd = 'mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + escapedCredentials + '\' > \'' + credentialsLocation + '\' && chmod 600 \'' + credentialsLocation + '\'';
  790. let prepareCmd = 'pip install ' + dns_plugin.package_name + (dns_plugin.version_requirement || '') + ' ' + dns_plugin.dependencies;
  791. // Special case for cloudflare
  792. if (dns_plugin.package_name === 'certbot-dns-cloudflare') {
  793. prepareCmd = 'pip install certbot-dns-cloudflare --index-url https://www.piwheels.org/simple --prefer-binary';
  794. }
  795. // Whether the plugin has a --<name>-credentials argument
  796. const hasConfigArg = certificate.meta.dns_provider !== 'route53';
  797. let mainCmd = certbotCommand + ' certonly ' +
  798. '--config "' + letsencryptConfig + '" ' +
  799. '--cert-name "npm-' + certificate.id + '" ' +
  800. '--agree-tos ' +
  801. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  802. '--domains "' + certificate.domain_names.join(',') + '" ' +
  803. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  804. (
  805. hasConfigArg
  806. ? '--' + dns_plugin.full_plugin_name + '-credentials "' + credentialsLocation + '"'
  807. : ''
  808. ) +
  809. (
  810. certificate.meta.propagation_seconds !== undefined
  811. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  812. : ''
  813. ) +
  814. (letsencryptStaging ? ' --staging' : '');
  815. // Prepend the path to the credentials file as an environment variable
  816. if (certificate.meta.dns_provider === 'route53') {
  817. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  818. }
  819. logger.info('Command:', `${credentialsCmd} && ${prepareCmd} && ${mainCmd}`);
  820. return utils.exec(credentialsCmd)
  821. .then(() => {
  822. return utils.exec(prepareCmd)
  823. .then(() => {
  824. return utils.exec(mainCmd)
  825. .then(async (result) => {
  826. logger.info(result);
  827. return result;
  828. });
  829. });
  830. }).catch(async (err) => {
  831. // Don't fail if file does not exist
  832. const delete_credentialsCmd = `rm -f '${credentialsLocation}' || true`;
  833. await utils.exec(delete_credentialsCmd);
  834. throw err;
  835. });
  836. },
  837. /**
  838. * @param {Access} access
  839. * @param {Object} data
  840. * @param {Number} data.id
  841. * @returns {Promise}
  842. */
  843. renew: (access, data) => {
  844. return access.can('certificates:update', data)
  845. .then(() => {
  846. return internalCertificate.get(access, data);
  847. })
  848. .then((certificate) => {
  849. if (certificate.provider === 'letsencrypt') {
  850. const renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  851. return renewMethod(certificate)
  852. .then(() => {
  853. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  854. })
  855. .then((cert_info) => {
  856. return certificateModel
  857. .query()
  858. .patchAndFetchById(certificate.id, {
  859. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  860. });
  861. })
  862. .then((updated_certificate) => {
  863. // Add to audit log
  864. return internalAuditLog.add(access, {
  865. action: 'renewed',
  866. object_type: 'certificate',
  867. object_id: updated_certificate.id,
  868. meta: updated_certificate
  869. })
  870. .then(() => {
  871. return updated_certificate;
  872. });
  873. });
  874. } else {
  875. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  876. }
  877. });
  878. },
  879. /**
  880. * @param {Object} certificate the certificate row
  881. * @returns {Promise}
  882. */
  883. renewLetsEncryptSsl: (certificate) => {
  884. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  885. const cmd = certbotCommand + ' renew --force-renewal ' +
  886. '--config "' + letsencryptConfig + '" ' +
  887. '--cert-name "npm-' + certificate.id + '" ' +
  888. '--preferred-challenges "dns,http" ' +
  889. '--no-random-sleep-on-renew ' +
  890. '--disable-hook-validation ' +
  891. (letsencryptStaging ? '--staging' : '');
  892. logger.info('Command:', cmd);
  893. return utils.exec(cmd)
  894. .then((result) => {
  895. logger.info(result);
  896. return result;
  897. });
  898. },
  899. /**
  900. * @param {Object} certificate the certificate row
  901. * @returns {Promise}
  902. */
  903. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  904. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  905. if (!dns_plugin) {
  906. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  907. }
  908. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  909. let mainCmd = certbotCommand + ' renew ' +
  910. '--config "' + letsencryptConfig + '" ' +
  911. '--cert-name "npm-' + certificate.id + '" ' +
  912. '--disable-hook-validation ' +
  913. '--no-random-sleep-on-renew ' +
  914. (letsencryptStaging ? ' --staging' : '');
  915. // Prepend the path to the credentials file as an environment variable
  916. if (certificate.meta.dns_provider === 'route53') {
  917. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  918. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  919. }
  920. logger.info('Command:', mainCmd);
  921. return utils.exec(mainCmd)
  922. .then(async (result) => {
  923. logger.info(result);
  924. return result;
  925. });
  926. },
  927. /**
  928. * @param {Object} certificate the certificate row
  929. * @param {Boolean} [throw_errors]
  930. * @returns {Promise}
  931. */
  932. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  933. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  934. const mainCmd = certbotCommand + ' revoke ' +
  935. '--config "' + letsencryptConfig + '" ' +
  936. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  937. '--delete-after-revoke ' +
  938. (letsencryptStaging ? '--staging' : '');
  939. // Don't fail command if file does not exist
  940. const delete_credentialsCmd = `rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`;
  941. logger.info('Command:', mainCmd + '; ' + delete_credentialsCmd);
  942. return utils.exec(mainCmd)
  943. .then(async (result) => {
  944. await utils.exec(delete_credentialsCmd);
  945. logger.info(result);
  946. return result;
  947. })
  948. .catch((err) => {
  949. logger.error(err.message);
  950. if (throw_errors) {
  951. throw err;
  952. }
  953. });
  954. },
  955. /**
  956. * @param {Object} certificate
  957. * @returns {Boolean}
  958. */
  959. hasLetsEncryptSslCerts: (certificate) => {
  960. const letsencryptPath = '/etc/letsencrypt/live/npm-' + certificate.id;
  961. return fs.existsSync(letsencryptPath + '/fullchain.pem') && fs.existsSync(letsencryptPath + '/privkey.pem');
  962. },
  963. /**
  964. * @param {Object} in_use_result
  965. * @param {Number} in_use_result.total_count
  966. * @param {Array} in_use_result.proxy_hosts
  967. * @param {Array} in_use_result.redirection_hosts
  968. * @param {Array} in_use_result.dead_hosts
  969. */
  970. disableInUseHosts: (in_use_result) => {
  971. if (in_use_result.total_count) {
  972. let promises = [];
  973. if (in_use_result.proxy_hosts.length) {
  974. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  975. }
  976. if (in_use_result.redirection_hosts.length) {
  977. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  978. }
  979. if (in_use_result.dead_hosts.length) {
  980. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  981. }
  982. return Promise.all(promises);
  983. } else {
  984. return Promise.resolve();
  985. }
  986. },
  987. /**
  988. * @param {Object} in_use_result
  989. * @param {Number} in_use_result.total_count
  990. * @param {Array} in_use_result.proxy_hosts
  991. * @param {Array} in_use_result.redirection_hosts
  992. * @param {Array} in_use_result.dead_hosts
  993. */
  994. enableInUseHosts: (in_use_result) => {
  995. if (in_use_result.total_count) {
  996. let promises = [];
  997. if (in_use_result.proxy_hosts.length) {
  998. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  999. }
  1000. if (in_use_result.redirection_hosts.length) {
  1001. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  1002. }
  1003. if (in_use_result.dead_hosts.length) {
  1004. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  1005. }
  1006. return Promise.all(promises);
  1007. } else {
  1008. return Promise.resolve();
  1009. }
  1010. },
  1011. testHttpsChallenge: async (access, domains) => {
  1012. await access.can('certificates:list');
  1013. if (!isArray(domains)) {
  1014. throw new error.InternalValidationError('Domains must be an array of strings');
  1015. }
  1016. if (domains.length === 0) {
  1017. throw new error.InternalValidationError('No domains provided');
  1018. }
  1019. // Create a test challenge file
  1020. const testChallengeDir = '/data/letsencrypt-acme-challenge/.well-known/acme-challenge';
  1021. const testChallengeFile = testChallengeDir + '/test-challenge';
  1022. fs.mkdirSync(testChallengeDir, {recursive: true});
  1023. fs.writeFileSync(testChallengeFile, 'Success', {encoding: 'utf8'});
  1024. async function performTestForDomain (domain) {
  1025. logger.info('Testing http challenge for ' + domain);
  1026. const url = `http://${domain}/.well-known/acme-challenge/test-challenge`;
  1027. const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`;
  1028. const options = {
  1029. method: 'POST',
  1030. headers: {
  1031. 'Content-Type': 'application/x-www-form-urlencoded',
  1032. 'Content-Length': Buffer.byteLength(formBody)
  1033. }
  1034. };
  1035. const result = await new Promise((resolve) => {
  1036. const req = https.request('https://www.site24x7.com/tools/restapi-tester', options, function (res) {
  1037. let responseBody = '';
  1038. res.on('data', (chunk) => responseBody = responseBody + chunk);
  1039. res.on('end', function () {
  1040. const parsedBody = JSON.parse(responseBody + '');
  1041. if (res.statusCode !== 200) {
  1042. logger.warn(`Failed to test HTTP challenge for domain ${domain}`, res);
  1043. resolve(undefined);
  1044. }
  1045. resolve(parsedBody);
  1046. });
  1047. });
  1048. // Make sure to write the request body.
  1049. req.write(formBody);
  1050. req.end();
  1051. req.on('error', function (e) { logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e);
  1052. resolve(undefined); });
  1053. });
  1054. if (!result) {
  1055. // Some error occurred while trying to get the data
  1056. return 'failed';
  1057. } else if (`${result.responsecode}` === '200' && result.htmlresponse === 'Success') {
  1058. // Server exists and has responded with the correct data
  1059. return 'ok';
  1060. } else if (`${result.responsecode}` === '200') {
  1061. // Server exists but has responded with wrong data
  1062. logger.info(`HTTP challenge test failed for domain ${domain} because of invalid returned data:`, result.htmlresponse);
  1063. return 'wrong-data';
  1064. } else if (`${result.responsecode}` === '404') {
  1065. // Server exists but responded with a 404
  1066. logger.info(`HTTP challenge test failed for domain ${domain} because code 404 was returned`);
  1067. return '404';
  1068. } else if (`${result.responsecode}` === '0' || (typeof result.reason === 'string' && result.reason.toLowerCase() === 'host unavailable')) {
  1069. // Server does not exist at domain
  1070. logger.info(`HTTP challenge test failed for domain ${domain} the host was not found`);
  1071. return 'no-host';
  1072. } else {
  1073. // Other errors
  1074. logger.info(`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`);
  1075. return `other:${result.responsecode}`;
  1076. }
  1077. }
  1078. const results = {};
  1079. for (const domain of domains){
  1080. results[domain] = await performTestForDomain(domain);
  1081. }
  1082. // Remove the test challenge file
  1083. fs.unlinkSync(testChallengeFile);
  1084. return results;
  1085. }
  1086. };
  1087. module.exports = internalCertificate;