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