certificate.js 36 KB

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