certificate.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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 error = require('../lib/error');
  8. const utils = require('../lib/utils');
  9. const certificateModel = require('../models/certificate');
  10. const dnsPlugins = require('../global/certbot-dns-plugins');
  11. const internalAuditLog = require('./audit-log');
  12. const internalNginx = require('./nginx');
  13. const internalHost = require('./host');
  14. const letsencryptStaging = process.env.NODE_ENV !== 'production';
  15. const letsencryptConfig = '/etc/letsencrypt.ini';
  16. const certbotCommand = 'certbot';
  17. const archiver = require('archiver');
  18. const path = require('path');
  19. const { isArray } = require('lodash');
  20. function omissions() {
  21. return ['is_deleted'];
  22. }
  23. const internalCertificate = {
  24. allowedSslFiles: ['certificate', 'certificate_key', 'intermediate_certificate'],
  25. intervalTimeout: 1000 * 60 * 60, // 1 hour
  26. interval: null,
  27. intervalProcessing: false,
  28. initTimer: () => {
  29. logger.info('Let\'s Encrypt Renewal Timer initialized');
  30. internalCertificate.interval = setInterval(internalCertificate.processExpiringHosts, internalCertificate.intervalTimeout);
  31. // And do this now as well
  32. internalCertificate.processExpiringHosts();
  33. },
  34. /**
  35. * Triggered by a timer, this will check for expiring hosts and renew their ssl certs if required
  36. */
  37. processExpiringHosts: () => {
  38. if (!internalCertificate.intervalProcessing) {
  39. internalCertificate.intervalProcessing = true;
  40. logger.info('Renewing SSL certs close to expiry...');
  41. const cmd = certbotCommand + ' renew --non-interactive --quiet ' +
  42. '--config "' + letsencryptConfig + '" ' +
  43. '--preferred-challenges "dns,http" ' +
  44. '--disable-hook-validation ' +
  45. (letsencryptStaging ? '--staging' : '');
  46. return utils.exec(cmd)
  47. .then((result) => {
  48. if (result) {
  49. logger.info('Renew Result: ' + result);
  50. }
  51. return internalNginx.reload()
  52. .then(() => {
  53. logger.info('Renew Complete');
  54. return result;
  55. });
  56. })
  57. .then(() => {
  58. // Now go and fetch all the letsencrypt certs from the db and query the files and update expiry times
  59. return certificateModel
  60. .query()
  61. .where('is_deleted', 0)
  62. .andWhere('provider', 'letsencrypt')
  63. .then((certificates) => {
  64. if (certificates && certificates.length) {
  65. let promises = [];
  66. certificates.map(function (certificate) {
  67. promises.push(
  68. internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  69. .then((cert_info) => {
  70. return certificateModel
  71. .query()
  72. .where('id', certificate.id)
  73. .andWhere('provider', 'letsencrypt')
  74. .patch({
  75. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  76. });
  77. })
  78. .catch((err) => {
  79. // Don't want to stop the train here, just log the error
  80. logger.error(err.message);
  81. })
  82. );
  83. });
  84. return Promise.all(promises);
  85. }
  86. });
  87. })
  88. .then(() => {
  89. internalCertificate.intervalProcessing = false;
  90. })
  91. .catch((err) => {
  92. logger.error(err);
  93. internalCertificate.intervalProcessing = false;
  94. });
  95. }
  96. },
  97. /**
  98. * @param {Access} access
  99. * @param {Object} data
  100. * @returns {Promise}
  101. */
  102. create: (access, data) => {
  103. return access.can('certificates:create', data)
  104. .then(() => {
  105. data.owner_user_id = access.token.getUserId(1);
  106. if (data.provider === 'letsencrypt') {
  107. data.nice_name = data.domain_names.join(', ');
  108. }
  109. return certificateModel
  110. .query()
  111. .omit(omissions())
  112. .insertAndFetch(data);
  113. })
  114. .then((certificate) => {
  115. if (certificate.provider === 'letsencrypt') {
  116. // Request a new Cert from LE. Let the fun begin.
  117. // 1. Find out any hosts that are using any of the hostnames in this cert
  118. // 2. Disable them in nginx temporarily
  119. // 3. Generate the LE config
  120. // 4. Request cert
  121. // 5. Remove LE config
  122. // 6. Re-instate previously disabled hosts
  123. // 1. Find out any hosts that are using any of the hostnames in this cert
  124. return internalHost.getHostsWithDomains(certificate.domain_names)
  125. .then((in_use_result) => {
  126. // 2. Disable them in nginx temporarily
  127. return internalCertificate.disableInUseHosts(in_use_result)
  128. .then(() => {
  129. return in_use_result;
  130. });
  131. })
  132. .then((in_use_result) => {
  133. // With DNS challenge no config is needed, so skip 3 and 5.
  134. if (certificate.meta.dns_challenge) {
  135. return internalNginx.reload().then(() => {
  136. // 4. Request cert
  137. return internalCertificate.requestLetsEncryptSslWithDnsChallenge(certificate);
  138. })
  139. .then(internalNginx.reload)
  140. .then(() => {
  141. // 6. Re-instate previously disabled hosts
  142. return internalCertificate.enableInUseHosts(in_use_result);
  143. })
  144. .then(() => {
  145. return certificate;
  146. })
  147. .catch((err) => {
  148. // In the event of failure, revert things and throw err back
  149. return internalCertificate.enableInUseHosts(in_use_result)
  150. .then(internalNginx.reload)
  151. .then(() => {
  152. throw err;
  153. });
  154. });
  155. } else {
  156. // 3. Generate the LE config
  157. return internalNginx.generateLetsEncryptRequestConfig(certificate)
  158. .then(internalNginx.reload)
  159. .then(async() => await new Promise((r) => setTimeout(r, 5000)))
  160. .then(() => {
  161. // 4. Request cert
  162. return internalCertificate.requestLetsEncryptSsl(certificate);
  163. })
  164. .then(() => {
  165. // 5. Remove LE config
  166. return internalNginx.deleteLetsEncryptRequestConfig(certificate);
  167. })
  168. .then(internalNginx.reload)
  169. .then(() => {
  170. // 6. Re-instate previously disabled hosts
  171. return internalCertificate.enableInUseHosts(in_use_result);
  172. })
  173. .then(() => {
  174. return certificate;
  175. })
  176. .catch((err) => {
  177. // In the event of failure, revert things and throw err back
  178. return internalNginx.deleteLetsEncryptRequestConfig(certificate)
  179. .then(() => {
  180. return internalCertificate.enableInUseHosts(in_use_result);
  181. })
  182. .then(internalNginx.reload)
  183. .then(() => {
  184. throw err;
  185. });
  186. });
  187. }
  188. })
  189. .then(() => {
  190. // At this point, the letsencrypt cert should exist on disk.
  191. // Lets get the expiry date from the file and update the row silently
  192. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  193. .then((cert_info) => {
  194. return certificateModel
  195. .query()
  196. .patchAndFetchById(certificate.id, {
  197. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  198. })
  199. .then((saved_row) => {
  200. // Add cert data for audit log
  201. saved_row.meta = _.assign({}, saved_row.meta, {
  202. letsencrypt_certificate: cert_info
  203. });
  204. return saved_row;
  205. });
  206. });
  207. }).catch(async (error) => {
  208. // Delete the certificate from the database if it was not created successfully
  209. await certificateModel
  210. .query()
  211. .deleteById(certificate.id);
  212. throw error;
  213. });
  214. } else {
  215. return certificate;
  216. }
  217. }).then((certificate) => {
  218. data.meta = _.assign({}, data.meta || {}, certificate.meta);
  219. // Add to audit log
  220. return internalAuditLog.add(access, {
  221. action: 'created',
  222. object_type: 'certificate',
  223. object_id: certificate.id,
  224. meta: data
  225. })
  226. .then(() => {
  227. return certificate;
  228. });
  229. });
  230. },
  231. /**
  232. * @param {Access} access
  233. * @param {Object} data
  234. * @param {Number} data.id
  235. * @param {String} [data.email]
  236. * @param {String} [data.name]
  237. * @return {Promise}
  238. */
  239. update: (access, data) => {
  240. return access.can('certificates:update', data.id)
  241. .then((/*access_data*/) => {
  242. return internalCertificate.get(access, {id: data.id});
  243. })
  244. .then((row) => {
  245. if (row.id !== data.id) {
  246. // Sanity check that something crazy hasn't happened
  247. throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  248. }
  249. return certificateModel
  250. .query()
  251. .omit(omissions())
  252. .patchAndFetchById(row.id, data)
  253. .then((saved_row) => {
  254. saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
  255. data.meta = internalCertificate.cleanMeta(data.meta);
  256. // Add row.nice_name for custom certs
  257. if (saved_row.provider === 'other') {
  258. data.nice_name = saved_row.nice_name;
  259. }
  260. // Add to audit log
  261. return internalAuditLog.add(access, {
  262. action: 'updated',
  263. object_type: 'certificate',
  264. object_id: row.id,
  265. meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
  266. })
  267. .then(() => {
  268. return _.omit(saved_row, omissions());
  269. });
  270. });
  271. });
  272. },
  273. /**
  274. * @param {Access} access
  275. * @param {Object} data
  276. * @param {Number} data.id
  277. * @param {Array} [data.expand]
  278. * @param {Array} [data.omit]
  279. * @return {Promise}
  280. */
  281. get: (access, data) => {
  282. if (typeof data === 'undefined') {
  283. data = {};
  284. }
  285. return access.can('certificates:get', data.id)
  286. .then((access_data) => {
  287. let query = certificateModel
  288. .query()
  289. .where('is_deleted', 0)
  290. .andWhere('id', data.id)
  291. .allowEager('[owner]')
  292. .first();
  293. if (access_data.permission_visibility !== 'all') {
  294. query.andWhere('owner_user_id', access.token.getUserId(1));
  295. }
  296. // Custom omissions
  297. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  298. query.omit(data.omit);
  299. }
  300. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  301. query.eager('[' + data.expand.join(', ') + ']');
  302. }
  303. return query;
  304. })
  305. .then((row) => {
  306. if (row) {
  307. return _.omit(row, omissions());
  308. } else {
  309. throw new error.ItemNotFoundError(data.id);
  310. }
  311. });
  312. },
  313. /**
  314. * @param {Access} access
  315. * @param {Object} data
  316. * @param {Number} data.id
  317. * @returns {Promise}
  318. */
  319. download: (access, data) => {
  320. return new Promise((resolve, reject) => {
  321. access.can('certificates:get', data)
  322. .then(() => {
  323. return internalCertificate.get(access, data);
  324. })
  325. .then((certificate) => {
  326. if (certificate.provider === 'letsencrypt') {
  327. const zipDirectory = '/etc/letsencrypt/live/npm-' + data.id;
  328. if (!fs.existsSync(zipDirectory)) {
  329. throw new error.ItemNotFoundError('Certificate ' + certificate.nice_name + ' does not exists');
  330. }
  331. let certFiles = fs.readdirSync(zipDirectory)
  332. .filter((fn) => fn.endsWith('.pem'))
  333. .map((fn) => fs.realpathSync(path.join(zipDirectory, fn)));
  334. const downloadName = 'npm-' + data.id + '-' + `${Date.now()}.zip`;
  335. const opName = '/tmp/' + downloadName;
  336. internalCertificate.zipFiles(certFiles, opName)
  337. .then(() => {
  338. logger.debug('zip completed : ', opName);
  339. const resp = {
  340. fileName: opName
  341. };
  342. resolve(resp);
  343. }).catch((err) => reject(err));
  344. } else {
  345. throw new error.ValidationError('Only Let\'sEncrypt certificates can be downloaded');
  346. }
  347. }).catch((err) => reject(err));
  348. });
  349. },
  350. /**
  351. * @param {String} source
  352. * @param {String} out
  353. * @returns {Promise}
  354. */
  355. zipFiles(source, out) {
  356. const archive = archiver('zip', { zlib: { level: 9 } });
  357. const stream = fs.createWriteStream(out);
  358. return new Promise((resolve, reject) => {
  359. source
  360. .map((fl) => {
  361. let fileName = path.basename(fl);
  362. logger.debug(fl, 'added to certificate zip');
  363. archive.file(fl, { name: fileName });
  364. });
  365. archive
  366. .on('error', (err) => reject(err))
  367. .pipe(stream);
  368. stream.on('close', () => resolve());
  369. archive.finalize();
  370. });
  371. },
  372. /**
  373. * @param {Access} access
  374. * @param {Object} data
  375. * @param {Number} data.id
  376. * @param {String} [data.reason]
  377. * @returns {Promise}
  378. */
  379. delete: (access, data) => {
  380. return access.can('certificates:delete', data.id)
  381. .then(() => {
  382. return internalCertificate.get(access, {id: data.id});
  383. })
  384. .then((row) => {
  385. if (!row) {
  386. throw new error.ItemNotFoundError(data.id);
  387. }
  388. return certificateModel
  389. .query()
  390. .where('id', row.id)
  391. .patch({
  392. is_deleted: 1
  393. })
  394. .then(() => {
  395. // Add to audit log
  396. row.meta = internalCertificate.cleanMeta(row.meta);
  397. return internalAuditLog.add(access, {
  398. action: 'deleted',
  399. object_type: 'certificate',
  400. object_id: row.id,
  401. meta: _.omit(row, omissions())
  402. });
  403. })
  404. .then(() => {
  405. if (row.provider === 'letsencrypt') {
  406. // Revoke the cert
  407. return internalCertificate.revokeLetsEncryptSsl(row);
  408. }
  409. });
  410. })
  411. .then(() => {
  412. return true;
  413. });
  414. },
  415. /**
  416. * All Certs
  417. *
  418. * @param {Access} access
  419. * @param {Array} [expand]
  420. * @param {String} [search_query]
  421. * @returns {Promise}
  422. */
  423. getAll: (access, expand, search_query) => {
  424. return access.can('certificates:list')
  425. .then((access_data) => {
  426. let query = certificateModel
  427. .query()
  428. .where('is_deleted', 0)
  429. .groupBy('id')
  430. .omit(['is_deleted'])
  431. .allowEager('[owner]')
  432. .orderBy('nice_name', 'ASC');
  433. if (access_data.permission_visibility !== 'all') {
  434. query.andWhere('owner_user_id', access.token.getUserId(1));
  435. }
  436. // Query is used for searching
  437. if (typeof search_query === 'string') {
  438. query.where(function () {
  439. this.where('name', 'like', '%' + search_query + '%');
  440. });
  441. }
  442. if (typeof expand !== 'undefined' && expand !== null) {
  443. query.eager('[' + expand.join(', ') + ']');
  444. }
  445. return query;
  446. });
  447. },
  448. /**
  449. * Report use
  450. *
  451. * @param {Number} user_id
  452. * @param {String} visibility
  453. * @returns {Promise}
  454. */
  455. getCount: (user_id, visibility) => {
  456. let query = certificateModel
  457. .query()
  458. .count('id as count')
  459. .where('is_deleted', 0);
  460. if (visibility !== 'all') {
  461. query.andWhere('owner_user_id', user_id);
  462. }
  463. return query.first()
  464. .then((row) => {
  465. return parseInt(row.count, 10);
  466. });
  467. },
  468. /**
  469. * @param {Object} certificate
  470. * @returns {Promise}
  471. */
  472. writeCustomCert: (certificate) => {
  473. logger.info('Writing Custom Certificate:', certificate);
  474. const dir = '/data/custom_ssl/npm-' + certificate.id;
  475. return new Promise((resolve, reject) => {
  476. if (certificate.provider === 'letsencrypt') {
  477. reject(new Error('Refusing to write letsencrypt certs here'));
  478. return;
  479. }
  480. let certData = certificate.meta.certificate;
  481. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  482. certData = certData + '\n' + certificate.meta.intermediate_certificate;
  483. }
  484. try {
  485. if (!fs.existsSync(dir)) {
  486. fs.mkdirSync(dir);
  487. }
  488. } catch (err) {
  489. reject(err);
  490. return;
  491. }
  492. fs.writeFile(dir + '/fullchain.pem', certData, function (err) {
  493. if (err) {
  494. reject(err);
  495. } else {
  496. resolve();
  497. }
  498. });
  499. })
  500. .then(() => {
  501. return new Promise((resolve, reject) => {
  502. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  503. if (err) {
  504. reject(err);
  505. } else {
  506. resolve();
  507. }
  508. });
  509. });
  510. });
  511. },
  512. /**
  513. * @param {Access} access
  514. * @param {Object} data
  515. * @param {Array} data.domain_names
  516. * @param {String} data.meta.letsencrypt_email
  517. * @param {Boolean} data.meta.letsencrypt_agree
  518. * @returns {Promise}
  519. */
  520. createQuickCertificate: (access, data) => {
  521. return internalCertificate.create(access, {
  522. provider: 'letsencrypt',
  523. domain_names: data.domain_names,
  524. meta: data.meta
  525. });
  526. },
  527. /**
  528. * Validates that the certs provided are good.
  529. * No access required here, nothing is changed or stored.
  530. *
  531. * @param {Object} data
  532. * @param {Object} data.files
  533. * @returns {Promise}
  534. */
  535. validate: (data) => {
  536. return new Promise((resolve) => {
  537. // Put file contents into an object
  538. let files = {};
  539. _.map(data.files, (file, name) => {
  540. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  541. files[name] = file.data.toString();
  542. }
  543. });
  544. resolve(files);
  545. })
  546. .then((files) => {
  547. // For each file, create a temp file and write the contents to it
  548. // Then test it depending on the file type
  549. let promises = [];
  550. _.map(files, (content, type) => {
  551. promises.push(new Promise((resolve) => {
  552. if (type === 'certificate_key') {
  553. resolve(internalCertificate.checkPrivateKey(content));
  554. } else {
  555. // this should handle `certificate` and intermediate certificate
  556. resolve(internalCertificate.getCertificateInfo(content, true));
  557. }
  558. }).then((res) => {
  559. return {[type]: res};
  560. }));
  561. });
  562. return Promise.all(promises)
  563. .then((files) => {
  564. let data = {};
  565. _.each(files, (file) => {
  566. data = _.assign({}, data, file);
  567. });
  568. return data;
  569. });
  570. });
  571. },
  572. /**
  573. * @param {Access} access
  574. * @param {Object} data
  575. * @param {Number} data.id
  576. * @param {Object} data.files
  577. * @returns {Promise}
  578. */
  579. upload: (access, data) => {
  580. return internalCertificate.get(access, {id: data.id})
  581. .then((row) => {
  582. if (row.provider !== 'other') {
  583. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  584. }
  585. return internalCertificate.validate(data)
  586. .then((validations) => {
  587. if (typeof validations.certificate === 'undefined') {
  588. throw new error.ValidationError('Certificate file was not provided');
  589. }
  590. _.map(data.files, (file, name) => {
  591. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  592. row.meta[name] = file.data.toString();
  593. }
  594. });
  595. // TODO: This uses a mysql only raw function that won't translate to postgres
  596. return internalCertificate.update(access, {
  597. id: data.id,
  598. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  599. domain_names: [validations.certificate.cn],
  600. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  601. })
  602. .then((certificate) => {
  603. console.log('ROWMETA:', row.meta);
  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. '--cert-name "npm-' + certificate.id + '" ' +
  760. '--agree-tos ' +
  761. '--authenticator webroot ' +
  762. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  763. '--preferred-challenges "dns,http" ' +
  764. '--domains "' + certificate.domain_names.join(',') + '" ' +
  765. (letsencryptStaging ? '--staging' : '');
  766. logger.info('Command:', cmd);
  767. return utils.exec(cmd)
  768. .then((result) => {
  769. logger.success(result);
  770. return result;
  771. });
  772. },
  773. /**
  774. * @param {Object} certificate the certificate row
  775. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  776. * @param {String | null} credentials the content of this providers credentials file
  777. * @param {String} propagation_seconds the cloudflare api token
  778. * @returns {Promise}
  779. */
  780. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  781. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  782. if (!dns_plugin) {
  783. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  784. }
  785. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  786. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  787. // Escape single quotes and backslashes
  788. const escapedCredentials = certificate.meta.dns_provider_credentials.replaceAll('\'', '\\\'').replaceAll('\\', '\\\\');
  789. const credentialsCmd = 'mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + escapedCredentials + '\' > \'' + credentialsLocation + '\' && chmod 600 \'' + credentialsLocation + '\'';
  790. const prepareCmd = 'pip install ' + dns_plugin.package_name + (dns_plugin.version_requirement || '') + ' ' + dns_plugin.dependencies;
  791. // Whether the plugin has a --<name>-credentials argument
  792. const hasConfigArg = certificate.meta.dns_provider !== 'route53';
  793. let mainCmd = certbotCommand + ' certonly ' +
  794. '--config "' + letsencryptConfig + '" ' +
  795. '--cert-name "npm-' + certificate.id + '" ' +
  796. '--agree-tos ' +
  797. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  798. '--domains "' + certificate.domain_names.join(',') + '" ' +
  799. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  800. (
  801. hasConfigArg
  802. ? '--' + dns_plugin.full_plugin_name + '-credentials "' + credentialsLocation + '"'
  803. : ''
  804. ) +
  805. (
  806. certificate.meta.propagation_seconds !== undefined
  807. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  808. : ''
  809. ) +
  810. (letsencryptStaging ? ' --staging' : '');
  811. // Prepend the path to the credentials file as an environment variable
  812. if (certificate.meta.dns_provider === 'route53') {
  813. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  814. }
  815. logger.info('Command:', `${credentialsCmd} && ${prepareCmd} && ${mainCmd}`);
  816. return utils.exec(credentialsCmd)
  817. .then(() => {
  818. return utils.exec(prepareCmd)
  819. .then(() => {
  820. return utils.exec(mainCmd)
  821. .then(async (result) => {
  822. logger.info(result);
  823. return result;
  824. });
  825. });
  826. }).catch(async (err) => {
  827. // Don't fail if file does not exist
  828. const delete_credentialsCmd = `rm -f '${credentialsLocation}' || true`;
  829. await utils.exec(delete_credentialsCmd);
  830. throw err;
  831. });
  832. },
  833. /**
  834. * @param {Access} access
  835. * @param {Object} data
  836. * @param {Number} data.id
  837. * @returns {Promise}
  838. */
  839. renew: (access, data) => {
  840. return access.can('certificates:update', data)
  841. .then(() => {
  842. return internalCertificate.get(access, data);
  843. })
  844. .then((certificate) => {
  845. if (certificate.provider === 'letsencrypt') {
  846. const renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  847. return renewMethod(certificate)
  848. .then(() => {
  849. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  850. })
  851. .then((cert_info) => {
  852. return certificateModel
  853. .query()
  854. .patchAndFetchById(certificate.id, {
  855. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  856. });
  857. })
  858. .then((updated_certificate) => {
  859. // Add to audit log
  860. return internalAuditLog.add(access, {
  861. action: 'renewed',
  862. object_type: 'certificate',
  863. object_id: updated_certificate.id,
  864. meta: updated_certificate
  865. })
  866. .then(() => {
  867. return updated_certificate;
  868. });
  869. });
  870. } else {
  871. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  872. }
  873. });
  874. },
  875. /**
  876. * @param {Object} certificate the certificate row
  877. * @returns {Promise}
  878. */
  879. renewLetsEncryptSsl: (certificate) => {
  880. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  881. const cmd = certbotCommand + ' renew --force-renewal ' +
  882. '--config "' + letsencryptConfig + '" ' +
  883. '--cert-name "npm-' + certificate.id + '" ' +
  884. '--preferred-challenges "dns,http" ' +
  885. '--no-random-sleep-on-renew ' +
  886. '--disable-hook-validation ' +
  887. (letsencryptStaging ? '--staging' : '');
  888. logger.info('Command:', cmd);
  889. return utils.exec(cmd)
  890. .then((result) => {
  891. logger.info(result);
  892. return result;
  893. });
  894. },
  895. /**
  896. * @param {Object} certificate the certificate row
  897. * @returns {Promise}
  898. */
  899. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  900. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  901. if (!dns_plugin) {
  902. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  903. }
  904. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  905. let mainCmd = certbotCommand + ' renew ' +
  906. '--config "' + letsencryptConfig + '" ' +
  907. '--cert-name "npm-' + certificate.id + '" ' +
  908. '--disable-hook-validation ' +
  909. '--no-random-sleep-on-renew ' +
  910. (letsencryptStaging ? ' --staging' : '');
  911. // Prepend the path to the credentials file as an environment variable
  912. if (certificate.meta.dns_provider === 'route53') {
  913. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  914. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  915. }
  916. logger.info('Command:', mainCmd);
  917. return utils.exec(mainCmd)
  918. .then(async (result) => {
  919. logger.info(result);
  920. return result;
  921. });
  922. },
  923. /**
  924. * @param {Object} certificate the certificate row
  925. * @param {Boolean} [throw_errors]
  926. * @returns {Promise}
  927. */
  928. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  929. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  930. const mainCmd = certbotCommand + ' revoke ' +
  931. '--config "' + letsencryptConfig + '" ' +
  932. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  933. '--delete-after-revoke ' +
  934. (letsencryptStaging ? '--staging' : '');
  935. // Don't fail command if file does not exist
  936. const delete_credentialsCmd = `rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`;
  937. logger.info('Command:', mainCmd + '; ' + delete_credentialsCmd);
  938. return utils.exec(mainCmd)
  939. .then(async (result) => {
  940. await utils.exec(delete_credentialsCmd);
  941. logger.info(result);
  942. return result;
  943. })
  944. .catch((err) => {
  945. logger.error(err.message);
  946. if (throw_errors) {
  947. throw err;
  948. }
  949. });
  950. },
  951. /**
  952. * @param {Object} certificate
  953. * @returns {Boolean}
  954. */
  955. hasLetsEncryptSslCerts: (certificate) => {
  956. const letsencryptPath = '/etc/letsencrypt/live/npm-' + certificate.id;
  957. return fs.existsSync(letsencryptPath + '/fullchain.pem') && fs.existsSync(letsencryptPath + '/privkey.pem');
  958. },
  959. /**
  960. * @param {Object} in_use_result
  961. * @param {Number} in_use_result.total_count
  962. * @param {Array} in_use_result.proxy_hosts
  963. * @param {Array} in_use_result.redirection_hosts
  964. * @param {Array} in_use_result.dead_hosts
  965. */
  966. disableInUseHosts: (in_use_result) => {
  967. if (in_use_result.total_count) {
  968. let promises = [];
  969. if (in_use_result.proxy_hosts.length) {
  970. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  971. }
  972. if (in_use_result.redirection_hosts.length) {
  973. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  974. }
  975. if (in_use_result.dead_hosts.length) {
  976. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  977. }
  978. return Promise.all(promises);
  979. } else {
  980. return Promise.resolve();
  981. }
  982. },
  983. /**
  984. * @param {Object} in_use_result
  985. * @param {Number} in_use_result.total_count
  986. * @param {Array} in_use_result.proxy_hosts
  987. * @param {Array} in_use_result.redirection_hosts
  988. * @param {Array} in_use_result.dead_hosts
  989. */
  990. enableInUseHosts: (in_use_result) => {
  991. if (in_use_result.total_count) {
  992. let promises = [];
  993. if (in_use_result.proxy_hosts.length) {
  994. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  995. }
  996. if (in_use_result.redirection_hosts.length) {
  997. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  998. }
  999. if (in_use_result.dead_hosts.length) {
  1000. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  1001. }
  1002. return Promise.all(promises);
  1003. } else {
  1004. return Promise.resolve();
  1005. }
  1006. },
  1007. testHttpsChallenge: async (access, domains) => {
  1008. await access.can('certificates:list');
  1009. if (!isArray(domains)) {
  1010. throw new error.InternalValidationError('Domains must be an array of strings');
  1011. }
  1012. if (domains.length === 0) {
  1013. throw new error.InternalValidationError('No domains provided');
  1014. }
  1015. // Create a test challenge file
  1016. const testChallengeDir = '/data/letsencrypt-acme-challenge/.well-known/acme-challenge';
  1017. const testChallengeFile = testChallengeDir + '/test-challenge';
  1018. fs.mkdirSync(testChallengeDir, {recursive: true});
  1019. fs.writeFileSync(testChallengeFile, 'Success', {encoding: 'utf8'});
  1020. async function performTestForDomain (domain) {
  1021. logger.info('Testing http challenge for ' + domain);
  1022. const url = `http://${domain}/.well-known/acme-challenge/test-challenge`;
  1023. const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`;
  1024. const options = {
  1025. method: 'POST',
  1026. headers: {
  1027. 'Content-Type': 'application/x-www-form-urlencoded',
  1028. 'Content-Length': Buffer.byteLength(formBody)
  1029. }
  1030. };
  1031. const result = await new Promise((resolve) => {
  1032. const req = https.request('https://www.site24x7.com/tools/restapi-tester', options, function (res) {
  1033. let responseBody = '';
  1034. res.on('data', (chunk) => responseBody = responseBody + chunk);
  1035. res.on('end', function () {
  1036. const parsedBody = JSON.parse(responseBody + '');
  1037. if (res.statusCode !== 200) {
  1038. logger.warn(`Failed to test HTTP challenge for domain ${domain}`, res);
  1039. resolve(undefined);
  1040. }
  1041. resolve(parsedBody);
  1042. });
  1043. });
  1044. // Make sure to write the request body.
  1045. req.write(formBody);
  1046. req.end();
  1047. req.on('error', function (e) { logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e);
  1048. resolve(undefined); });
  1049. });
  1050. if (!result) {
  1051. // Some error occurred while trying to get the data
  1052. return 'failed';
  1053. } else if (`${result.responsecode}` === '200' && result.htmlresponse === 'Success') {
  1054. // Server exists and has responded with the correct data
  1055. return 'ok';
  1056. } else if (`${result.responsecode}` === '200') {
  1057. // Server exists but has responded with wrong data
  1058. logger.info(`HTTP challenge test failed for domain ${domain} because of invalid returned data:`, result.htmlresponse);
  1059. return 'wrong-data';
  1060. } else if (`${result.responsecode}` === '404') {
  1061. // Server exists but responded with a 404
  1062. logger.info(`HTTP challenge test failed for domain ${domain} because code 404 was returned`);
  1063. return '404';
  1064. } else if (`${result.responsecode}` === '0' || (typeof result.reason === 'string' && result.reason.toLowerCase() === 'host unavailable')) {
  1065. // Server does not exist at domain
  1066. logger.info(`HTTP challenge test failed for domain ${domain} the host was not found`);
  1067. return 'no-host';
  1068. } else {
  1069. // Other errors
  1070. logger.info(`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`);
  1071. return `other:${result.responsecode}`;
  1072. }
  1073. }
  1074. const results = {};
  1075. for (const domain of domains){
  1076. results[domain] = await performTestForDomain(domain);
  1077. }
  1078. // Remove the test challenge file
  1079. fs.unlinkSync(testChallengeFile);
  1080. return results;
  1081. }
  1082. };
  1083. module.exports = internalCertificate;