certificate.js 37 KB

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