certificate.js 38 KB

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