certificate.js 35 KB

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