certificate.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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);
  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. const filepath = await tempWrite(certificate);
  585. try {
  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. // Add key-type parameter if specified
  708. if (certificate.meta?.key_type) {
  709. args.push("--key-type", certificate.meta.key_type);
  710. }
  711. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id);
  712. args.push(...adds.args);
  713. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  714. const result = await utils.execFile(certbotCommand, args, adds.opts);
  715. logger.success(result);
  716. return result;
  717. },
  718. /**
  719. * @param {Object} certificate the certificate row
  720. * @param {String} email the email address to use for registration
  721. * @returns {Promise}
  722. */
  723. requestLetsEncryptSslWithDnsChallenge: async (certificate, email) => {
  724. await installPlugin(certificate.meta.dns_provider);
  725. const dnsPlugin = dnsPlugins[certificate.meta.dns_provider];
  726. logger.info(
  727. `Requesting LetsEncrypt certificates via ${dnsPlugin.name} for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  728. );
  729. const credentialsLocation = `/etc/letsencrypt/credentials/credentials-${certificate.id}`;
  730. fs.mkdirSync("/etc/letsencrypt/credentials", { recursive: true });
  731. fs.writeFileSync(credentialsLocation, certificate.meta.dns_provider_credentials, { mode: 0o600 });
  732. // Whether the plugin has a --<name>-credentials argument
  733. const hasConfigArg = certificate.meta.dns_provider !== "route53";
  734. const args = [
  735. "certonly",
  736. "--config",
  737. letsencryptConfig,
  738. "--work-dir",
  739. certbotWorkDir,
  740. "--logs-dir",
  741. certbotLogsDir,
  742. "--cert-name",
  743. `npm-${certificate.id}`,
  744. "--agree-tos",
  745. "-m",
  746. email,
  747. "--preferred-challenges",
  748. "dns",
  749. "--domains",
  750. certificate.domain_names.join(","),
  751. "--authenticator",
  752. dnsPlugin.full_plugin_name,
  753. ];
  754. if (hasConfigArg) {
  755. args.push(`--${dnsPlugin.full_plugin_name}-credentials`, credentialsLocation);
  756. }
  757. if (certificate.meta.propagation_seconds !== undefined) {
  758. args.push(
  759. `--${dnsPlugin.full_plugin_name}-propagation-seconds`,
  760. certificate.meta.propagation_seconds.toString(),
  761. );
  762. }
  763. // Add key-type parameter if specified
  764. if (certificate.meta?.key_type) {
  765. args.push("--key-type", certificate.meta.key_type);
  766. }
  767. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id, certificate.meta.dns_provider);
  768. args.push(...adds.args);
  769. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  770. try {
  771. const result = await utils.execFile(certbotCommand, args, adds.opts);
  772. logger.info(result);
  773. return result;
  774. } catch (err) {
  775. // Don't fail if file does not exist, so no need for action in the callback
  776. fs.unlink(credentialsLocation, () => {});
  777. throw err;
  778. }
  779. },
  780. /**
  781. * @param {Access} access
  782. * @param {Object} data
  783. * @param {Number} data.id
  784. * @returns {Promise}
  785. */
  786. renew: async (access, data) => {
  787. await access.can("certificates:update", data);
  788. const certificate = await internalCertificate.get(access, data);
  789. if (certificate.provider === "letsencrypt") {
  790. const renewMethod = certificate.meta.dns_challenge
  791. ? internalCertificate.renewLetsEncryptSslWithDnsChallenge
  792. : internalCertificate.renewLetsEncryptSsl;
  793. await renewMethod(certificate);
  794. const certInfo = await internalCertificate.getCertificateInfoFromFile(
  795. `${internalCertificate.getLiveCertPath(certificate.id)}/fullchain.pem`,
  796. );
  797. const updatedCertificate = await certificateModel.query().patchAndFetchById(certificate.id, {
  798. expires_on: moment(certInfo.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"),
  799. });
  800. // Add to audit log
  801. await internalAuditLog.add(access, {
  802. action: "renewed",
  803. object_type: "certificate",
  804. object_id: updatedCertificate.id,
  805. meta: updatedCertificate,
  806. });
  807. return updatedCertificate;
  808. }
  809. throw new error.ValidationError("Only Let'sEncrypt certificates can be renewed");
  810. },
  811. /**
  812. * @param {Object} certificate the certificate row
  813. * @returns {Promise}
  814. */
  815. renewLetsEncryptSsl: async (certificate) => {
  816. logger.info(
  817. `Renewing LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  818. );
  819. const args = [
  820. "renew",
  821. "--force-renewal",
  822. "--config",
  823. letsencryptConfig,
  824. "--work-dir",
  825. certbotWorkDir,
  826. "--logs-dir",
  827. certbotLogsDir,
  828. "--cert-name",
  829. `npm-${certificate.id}`,
  830. "--preferred-challenges",
  831. "http",
  832. "--no-random-sleep-on-renew",
  833. "--disable-hook-validation",
  834. ];
  835. // Add key-type parameter if specified
  836. if (certificate.meta?.key_type) {
  837. args.push("--key-type", certificate.meta.key_type);
  838. }
  839. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id, certificate.meta.dns_provider);
  840. args.push(...adds.args);
  841. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  842. const result = await utils.execFile(certbotCommand, args, adds.opts);
  843. logger.info(result);
  844. return result;
  845. },
  846. /**
  847. * @param {Object} certificate the certificate row
  848. * @returns {Promise}
  849. */
  850. renewLetsEncryptSslWithDnsChallenge: async (certificate) => {
  851. const dnsPlugin = dnsPlugins[certificate.meta.dns_provider];
  852. if (!dnsPlugin) {
  853. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  854. }
  855. logger.info(
  856. `Renewing LetsEncrypt certificates via ${dnsPlugin.name} for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  857. );
  858. const args = [
  859. "renew",
  860. "--force-renewal",
  861. "--config",
  862. letsencryptConfig,
  863. "--work-dir",
  864. certbotWorkDir,
  865. "--logs-dir",
  866. certbotLogsDir,
  867. "--cert-name",
  868. `npm-${certificate.id}`,
  869. "--preferred-challenges",
  870. "dns",
  871. "--disable-hook-validation",
  872. "--no-random-sleep-on-renew",
  873. ];
  874. // Add key-type parameter if specified
  875. if (certificate.meta?.key_type) {
  876. args.push("--key-type", certificate.meta.key_type);
  877. }
  878. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id, certificate.meta.dns_provider);
  879. args.push(...adds.args);
  880. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  881. const result = await utils.execFile(certbotCommand, args, adds.opts);
  882. logger.info(result);
  883. return result;
  884. },
  885. /**
  886. * @param {Object} certificate the certificate row
  887. * @param {Boolean} [throwErrors]
  888. * @returns {Promise}
  889. */
  890. revokeLetsEncryptSsl: async (certificate, throwErrors) => {
  891. logger.info(
  892. `Revoking LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
  893. );
  894. const args = [
  895. "revoke",
  896. "--config",
  897. letsencryptConfig,
  898. "--work-dir",
  899. certbotWorkDir,
  900. "--logs-dir",
  901. certbotLogsDir,
  902. "--cert-path",
  903. `${internalCertificate.getLiveCertPath(certificate.id)}/fullchain.pem`,
  904. "--delete-after-revoke",
  905. ];
  906. const adds = internalCertificate.getAdditionalCertbotArgs(certificate.id);
  907. args.push(...adds.args);
  908. logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
  909. try {
  910. const result = await utils.execFile(certbotCommand, args, adds.opts);
  911. await utils.exec(`rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`);
  912. logger.info(result);
  913. return result;
  914. } catch (err) {
  915. logger.error(err.message);
  916. if (throwErrors) {
  917. throw err;
  918. }
  919. }
  920. },
  921. /**
  922. * @param {Object} certificate
  923. * @returns {Boolean}
  924. */
  925. hasLetsEncryptSslCerts: (certificate) => {
  926. const letsencryptPath = internalCertificate.getLiveCertPath(certificate.id);
  927. return fs.existsSync(`${letsencryptPath}/fullchain.pem`) && fs.existsSync(`${letsencryptPath}/privkey.pem`);
  928. },
  929. /**
  930. * @param {Object} inUseResult
  931. * @param {Number} inUseResult.total_count
  932. * @param {Array} inUseResult.proxy_hosts
  933. * @param {Array} inUseResult.redirection_hosts
  934. * @param {Array} inUseResult.dead_hosts
  935. * @returns {Promise}
  936. */
  937. disableInUseHosts: async (inUseResult) => {
  938. if (inUseResult?.total_count) {
  939. if (inUseResult?.proxy_hosts.length) {
  940. await internalNginx.bulkDeleteConfigs("proxy_host", inUseResult.proxy_hosts);
  941. }
  942. if (inUseResult?.redirection_hosts.length) {
  943. await internalNginx.bulkDeleteConfigs("redirection_host", inUseResult.redirection_hosts);
  944. }
  945. if (inUseResult?.dead_hosts.length) {
  946. await internalNginx.bulkDeleteConfigs("dead_host", inUseResult.dead_hosts);
  947. }
  948. }
  949. },
  950. /**
  951. * @param {Object} inUseResult
  952. * @param {Number} inUseResult.total_count
  953. * @param {Array} inUseResult.proxy_hosts
  954. * @param {Array} inUseResult.redirection_hosts
  955. * @param {Array} inUseResult.dead_hosts
  956. * @returns {Promise}
  957. */
  958. enableInUseHosts: async (inUseResult) => {
  959. if (inUseResult.total_count) {
  960. if (inUseResult.proxy_hosts.length) {
  961. await internalNginx.bulkGenerateConfigs("proxy_host", inUseResult.proxy_hosts);
  962. }
  963. if (inUseResult.redirection_hosts.length) {
  964. await internalNginx.bulkGenerateConfigs("redirection_host", inUseResult.redirection_hosts);
  965. }
  966. if (inUseResult.dead_hosts.length) {
  967. await internalNginx.bulkGenerateConfigs("dead_host", inUseResult.dead_hosts);
  968. }
  969. }
  970. },
  971. /**
  972. *
  973. * @param {Object} payload
  974. * @param {string[]} payload.domains
  975. * @returns
  976. */
  977. testHttpsChallenge: async (access, payload) => {
  978. await access.can("certificates:list");
  979. // Create a test challenge file
  980. const testChallengeDir = "/data/letsencrypt-acme-challenge/.well-known/acme-challenge";
  981. const testChallengeFile = `${testChallengeDir}/test-challenge`;
  982. fs.mkdirSync(testChallengeDir, { recursive: true });
  983. fs.writeFileSync(testChallengeFile, "Success", { encoding: "utf8" });
  984. const results = {};
  985. for (const domain of payload.domains) {
  986. results[domain] = await internalCertificate.performTestForDomain(domain);
  987. }
  988. // Remove the test challenge file
  989. fs.unlinkSync(testChallengeFile);
  990. return results;
  991. },
  992. performTestForDomain: async (domain) => {
  993. logger.info(`Testing http challenge for ${domain}`);
  994. const agent = new ProxyAgent();
  995. const url = `http://${domain}/.well-known/acme-challenge/test-challenge`;
  996. const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`;
  997. const options = {
  998. method: "POST",
  999. headers: {
  1000. "User-Agent": "Mozilla/5.0",
  1001. "Content-Type": "application/x-www-form-urlencoded",
  1002. "Content-Length": Buffer.byteLength(formBody),
  1003. },
  1004. agent,
  1005. };
  1006. const result = await new Promise((resolve) => {
  1007. const req = https.request("https://www.site24x7.com/tools/restapi-tester", options, (res) => {
  1008. let responseBody = "";
  1009. res.on("data", (chunk) => {
  1010. responseBody = responseBody + chunk;
  1011. });
  1012. res.on("end", () => {
  1013. try {
  1014. const parsedBody = JSON.parse(`${responseBody}`);
  1015. if (res.statusCode !== 200) {
  1016. logger.warn(
  1017. `Failed to test HTTP challenge for domain ${domain} because HTTP status code ${res.statusCode} was returned: ${parsedBody.message}`,
  1018. );
  1019. resolve(undefined);
  1020. } else {
  1021. resolve(parsedBody);
  1022. }
  1023. } catch (err) {
  1024. if (res.statusCode !== 200) {
  1025. logger.warn(
  1026. `Failed to test HTTP challenge for domain ${domain} because HTTP status code ${res.statusCode} was returned`,
  1027. );
  1028. } else {
  1029. logger.warn(
  1030. `Failed to test HTTP challenge for domain ${domain} because response failed to be parsed: ${err.message}`,
  1031. );
  1032. }
  1033. resolve(undefined);
  1034. }
  1035. });
  1036. });
  1037. // Make sure to write the request body.
  1038. req.write(formBody);
  1039. req.end();
  1040. req.on("error", (e) => {
  1041. logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e);
  1042. resolve(undefined);
  1043. });
  1044. });
  1045. if (!result) {
  1046. // Some error occurred while trying to get the data
  1047. return "failed";
  1048. }
  1049. if (result.error) {
  1050. logger.info(
  1051. `HTTP challenge test failed for domain ${domain} because error was returned: ${result.error.msg}`,
  1052. );
  1053. return `other:${result.error.msg}`;
  1054. }
  1055. if (`${result.responsecode}` === "200" && result.htmlresponse === "Success") {
  1056. // Server exists and has responded with the correct data
  1057. return "ok";
  1058. }
  1059. if (`${result.responsecode}` === "200") {
  1060. // Server exists but has responded with wrong data
  1061. logger.info(
  1062. `HTTP challenge test failed for domain ${domain} because of invalid returned data:`,
  1063. result.htmlresponse,
  1064. );
  1065. return "wrong-data";
  1066. }
  1067. if (`${result.responsecode}` === "404") {
  1068. // Server exists but responded with a 404
  1069. logger.info(`HTTP challenge test failed for domain ${domain} because code 404 was returned`);
  1070. return "404";
  1071. }
  1072. if (
  1073. `${result.responsecode}` === "0" ||
  1074. (typeof result.reason === "string" && result.reason.toLowerCase() === "host unavailable")
  1075. ) {
  1076. // Server does not exist at domain
  1077. logger.info(`HTTP challenge test failed for domain ${domain} the host was not found`);
  1078. return "no-host";
  1079. }
  1080. // Other errors
  1081. logger.info(`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`);
  1082. return `other:${result.responsecode}`;
  1083. },
  1084. getAdditionalCertbotArgs: (certificate_id, dns_provider) => {
  1085. const args = [];
  1086. if (useLetsencryptServer() !== null) {
  1087. args.push("--server", useLetsencryptServer());
  1088. }
  1089. if (useLetsencryptStaging() && useLetsencryptServer() === null) {
  1090. args.push("--staging");
  1091. }
  1092. // For route53, add the credentials file as an environment variable,
  1093. // inheriting the process env
  1094. const opts = {};
  1095. if (certificate_id && dns_provider === "route53") {
  1096. opts.env = process.env;
  1097. opts.env.AWS_CONFIG_FILE = `/etc/letsencrypt/credentials/credentials-${certificate_id}`;
  1098. }
  1099. if (dns_provider === "duckdns") {
  1100. args.push("--dns-duckdns-no-txt-restore");
  1101. }
  1102. return { args: args, opts: opts };
  1103. },
  1104. getLiveCertPath: (certificateId) => {
  1105. return `/etc/letsencrypt/live/npm-${certificateId}`;
  1106. },
  1107. };
  1108. export default internalCertificate;