certificate.js 37 KB

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