certificate.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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 logger = require('../logger').ssl;
  7. const config = require('../lib/config');
  8. const error = require('../lib/error');
  9. const utils = require('../lib/utils');
  10. const certificateModel = require('../models/certificate');
  11. const dnsPlugins = require('../global/certbot-dns-plugins');
  12. const internalAuditLog = require('./audit-log');
  13. const internalNginx = require('./nginx');
  14. const internalHost = require('./host');
  15. const archiver = require('archiver');
  16. const path = require('path');
  17. const { isArray } = require('lodash');
  18. const letsencryptStaging = config.useLetsencryptStaging();
  19. const letsencryptConfig = '/etc/letsencrypt.ini';
  20. const certbotCommand = 'certbot';
  21. function omissions() {
  22. return ['is_deleted'];
  23. }
  24. const internalCertificate = {
  25. allowedSslFiles: ['certificate', 'certificate_key', 'intermediate_certificate'],
  26. intervalTimeout: 1000 * 60 * 60, // 1 hour
  27. interval: null,
  28. intervalProcessing: false,
  29. initTimer: () => {
  30. logger.info('Let\'s Encrypt Renewal Timer initialized');
  31. internalCertificate.interval = setInterval(internalCertificate.processExpiringHosts, internalCertificate.intervalTimeout);
  32. // And do this now as well
  33. internalCertificate.processExpiringHosts();
  34. },
  35. /**
  36. * Triggered by a timer, this will check for expiring hosts and renew their ssl certs if required
  37. */
  38. processExpiringHosts: () => {
  39. if (!internalCertificate.intervalProcessing) {
  40. internalCertificate.intervalProcessing = true;
  41. logger.info('Renewing SSL certs close to expiry...');
  42. const cmd = certbotCommand + ' renew --non-interactive --quiet ' +
  43. '--config "' + letsencryptConfig + '" ' +
  44. '--work-dir "/tmp/letsencrypt-lib" ' +
  45. '--logs-dir "/tmp/letsencrypt-log" ' +
  46. '--preferred-challenges "dns,http" ' +
  47. '--disable-hook-validation ' +
  48. (letsencryptStaging ? '--staging' : '');
  49. return utils.exec(cmd)
  50. .then((result) => {
  51. if (result) {
  52. logger.info('Renew Result: ' + result);
  53. }
  54. return internalNginx.reload()
  55. .then(() => {
  56. logger.info('Renew Complete');
  57. return result;
  58. });
  59. })
  60. .then(() => {
  61. // Now go and fetch all the letsencrypt certs from the db and query the files and update expiry times
  62. return certificateModel
  63. .query()
  64. .where('is_deleted', 0)
  65. .andWhere('provider', 'letsencrypt')
  66. .then((certificates) => {
  67. if (certificates && certificates.length) {
  68. let promises = [];
  69. certificates.map(function (certificate) {
  70. promises.push(
  71. internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  72. .then((cert_info) => {
  73. return certificateModel
  74. .query()
  75. .where('id', certificate.id)
  76. .andWhere('provider', 'letsencrypt')
  77. .patch({
  78. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  79. });
  80. })
  81. .catch((err) => {
  82. // Don't want to stop the train here, just log the error
  83. logger.error(err.message);
  84. })
  85. );
  86. });
  87. return Promise.all(promises);
  88. }
  89. });
  90. })
  91. .then(() => {
  92. internalCertificate.intervalProcessing = false;
  93. })
  94. .catch((err) => {
  95. logger.error(err);
  96. internalCertificate.intervalProcessing = false;
  97. });
  98. }
  99. },
  100. /**
  101. * @param {Access} access
  102. * @param {Object} data
  103. * @returns {Promise}
  104. */
  105. create: (access, data) => {
  106. return access.can('certificates:create', data)
  107. .then(() => {
  108. data.owner_user_id = access.token.getUserId(1);
  109. if (data.provider === 'letsencrypt') {
  110. data.nice_name = data.domain_names.join(', ');
  111. }
  112. return certificateModel
  113. .query()
  114. .insertAndFetch(data)
  115. .then(utils.omitRow(omissions()));
  116. })
  117. .then((certificate) => {
  118. if (certificate.provider === 'letsencrypt') {
  119. // Request a new Cert from LE. Let the fun begin.
  120. // 1. Find out any hosts that are using any of the hostnames in this cert
  121. // 2. Disable them in nginx temporarily
  122. // 3. Generate the LE config
  123. // 4. Request cert
  124. // 5. Remove LE config
  125. // 6. Re-instate previously disabled hosts
  126. // 1. Find out any hosts that are using any of the hostnames in this cert
  127. return internalHost.getHostsWithDomains(certificate.domain_names)
  128. .then((in_use_result) => {
  129. // 2. Disable them in nginx temporarily
  130. return internalCertificate.disableInUseHosts(in_use_result)
  131. .then(() => {
  132. return in_use_result;
  133. });
  134. })
  135. .then((in_use_result) => {
  136. // With DNS challenge no config is needed, so skip 3 and 5.
  137. if (certificate.meta.dns_challenge) {
  138. return internalNginx.reload().then(() => {
  139. // 4. Request cert
  140. return internalCertificate.requestLetsEncryptSslWithDnsChallenge(certificate);
  141. })
  142. .then(internalNginx.reload)
  143. .then(() => {
  144. // 6. Re-instate previously disabled hosts
  145. return internalCertificate.enableInUseHosts(in_use_result);
  146. })
  147. .then(() => {
  148. return certificate;
  149. })
  150. .catch((err) => {
  151. // In the event of failure, revert things and throw err back
  152. return internalCertificate.enableInUseHosts(in_use_result)
  153. .then(internalNginx.reload)
  154. .then(() => {
  155. throw err;
  156. });
  157. });
  158. } else {
  159. // 3. Generate the LE config
  160. return internalNginx.generateLetsEncryptRequestConfig(certificate)
  161. .then(internalNginx.reload)
  162. .then(async() => await new Promise((r) => setTimeout(r, 5000)))
  163. .then(() => {
  164. // 4. Request cert
  165. return internalCertificate.requestLetsEncryptSsl(certificate);
  166. })
  167. .then(() => {
  168. // 5. Remove LE config
  169. return internalNginx.deleteLetsEncryptRequestConfig(certificate);
  170. })
  171. .then(internalNginx.reload)
  172. .then(() => {
  173. // 6. Re-instate previously disabled hosts
  174. return internalCertificate.enableInUseHosts(in_use_result);
  175. })
  176. .then(() => {
  177. return certificate;
  178. })
  179. .catch((err) => {
  180. // In the event of failure, revert things and throw err back
  181. return internalNginx.deleteLetsEncryptRequestConfig(certificate)
  182. .then(() => {
  183. return internalCertificate.enableInUseHosts(in_use_result);
  184. })
  185. .then(internalNginx.reload)
  186. .then(() => {
  187. throw err;
  188. });
  189. });
  190. }
  191. })
  192. .then(() => {
  193. // At this point, the letsencrypt cert should exist on disk.
  194. // Lets get the expiry date from the file and update the row silently
  195. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  196. .then((cert_info) => {
  197. return certificateModel
  198. .query()
  199. .patchAndFetchById(certificate.id, {
  200. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  201. })
  202. .then((saved_row) => {
  203. // Add cert data for audit log
  204. saved_row.meta = _.assign({}, saved_row.meta, {
  205. letsencrypt_certificate: cert_info
  206. });
  207. return saved_row;
  208. });
  209. });
  210. }).catch(async (error) => {
  211. // Delete the certificate from the database if it was not created successfully
  212. await certificateModel
  213. .query()
  214. .deleteById(certificate.id);
  215. throw error;
  216. });
  217. } else {
  218. return certificate;
  219. }
  220. }).then((certificate) => {
  221. data.meta = _.assign({}, data.meta || {}, certificate.meta);
  222. // Add to audit log
  223. return internalAuditLog.add(access, {
  224. action: 'created',
  225. object_type: 'certificate',
  226. object_id: certificate.id,
  227. meta: data
  228. })
  229. .then(() => {
  230. return certificate;
  231. });
  232. });
  233. },
  234. /**
  235. * @param {Access} access
  236. * @param {Object} data
  237. * @param {Number} data.id
  238. * @param {String} [data.email]
  239. * @param {String} [data.name]
  240. * @return {Promise}
  241. */
  242. update: (access, data) => {
  243. return access.can('certificates:update', data.id)
  244. .then((/*access_data*/) => {
  245. return internalCertificate.get(access, {id: data.id});
  246. })
  247. .then((row) => {
  248. if (row.id !== data.id) {
  249. // Sanity check that something crazy hasn't happened
  250. throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  251. }
  252. return certificateModel
  253. .query()
  254. .patchAndFetchById(row.id, data)
  255. .then(utils.omitRow(omissions()))
  256. .then((saved_row) => {
  257. saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
  258. data.meta = internalCertificate.cleanMeta(data.meta);
  259. // Add row.nice_name for custom certs
  260. if (saved_row.provider === 'other') {
  261. data.nice_name = saved_row.nice_name;
  262. }
  263. // Add to audit log
  264. return internalAuditLog.add(access, {
  265. action: 'updated',
  266. object_type: 'certificate',
  267. object_id: row.id,
  268. meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
  269. })
  270. .then(() => {
  271. return saved_row;
  272. });
  273. });
  274. });
  275. },
  276. /**
  277. * @param {Access} access
  278. * @param {Object} data
  279. * @param {Number} data.id
  280. * @param {Array} [data.expand]
  281. * @param {Array} [data.omit]
  282. * @return {Promise}
  283. */
  284. get: (access, data) => {
  285. if (typeof data === 'undefined') {
  286. data = {};
  287. }
  288. return access.can('certificates:get', data.id)
  289. .then((access_data) => {
  290. let query = certificateModel
  291. .query()
  292. .where('is_deleted', 0)
  293. .andWhere('id', data.id)
  294. .allowGraph('[owner]')
  295. .first();
  296. if (access_data.permission_visibility !== 'all') {
  297. query.andWhere('owner_user_id', access.token.getUserId(1));
  298. }
  299. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  300. query.withGraphFetched('[' + data.expand.join(', ') + ']');
  301. }
  302. return query.then(utils.omitRow(omissions()));
  303. })
  304. .then((row) => {
  305. if (!row) {
  306. throw new error.ItemNotFoundError(data.id);
  307. }
  308. // Custom omissions
  309. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  310. row = _.omit(row, data.omit);
  311. }
  312. return row;
  313. });
  314. },
  315. /**
  316. * @param {Access} access
  317. * @param {Object} data
  318. * @param {Number} data.id
  319. * @returns {Promise}
  320. */
  321. download: (access, data) => {
  322. return new Promise((resolve, reject) => {
  323. access.can('certificates:get', data)
  324. .then(() => {
  325. return internalCertificate.get(access, data);
  326. })
  327. .then((certificate) => {
  328. if (certificate.provider === 'letsencrypt') {
  329. const zipDirectory = '/etc/letsencrypt/live/npm-' + data.id;
  330. if (!fs.existsSync(zipDirectory)) {
  331. throw new error.ItemNotFoundError('Certificate ' + certificate.nice_name + ' does not exists');
  332. }
  333. let certFiles = fs.readdirSync(zipDirectory)
  334. .filter((fn) => fn.endsWith('.pem'))
  335. .map((fn) => fs.realpathSync(path.join(zipDirectory, fn)));
  336. const downloadName = 'npm-' + data.id + '-' + `${Date.now()}.zip`;
  337. const opName = '/tmp/' + downloadName;
  338. internalCertificate.zipFiles(certFiles, opName)
  339. .then(() => {
  340. logger.debug('zip completed : ', opName);
  341. const resp = {
  342. fileName: opName
  343. };
  344. resolve(resp);
  345. }).catch((err) => reject(err));
  346. } else {
  347. throw new error.ValidationError('Only Let\'sEncrypt certificates can be downloaded');
  348. }
  349. }).catch((err) => reject(err));
  350. });
  351. },
  352. /**
  353. * @param {String} source
  354. * @param {String} out
  355. * @returns {Promise}
  356. */
  357. zipFiles(source, out) {
  358. const archive = archiver('zip', { zlib: { level: 9 } });
  359. const stream = fs.createWriteStream(out);
  360. return new Promise((resolve, reject) => {
  361. source
  362. .map((fl) => {
  363. let fileName = path.basename(fl);
  364. logger.debug(fl, 'added to certificate zip');
  365. archive.file(fl, { name: fileName });
  366. });
  367. archive
  368. .on('error', (err) => reject(err))
  369. .pipe(stream);
  370. stream.on('close', () => resolve());
  371. archive.finalize();
  372. });
  373. },
  374. /**
  375. * @param {Access} access
  376. * @param {Object} data
  377. * @param {Number} data.id
  378. * @param {String} [data.reason]
  379. * @returns {Promise}
  380. */
  381. delete: (access, data) => {
  382. return access.can('certificates:delete', data.id)
  383. .then(() => {
  384. return internalCertificate.get(access, {id: data.id});
  385. })
  386. .then((row) => {
  387. if (!row) {
  388. throw new error.ItemNotFoundError(data.id);
  389. }
  390. return certificateModel
  391. .query()
  392. .where('id', row.id)
  393. .patch({
  394. is_deleted: 1
  395. })
  396. .then(() => {
  397. // Add to audit log
  398. row.meta = internalCertificate.cleanMeta(row.meta);
  399. return internalAuditLog.add(access, {
  400. action: 'deleted',
  401. object_type: 'certificate',
  402. object_id: row.id,
  403. meta: _.omit(row, omissions())
  404. });
  405. })
  406. .then(() => {
  407. if (row.provider === 'letsencrypt') {
  408. // Revoke the cert
  409. return internalCertificate.revokeLetsEncryptSsl(row);
  410. }
  411. });
  412. })
  413. .then(() => {
  414. return true;
  415. });
  416. },
  417. /**
  418. * All Certs
  419. *
  420. * @param {Access} access
  421. * @param {Array} [expand]
  422. * @param {String} [search_query]
  423. * @returns {Promise}
  424. */
  425. getAll: (access, expand, search_query) => {
  426. return access.can('certificates:list')
  427. .then((access_data) => {
  428. let query = certificateModel
  429. .query()
  430. .where('is_deleted', 0)
  431. .groupBy('id')
  432. .allowGraph('[owner]')
  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. // subject=CN = something.example.com
  676. const regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  677. const match = regex.exec(result);
  678. if (typeof match[1] === 'undefined') {
  679. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  680. }
  681. certData['cn'] = match[1];
  682. })
  683. .then(() => {
  684. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  685. })
  686. .then((result) => {
  687. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  688. const regex = /^(?:issuer=)?(.*)$/gim;
  689. const match = regex.exec(result);
  690. if (typeof match[1] === 'undefined') {
  691. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  692. }
  693. certData['issuer'] = match[1];
  694. })
  695. .then(() => {
  696. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  697. })
  698. .then((result) => {
  699. // notBefore=Jul 14 04:04:29 2018 GMT
  700. // notAfter=Oct 12 04:04:29 2018 GMT
  701. let validFrom = null;
  702. let validTo = null;
  703. const lines = result.split('\n');
  704. lines.map(function (str) {
  705. const regex = /^(\S+)=(.*)$/gim;
  706. const match = regex.exec(str.trim());
  707. if (match && typeof match[2] !== 'undefined') {
  708. const date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  709. if (match[1].toLowerCase() === 'notbefore') {
  710. validFrom = date;
  711. } else if (match[1].toLowerCase() === 'notafter') {
  712. validTo = date;
  713. }
  714. }
  715. });
  716. if (!validFrom || !validTo) {
  717. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  718. }
  719. if (throw_expired && validTo < parseInt(moment().format('X'), 10)) {
  720. throw new error.ValidationError('Certificate has expired');
  721. }
  722. certData['dates'] = {
  723. from: validFrom,
  724. to: validTo
  725. };
  726. return certData;
  727. }).catch((err) => {
  728. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  729. });
  730. },
  731. /**
  732. * Cleans the ssl keys from the meta object and sets them to "true"
  733. *
  734. * @param {Object} meta
  735. * @param {Boolean} [remove]
  736. * @returns {Object}
  737. */
  738. cleanMeta: function (meta, remove) {
  739. internalCertificate.allowedSslFiles.map((key) => {
  740. if (typeof meta[key] !== 'undefined' && meta[key]) {
  741. if (remove) {
  742. delete meta[key];
  743. } else {
  744. meta[key] = true;
  745. }
  746. }
  747. });
  748. return meta;
  749. },
  750. /**
  751. * Request a certificate using the http challenge
  752. * @param {Object} certificate the certificate row
  753. * @returns {Promise}
  754. */
  755. requestLetsEncryptSsl: (certificate) => {
  756. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  757. const cmd = certbotCommand + ' certonly ' +
  758. '--config "' + letsencryptConfig + '" ' +
  759. '--work-dir "/tmp/letsencrypt-lib" ' +
  760. '--logs-dir "/tmp/letsencrypt-log" ' +
  761. '--cert-name "npm-' + certificate.id + '" ' +
  762. '--agree-tos ' +
  763. '--authenticator webroot ' +
  764. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  765. '--preferred-challenges "dns,http" ' +
  766. '--domains "' + certificate.domain_names.join(',') + '" ' +
  767. (letsencryptStaging ? '--staging' : '');
  768. logger.info('Command:', cmd);
  769. return utils.exec(cmd)
  770. .then((result) => {
  771. logger.success(result);
  772. return result;
  773. });
  774. },
  775. /**
  776. * @param {Object} certificate the certificate row
  777. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  778. * @param {String | null} credentials the content of this providers credentials file
  779. * @param {String} propagation_seconds the cloudflare api token
  780. * @returns {Promise}
  781. */
  782. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  783. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  784. if (!dns_plugin) {
  785. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  786. }
  787. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  788. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  789. // Escape single quotes and backslashes
  790. const escapedCredentials = certificate.meta.dns_provider_credentials.replaceAll('\'', '\\\'').replaceAll('\\', '\\\\');
  791. const credentialsCmd = 'mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + escapedCredentials + '\' > \'' + credentialsLocation + '\' && chmod 600 \'' + credentialsLocation + '\'';
  792. // we call `. /opt/certbot/bin/activate` (`.` is alternative to `source` in dash) to access certbot venv
  793. const prepareCmd = '. /opt/certbot/bin/activate && pip install --no-cache-dir ' + dns_plugin.package_name + (dns_plugin.version_requirement || '') + ' ' + dns_plugin.dependencies + ' && deactivate';
  794. // Whether the plugin has a --<name>-credentials argument
  795. const hasConfigArg = certificate.meta.dns_provider !== 'route53';
  796. let mainCmd = certbotCommand + ' certonly ' +
  797. '--config "' + letsencryptConfig + '" ' +
  798. '--work-dir "/tmp/letsencrypt-lib" ' +
  799. '--logs-dir "/tmp/letsencrypt-log" ' +
  800. '--cert-name "npm-' + certificate.id + '" ' +
  801. '--agree-tos ' +
  802. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  803. '--domains "' + certificate.domain_names.join(',') + '" ' +
  804. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  805. (
  806. hasConfigArg
  807. ? '--' + dns_plugin.full_plugin_name + '-credentials "' + credentialsLocation + '"'
  808. : ''
  809. ) +
  810. (
  811. certificate.meta.propagation_seconds !== undefined
  812. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  813. : ''
  814. ) +
  815. (letsencryptStaging ? ' --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:', `${credentialsCmd} && ${prepareCmd} && ${mainCmd}`);
  824. return utils.exec(credentialsCmd)
  825. .then(() => {
  826. return utils.exec(prepareCmd)
  827. .then(() => {
  828. return utils.exec(mainCmd)
  829. .then(async (result) => {
  830. logger.info(result);
  831. return result;
  832. });
  833. });
  834. }).catch(async (err) => {
  835. // Don't fail if file does not exist
  836. const delete_credentialsCmd = `rm -f '${credentialsLocation}' || true`;
  837. await utils.exec(delete_credentialsCmd);
  838. throw err;
  839. });
  840. },
  841. /**
  842. * @param {Access} access
  843. * @param {Object} data
  844. * @param {Number} data.id
  845. * @returns {Promise}
  846. */
  847. renew: (access, data) => {
  848. return access.can('certificates:update', data)
  849. .then(() => {
  850. return internalCertificate.get(access, data);
  851. })
  852. .then((certificate) => {
  853. if (certificate.provider === 'letsencrypt') {
  854. const renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  855. return renewMethod(certificate)
  856. .then(() => {
  857. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  858. })
  859. .then((cert_info) => {
  860. return certificateModel
  861. .query()
  862. .patchAndFetchById(certificate.id, {
  863. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  864. });
  865. })
  866. .then((updated_certificate) => {
  867. // Add to audit log
  868. return internalAuditLog.add(access, {
  869. action: 'renewed',
  870. object_type: 'certificate',
  871. object_id: updated_certificate.id,
  872. meta: updated_certificate
  873. })
  874. .then(() => {
  875. return updated_certificate;
  876. });
  877. });
  878. } else {
  879. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  880. }
  881. });
  882. },
  883. /**
  884. * @param {Object} certificate the certificate row
  885. * @returns {Promise}
  886. */
  887. renewLetsEncryptSsl: (certificate) => {
  888. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  889. const cmd = certbotCommand + ' renew --force-renewal ' +
  890. '--config "' + letsencryptConfig + '" ' +
  891. '--work-dir "/tmp/letsencrypt-lib" ' +
  892. '--logs-dir "/tmp/letsencrypt-log" ' +
  893. '--cert-name "npm-' + certificate.id + '" ' +
  894. '--preferred-challenges "dns,http" ' +
  895. '--no-random-sleep-on-renew ' +
  896. '--disable-hook-validation ' +
  897. (letsencryptStaging ? '--staging' : '');
  898. logger.info('Command:', cmd);
  899. return utils.exec(cmd)
  900. .then((result) => {
  901. logger.info(result);
  902. return result;
  903. });
  904. },
  905. /**
  906. * @param {Object} certificate the certificate row
  907. * @returns {Promise}
  908. */
  909. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  910. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  911. if (!dns_plugin) {
  912. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  913. }
  914. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  915. let mainCmd = certbotCommand + ' renew --force-renewal ' +
  916. '--config "' + letsencryptConfig + '" ' +
  917. '--work-dir "/tmp/letsencrypt-lib" ' +
  918. '--logs-dir "/tmp/letsencrypt-log" ' +
  919. '--cert-name "npm-' + certificate.id + '" ' +
  920. '--disable-hook-validation ' +
  921. '--no-random-sleep-on-renew ' +
  922. (letsencryptStaging ? ' --staging' : '');
  923. // Prepend the path to the credentials file as an environment variable
  924. if (certificate.meta.dns_provider === 'route53') {
  925. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  926. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  927. }
  928. logger.info('Command:', mainCmd);
  929. return utils.exec(mainCmd)
  930. .then(async (result) => {
  931. logger.info(result);
  932. return result;
  933. });
  934. },
  935. /**
  936. * @param {Object} certificate the certificate row
  937. * @param {Boolean} [throw_errors]
  938. * @returns {Promise}
  939. */
  940. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  941. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  942. const mainCmd = certbotCommand + ' revoke ' +
  943. '--config "' + letsencryptConfig + '" ' +
  944. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  945. '--delete-after-revoke ' +
  946. (letsencryptStaging ? '--staging' : '');
  947. // Don't fail command if file does not exist
  948. const delete_credentialsCmd = `rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`;
  949. logger.info('Command:', mainCmd + '; ' + delete_credentialsCmd);
  950. return utils.exec(mainCmd)
  951. .then(async (result) => {
  952. await utils.exec(delete_credentialsCmd);
  953. logger.info(result);
  954. return result;
  955. })
  956. .catch((err) => {
  957. logger.error(err.message);
  958. if (throw_errors) {
  959. throw err;
  960. }
  961. });
  962. },
  963. /**
  964. * @param {Object} certificate
  965. * @returns {Boolean}
  966. */
  967. hasLetsEncryptSslCerts: (certificate) => {
  968. const letsencryptPath = '/etc/letsencrypt/live/npm-' + certificate.id;
  969. return fs.existsSync(letsencryptPath + '/fullchain.pem') && fs.existsSync(letsencryptPath + '/privkey.pem');
  970. },
  971. /**
  972. * @param {Object} in_use_result
  973. * @param {Number} in_use_result.total_count
  974. * @param {Array} in_use_result.proxy_hosts
  975. * @param {Array} in_use_result.redirection_hosts
  976. * @param {Array} in_use_result.dead_hosts
  977. */
  978. disableInUseHosts: (in_use_result) => {
  979. if (in_use_result.total_count) {
  980. let promises = [];
  981. if (in_use_result.proxy_hosts.length) {
  982. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  983. }
  984. if (in_use_result.redirection_hosts.length) {
  985. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  986. }
  987. if (in_use_result.dead_hosts.length) {
  988. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  989. }
  990. return Promise.all(promises);
  991. } else {
  992. return Promise.resolve();
  993. }
  994. },
  995. /**
  996. * @param {Object} in_use_result
  997. * @param {Number} in_use_result.total_count
  998. * @param {Array} in_use_result.proxy_hosts
  999. * @param {Array} in_use_result.redirection_hosts
  1000. * @param {Array} in_use_result.dead_hosts
  1001. */
  1002. enableInUseHosts: (in_use_result) => {
  1003. if (in_use_result.total_count) {
  1004. let promises = [];
  1005. if (in_use_result.proxy_hosts.length) {
  1006. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  1007. }
  1008. if (in_use_result.redirection_hosts.length) {
  1009. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  1010. }
  1011. if (in_use_result.dead_hosts.length) {
  1012. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  1013. }
  1014. return Promise.all(promises);
  1015. } else {
  1016. return Promise.resolve();
  1017. }
  1018. },
  1019. testHttpsChallenge: async (access, domains) => {
  1020. await access.can('certificates:list');
  1021. if (!isArray(domains)) {
  1022. throw new error.InternalValidationError('Domains must be an array of strings');
  1023. }
  1024. if (domains.length === 0) {
  1025. throw new error.InternalValidationError('No domains provided');
  1026. }
  1027. // Create a test challenge file
  1028. const testChallengeDir = '/data/letsencrypt-acme-challenge/.well-known/acme-challenge';
  1029. const testChallengeFile = testChallengeDir + '/test-challenge';
  1030. fs.mkdirSync(testChallengeDir, {recursive: true});
  1031. fs.writeFileSync(testChallengeFile, 'Success', {encoding: 'utf8'});
  1032. async function performTestForDomain (domain) {
  1033. logger.info('Testing http challenge for ' + domain);
  1034. const url = `http://${domain}/.well-known/acme-challenge/test-challenge`;
  1035. const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`;
  1036. const options = {
  1037. method: 'POST',
  1038. headers: {
  1039. 'User-Agent': 'Mozilla/5.0',
  1040. 'Content-Type': 'application/x-www-form-urlencoded',
  1041. 'Content-Length': Buffer.byteLength(formBody)
  1042. }
  1043. };
  1044. const result = await new Promise((resolve) => {
  1045. const req = https.request('https://www.site24x7.com/tools/restapi-tester', options, function (res) {
  1046. let responseBody = '';
  1047. res.on('data', (chunk) => responseBody = responseBody + chunk);
  1048. res.on('end', function () {
  1049. try {
  1050. const parsedBody = JSON.parse(responseBody + '');
  1051. if (res.statusCode !== 200) {
  1052. logger.warn(`Failed to test HTTP challenge for domain ${domain} because HTTP status code ${res.statusCode} was returned: ${parsedBody.message}`);
  1053. resolve(undefined);
  1054. } else {
  1055. resolve(parsedBody);
  1056. }
  1057. } catch (err) {
  1058. if (res.statusCode !== 200) {
  1059. logger.warn(`Failed to test HTTP challenge for domain ${domain} because HTTP status code ${res.statusCode} was returned`);
  1060. } else {
  1061. logger.warn(`Failed to test HTTP challenge for domain ${domain} because response failed to be parsed: ${err.message}`);
  1062. }
  1063. resolve(undefined);
  1064. }
  1065. });
  1066. });
  1067. // Make sure to write the request body.
  1068. req.write(formBody);
  1069. req.end();
  1070. req.on('error', function (e) { logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e);
  1071. resolve(undefined); });
  1072. });
  1073. if (!result) {
  1074. // Some error occurred while trying to get the data
  1075. return 'failed';
  1076. } else if (result.error) {
  1077. logger.info(`HTTP challenge test failed for domain ${domain} because error was returned: ${result.error.msg}`);
  1078. return `other:${result.error.msg}`;
  1079. } else if (`${result.responsecode}` === '200' && result.htmlresponse === 'Success') {
  1080. // Server exists and has responded with the correct data
  1081. return 'ok';
  1082. } else if (`${result.responsecode}` === '200') {
  1083. // Server exists but has responded with wrong data
  1084. logger.info(`HTTP challenge test failed for domain ${domain} because of invalid returned data:`, result.htmlresponse);
  1085. return 'wrong-data';
  1086. } else if (`${result.responsecode}` === '404') {
  1087. // Server exists but responded with a 404
  1088. logger.info(`HTTP challenge test failed for domain ${domain} because code 404 was returned`);
  1089. return '404';
  1090. } else if (`${result.responsecode}` === '0' || (typeof result.reason === 'string' && result.reason.toLowerCase() === 'host unavailable')) {
  1091. // Server does not exist at domain
  1092. logger.info(`HTTP challenge test failed for domain ${domain} the host was not found`);
  1093. return 'no-host';
  1094. } else {
  1095. // Other errors
  1096. logger.info(`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`);
  1097. return `other:${result.responsecode}`;
  1098. }
  1099. }
  1100. const results = {};
  1101. for (const domain of domains){
  1102. results[domain] = await performTestForDomain(domain);
  1103. }
  1104. // Remove the test challenge file
  1105. fs.unlinkSync(testChallengeFile);
  1106. return results;
  1107. }
  1108. };
  1109. module.exports = internalCertificate;