certificate.js 39 KB

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