certificate.js 35 KB

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