certificate.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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. .insertAndFetch(data)
  112. .then(utils.omitRow(omissions()));
  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. .patchAndFetchById(row.id, data)
  252. .then(utils.omitRow(omissions()))
  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 saved_row;
  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. .allowGraph('[owner]')
  292. .first();
  293. if (access_data.permission_visibility !== 'all') {
  294. query.andWhere('owner_user_id', access.token.getUserId(1));
  295. }
  296. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  297. query.withGraphFetched('[' + data.expand.join(', ') + ']');
  298. }
  299. return query.then(utils.omitRow(omissions()));
  300. })
  301. .then((row) => {
  302. if (!row) {
  303. throw new error.ItemNotFoundError(data.id);
  304. }
  305. // Custom omissions
  306. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  307. row = _.omit(row, data.omit);
  308. }
  309. return row;
  310. });
  311. },
  312. /**
  313. * @param {Access} access
  314. * @param {Object} data
  315. * @param {Number} data.id
  316. * @returns {Promise}
  317. */
  318. download: (access, data) => {
  319. return new Promise((resolve, reject) => {
  320. access.can('certificates:get', data)
  321. .then(() => {
  322. return internalCertificate.get(access, data);
  323. })
  324. .then((certificate) => {
  325. if (certificate.provider === 'letsencrypt') {
  326. const zipDirectory = '/etc/letsencrypt/live/npm-' + data.id;
  327. if (!fs.existsSync(zipDirectory)) {
  328. throw new error.ItemNotFoundError('Certificate ' + certificate.nice_name + ' does not exists');
  329. }
  330. let certFiles = fs.readdirSync(zipDirectory)
  331. .filter((fn) => fn.endsWith('.pem'))
  332. .map((fn) => fs.realpathSync(path.join(zipDirectory, fn)));
  333. const downloadName = 'npm-' + data.id + '-' + `${Date.now()}.zip`;
  334. const opName = '/tmp/' + downloadName;
  335. internalCertificate.zipFiles(certFiles, opName)
  336. .then(() => {
  337. logger.debug('zip completed : ', opName);
  338. const resp = {
  339. fileName: opName
  340. };
  341. resolve(resp);
  342. }).catch((err) => reject(err));
  343. } else {
  344. throw new error.ValidationError('Only Let\'sEncrypt certificates can be downloaded');
  345. }
  346. }).catch((err) => reject(err));
  347. });
  348. },
  349. /**
  350. * @param {String} source
  351. * @param {String} out
  352. * @returns {Promise}
  353. */
  354. zipFiles(source, out) {
  355. const archive = archiver('zip', { zlib: { level: 9 } });
  356. const stream = fs.createWriteStream(out);
  357. return new Promise((resolve, reject) => {
  358. source
  359. .map((fl) => {
  360. let fileName = path.basename(fl);
  361. logger.debug(fl, 'added to certificate zip');
  362. archive.file(fl, { name: fileName });
  363. });
  364. archive
  365. .on('error', (err) => reject(err))
  366. .pipe(stream);
  367. stream.on('close', () => resolve());
  368. archive.finalize();
  369. });
  370. },
  371. /**
  372. * @param {Access} access
  373. * @param {Object} data
  374. * @param {Number} data.id
  375. * @param {String} [data.reason]
  376. * @returns {Promise}
  377. */
  378. delete: (access, data) => {
  379. return access.can('certificates:delete', data.id)
  380. .then(() => {
  381. return internalCertificate.get(access, {id: data.id});
  382. })
  383. .then((row) => {
  384. if (!row) {
  385. throw new error.ItemNotFoundError(data.id);
  386. }
  387. return certificateModel
  388. .query()
  389. .where('id', row.id)
  390. .patch({
  391. is_deleted: 1
  392. })
  393. .then(() => {
  394. // Add to audit log
  395. row.meta = internalCertificate.cleanMeta(row.meta);
  396. return internalAuditLog.add(access, {
  397. action: 'deleted',
  398. object_type: 'certificate',
  399. object_id: row.id,
  400. meta: _.omit(row, omissions())
  401. });
  402. })
  403. .then(() => {
  404. if (row.provider === 'letsencrypt') {
  405. // Revoke the cert
  406. return internalCertificate.revokeLetsEncryptSsl(row);
  407. }
  408. });
  409. })
  410. .then(() => {
  411. return true;
  412. });
  413. },
  414. /**
  415. * All Certs
  416. *
  417. * @param {Access} access
  418. * @param {Array} [expand]
  419. * @param {String} [search_query]
  420. * @returns {Promise}
  421. */
  422. getAll: (access, expand, search_query) => {
  423. return access.can('certificates:list')
  424. .then((access_data) => {
  425. let query = certificateModel
  426. .query()
  427. .where('is_deleted', 0)
  428. .groupBy('id')
  429. .allowGraph('[owner]')
  430. .orderBy('nice_name', 'ASC');
  431. if (access_data.permission_visibility !== 'all') {
  432. query.andWhere('owner_user_id', access.token.getUserId(1));
  433. }
  434. // Query is used for searching
  435. if (typeof search_query === 'string') {
  436. query.where(function () {
  437. this.where('nice_name', 'like', '%' + search_query + '%');
  438. });
  439. }
  440. if (typeof expand !== 'undefined' && expand !== null) {
  441. query.withGraphFetched('[' + expand.join(', ') + ']');
  442. }
  443. return query.then(utils.omitRows(omissions()));
  444. });
  445. },
  446. /**
  447. * Report use
  448. *
  449. * @param {Number} user_id
  450. * @param {String} visibility
  451. * @returns {Promise}
  452. */
  453. getCount: (user_id, visibility) => {
  454. let query = certificateModel
  455. .query()
  456. .count('id as count')
  457. .where('is_deleted', 0);
  458. if (visibility !== 'all') {
  459. query.andWhere('owner_user_id', user_id);
  460. }
  461. return query.first()
  462. .then((row) => {
  463. return parseInt(row.count, 10);
  464. });
  465. },
  466. /**
  467. * @param {Object} certificate
  468. * @returns {Promise}
  469. */
  470. writeCustomCert: (certificate) => {
  471. logger.info('Writing Custom Certificate:', certificate);
  472. const dir = '/data/custom_ssl/npm-' + certificate.id;
  473. return new Promise((resolve, reject) => {
  474. if (certificate.provider === 'letsencrypt') {
  475. reject(new Error('Refusing to write letsencrypt certs here'));
  476. return;
  477. }
  478. let certData = certificate.meta.certificate;
  479. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  480. certData = certData + '\n' + certificate.meta.intermediate_certificate;
  481. }
  482. try {
  483. if (!fs.existsSync(dir)) {
  484. fs.mkdirSync(dir);
  485. }
  486. } catch (err) {
  487. reject(err);
  488. return;
  489. }
  490. fs.writeFile(dir + '/fullchain.pem', certData, function (err) {
  491. if (err) {
  492. reject(err);
  493. } else {
  494. resolve();
  495. }
  496. });
  497. })
  498. .then(() => {
  499. return new Promise((resolve, reject) => {
  500. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  501. if (err) {
  502. reject(err);
  503. } else {
  504. resolve();
  505. }
  506. });
  507. });
  508. });
  509. },
  510. /**
  511. * @param {Access} access
  512. * @param {Object} data
  513. * @param {Array} data.domain_names
  514. * @param {String} data.meta.letsencrypt_email
  515. * @param {Boolean} data.meta.letsencrypt_agree
  516. * @returns {Promise}
  517. */
  518. createQuickCertificate: (access, data) => {
  519. return internalCertificate.create(access, {
  520. provider: 'letsencrypt',
  521. domain_names: data.domain_names,
  522. meta: data.meta
  523. });
  524. },
  525. /**
  526. * Validates that the certs provided are good.
  527. * No access required here, nothing is changed or stored.
  528. *
  529. * @param {Object} data
  530. * @param {Object} data.files
  531. * @returns {Promise}
  532. */
  533. validate: (data) => {
  534. return new Promise((resolve) => {
  535. // Put file contents into an object
  536. let files = {};
  537. _.map(data.files, (file, name) => {
  538. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  539. files[name] = file.data.toString();
  540. }
  541. });
  542. resolve(files);
  543. })
  544. .then((files) => {
  545. // For each file, create a temp file and write the contents to it
  546. // Then test it depending on the file type
  547. let promises = [];
  548. _.map(files, (content, type) => {
  549. promises.push(new Promise((resolve) => {
  550. if (type === 'certificate_key') {
  551. resolve(internalCertificate.checkPrivateKey(content));
  552. } else {
  553. // this should handle `certificate` and intermediate certificate
  554. resolve(internalCertificate.getCertificateInfo(content, true));
  555. }
  556. }).then((res) => {
  557. return {[type]: res};
  558. }));
  559. });
  560. return Promise.all(promises)
  561. .then((files) => {
  562. let data = {};
  563. _.each(files, (file) => {
  564. data = _.assign({}, data, file);
  565. });
  566. return data;
  567. });
  568. });
  569. },
  570. /**
  571. * @param {Access} access
  572. * @param {Object} data
  573. * @param {Number} data.id
  574. * @param {Object} data.files
  575. * @returns {Promise}
  576. */
  577. upload: (access, data) => {
  578. return internalCertificate.get(access, {id: data.id})
  579. .then((row) => {
  580. if (row.provider !== 'other') {
  581. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  582. }
  583. return internalCertificate.validate(data)
  584. .then((validations) => {
  585. if (typeof validations.certificate === 'undefined') {
  586. throw new error.ValidationError('Certificate file was not provided');
  587. }
  588. _.map(data.files, (file, name) => {
  589. if (internalCertificate.allowedSslFiles.indexOf(name) !== -1) {
  590. row.meta[name] = file.data.toString();
  591. }
  592. });
  593. // TODO: This uses a mysql only raw function that won't translate to postgres
  594. return internalCertificate.update(access, {
  595. id: data.id,
  596. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  597. domain_names: [validations.certificate.cn],
  598. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  599. })
  600. .then((certificate) => {
  601. certificate.meta = row.meta;
  602. return internalCertificate.writeCustomCert(certificate);
  603. });
  604. })
  605. .then(() => {
  606. return _.pick(row.meta, internalCertificate.allowedSslFiles);
  607. });
  608. });
  609. },
  610. /**
  611. * Uses the openssl command to validate the private key.
  612. * It will save the file to disk first, then run commands on it, then delete the file.
  613. *
  614. * @param {String} private_key This is the entire key contents as a string
  615. */
  616. checkPrivateKey: (private_key) => {
  617. return tempWrite(private_key, '/tmp')
  618. .then((filepath) => {
  619. return new Promise((resolve, reject) => {
  620. const failTimeout = setTimeout(() => {
  621. reject(new error.ValidationError('Result Validation Error: Validation timed out. This could be due to the key being passphrase-protected.'));
  622. }, 10000);
  623. utils
  624. .exec('openssl pkey -in ' + filepath + ' -check -noout 2>&1 ')
  625. .then((result) => {
  626. clearTimeout(failTimeout);
  627. if (!result.toLowerCase().includes('key is valid')) {
  628. reject(new error.ValidationError('Result Validation Error: ' + result));
  629. }
  630. fs.unlinkSync(filepath);
  631. resolve(true);
  632. })
  633. .catch((err) => {
  634. clearTimeout(failTimeout);
  635. fs.unlinkSync(filepath);
  636. reject(new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err));
  637. });
  638. });
  639. });
  640. },
  641. /**
  642. * Uses the openssl command to both validate and get info out of the certificate.
  643. * It will save the file to disk first, then run commands on it, then delete the file.
  644. *
  645. * @param {String} certificate This is the entire cert contents as a string
  646. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  647. */
  648. getCertificateInfo: (certificate, throw_expired) => {
  649. return tempWrite(certificate, '/tmp')
  650. .then((filepath) => {
  651. return internalCertificate.getCertificateInfoFromFile(filepath, throw_expired)
  652. .then((certData) => {
  653. fs.unlinkSync(filepath);
  654. return certData;
  655. }).catch((err) => {
  656. fs.unlinkSync(filepath);
  657. throw err;
  658. });
  659. });
  660. },
  661. /**
  662. * Uses the openssl command to both validate and get info out of the certificate.
  663. * It will save the file to disk first, then run commands on it, then delete the file.
  664. *
  665. * @param {String} certificate_file The file location on disk
  666. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  667. */
  668. getCertificateInfoFromFile: (certificate_file, throw_expired) => {
  669. let certData = {};
  670. return utils.exec('openssl x509 -in ' + certificate_file + ' -subject -noout')
  671. .then((result) => {
  672. // subject=CN = something.example.com
  673. const regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  674. const match = regex.exec(result);
  675. if (typeof match[1] === 'undefined') {
  676. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  677. }
  678. certData['cn'] = match[1];
  679. })
  680. .then(() => {
  681. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  682. })
  683. .then((result) => {
  684. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  685. const regex = /^(?:issuer=)?(.*)$/gim;
  686. const match = regex.exec(result);
  687. if (typeof match[1] === 'undefined') {
  688. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  689. }
  690. certData['issuer'] = match[1];
  691. })
  692. .then(() => {
  693. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  694. })
  695. .then((result) => {
  696. // notBefore=Jul 14 04:04:29 2018 GMT
  697. // notAfter=Oct 12 04:04:29 2018 GMT
  698. let validFrom = null;
  699. let validTo = null;
  700. const lines = result.split('\n');
  701. lines.map(function (str) {
  702. const regex = /^(\S+)=(.*)$/gim;
  703. const match = regex.exec(str.trim());
  704. if (match && typeof match[2] !== 'undefined') {
  705. const date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  706. if (match[1].toLowerCase() === 'notbefore') {
  707. validFrom = date;
  708. } else if (match[1].toLowerCase() === 'notafter') {
  709. validTo = date;
  710. }
  711. }
  712. });
  713. if (!validFrom || !validTo) {
  714. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  715. }
  716. if (throw_expired && validTo < parseInt(moment().format('X'), 10)) {
  717. throw new error.ValidationError('Certificate has expired');
  718. }
  719. certData['dates'] = {
  720. from: validFrom,
  721. to: validTo
  722. };
  723. return certData;
  724. }).catch((err) => {
  725. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  726. });
  727. },
  728. /**
  729. * Cleans the ssl keys from the meta object and sets them to "true"
  730. *
  731. * @param {Object} meta
  732. * @param {Boolean} [remove]
  733. * @returns {Object}
  734. */
  735. cleanMeta: function (meta, remove) {
  736. internalCertificate.allowedSslFiles.map((key) => {
  737. if (typeof meta[key] !== 'undefined' && meta[key]) {
  738. if (remove) {
  739. delete meta[key];
  740. } else {
  741. meta[key] = true;
  742. }
  743. }
  744. });
  745. return meta;
  746. },
  747. /**
  748. * Request a certificate using the http challenge
  749. * @param {Object} certificate the certificate row
  750. * @returns {Promise}
  751. */
  752. requestLetsEncryptSsl: (certificate) => {
  753. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  754. const cmd = certbotCommand + ' certonly ' +
  755. '--config "' + letsencryptConfig + '" ' +
  756. '--cert-name "npm-' + certificate.id + '" ' +
  757. '--agree-tos ' +
  758. '--authenticator webroot ' +
  759. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  760. '--preferred-challenges "dns,http" ' +
  761. '--domains "' + certificate.domain_names.join(',') + '" ' +
  762. (letsencryptStaging ? '--staging' : '');
  763. logger.info('Command:', cmd);
  764. return utils.exec(cmd)
  765. .then((result) => {
  766. logger.success(result);
  767. return result;
  768. });
  769. },
  770. /**
  771. * @param {Object} certificate the certificate row
  772. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  773. * @param {String | null} credentials the content of this providers credentials file
  774. * @param {String} propagation_seconds the cloudflare api token
  775. * @returns {Promise}
  776. */
  777. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  778. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  779. if (!dns_plugin) {
  780. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  781. }
  782. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  783. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  784. // Escape single quotes and backslashes
  785. const escapedCredentials = certificate.meta.dns_provider_credentials.replaceAll('\'', '\\\'').replaceAll('\\', '\\\\');
  786. const credentialsCmd = 'mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + escapedCredentials + '\' > \'' + credentialsLocation + '\' && chmod 600 \'' + credentialsLocation + '\'';
  787. // we call `. /opt/certbot/bin/activate` (`.` is alternative to `source` in dash) to access certbot venv
  788. let prepareCmd = '. /opt/certbot/bin/activate && pip install ' + dns_plugin.package_name + (dns_plugin.version_requirement || '') + ' ' + dns_plugin.dependencies + ' && deactivate';
  789. // Whether the plugin has a --<name>-credentials argument
  790. const hasConfigArg = certificate.meta.dns_provider !== 'route53';
  791. let mainCmd = certbotCommand + ' certonly ' +
  792. '--config "' + letsencryptConfig + '" ' +
  793. '--cert-name "npm-' + certificate.id + '" ' +
  794. '--agree-tos ' +
  795. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  796. '--domains "' + certificate.domain_names.join(',') + '" ' +
  797. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  798. (
  799. hasConfigArg
  800. ? '--' + dns_plugin.full_plugin_name + '-credentials "' + credentialsLocation + '"'
  801. : ''
  802. ) +
  803. (
  804. certificate.meta.propagation_seconds !== undefined
  805. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  806. : ''
  807. ) +
  808. (letsencryptStaging ? ' --staging' : '');
  809. // Prepend the path to the credentials file as an environment variable
  810. if (certificate.meta.dns_provider === 'route53') {
  811. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  812. }
  813. logger.info('Command:', `${credentialsCmd} && ${prepareCmd} && ${mainCmd}`);
  814. return utils.exec(credentialsCmd)
  815. .then(() => {
  816. return utils.exec(prepareCmd)
  817. .then(() => {
  818. return utils.exec(mainCmd)
  819. .then(async (result) => {
  820. logger.info(result);
  821. return result;
  822. });
  823. });
  824. }).catch(async (err) => {
  825. // Don't fail if file does not exist
  826. const delete_credentialsCmd = `rm -f '${credentialsLocation}' || true`;
  827. await utils.exec(delete_credentialsCmd);
  828. throw err;
  829. });
  830. },
  831. /**
  832. * @param {Access} access
  833. * @param {Object} data
  834. * @param {Number} data.id
  835. * @returns {Promise}
  836. */
  837. renew: (access, data) => {
  838. return access.can('certificates:update', data)
  839. .then(() => {
  840. return internalCertificate.get(access, data);
  841. })
  842. .then((certificate) => {
  843. if (certificate.provider === 'letsencrypt') {
  844. const renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  845. return renewMethod(certificate)
  846. .then(() => {
  847. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  848. })
  849. .then((cert_info) => {
  850. return certificateModel
  851. .query()
  852. .patchAndFetchById(certificate.id, {
  853. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  854. });
  855. })
  856. .then((updated_certificate) => {
  857. // Add to audit log
  858. return internalAuditLog.add(access, {
  859. action: 'renewed',
  860. object_type: 'certificate',
  861. object_id: updated_certificate.id,
  862. meta: updated_certificate
  863. })
  864. .then(() => {
  865. return updated_certificate;
  866. });
  867. });
  868. } else {
  869. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  870. }
  871. });
  872. },
  873. /**
  874. * @param {Object} certificate the certificate row
  875. * @returns {Promise}
  876. */
  877. renewLetsEncryptSsl: (certificate) => {
  878. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  879. const cmd = certbotCommand + ' renew --force-renewal ' +
  880. '--config "' + letsencryptConfig + '" ' +
  881. '--cert-name "npm-' + certificate.id + '" ' +
  882. '--preferred-challenges "dns,http" ' +
  883. '--no-random-sleep-on-renew ' +
  884. '--disable-hook-validation ' +
  885. (letsencryptStaging ? '--staging' : '');
  886. logger.info('Command:', cmd);
  887. return utils.exec(cmd)
  888. .then((result) => {
  889. logger.info(result);
  890. return result;
  891. });
  892. },
  893. /**
  894. * @param {Object} certificate the certificate row
  895. * @returns {Promise}
  896. */
  897. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  898. const dns_plugin = dnsPlugins[certificate.meta.dns_provider];
  899. if (!dns_plugin) {
  900. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  901. }
  902. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  903. let mainCmd = certbotCommand + ' renew ' +
  904. '--config "' + letsencryptConfig + '" ' +
  905. '--cert-name "npm-' + certificate.id + '" ' +
  906. '--disable-hook-validation ' +
  907. '--no-random-sleep-on-renew ' +
  908. (letsencryptStaging ? ' --staging' : '');
  909. // Prepend the path to the credentials file as an environment variable
  910. if (certificate.meta.dns_provider === 'route53') {
  911. const credentialsLocation = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  912. mainCmd = 'AWS_CONFIG_FILE=\'' + credentialsLocation + '\' ' + mainCmd;
  913. }
  914. logger.info('Command:', mainCmd);
  915. return utils.exec(mainCmd)
  916. .then(async (result) => {
  917. logger.info(result);
  918. return result;
  919. });
  920. },
  921. /**
  922. * @param {Object} certificate the certificate row
  923. * @param {Boolean} [throw_errors]
  924. * @returns {Promise}
  925. */
  926. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  927. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  928. const mainCmd = certbotCommand + ' revoke ' +
  929. '--config "' + letsencryptConfig + '" ' +
  930. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  931. '--delete-after-revoke ' +
  932. (letsencryptStaging ? '--staging' : '');
  933. // Don't fail command if file does not exist
  934. const delete_credentialsCmd = `rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`;
  935. logger.info('Command:', mainCmd + '; ' + delete_credentialsCmd);
  936. return utils.exec(mainCmd)
  937. .then(async (result) => {
  938. await utils.exec(delete_credentialsCmd);
  939. logger.info(result);
  940. return result;
  941. })
  942. .catch((err) => {
  943. logger.error(err.message);
  944. if (throw_errors) {
  945. throw err;
  946. }
  947. });
  948. },
  949. /**
  950. * @param {Object} certificate
  951. * @returns {Boolean}
  952. */
  953. hasLetsEncryptSslCerts: (certificate) => {
  954. const letsencryptPath = '/etc/letsencrypt/live/npm-' + certificate.id;
  955. return fs.existsSync(letsencryptPath + '/fullchain.pem') && fs.existsSync(letsencryptPath + '/privkey.pem');
  956. },
  957. /**
  958. * @param {Object} in_use_result
  959. * @param {Number} in_use_result.total_count
  960. * @param {Array} in_use_result.proxy_hosts
  961. * @param {Array} in_use_result.redirection_hosts
  962. * @param {Array} in_use_result.dead_hosts
  963. */
  964. disableInUseHosts: (in_use_result) => {
  965. if (in_use_result.total_count) {
  966. let promises = [];
  967. if (in_use_result.proxy_hosts.length) {
  968. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  969. }
  970. if (in_use_result.redirection_hosts.length) {
  971. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  972. }
  973. if (in_use_result.dead_hosts.length) {
  974. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  975. }
  976. return Promise.all(promises);
  977. } else {
  978. return Promise.resolve();
  979. }
  980. },
  981. /**
  982. * @param {Object} in_use_result
  983. * @param {Number} in_use_result.total_count
  984. * @param {Array} in_use_result.proxy_hosts
  985. * @param {Array} in_use_result.redirection_hosts
  986. * @param {Array} in_use_result.dead_hosts
  987. */
  988. enableInUseHosts: (in_use_result) => {
  989. if (in_use_result.total_count) {
  990. let promises = [];
  991. if (in_use_result.proxy_hosts.length) {
  992. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  993. }
  994. if (in_use_result.redirection_hosts.length) {
  995. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  996. }
  997. if (in_use_result.dead_hosts.length) {
  998. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  999. }
  1000. return Promise.all(promises);
  1001. } else {
  1002. return Promise.resolve();
  1003. }
  1004. },
  1005. testHttpsChallenge: async (access, domains) => {
  1006. await access.can('certificates:list');
  1007. if (!isArray(domains)) {
  1008. throw new error.InternalValidationError('Domains must be an array of strings');
  1009. }
  1010. if (domains.length === 0) {
  1011. throw new error.InternalValidationError('No domains provided');
  1012. }
  1013. // Create a test challenge file
  1014. const testChallengeDir = '/data/letsencrypt-acme-challenge/.well-known/acme-challenge';
  1015. const testChallengeFile = testChallengeDir + '/test-challenge';
  1016. fs.mkdirSync(testChallengeDir, {recursive: true});
  1017. fs.writeFileSync(testChallengeFile, 'Success', {encoding: 'utf8'});
  1018. async function performTestForDomain (domain) {
  1019. logger.info('Testing http challenge for ' + domain);
  1020. const url = `http://${domain}/.well-known/acme-challenge/test-challenge`;
  1021. const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`;
  1022. const options = {
  1023. method: 'POST',
  1024. headers: {
  1025. 'Content-Type': 'application/x-www-form-urlencoded',
  1026. 'Content-Length': Buffer.byteLength(formBody)
  1027. }
  1028. };
  1029. const result = await new Promise((resolve) => {
  1030. const req = https.request('https://www.site24x7.com/tools/restapi-tester', options, function (res) {
  1031. let responseBody = '';
  1032. res.on('data', (chunk) => responseBody = responseBody + chunk);
  1033. res.on('end', function () {
  1034. const parsedBody = JSON.parse(responseBody + '');
  1035. if (res.statusCode !== 200) {
  1036. logger.warn(`Failed to test HTTP challenge for domain ${domain}`, res);
  1037. resolve(undefined);
  1038. }
  1039. resolve(parsedBody);
  1040. });
  1041. });
  1042. // Make sure to write the request body.
  1043. req.write(formBody);
  1044. req.end();
  1045. req.on('error', function (e) { logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e);
  1046. resolve(undefined); });
  1047. });
  1048. if (!result) {
  1049. // Some error occurred while trying to get the data
  1050. return 'failed';
  1051. } else if (`${result.responsecode}` === '200' && result.htmlresponse === 'Success') {
  1052. // Server exists and has responded with the correct data
  1053. return 'ok';
  1054. } else if (`${result.responsecode}` === '200') {
  1055. // Server exists but has responded with wrong data
  1056. logger.info(`HTTP challenge test failed for domain ${domain} because of invalid returned data:`, result.htmlresponse);
  1057. return 'wrong-data';
  1058. } else if (`${result.responsecode}` === '404') {
  1059. // Server exists but responded with a 404
  1060. logger.info(`HTTP challenge test failed for domain ${domain} because code 404 was returned`);
  1061. return '404';
  1062. } else if (`${result.responsecode}` === '0' || (typeof result.reason === 'string' && result.reason.toLowerCase() === 'host unavailable')) {
  1063. // Server does not exist at domain
  1064. logger.info(`HTTP challenge test failed for domain ${domain} the host was not found`);
  1065. return 'no-host';
  1066. } else {
  1067. // Other errors
  1068. logger.info(`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`);
  1069. return `other:${result.responsecode}`;
  1070. }
  1071. }
  1072. const results = {};
  1073. for (const domain of domains){
  1074. results[domain] = await performTestForDomain(domain);
  1075. }
  1076. // Remove the test challenge file
  1077. fs.unlinkSync(testChallengeFile);
  1078. return results;
  1079. }
  1080. };
  1081. module.exports = internalCertificate;