certificate.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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(() => {
  160. // 4. Request cert
  161. return internalCertificate.requestLetsEncryptSsl(certificate);
  162. })
  163. .then(() => {
  164. // 5. Remove LE config
  165. return internalNginx.deleteLetsEncryptRequestConfig(certificate);
  166. })
  167. .then(internalNginx.reload)
  168. .then(() => {
  169. // 6. Re-instate previously disabled hosts
  170. return internalCertificate.enableInUseHosts(in_use_result);
  171. })
  172. .then(() => {
  173. return certificate;
  174. })
  175. .catch((err) => {
  176. // In the event of failure, revert things and throw err back
  177. return internalNginx.deleteLetsEncryptRequestConfig(certificate)
  178. .then(() => {
  179. return internalCertificate.enableInUseHosts(in_use_result);
  180. })
  181. .then(internalNginx.reload)
  182. .then(() => {
  183. throw err;
  184. });
  185. });
  186. }
  187. })
  188. .then(() => {
  189. // At this point, the letsencrypt cert should exist on disk.
  190. // Lets get the expiry date from the file and update the row silently
  191. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  192. .then((cert_info) => {
  193. return certificateModel
  194. .query()
  195. .patchAndFetchById(certificate.id, {
  196. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  197. })
  198. .then((saved_row) => {
  199. // Add cert data for audit log
  200. saved_row.meta = _.assign({}, saved_row.meta, {
  201. letsencrypt_certificate: cert_info
  202. });
  203. return saved_row;
  204. });
  205. });
  206. }).catch(async (error) => {
  207. // Delete the certificate from the database if it was not created successfully
  208. await certificateModel
  209. .query()
  210. .deleteById(certificate.id);
  211. throw error;
  212. });
  213. } else {
  214. return certificate;
  215. }
  216. }).then((certificate) => {
  217. data.meta = _.assign({}, data.meta || {}, certificate.meta);
  218. // Add to audit log
  219. return internalAuditLog.add(access, {
  220. action: 'created',
  221. object_type: 'certificate',
  222. object_id: certificate.id,
  223. meta: data
  224. })
  225. .then(() => {
  226. return certificate;
  227. });
  228. });
  229. },
  230. /**
  231. * @param {Access} access
  232. * @param {Object} data
  233. * @param {Number} data.id
  234. * @param {String} [data.email]
  235. * @param {String} [data.name]
  236. * @return {Promise}
  237. */
  238. update: (access, data) => {
  239. return access.can('certificates:update', data.id)
  240. .then((/*access_data*/) => {
  241. return internalCertificate.get(access, {id: data.id});
  242. })
  243. .then((row) => {
  244. if (row.id !== data.id) {
  245. // Sanity check that something crazy hasn't happened
  246. throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  247. }
  248. return certificateModel
  249. .query()
  250. .omit(omissions())
  251. .patchAndFetchById(row.id, data)
  252. .then((saved_row) => {
  253. saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
  254. data.meta = internalCertificate.cleanMeta(data.meta);
  255. // Add row.nice_name for custom certs
  256. if (saved_row.provider === 'other') {
  257. data.nice_name = saved_row.nice_name;
  258. }
  259. // Add to audit log
  260. return internalAuditLog.add(access, {
  261. action: 'updated',
  262. object_type: 'certificate',
  263. object_id: row.id,
  264. meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
  265. })
  266. .then(() => {
  267. return _.omit(saved_row, omissions());
  268. });
  269. });
  270. });
  271. },
  272. /**
  273. * @param {Access} access
  274. * @param {Object} data
  275. * @param {Number} data.id
  276. * @param {Array} [data.expand]
  277. * @param {Array} [data.omit]
  278. * @return {Promise}
  279. */
  280. get: (access, data) => {
  281. if (typeof data === 'undefined') {
  282. data = {};
  283. }
  284. return access.can('certificates:get', data.id)
  285. .then((access_data) => {
  286. let query = certificateModel
  287. .query()
  288. .where('is_deleted', 0)
  289. .andWhere('id', data.id)
  290. .allowEager('[owner]')
  291. .first();
  292. if (access_data.permission_visibility !== 'all') {
  293. query.andWhere('owner_user_id', access.token.getUserId(1));
  294. }
  295. // Custom omissions
  296. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  297. query.omit(data.omit);
  298. }
  299. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  300. query.eager('[' + data.expand.join(', ') + ']');
  301. }
  302. return query;
  303. })
  304. .then((row) => {
  305. if (row) {
  306. return _.omit(row, omissions());
  307. } else {
  308. throw new error.ItemNotFoundError(data.id);
  309. }
  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) {
  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. .omit(['is_deleted'])
  430. .allowEager('[owner]')
  431. .orderBy('nice_name', 'ASC');
  432. if (access_data.permission_visibility !== 'all') {
  433. query.andWhere('owner_user_id', access.token.getUserId(1));
  434. }
  435. // Query is used for searching
  436. if (typeof search_query === 'string') {
  437. query.where(function () {
  438. this.where('name', 'like', '%' + search_query + '%');
  439. });
  440. }
  441. if (typeof expand !== 'undefined' && expand !== null) {
  442. query.eager('[' + expand.join(', ') + ']');
  443. }
  444. return query;
  445. });
  446. },
  447. /**
  448. * Report use
  449. *
  450. * @param {Number} user_id
  451. * @param {String} visibility
  452. * @returns {Promise}
  453. */
  454. getCount: (user_id, visibility) => {
  455. let query = certificateModel
  456. .query()
  457. .count('id as count')
  458. .where('is_deleted', 0);
  459. if (visibility !== 'all') {
  460. query.andWhere('owner_user_id', user_id);
  461. }
  462. return query.first()
  463. .then((row) => {
  464. return parseInt(row.count, 10);
  465. });
  466. },
  467. /**
  468. * @param {Object} certificate
  469. * @returns {Promise}
  470. */
  471. writeCustomCert: (certificate) => {
  472. logger.info('Writing Custom Certificate:', certificate);
  473. const dir = '/data/custom_ssl/npm-' + certificate.id;
  474. return new Promise((resolve, reject) => {
  475. if (certificate.provider === 'letsencrypt') {
  476. reject(new Error('Refusing to write letsencrypt certs here'));
  477. return;
  478. }
  479. let certData = certificate.meta.certificate;
  480. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  481. certData = certData + '\n' + certificate.meta.intermediate_certificate;
  482. }
  483. try {
  484. if (!fs.existsSync(dir)) {
  485. fs.mkdirSync(dir);
  486. }
  487. } catch (err) {
  488. reject(err);
  489. return;
  490. }
  491. fs.writeFile(dir + '/fullchain.pem', certData, function (err) {
  492. if (err) {
  493. reject(err);
  494. } else {
  495. resolve();
  496. }
  497. });
  498. })
  499. .then(() => {
  500. return new Promise((resolve, reject) => {
  501. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  502. if (err) {
  503. reject(err);
  504. } else {
  505. resolve();
  506. }
  507. });
  508. });
  509. });
  510. },
  511. /**
  512. * @param {Access} access
  513. * @param {Object} data
  514. * @param {Array} data.domain_names
  515. * @param {String} data.meta.letsencrypt_email
  516. * @param {Boolean} data.meta.letsencrypt_agree
  517. * @returns {Promise}
  518. */
  519. createQuickCertificate: (access, data) => {
  520. return internalCertificate.create(access, {
  521. provider: 'letsencrypt',
  522. domain_names: data.domain_names,
  523. meta: data.meta
  524. });
  525. },
  526. /**
  527. * Validates that the certs provided are good.
  528. * No access required here, nothing is changed or stored.
  529. *
  530. * @param {Object} data
  531. * @param {Object} data.files
  532. * @returns {Promise}
  533. */
  534. validate: (data) => {
  535. return new Promise((resolve) => {
  536. // Put file contents into an object
  537. let files = {};
  538. _.map(data.files, (file, name) => {
  539. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  540. files[name] = file.data.toString();
  541. }
  542. });
  543. resolve(files);
  544. })
  545. .then((files) => {
  546. // For each file, create a temp file and write the contents to it
  547. // Then test it depending on the file type
  548. let promises = [];
  549. _.map(files, (content, type) => {
  550. promises.push(new Promise((resolve) => {
  551. if (type === 'certificate_key') {
  552. resolve(internalCertificate.checkPrivateKey(content));
  553. } else {
  554. // this should handle `certificate` and intermediate certificate
  555. resolve(internalCertificate.getCertificateInfo(content, true));
  556. }
  557. }).then((res) => {
  558. return {[type]: res};
  559. }));
  560. });
  561. return Promise.all(promises)
  562. .then((files) => {
  563. let data = {};
  564. _.each(files, (file) => {
  565. data = _.assign({}, data, file);
  566. });
  567. return data;
  568. });
  569. });
  570. },
  571. /**
  572. * @param {Access} access
  573. * @param {Object} data
  574. * @param {Number} data.id
  575. * @param {Object} data.files
  576. * @returns {Promise}
  577. */
  578. upload: (access, data) => {
  579. return internalCertificate.get(access, {id: data.id})
  580. .then((row) => {
  581. if (row.provider !== 'other') {
  582. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  583. }
  584. return internalCertificate.validate(data)
  585. .then((validations) => {
  586. if (typeof validations.certificate === 'undefined') {
  587. throw new error.ValidationError('Certificate file was not provided');
  588. }
  589. _.map(data.files, (file, name) => {
  590. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  591. row.meta[name] = file.data.toString();
  592. }
  593. });
  594. // TODO: This uses a mysql only raw function that won't translate to postgres
  595. return internalCertificate.update(access, {
  596. id: data.id,
  597. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  598. domain_names: [validations.certificate.cn],
  599. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  600. })
  601. .then((certificate) => {
  602. console.log('ROWMETA:', row.meta);
  603. certificate.meta = row.meta;
  604. return internalCertificate.writeCustomCert(certificate);
  605. });
  606. })
  607. .then(() => {
  608. return _.pick(row.meta, internalCertificate.allowedSslFiles);
  609. });
  610. });
  611. },
  612. /**
  613. * Uses the openssl command to validate the private key.
  614. * It will save the file to disk first, then run commands on it, then delete the file.
  615. *
  616. * @param {String} private_key This is the entire key contents as a string
  617. */
  618. checkPrivateKey: (private_key) => {
  619. return tempWrite(private_key, '/tmp')
  620. .then((filepath) => {
  621. return new Promise((resolve, reject) => {
  622. const failTimeout = setTimeout(() => {
  623. reject(new error.ValidationError('Result Validation Error: Validation timed out. This could be due to the key being passphrase-protected.'));
  624. }, 10000);
  625. utils
  626. .exec('openssl pkey -in ' + filepath + ' -check -noout 2>&1 ')
  627. .then((result) => {
  628. clearTimeout(failTimeout);
  629. if (!result.toLowerCase().includes('key is valid')) {
  630. reject(new error.ValidationError('Result Validation Error: ' + result));
  631. }
  632. fs.unlinkSync(filepath);
  633. resolve(true);
  634. })
  635. .catch((err) => {
  636. clearTimeout(failTimeout);
  637. fs.unlinkSync(filepath);
  638. reject(new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err));
  639. });
  640. });
  641. });
  642. },
  643. /**
  644. * Uses the openssl command to both validate and get info out of the certificate.
  645. * It will save the file to disk first, then run commands on it, then delete the file.
  646. *
  647. * @param {String} certificate This is the entire cert contents as a string
  648. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  649. */
  650. getCertificateInfo: (certificate, throw_expired) => {
  651. return tempWrite(certificate, '/tmp')
  652. .then((filepath) => {
  653. return internalCertificate.getCertificateInfoFromFile(filepath, throw_expired)
  654. .then((certData) => {
  655. fs.unlinkSync(filepath);
  656. return certData;
  657. }).catch((err) => {
  658. fs.unlinkSync(filepath);
  659. throw err;
  660. });
  661. });
  662. },
  663. /**
  664. * Uses the openssl command to both validate and get info out of the certificate.
  665. * It will save the file to disk first, then run commands on it, then delete the file.
  666. *
  667. * @param {String} certificate_file The file location on disk
  668. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  669. */
  670. getCertificateInfoFromFile: (certificate_file, throw_expired) => {
  671. let certData = {};
  672. return utils.exec('openssl x509 -in ' + certificate_file + ' -subject -noout')
  673. .then((result) => {
  674. // subject=CN = something.example.com
  675. const regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  676. const match = regex.exec(result);
  677. if (typeof match[1] === 'undefined') {
  678. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  679. }
  680. certData['cn'] = match[1];
  681. })
  682. .then(() => {
  683. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  684. })
  685. .then((result) => {
  686. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  687. const regex = /^(?:issuer=)?(.*)$/gim;
  688. const match = regex.exec(result);
  689. if (typeof match[1] === 'undefined') {
  690. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  691. }
  692. certData['issuer'] = match[1];
  693. })
  694. .then(() => {
  695. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  696. })
  697. .then((result) => {
  698. // notBefore=Jul 14 04:04:29 2018 GMT
  699. // notAfter=Oct 12 04:04:29 2018 GMT
  700. let validFrom = null;
  701. let validTo = null;
  702. const lines = result.split('\n');
  703. lines.map(function (str) {
  704. const regex = /^(\S+)=(.*)$/gim;
  705. const match = regex.exec(str.trim());
  706. if (match && typeof match[2] !== 'undefined') {
  707. const date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  708. if (match[1].toLowerCase() === 'notbefore') {
  709. validFrom = date;
  710. } else if (match[1].toLowerCase() === 'notafter') {
  711. validTo = date;
  712. }
  713. }
  714. });
  715. if (!validFrom || !validTo) {
  716. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  717. }
  718. if (throw_expired && validTo < parseInt(moment().format('X'), 10)) {
  719. throw new error.ValidationError('Certificate has expired');
  720. }
  721. certData['dates'] = {
  722. from: validFrom,
  723. to: validTo
  724. };
  725. return certData;
  726. }).catch((err) => {
  727. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  728. });
  729. },
  730. /**
  731. * Cleans the ssl keys from the meta object and sets them to "true"
  732. *
  733. * @param {Object} meta
  734. * @param {Boolean} [remove]
  735. * @returns {Object}
  736. */
  737. cleanMeta: function (meta, remove) {
  738. internalCertificate.allowedSslFiles.map((key) => {
  739. if (typeof meta[key] !== 'undefined' && meta[key]) {
  740. if (remove) {
  741. delete meta[key];
  742. } else {
  743. meta[key] = true;
  744. }
  745. }
  746. });
  747. return meta;
  748. },
  749. /**
  750. * Request a certificate using the http challenge
  751. * @param {Object} certificate the certificate row
  752. * @returns {Promise}
  753. */
  754. requestLetsEncryptSsl: (certificate) => {
  755. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  756. const cmd = certbotCommand + ' certonly --non-interactive ' +
  757. '--config "' + letsencryptConfig + '" ' +
  758. '--cert-name "npm-' + certificate.id + '" ' +
  759. '--agree-tos ' +
  760. '--authenticator webroot ' +
  761. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  762. '--preferred-challenges "dns,http" ' +
  763. '--domains "' + certificate.domain_names.join(',') + '" ' +
  764. (letsencryptStaging ? '--staging' : '');
  765. logger.info('Command:', cmd);
  766. return utils.exec(cmd)
  767. .then((result) => {
  768. logger.success(result);
  769. return result;
  770. });
  771. },
  772. /**
  773. * @param {Object} certificate the certificate row
  774. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  775. * @param {String | null} credentials the content of this providers credentials file
  776. * @param {String} propagation_seconds the cloudflare api token
  777. * @returns {Promise}
  778. */
  779. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  780. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  781. if (!dns_plugin) {
  782. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  783. }
  784. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  785. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  786. const credentialsCmd = 'mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + certificate.meta.dns_provider_credentials.replace('\'', '\\\'') + '\' > \'' + credentialsLocation + '\' && chmod 600 \'' + credentialsLocation + '\'';
  787. const prepareCmd = 'pip install ' + dns_plugin.package_name + (dns_plugin.version_requirement || '') + ' ' + dns_plugin.dependencies;
  788. // Whether the plugin has a --<name>-credentials argument
  789. const hasConfigArg = certificate.meta.dns_provider !== 'route53';
  790. let mainCmd = certbotCommand + ' certonly --non-interactive ' +
  791. '--cert-name "npm-' + certificate.id + '" ' +
  792. '--agree-tos ' +
  793. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  794. '--domains "' + certificate.domain_names.join(',') + '" ' +
  795. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  796. (
  797. hasConfigArg
  798. ? '--' + dns_plugin.full_plugin_name + '-credentials "' + credentialsLocation + '"'
  799. : ''
  800. ) +
  801. (
  802. certificate.meta.propagation_seconds !== undefined
  803. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  804. : ''
  805. ) +
  806. (letsencryptStaging ? ' --staging' : '');
  807. // Prepend the path to the credentials file as an environment variable
  808. if (certificate.meta.dns_provider === 'route53') {
  809. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  810. }
  811. logger.info('Command:', `${credentialsCmd} && ${prepareCmd} && ${mainCmd}`);
  812. return utils.exec(credentialsCmd)
  813. .then(() => {
  814. return utils.exec(prepareCmd)
  815. .then(() => {
  816. return utils.exec(mainCmd)
  817. .then(async (result) => {
  818. logger.info(result);
  819. return result;
  820. });
  821. });
  822. }).catch(async (err) => {
  823. // Don't fail if file does not exist
  824. const delete_credentialsCmd = `rm -f '${credentialsLocation}' || true`;
  825. await utils.exec(delete_credentialsCmd);
  826. throw err;
  827. });
  828. },
  829. /**
  830. * @param {Access} access
  831. * @param {Object} data
  832. * @param {Number} data.id
  833. * @returns {Promise}
  834. */
  835. renew: (access, data) => {
  836. return access.can('certificates:update', data)
  837. .then(() => {
  838. return internalCertificate.get(access, data);
  839. })
  840. .then((certificate) => {
  841. if (certificate.provider === 'letsencrypt') {
  842. const renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  843. return renewMethod(certificate)
  844. .then(() => {
  845. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  846. })
  847. .then((cert_info) => {
  848. return certificateModel
  849. .query()
  850. .patchAndFetchById(certificate.id, {
  851. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  852. });
  853. })
  854. .then((updated_certificate) => {
  855. // Add to audit log
  856. return internalAuditLog.add(access, {
  857. action: 'renewed',
  858. object_type: 'certificate',
  859. object_id: updated_certificate.id,
  860. meta: updated_certificate
  861. })
  862. .then(() => {
  863. return updated_certificate;
  864. });
  865. });
  866. } else {
  867. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  868. }
  869. });
  870. },
  871. /**
  872. * @param {Object} certificate the certificate row
  873. * @returns {Promise}
  874. */
  875. renewLetsEncryptSsl: (certificate) => {
  876. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  877. const cmd = certbotCommand + ' renew --force-renewal --non-interactive ' +
  878. '--config "' + letsencryptConfig + '" ' +
  879. '--cert-name "npm-' + certificate.id + '" ' +
  880. '--preferred-challenges "dns,http" ' +
  881. '--disable-hook-validation ' +
  882. (letsencryptStaging ? '--staging' : '');
  883. logger.info('Command:', cmd);
  884. return utils.exec(cmd)
  885. .then((result) => {
  886. logger.info(result);
  887. return result;
  888. });
  889. },
  890. /**
  891. * @param {Object} certificate the certificate row
  892. * @returns {Promise}
  893. */
  894. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  895. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  896. if (!dns_plugin) {
  897. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  898. }
  899. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  900. let mainCmd = certbotCommand + ' renew --non-interactive ' +
  901. '--cert-name "npm-' + certificate.id + '" ' +
  902. '--disable-hook-validation' +
  903. (letsencryptStaging ? ' --staging' : '');
  904. // Prepend the path to the credentials file as an environment variable
  905. if (certificate.meta.dns_provider === 'route53') {
  906. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  907. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  908. }
  909. logger.info('Command:', mainCmd);
  910. return utils.exec(mainCmd)
  911. .then(async (result) => {
  912. logger.info(result);
  913. return result;
  914. });
  915. },
  916. /**
  917. * @param {Object} certificate the certificate row
  918. * @param {Boolean} [throw_errors]
  919. * @returns {Promise}
  920. */
  921. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  922. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  923. const mainCmd = certbotCommand + ' revoke --non-interactive ' +
  924. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  925. '--delete-after-revoke ' +
  926. (letsencryptStaging ? '--staging' : '');
  927. // Don't fail command if file does not exist
  928. const delete_credentialsCmd = `rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`;
  929. logger.info('Command:', mainCmd + '; ' + delete_credentialsCmd);
  930. return utils.exec(mainCmd)
  931. .then(async (result) => {
  932. await utils.exec(delete_credentialsCmd);
  933. logger.info(result);
  934. return result;
  935. })
  936. .catch((err) => {
  937. logger.error(err.message);
  938. if (throw_errors) {
  939. throw err;
  940. }
  941. });
  942. },
  943. /**
  944. * @param {Object} certificate
  945. * @returns {Boolean}
  946. */
  947. hasLetsEncryptSslCerts: (certificate) => {
  948. const letsencryptPath = '/etc/letsencrypt/live/npm-' + certificate.id;
  949. return fs.existsSync(letsencryptPath + '/fullchain.pem') && fs.existsSync(letsencryptPath + '/privkey.pem');
  950. },
  951. /**
  952. * @param {Object} in_use_result
  953. * @param {Number} in_use_result.total_count
  954. * @param {Array} in_use_result.proxy_hosts
  955. * @param {Array} in_use_result.redirection_hosts
  956. * @param {Array} in_use_result.dead_hosts
  957. */
  958. disableInUseHosts: (in_use_result) => {
  959. if (in_use_result.total_count) {
  960. let promises = [];
  961. if (in_use_result.proxy_hosts.length) {
  962. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  963. }
  964. if (in_use_result.redirection_hosts.length) {
  965. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  966. }
  967. if (in_use_result.dead_hosts.length) {
  968. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  969. }
  970. return Promise.all(promises);
  971. } else {
  972. return Promise.resolve();
  973. }
  974. },
  975. /**
  976. * @param {Object} in_use_result
  977. * @param {Number} in_use_result.total_count
  978. * @param {Array} in_use_result.proxy_hosts
  979. * @param {Array} in_use_result.redirection_hosts
  980. * @param {Array} in_use_result.dead_hosts
  981. */
  982. enableInUseHosts: (in_use_result) => {
  983. if (in_use_result.total_count) {
  984. let promises = [];
  985. if (in_use_result.proxy_hosts.length) {
  986. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  987. }
  988. if (in_use_result.redirection_hosts.length) {
  989. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  990. }
  991. if (in_use_result.dead_hosts.length) {
  992. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  993. }
  994. return Promise.all(promises);
  995. } else {
  996. return Promise.resolve();
  997. }
  998. },
  999. testHttpsChallenge: async (access, domains) => {
  1000. await access.can('certificates:list');
  1001. if (!isArray(domains)) {
  1002. throw new error.InternalValidationError('Domains must be an array of strings');
  1003. }
  1004. if (domains.length === 0) {
  1005. throw new error.InternalValidationError('No domains provided');
  1006. }
  1007. // Create a test challenge file
  1008. const testChallengeDir = '/data/letsencrypt-acme-challenge/.well-known/acme-challenge';
  1009. const testChallengeFile = testChallengeDir + '/test-challenge';
  1010. fs.mkdirSync(testChallengeDir, {recursive: true});
  1011. fs.writeFileSync(testChallengeFile, 'Success', {encoding: 'utf8'});
  1012. async function performTestForDomain (domain) {
  1013. logger.info('Testing http challenge for ' + domain);
  1014. const url = `http://${domain}/.well-known/acme-challenge/test-challenge`;
  1015. const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`;
  1016. const options = {
  1017. method: 'POST',
  1018. headers: {
  1019. 'Content-Type': 'application/x-www-form-urlencoded',
  1020. 'Content-Length': Buffer.byteLength(formBody)
  1021. }
  1022. };
  1023. const result = await new Promise((resolve) => {
  1024. const req = https.request('https://www.site24x7.com/tools/restapi-tester', options, function (res) {
  1025. let responseBody = '';
  1026. res.on('data', (chunk) => responseBody = responseBody + chunk);
  1027. res.on('end', function () {
  1028. const parsedBody = JSON.parse(responseBody + '');
  1029. if (res.statusCode !== 200) {
  1030. logger.warn(`Failed to test HTTP challenge for domain ${domain}`, res);
  1031. resolve(undefined);
  1032. }
  1033. resolve(parsedBody);
  1034. });
  1035. });
  1036. // Make sure to write the request body.
  1037. req.write(formBody);
  1038. req.end();
  1039. req.on('error', function (e) { logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e);
  1040. resolve(undefined); });
  1041. });
  1042. if (!result) {
  1043. // Some error occurred while trying to get the data
  1044. return 'failed';
  1045. } else if (`${result.responsecode}` === '200' && result.htmlresponse === 'Success') {
  1046. // Server exists and has responded with the correct data
  1047. return 'ok';
  1048. } else if (`${result.responsecode}` === '404') {
  1049. // Server exists but responded with a 404
  1050. return '404';
  1051. } else if (`${result.responsecode}` === '0' || result.reason.toLowerCase() === 'host unavailable') {
  1052. // Server does not exist at domain
  1053. return 'no-host';
  1054. } else {
  1055. // Other errors
  1056. return `other:${result.responsecode}`;
  1057. }
  1058. }
  1059. const results = {};
  1060. for (const domain of domains){
  1061. results[domain] = await performTestForDomain(domain);
  1062. }
  1063. // Remove the test challenge file
  1064. fs.unlinkSync(testChallengeFile);
  1065. return results;
  1066. }
  1067. };
  1068. module.exports = internalCertificate;