certificate.js 37 KB

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