certificate.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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]")
  362. .allowGraph("[proxy_hosts]")
  363. .allowGraph("[redirection_hosts]")
  364. .allowGraph("[dead_hosts]")
  365. .orderBy("nice_name", "ASC");
  366. if (accessData.permission_visibility !== "all") {
  367. query.andWhere("owner_user_id", access.token.getUserId(1));
  368. }
  369. // Query is used for searching
  370. if (typeof searchQuery === "string") {
  371. query.where(function () {
  372. this.where("nice_name", "like", `%${searchQuery}%`);
  373. });
  374. }
  375. if (typeof expand !== "undefined" && expand !== null) {
  376. query.withGraphFetched(`[${expand.join(", ")}]`);
  377. }
  378. return await query.then(utils.omitRows(omissions()));
  379. },
  380. /**
  381. * Report use
  382. *
  383. * @param {Number} userId
  384. * @param {String} visibility
  385. * @returns {Promise}
  386. */
  387. getCount: async (userId, visibility) => {
  388. const query = certificateModel
  389. .query()
  390. .count("id as count")
  391. .where("is_deleted", 0);
  392. if (visibility !== "all") {
  393. query.andWhere("owner_user_id", userId);
  394. }
  395. const row = await query.first();
  396. return Number.parseInt(row.count, 10);
  397. },
  398. /**
  399. * @param {Object} certificate
  400. * @returns {Promise}
  401. */
  402. writeCustomCert: async (certificate) => {
  403. logger.info("Writing Custom Certificate:", certificate);
  404. const dir = `/data/custom_ssl/npm-${certificate.id}`;
  405. return new Promise((resolve, reject) => {
  406. if (certificate.provider === "letsencrypt") {
  407. reject(new Error("Refusing to write letsencrypt certs here"));
  408. return;
  409. }
  410. let certData = certificate.meta.certificate;
  411. if (typeof certificate.meta.intermediate_certificate !== "undefined") {
  412. certData = `${certData}\n${certificate.meta.intermediate_certificate}`;
  413. }
  414. try {
  415. if (!fs.existsSync(dir)) {
  416. fs.mkdirSync(dir);
  417. }
  418. } catch (err) {
  419. reject(err);
  420. return;
  421. }
  422. fs.writeFile(`${dir}/fullchain.pem`, certData, (err) => {
  423. if (err) {
  424. reject(err);
  425. } else {
  426. resolve();
  427. }
  428. });
  429. }).then(() => {
  430. return new Promise((resolve, reject) => {
  431. fs.writeFile(`${dir}/privkey.pem`, certificate.meta.certificate_key, (err) => {
  432. if (err) {
  433. reject(err);
  434. } else {
  435. resolve();
  436. }
  437. });
  438. });
  439. });
  440. },
  441. /**
  442. * @param {Access} access
  443. * @param {Object} data
  444. * @param {Array} data.domain_names
  445. * @param {String} data.meta.letsencrypt_email
  446. * @param {Boolean} data.meta.letsencrypt_agree
  447. * @returns {Promise}
  448. */
  449. createQuickCertificate: async (access, data) => {
  450. return internalCertificate.create(access, {
  451. provider: "letsencrypt",
  452. domain_names: data.domain_names,
  453. meta: data.meta,
  454. });
  455. },
  456. /**
  457. * Validates that the certs provided are good.
  458. * No access required here, nothing is changed or stored.
  459. *
  460. * @param {Object} data
  461. * @param {Object} data.files
  462. * @returns {Promise}
  463. */
  464. validate: (data) => {
  465. // Put file contents into an object
  466. const files = {};
  467. _.map(data.files, (file, name) => {
  468. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  469. files[name] = file.data.toString();
  470. }
  471. });
  472. // For each file, create a temp file and write the contents to it
  473. // Then test it depending on the file type
  474. const promises = [];
  475. _.map(files, (content, type) => {
  476. promises.push(
  477. new Promise((resolve) => {
  478. if (type === "certificate_key") {
  479. resolve(internalCertificate.checkPrivateKey(content));
  480. } else {
  481. // this should handle `certificate` and intermediate certificate
  482. resolve(internalCertificate.getCertificateInfo(content, true));
  483. }
  484. }).then((res) => {
  485. return { [type]: res };
  486. }),
  487. );
  488. });
  489. return Promise.all(promises).then((files) => {
  490. let data = {};
  491. _.each(files, (file) => {
  492. data = _.assign({}, data, file);
  493. });
  494. return data;
  495. });
  496. },
  497. /**
  498. * @param {Access} access
  499. * @param {Object} data
  500. * @param {Number} data.id
  501. * @param {Object} data.files
  502. * @returns {Promise}
  503. */
  504. upload: async (access, data) => {
  505. const row = await internalCertificate.get(access, { id: data.id });
  506. if (row.provider !== "other") {
  507. throw new error.ValidationError("Cannot upload certificates for this type of provider");
  508. }
  509. const validations = await internalCertificate.validate(data);
  510. if (typeof validations.certificate === "undefined") {
  511. throw new error.ValidationError("Certificate file was not provided");
  512. }
  513. _.map(data.files, (file, name) => {
  514. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  515. row.meta[name] = file.data.toString();
  516. }
  517. });
  518. const certificate = await internalCertificate.update(access, {
  519. id: data.id,
  520. expires_on: moment(validations.certificate.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"),
  521. domain_names: [validations.certificate.cn],
  522. meta: _.clone(row.meta), // Prevent the update method from changing this value that we'll use later
  523. });
  524. certificate.meta = row.meta;
  525. await internalCertificate.writeCustomCert(certificate);
  526. return _.pick(row.meta, internalCertificate.allowedSslFiles);
  527. },
  528. /**
  529. * Uses the openssl command to validate the private key.
  530. * It will save the file to disk first, then run commands on it, then delete the file.
  531. *
  532. * @param {String} privateKey This is the entire key contents as a string
  533. */
  534. checkPrivateKey: async (privateKey) => {
  535. const filepath = await tempWrite(privateKey, "/tmp");
  536. const failTimeout = setTimeout(() => {
  537. throw new error.ValidationError(
  538. "Result Validation Error: Validation timed out. This could be due to the key being passphrase-protected.",
  539. );
  540. }, 10000);
  541. try {
  542. const result = await utils.exec(`openssl pkey -in ${filepath} -check -noout 2>&1 `);
  543. clearTimeout(failTimeout);
  544. if (!result.toLowerCase().includes("key is valid")) {
  545. throw new error.ValidationError(`Result Validation Error: ${result}`);
  546. }
  547. fs.unlinkSync(filepath);
  548. return true;
  549. } catch (err) {
  550. clearTimeout(failTimeout);
  551. fs.unlinkSync(filepath);
  552. throw new error.ValidationError(`Certificate Key is not valid (${err.message})`, err);
  553. }
  554. },
  555. /**
  556. * Uses the openssl command to both validate and get info out of the certificate.
  557. * It will save the file to disk first, then run commands on it, then delete the file.
  558. *
  559. * @param {String} certificate This is the entire cert contents as a string
  560. * @param {Boolean} [throwExpired] Throw when the certificate is out of date
  561. */
  562. getCertificateInfo: async (certificate, throwExpired) => {
  563. try {
  564. const filepath = await tempWrite(certificate, "/tmp");
  565. const certData = await internalCertificate.getCertificateInfoFromFile(filepath, throwExpired);
  566. fs.unlinkSync(filepath);
  567. return certData;
  568. } catch (err) {
  569. fs.unlinkSync(filepath);
  570. throw err;
  571. }
  572. },
  573. /**
  574. * Uses the openssl command to both validate and get info out of the certificate.
  575. * It will save the file to disk first, then run commands on it, then delete the file.
  576. *
  577. * @param {String} certificateFile The file location on disk
  578. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  579. */
  580. getCertificateInfoFromFile: async (certificateFile, throw_expired) => {
  581. const certData = {};
  582. try {
  583. const result = await utils.execFile("openssl", ["x509", "-in", certificateFile, "-subject", "-noout"])
  584. // Examples:
  585. // subject=CN = *.jc21.com
  586. // subject=CN = something.example.com
  587. const regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  588. const match = regex.exec(result);
  589. if (match && typeof match[1] !== "undefined") {
  590. certData.cn = match[1];
  591. }
  592. const result2 = await utils.execFile("openssl", ["x509", "-in", certificateFile, "-issuer", "-noout"]);
  593. // Examples:
  594. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  595. // issuer=C = US, O = Let's Encrypt, CN = E5
  596. // issuer=O = NginxProxyManager, CN = NginxProxyManager Intermediate CA","O = NginxProxyManager, CN = NginxProxyManager Intermediate CA
  597. const regex2 = /^(?:issuer=)?(.*)$/gim;
  598. const match2 = regex2.exec(result2);
  599. if (match2 && typeof match2[1] !== "undefined") {
  600. certData.issuer = match2[1];
  601. }
  602. const result3 = await utils.execFile("openssl", ["x509", "-in", certificateFile, "-dates", "-noout"]);
  603. // notBefore=Jul 14 04:04:29 2018 GMT
  604. // notAfter=Oct 12 04:04:29 2018 GMT
  605. let validFrom = null;
  606. let validTo = null;
  607. const lines = result3.split("\n");
  608. lines.map((str) => {
  609. const regex = /^(\S+)=(.*)$/gim;
  610. const match = regex.exec(str.trim());
  611. if (match && typeof match[2] !== "undefined") {
  612. const date = Number.parseInt(moment(match[2], "MMM DD HH:mm:ss YYYY z").format("X"), 10);
  613. if (match[1].toLowerCase() === "notbefore") {
  614. validFrom = date;
  615. } else if (match[1].toLowerCase() === "notafter") {
  616. validTo = date;
  617. }
  618. }
  619. return true;
  620. });
  621. if (!validFrom || !validTo) {
  622. throw new error.ValidationError(`Could not determine dates from certificate: ${result}`);
  623. }
  624. if (throw_expired && validTo < Number.parseInt(moment().format("X"), 10)) {
  625. throw new error.ValidationError("Certificate has expired");
  626. }
  627. certData.dates = {
  628. from: validFrom,
  629. to: validTo,
  630. };
  631. return certData;
  632. } catch (err) {
  633. throw new error.ValidationError(`Certificate is not valid (${err.message})`, err);
  634. }
  635. },
  636. /**
  637. * Cleans the ssl keys from the meta object and sets them to "true"
  638. *
  639. * @param {Object} meta
  640. * @param {Boolean} [remove]
  641. * @returns {Object}
  642. */
  643. cleanMeta: (meta, remove) => {
  644. internalCertificate.allowedSslFiles.map((key) => {
  645. if (typeof meta[key] !== "undefined" && meta[key]) {
  646. if (remove) {
  647. delete meta[key];
  648. } else {
  649. meta[key] = true;
  650. }
  651. }
  652. return true;
  653. });
  654. return meta;
  655. },
  656. /**
  657. * Request a certificate using the http challenge
  658. * @param {Object} certificate the certificate row
  659. * @returns {Promise}
  660. */
  661. requestLetsEncryptSsl: async (certificate) => {
  662. logger.info(
  663. `Requesting LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  664. );
  665. const args = [
  666. "certonly",
  667. "--config",
  668. letsencryptConfig,
  669. "--work-dir",
  670. "/tmp/letsencrypt-lib",
  671. "--logs-dir",
  672. "/tmp/letsencrypt-log",
  673. "--cert-name",
  674. `npm-${certificate.id}`,
  675. "--agree-tos",
  676. "--authenticator",
  677. "webroot",
  678. "--email",
  679. certificate.meta.letsencrypt_email,
  680. "--preferred-challenges",
  681. "dns,http",
  682. "--domains",
  683. certificate.domain_names.join(","),
  684. ];
  685. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id);
  686. args.push(...adds.args);
  687. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  688. const result = await utils.execFile(certbotCommand, args, adds.opts);
  689. logger.success(result);
  690. return result;
  691. },
  692. /**
  693. * @param {Object} certificate the certificate row
  694. * @returns {Promise}
  695. */
  696. requestLetsEncryptSslWithDnsChallenge: async (certificate) => {
  697. await installPlugin(certificate.meta.dns_provider);
  698. const dnsPlugin = dnsPlugins[certificate.meta.dns_provider];
  699. logger.info(
  700. `Requesting LetsEncrypt certificates via ${dnsPlugin.name} for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  701. );
  702. const credentialsLocation = `/etc/letsencrypt/credentials/credentials-${certificate.id}`;
  703. fs.mkdirSync("/etc/letsencrypt/credentials", { recursive: true });
  704. fs.writeFileSync(credentialsLocation, certificate.meta.dns_provider_credentials, { mode: 0o600 });
  705. // Whether the plugin has a --<name>-credentials argument
  706. const hasConfigArg = certificate.meta.dns_provider !== "route53";
  707. const args = [
  708. "certonly",
  709. "--config",
  710. letsencryptConfig,
  711. "--work-dir",
  712. "/tmp/letsencrypt-lib",
  713. "--logs-dir",
  714. "/tmp/letsencrypt-log",
  715. "--cert-name",
  716. `npm-${certificate.id}`,
  717. "--agree-tos",
  718. "--email",
  719. certificate.meta.letsencrypt_email,
  720. "--domains",
  721. certificate.domain_names.join(","),
  722. "--authenticator",
  723. dnsPlugin.full_plugin_name,
  724. ];
  725. if (hasConfigArg) {
  726. args.push(`--${dnsPlugin.full_plugin_name}-credentials`, credentialsLocation);
  727. }
  728. if (certificate.meta.propagation_seconds !== undefined) {
  729. args.push(
  730. `--${dnsPlugin.full_plugin_name}-propagation-seconds`,
  731. certificate.meta.propagation_seconds.toString(),
  732. );
  733. }
  734. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id, certificate.meta.dns_provider);
  735. args.push(...adds.args);
  736. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  737. try {
  738. const result = await utils.execFile(certbotCommand, args, adds.opts);
  739. logger.info(result);
  740. return result;
  741. } catch (err) {
  742. // Don't fail if file does not exist, so no need for action in the callback
  743. fs.unlink(credentialsLocation, () => {});
  744. throw err;
  745. }
  746. },
  747. /**
  748. * @param {Access} access
  749. * @param {Object} data
  750. * @param {Number} data.id
  751. * @returns {Promise}
  752. */
  753. renew: async (access, data) => {
  754. await access.can("certificates:update", data)
  755. const certificate = await internalCertificate.get(access, data);
  756. if (certificate.provider === "letsencrypt") {
  757. const renewMethod = certificate.meta.dns_challenge
  758. ? internalCertificate.renewLetsEncryptSslWithDnsChallenge
  759. : internalCertificate.renewLetsEncryptSsl;
  760. await renewMethod(certificate);
  761. const certInfo = await internalCertificate.getCertificateInfoFromFile(
  762. `${internalCertificate.getLiveCertPath(certificate.id)}/fullchain.pem`,
  763. );
  764. const updatedCertificate = await certificateModel
  765. .query()
  766. .patchAndFetchById(certificate.id, {
  767. expires_on: moment(certInfo.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"),
  768. });
  769. // Add to audit log
  770. await internalAuditLog.add(access, {
  771. action: "renewed",
  772. object_type: "certificate",
  773. object_id: updatedCertificate.id,
  774. meta: updatedCertificate,
  775. });
  776. } else {
  777. throw new error.ValidationError("Only Let'sEncrypt certificates can be renewed");
  778. }
  779. },
  780. /**
  781. * @param {Object} certificate the certificate row
  782. * @returns {Promise}
  783. */
  784. renewLetsEncryptSsl: async (certificate) => {
  785. logger.info(
  786. `Renewing LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  787. );
  788. const args = [
  789. "renew",
  790. "--force-renewal",
  791. "--config",
  792. letsencryptConfig,
  793. "--work-dir",
  794. "/tmp/letsencrypt-lib",
  795. "--logs-dir",
  796. "/tmp/letsencrypt-log",
  797. "--cert-name",
  798. `npm-${certificate.id}`,
  799. "--preferred-challenges",
  800. "dns,http",
  801. "--no-random-sleep-on-renew",
  802. "--disable-hook-validation",
  803. ];
  804. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id, certificate.meta.dns_provider);
  805. args.push(...adds.args);
  806. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  807. const result = await utils.execFile(certbotCommand, args, adds.opts);
  808. logger.info(result);
  809. return result;
  810. },
  811. /**
  812. * @param {Object} certificate the certificate row
  813. * @returns {Promise}
  814. */
  815. renewLetsEncryptSslWithDnsChallenge: async (certificate) => {
  816. const dnsPlugin = dnsPlugins[certificate.meta.dns_provider];
  817. if (!dnsPlugin) {
  818. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  819. }
  820. logger.info(
  821. `Renewing LetsEncrypt certificates via ${dnsPlugin.name} for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  822. );
  823. const args = [
  824. "renew",
  825. "--force-renewal",
  826. "--config",
  827. letsencryptConfig,
  828. "--work-dir",
  829. "/tmp/letsencrypt-lib",
  830. "--logs-dir",
  831. "/tmp/letsencrypt-log",
  832. "--cert-name",
  833. `npm-${certificate.id}`,
  834. "--disable-hook-validation",
  835. "--no-random-sleep-on-renew",
  836. ];
  837. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id, certificate.meta.dns_provider);
  838. args.push(...adds.args);
  839. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  840. const result = await utils.execFile(certbotCommand, args, adds.opts);
  841. logger.info(result);
  842. return result;
  843. },
  844. /**
  845. * @param {Object} certificate the certificate row
  846. * @param {Boolean} [throwErrors]
  847. * @returns {Promise}
  848. */
  849. revokeLetsEncryptSsl: async (certificate, throwErrors) => {
  850. logger.info(
  851. `Revoking LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  852. );
  853. const args = [
  854. "revoke",
  855. "--config",
  856. letsencryptConfig,
  857. "--work-dir",
  858. "/tmp/letsencrypt-lib",
  859. "--logs-dir",
  860. "/tmp/letsencrypt-log",
  861. "--cert-path",
  862. `${internalCertificate.getLiveCertPath(certificate.id)}/fullchain.pem`,
  863. "--delete-after-revoke",
  864. ];
  865. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id);
  866. args.push(...adds.args);
  867. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  868. try {
  869. const result = await utils.execFile(certbotCommand, args, adds.opts);
  870. await utils.exec(`rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`);
  871. logger.info(result);
  872. return result;
  873. } catch (err) {
  874. logger.error(err.message);
  875. if (throwErrors) {
  876. throw err;
  877. }
  878. }
  879. },
  880. /**
  881. * @param {Object} certificate
  882. * @returns {Boolean}
  883. */
  884. hasLetsEncryptSslCerts: (certificate) => {
  885. const letsencryptPath = internalCertificate.getLiveCertPath(certificate.id);
  886. return fs.existsSync(`${letsencryptPath}/fullchain.pem`) && fs.existsSync(`${letsencryptPath}/privkey.pem`);
  887. },
  888. /**
  889. * @param {Object} inUseResult
  890. * @param {Number} inUseResult.total_count
  891. * @param {Array} inUseResult.proxy_hosts
  892. * @param {Array} inUseResult.redirection_hosts
  893. * @param {Array} inUseResult.dead_hosts
  894. * @returns {Promise}
  895. */
  896. disableInUseHosts: async (inUseResult) => {
  897. if (inUseResult?.total_count) {
  898. if (inUseResult?.proxy_hosts.length) {
  899. await internalNginx.bulkDeleteConfigs("proxy_host", inUseResult.proxy_hosts);
  900. }
  901. if (inUseResult?.redirection_hosts.length) {
  902. await internalNginx.bulkDeleteConfigs("redirection_host", inUseResult.redirection_hosts);
  903. }
  904. if (inUseResult?.dead_hosts.length) {
  905. await internalNginx.bulkDeleteConfigs("dead_host", inUseResult.dead_hosts);
  906. }
  907. }
  908. },
  909. /**
  910. * @param {Object} inUseResult
  911. * @param {Number} inUseResult.total_count
  912. * @param {Array} inUseResult.proxy_hosts
  913. * @param {Array} inUseResult.redirection_hosts
  914. * @param {Array} inUseResult.dead_hosts
  915. * @returns {Promise}
  916. */
  917. enableInUseHosts: async (inUseResult) => {
  918. if (inUseResult.total_count) {
  919. if (inUseResult.proxy_hosts.length) {
  920. await internalNginx.bulkGenerateConfigs("proxy_host", inUseResult.proxy_hosts);
  921. }
  922. if (inUseResult.redirection_hosts.length) {
  923. await internalNginx.bulkGenerateConfigs("redirection_host", inUseResult.redirection_hosts);
  924. }
  925. if (inUseResult.dead_hosts.length) {
  926. await internalNginx.bulkGenerateConfigs("dead_host", inUseResult.dead_hosts);
  927. }
  928. }
  929. },
  930. testHttpsChallenge: async (access, domains) => {
  931. await access.can("certificates:list");
  932. if (!isArray(domains)) {
  933. throw new error.InternalValidationError("Domains must be an array of strings");
  934. }
  935. if (domains.length === 0) {
  936. throw new error.InternalValidationError("No domains provided");
  937. }
  938. // Create a test challenge file
  939. const testChallengeDir = "/data/letsencrypt-acme-challenge/.well-known/acme-challenge";
  940. const testChallengeFile = `${testChallengeDir}/test-challenge`;
  941. fs.mkdirSync(testChallengeDir, { recursive: true });
  942. fs.writeFileSync(testChallengeFile, "Success", { encoding: "utf8" });
  943. async function performTestForDomain(domain) {
  944. logger.info(`Testing http challenge for ${domain}`);
  945. const url = `http://${domain}/.well-known/acme-challenge/test-challenge`;
  946. const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`;
  947. const options = {
  948. method: "POST",
  949. headers: {
  950. "User-Agent": "Mozilla/5.0",
  951. "Content-Type": "application/x-www-form-urlencoded",
  952. "Content-Length": Buffer.byteLength(formBody),
  953. },
  954. };
  955. const result = await new Promise((resolve) => {
  956. const req = https.request("https://www.site24x7.com/tools/restapi-tester", options, (res) => {
  957. let responseBody = "";
  958. res.on("data", (chunk) => {
  959. responseBody = responseBody + chunk;
  960. });
  961. res.on("end", () => {
  962. try {
  963. const parsedBody = JSON.parse(`${responseBody}`);
  964. if (res.statusCode !== 200) {
  965. logger.warn(
  966. `Failed to test HTTP challenge for domain ${domain} because HTTP status code ${res.statusCode} was returned: ${parsedBody.message}`,
  967. );
  968. resolve(undefined);
  969. } else {
  970. resolve(parsedBody);
  971. }
  972. } catch (err) {
  973. if (res.statusCode !== 200) {
  974. logger.warn(
  975. `Failed to test HTTP challenge for domain ${domain} because HTTP status code ${res.statusCode} was returned`,
  976. );
  977. } else {
  978. logger.warn(
  979. `Failed to test HTTP challenge for domain ${domain} because response failed to be parsed: ${err.message}`,
  980. );
  981. }
  982. resolve(undefined);
  983. }
  984. });
  985. });
  986. // Make sure to write the request body.
  987. req.write(formBody);
  988. req.end();
  989. req.on("error", (e) => {
  990. logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e);
  991. resolve(undefined);
  992. });
  993. });
  994. if (!result) {
  995. // Some error occurred while trying to get the data
  996. return "failed";
  997. }
  998. if (result.error) {
  999. logger.info(
  1000. `HTTP challenge test failed for domain ${domain} because error was returned: ${result.error.msg}`,
  1001. );
  1002. return `other:${result.error.msg}`;
  1003. }
  1004. if (`${result.responsecode}` === "200" && result.htmlresponse === "Success") {
  1005. // Server exists and has responded with the correct data
  1006. return "ok";
  1007. }
  1008. if (`${result.responsecode}` === "200") {
  1009. // Server exists but has responded with wrong data
  1010. logger.info(
  1011. `HTTP challenge test failed for domain ${domain} because of invalid returned data:`,
  1012. result.htmlresponse,
  1013. );
  1014. return "wrong-data";
  1015. }
  1016. if (`${result.responsecode}` === "404") {
  1017. // Server exists but responded with a 404
  1018. logger.info(`HTTP challenge test failed for domain ${domain} because code 404 was returned`);
  1019. return "404";
  1020. }
  1021. if (
  1022. `${result.responsecode}` === "0" ||
  1023. (typeof result.reason === "string" && result.reason.toLowerCase() === "host unavailable")
  1024. ) {
  1025. // Server does not exist at domain
  1026. logger.info(`HTTP challenge test failed for domain ${domain} the host was not found`);
  1027. return "no-host";
  1028. }
  1029. // Other errors
  1030. logger.info(`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`);
  1031. return `other:${result.responsecode}`;
  1032. }
  1033. const results = {};
  1034. for (const domain of domains) {
  1035. results[domain] = await performTestForDomain(domain);
  1036. }
  1037. // Remove the test challenge file
  1038. fs.unlinkSync(testChallengeFile);
  1039. return results;
  1040. },
  1041. getAdditionalCertbotArgs: (certificate_id, dns_provider) => {
  1042. const args = [];
  1043. if (useLetsencryptServer() !== null) {
  1044. args.push("--server", useLetsencryptServer());
  1045. }
  1046. if (useLetsencryptStaging() && useLetsencryptServer() === null) {
  1047. args.push("--staging");
  1048. }
  1049. // For route53, add the credentials file as an environment variable,
  1050. // inheriting the process env
  1051. const opts = {};
  1052. if (certificate_id && dns_provider === "route53") {
  1053. opts.env = process.env;
  1054. opts.env.AWS_CONFIG_FILE = `/etc/letsencrypt/credentials/credentials-${certificate_id}`;
  1055. }
  1056. if (dns_provider === "duckdns") {
  1057. args.push("--dns-duckdns-no-txt-restore");
  1058. }
  1059. return { args: args, opts: opts };
  1060. },
  1061. getLiveCertPath: (certificateId) => {
  1062. return `/etc/letsencrypt/live/npm-${certificateId}`;
  1063. }
  1064. };
  1065. export default internalCertificate;