certificate.js 38 KB

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