certificate.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. const fs = require('fs');
  2. const _ = require('lodash');
  3. const logger = require('../logger').ssl;
  4. const error = require('../lib/error');
  5. const certificateModel = require('../models/certificate');
  6. const internalAuditLog = require('./audit-log');
  7. const tempWrite = require('temp-write');
  8. const utils = require('../lib/utils');
  9. const moment = require('moment');
  10. const debug_mode = process.env.NODE_ENV !== 'production' || !!process.env.DEBUG;
  11. const le_staging = process.env.NODE_ENV !== 'production';
  12. const internalNginx = require('./nginx');
  13. const internalHost = require('./host');
  14. const certbot_command = '/usr/bin/certbot';
  15. const le_config = '/etc/letsencrypt.ini';
  16. const dns_plugins = require('../global/certbot-dns-plugins');
  17. function omissions() {
  18. return ['is_deleted'];
  19. }
  20. const internalCertificate = {
  21. allowed_ssl_files: ['certificate', 'certificate_key', 'intermediate_certificate'],
  22. interval_timeout: 1000 * 60 * 60, // 1 hour
  23. interval: null,
  24. interval_processing: false,
  25. initTimer: () => {
  26. logger.info('Let\'s Encrypt Renewal Timer initialized');
  27. internalCertificate.interval = setInterval(internalCertificate.processExpiringHosts, internalCertificate.interval_timeout);
  28. // And do this now as well
  29. internalCertificate.processExpiringHosts();
  30. },
  31. /**
  32. * Triggered by a timer, this will check for expiring hosts and renew their ssl certs if required
  33. */
  34. processExpiringHosts: () => {
  35. if (!internalCertificate.interval_processing) {
  36. internalCertificate.interval_processing = true;
  37. logger.info('Renewing SSL certs close to expiry...');
  38. let cmd = certbot_command + ' renew --non-interactive --quiet ' +
  39. '--config "' + le_config + '" ' +
  40. '--preferred-challenges "dns,http" ' +
  41. '--disable-hook-validation ' +
  42. (le_staging ? '--staging' : '');
  43. return utils.exec(cmd)
  44. .then((result) => {
  45. if (result) {
  46. logger.info('Renew Result: ' + result);
  47. }
  48. return internalNginx.reload()
  49. .then(() => {
  50. logger.info('Renew Complete');
  51. return result;
  52. });
  53. })
  54. .then(() => {
  55. // Now go and fetch all the letsencrypt certs from the db and query the files and update expiry times
  56. return certificateModel
  57. .query()
  58. .where('is_deleted', 0)
  59. .andWhere('provider', 'letsencrypt')
  60. .then((certificates) => {
  61. if (certificates && certificates.length) {
  62. let promises = [];
  63. certificates.map(function (certificate) {
  64. promises.push(
  65. internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem')
  66. .then((cert_info) => {
  67. return certificateModel
  68. .query()
  69. .where('id', certificate.id)
  70. .andWhere('provider', 'letsencrypt')
  71. .patch({
  72. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  73. });
  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 Promise.all(promises);
  82. }
  83. });
  84. })
  85. .then(() => {
  86. internalCertificate.interval_processing = false;
  87. })
  88. .catch((err) => {
  89. logger.error(err);
  90. internalCertificate.interval_processing = false;
  91. });
  92. }
  93. },
  94. /**
  95. * @param {Access} access
  96. * @param {Object} data
  97. * @returns {Promise}
  98. */
  99. create: (access, data) => {
  100. return access.can('certificates:create', data)
  101. .then(() => {
  102. data.owner_user_id = access.token.getUserId(1);
  103. if (data.provider === 'letsencrypt') {
  104. data.nice_name = data.domain_names.sort().join(', ');
  105. }
  106. return certificateModel
  107. .query()
  108. .omit(omissions())
  109. .insertAndFetch(data);
  110. })
  111. .then((certificate) => {
  112. if (certificate.provider === 'letsencrypt') {
  113. // Request a new Cert from LE. Let the fun begin.
  114. // 1. Find out any hosts that are using any of the hostnames in this cert
  115. // 2. Disable them in nginx temporarily
  116. // 3. Generate the LE config
  117. // 4. Request cert
  118. // 5. Remove LE config
  119. // 6. Re-instate previously disabled hosts
  120. // 1. Find out any hosts that are using any of the hostnames in this cert
  121. return internalHost.getHostsWithDomains(certificate.domain_names)
  122. .then((in_use_result) => {
  123. // 2. Disable them in nginx temporarily
  124. return internalCertificate.disableInUseHosts(in_use_result)
  125. .then(() => {
  126. return in_use_result;
  127. });
  128. })
  129. .then((in_use_result) => {
  130. // With DNS challenge no config is needed, so skip 3 and 5.
  131. if (certificate.meta.dns_challenge) {
  132. return internalNginx.reload().then(() => {
  133. // 4. Request cert
  134. return internalCertificate.requestLetsEncryptSslWithDnsChallenge(certificate);
  135. })
  136. .then(internalNginx.reload)
  137. .then(() => {
  138. // 6. Re-instate previously disabled hosts
  139. return internalCertificate.enableInUseHosts(in_use_result);
  140. })
  141. .then(() => {
  142. return certificate;
  143. })
  144. .catch((err) => {
  145. // In the event of failure, revert things and throw err back
  146. return internalCertificate.enableInUseHosts(in_use_result)
  147. .then(internalNginx.reload)
  148. .then(() => {
  149. throw err;
  150. });
  151. });
  152. } else {
  153. // 3. Generate the LE config
  154. return internalNginx.generateLetsEncryptRequestConfig(certificate)
  155. .then(internalNginx.reload)
  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. });
  204. } else {
  205. return certificate;
  206. }
  207. }).then((certificate) => {
  208. data.meta = _.assign({}, data.meta || {}, certificate.meta);
  209. // Add to audit log
  210. return internalAuditLog.add(access, {
  211. action: 'created',
  212. object_type: 'certificate',
  213. object_id: certificate.id,
  214. meta: data
  215. })
  216. .then(() => {
  217. return certificate;
  218. });
  219. });
  220. },
  221. /**
  222. * @param {Access} access
  223. * @param {Object} data
  224. * @param {Number} data.id
  225. * @param {String} [data.email]
  226. * @param {String} [data.name]
  227. * @return {Promise}
  228. */
  229. update: (access, data) => {
  230. return access.can('certificates:update', data.id)
  231. .then((/*access_data*/) => {
  232. return internalCertificate.get(access, {id: data.id});
  233. })
  234. .then((row) => {
  235. if (row.id !== data.id) {
  236. // Sanity check that something crazy hasn't happened
  237. throw new error.InternalValidationError('Certificate could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  238. }
  239. return certificateModel
  240. .query()
  241. .omit(omissions())
  242. .patchAndFetchById(row.id, data)
  243. .then((saved_row) => {
  244. saved_row.meta = internalCertificate.cleanMeta(saved_row.meta);
  245. data.meta = internalCertificate.cleanMeta(data.meta);
  246. // Add row.nice_name for custom certs
  247. if (saved_row.provider === 'other') {
  248. data.nice_name = saved_row.nice_name;
  249. }
  250. // Add to audit log
  251. return internalAuditLog.add(access, {
  252. action: 'updated',
  253. object_type: 'certificate',
  254. object_id: row.id,
  255. meta: _.omit(data, ['expires_on']) // this prevents json circular reference because expires_on might be raw
  256. })
  257. .then(() => {
  258. return _.omit(saved_row, omissions());
  259. });
  260. });
  261. });
  262. },
  263. /**
  264. * @param {Access} access
  265. * @param {Object} data
  266. * @param {Number} data.id
  267. * @param {Array} [data.expand]
  268. * @param {Array} [data.omit]
  269. * @return {Promise}
  270. */
  271. get: (access, data) => {
  272. if (typeof data === 'undefined') {
  273. data = {};
  274. }
  275. return access.can('certificates:get', data.id)
  276. .then((access_data) => {
  277. let query = certificateModel
  278. .query()
  279. .where('is_deleted', 0)
  280. .andWhere('id', data.id)
  281. .allowEager('[owner]')
  282. .first();
  283. if (access_data.permission_visibility !== 'all') {
  284. query.andWhere('owner_user_id', access.token.getUserId(1));
  285. }
  286. // Custom omissions
  287. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  288. query.omit(data.omit);
  289. }
  290. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  291. query.eager('[' + data.expand.join(', ') + ']');
  292. }
  293. return query;
  294. })
  295. .then((row) => {
  296. if (row) {
  297. return _.omit(row, omissions());
  298. } else {
  299. throw new error.ItemNotFoundError(data.id);
  300. }
  301. });
  302. },
  303. /**
  304. * @param {Access} access
  305. * @param {Object} data
  306. * @param {Number} data.id
  307. * @param {String} [data.reason]
  308. * @returns {Promise}
  309. */
  310. delete: (access, data) => {
  311. return access.can('certificates:delete', data.id)
  312. .then(() => {
  313. return internalCertificate.get(access, {id: data.id});
  314. })
  315. .then((row) => {
  316. if (!row) {
  317. throw new error.ItemNotFoundError(data.id);
  318. }
  319. return certificateModel
  320. .query()
  321. .where('id', row.id)
  322. .patch({
  323. is_deleted: 1
  324. })
  325. .then(() => {
  326. // Add to audit log
  327. row.meta = internalCertificate.cleanMeta(row.meta);
  328. return internalAuditLog.add(access, {
  329. action: 'deleted',
  330. object_type: 'certificate',
  331. object_id: row.id,
  332. meta: _.omit(row, omissions())
  333. });
  334. })
  335. .then(() => {
  336. if (row.provider === 'letsencrypt') {
  337. // Revoke the cert
  338. return internalCertificate.revokeLetsEncryptSsl(row);
  339. }
  340. });
  341. })
  342. .then(() => {
  343. return true;
  344. });
  345. },
  346. /**
  347. * All Certs
  348. *
  349. * @param {Access} access
  350. * @param {Array} [expand]
  351. * @param {String} [search_query]
  352. * @returns {Promise}
  353. */
  354. getAll: (access, expand, search_query) => {
  355. return access.can('certificates:list')
  356. .then((access_data) => {
  357. let query = certificateModel
  358. .query()
  359. .where('is_deleted', 0)
  360. .groupBy('id')
  361. .omit(['is_deleted'])
  362. .allowEager('[owner]')
  363. .orderBy('nice_name', 'ASC');
  364. if (access_data.permission_visibility !== 'all') {
  365. query.andWhere('owner_user_id', access.token.getUserId(1));
  366. }
  367. // Query is used for searching
  368. if (typeof search_query === 'string') {
  369. query.where(function () {
  370. this.where('name', 'like', '%' + search_query + '%');
  371. });
  372. }
  373. if (typeof expand !== 'undefined' && expand !== null) {
  374. query.eager('[' + expand.join(', ') + ']');
  375. }
  376. return query;
  377. });
  378. },
  379. /**
  380. * Report use
  381. *
  382. * @param {Number} user_id
  383. * @param {String} visibility
  384. * @returns {Promise}
  385. */
  386. getCount: (user_id, visibility) => {
  387. let query = certificateModel
  388. .query()
  389. .count('id as count')
  390. .where('is_deleted', 0);
  391. if (visibility !== 'all') {
  392. query.andWhere('owner_user_id', user_id);
  393. }
  394. return query.first()
  395. .then((row) => {
  396. return parseInt(row.count, 10);
  397. });
  398. },
  399. /**
  400. * @param {Object} certificate
  401. * @returns {Promise}
  402. */
  403. writeCustomCert: (certificate) => {
  404. if (debug_mode) {
  405. logger.info('Writing Custom Certificate:', certificate);
  406. }
  407. let dir = '/data/custom_ssl/npm-' + certificate.id;
  408. return new Promise((resolve, reject) => {
  409. if (certificate.provider === 'letsencrypt') {
  410. reject(new Error('Refusing to write letsencrypt certs here'));
  411. return;
  412. }
  413. let cert_data = certificate.meta.certificate;
  414. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  415. cert_data = cert_data + '\n' + certificate.meta.intermediate_certificate;
  416. }
  417. try {
  418. if (!fs.existsSync(dir)) {
  419. fs.mkdirSync(dir);
  420. }
  421. } catch (err) {
  422. reject(err);
  423. return;
  424. }
  425. fs.writeFile(dir + '/fullchain.pem', cert_data, function (err) {
  426. if (err) {
  427. reject(err);
  428. } else {
  429. resolve();
  430. }
  431. });
  432. })
  433. .then(() => {
  434. return new Promise((resolve, reject) => {
  435. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  436. if (err) {
  437. reject(err);
  438. } else {
  439. resolve();
  440. }
  441. });
  442. });
  443. });
  444. },
  445. /**
  446. * @param {Access} access
  447. * @param {Object} data
  448. * @param {Array} data.domain_names
  449. * @param {String} data.meta.letsencrypt_email
  450. * @param {Boolean} data.meta.letsencrypt_agree
  451. * @returns {Promise}
  452. */
  453. createQuickCertificate: (access, data) => {
  454. return internalCertificate.create(access, {
  455. provider: 'letsencrypt',
  456. domain_names: data.domain_names,
  457. meta: data.meta
  458. });
  459. },
  460. /**
  461. * Validates that the certs provided are good.
  462. * No access required here, nothing is changed or stored.
  463. *
  464. * @param {Object} data
  465. * @param {Object} data.files
  466. * @returns {Promise}
  467. */
  468. validate: (data) => {
  469. return new Promise((resolve) => {
  470. // Put file contents into an object
  471. let files = {};
  472. _.map(data.files, (file, name) => {
  473. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  474. files[name] = file.data.toString();
  475. }
  476. });
  477. resolve(files);
  478. })
  479. .then((files) => {
  480. // For each file, create a temp file and write the contents to it
  481. // Then test it depending on the file type
  482. let promises = [];
  483. _.map(files, (content, type) => {
  484. promises.push(new Promise((resolve) => {
  485. if (type === 'certificate_key') {
  486. resolve(internalCertificate.checkPrivateKey(content));
  487. } else {
  488. // this should handle `certificate` and intermediate certificate
  489. resolve(internalCertificate.getCertificateInfo(content, true));
  490. }
  491. }).then((res) => {
  492. return {[type]: res};
  493. }));
  494. });
  495. return Promise.all(promises)
  496. .then((files) => {
  497. let data = {};
  498. _.each(files, (file) => {
  499. data = _.assign({}, data, file);
  500. });
  501. return data;
  502. });
  503. });
  504. },
  505. /**
  506. * @param {Access} access
  507. * @param {Object} data
  508. * @param {Number} data.id
  509. * @param {Object} data.files
  510. * @returns {Promise}
  511. */
  512. upload: (access, data) => {
  513. return internalCertificate.get(access, {id: data.id})
  514. .then((row) => {
  515. if (row.provider !== 'other') {
  516. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  517. }
  518. return internalCertificate.validate(data)
  519. .then((validations) => {
  520. if (typeof validations.certificate === 'undefined') {
  521. throw new error.ValidationError('Certificate file was not provided');
  522. }
  523. _.map(data.files, (file, name) => {
  524. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  525. row.meta[name] = file.data.toString();
  526. }
  527. });
  528. // TODO: This uses a mysql only raw function that won't translate to postgres
  529. return internalCertificate.update(access, {
  530. id: data.id,
  531. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  532. domain_names: [validations.certificate.cn],
  533. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  534. })
  535. .then((certificate) => {
  536. console.log('ROWMETA:', row.meta);
  537. certificate.meta = row.meta;
  538. return internalCertificate.writeCustomCert(certificate);
  539. });
  540. })
  541. .then(() => {
  542. return _.pick(row.meta, internalCertificate.allowed_ssl_files);
  543. });
  544. });
  545. },
  546. /**
  547. * Uses the openssl command to validate the private key.
  548. * It will save the file to disk first, then run commands on it, then delete the file.
  549. *
  550. * @param {String} private_key This is the entire key contents as a string
  551. */
  552. checkPrivateKey: (private_key) => {
  553. return tempWrite(private_key, '/tmp')
  554. .then((filepath) => {
  555. return utils.exec('openssl rsa -in ' + filepath + ' -check -noout')
  556. .then((result) => {
  557. if (!result.toLowerCase().includes('key ok')) {
  558. throw new error.ValidationError(result);
  559. }
  560. fs.unlinkSync(filepath);
  561. return true;
  562. }).catch((err) => {
  563. fs.unlinkSync(filepath);
  564. throw new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err);
  565. });
  566. });
  567. },
  568. /**
  569. * Uses the openssl command to both validate and get info out of the certificate.
  570. * It will save the file to disk first, then run commands on it, then delete the file.
  571. *
  572. * @param {String} certificate This is the entire cert contents as a string
  573. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  574. */
  575. getCertificateInfo: (certificate, throw_expired) => {
  576. return tempWrite(certificate, '/tmp')
  577. .then((filepath) => {
  578. return internalCertificate.getCertificateInfoFromFile(filepath, throw_expired)
  579. .then((cert_data) => {
  580. fs.unlinkSync(filepath);
  581. return cert_data;
  582. }).catch((err) => {
  583. fs.unlinkSync(filepath);
  584. throw err;
  585. });
  586. });
  587. },
  588. /**
  589. * Uses the openssl command to both validate and get info out of the certificate.
  590. * It will save the file to disk first, then run commands on it, then delete the file.
  591. *
  592. * @param {String} certificate_file The file location on disk
  593. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  594. */
  595. getCertificateInfoFromFile: (certificate_file, throw_expired) => {
  596. let cert_data = {};
  597. return utils.exec('openssl x509 -in ' + certificate_file + ' -subject -noout')
  598. .then((result) => {
  599. // subject=CN = something.example.com
  600. let regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  601. let match = regex.exec(result);
  602. if (typeof match[1] === 'undefined') {
  603. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  604. }
  605. cert_data['cn'] = match[1];
  606. })
  607. .then(() => {
  608. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  609. })
  610. .then((result) => {
  611. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  612. let regex = /^(?:issuer=)?(.*)$/gim;
  613. let match = regex.exec(result);
  614. if (typeof match[1] === 'undefined') {
  615. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  616. }
  617. cert_data['issuer'] = match[1];
  618. })
  619. .then(() => {
  620. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  621. })
  622. .then((result) => {
  623. // notBefore=Jul 14 04:04:29 2018 GMT
  624. // notAfter=Oct 12 04:04:29 2018 GMT
  625. let valid_from = null;
  626. let valid_to = null;
  627. let lines = result.split('\n');
  628. lines.map(function (str) {
  629. let regex = /^(\S+)=(.*)$/gim;
  630. let match = regex.exec(str.trim());
  631. if (match && typeof match[2] !== 'undefined') {
  632. let date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  633. if (match[1].toLowerCase() === 'notbefore') {
  634. valid_from = date;
  635. } else if (match[1].toLowerCase() === 'notafter') {
  636. valid_to = date;
  637. }
  638. }
  639. });
  640. if (!valid_from || !valid_to) {
  641. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  642. }
  643. if (throw_expired && valid_to < parseInt(moment().format('X'), 10)) {
  644. throw new error.ValidationError('Certificate has expired');
  645. }
  646. cert_data['dates'] = {
  647. from: valid_from,
  648. to: valid_to
  649. };
  650. return cert_data;
  651. }).catch((err) => {
  652. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  653. });
  654. },
  655. /**
  656. * Cleans the ssl keys from the meta object and sets them to "true"
  657. *
  658. * @param {Object} meta
  659. * @param {Boolean} [remove]
  660. * @returns {Object}
  661. */
  662. cleanMeta: function (meta, remove) {
  663. internalCertificate.allowed_ssl_files.map((key) => {
  664. if (typeof meta[key] !== 'undefined' && meta[key]) {
  665. if (remove) {
  666. delete meta[key];
  667. } else {
  668. meta[key] = true;
  669. }
  670. }
  671. });
  672. return meta;
  673. },
  674. /**
  675. * @param {Object} certificate the certificate row
  676. * @returns {Promise}
  677. */
  678. requestLetsEncryptSsl: (certificate) => {
  679. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  680. let cmd = certbot_command + ' certonly --non-interactive ' +
  681. '--config "' + le_config + '" ' +
  682. '--cert-name "npm-' + certificate.id + '" ' +
  683. '--agree-tos ' +
  684. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  685. '--preferred-challenges "dns,http" ' +
  686. '--domains "' + certificate.domain_names.join(',') + '" ' +
  687. (le_staging ? '--staging' : '');
  688. if (debug_mode) {
  689. logger.info('Command:', cmd);
  690. }
  691. return utils.exec(cmd)
  692. .then((result) => {
  693. logger.success(result);
  694. return result;
  695. });
  696. },
  697. /**
  698. * @param {Object} certificate the certificate row
  699. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  700. * @param {String | null} credentials the content of this providers credentials file
  701. * @param {String} propagation_seconds the cloudflare api token
  702. * @returns {Promise}
  703. */
  704. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  705. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  706. if(!dns_plugin){
  707. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`)
  708. }
  709. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  710. const credentials_loc = `/etc/letsencrypt/credentials-${certificate.id}`;
  711. const credentials_cmd = `echo '${certificate.meta.dns_provider_credentials.replace("'", "\'")}' > '${credentials_loc}' && chmod 600 '${credentials_loc}'`;
  712. const prepare_cmd = 'pip3 install ' + dns_plugin.package_name + '==' + dns_plugin.package_version;
  713. const main_cmd =
  714. certbot_command + ' certonly --non-interactive ' +
  715. '--cert-name "npm-' + certificate.id + '" ' +
  716. '--agree-tos ' +
  717. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  718. '--domains "' + certificate.domain_names.join(',') + '" ' +
  719. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  720. '--' + dns_plugin.full_plugin_name + '-credentials "' + credentials_loc + '"' +
  721. (
  722. certificate.meta.propagation_seconds !== undefined
  723. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  724. : ''
  725. ) +
  726. (le_staging ? ' --staging' : '');
  727. const teardown_cmd = `rm '${credentials_loc}'`;
  728. if (debug_mode) {
  729. logger.info('Command:', `${credentials_cmd} && ${prepare_cmd} && ${main_cmd} && ${teardown_cmd}`);
  730. }
  731. return utils.exec(credentials_cmd)
  732. .then(() => {
  733. return utils.exec(prepare_cmd)
  734. .then(() => {
  735. return utils.exec(main_cmd)
  736. .then(async (result) => {
  737. await utils.exec(teardown_cmd);
  738. logger.info(result);
  739. return result;
  740. });
  741. });
  742. });
  743. },
  744. /**
  745. * @param {Access} access
  746. * @param {Object} data
  747. * @param {Number} data.id
  748. * @returns {Promise}
  749. */
  750. renew: (access, data) => {
  751. return access.can('certificates:update', data)
  752. .then(() => {
  753. return internalCertificate.get(access, data);
  754. })
  755. .then((certificate) => {
  756. if (certificate.provider === 'letsencrypt') {
  757. let renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  758. return renewMethod(certificate)
  759. .then(() => {
  760. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  761. })
  762. .then((cert_info) => {
  763. return certificateModel
  764. .query()
  765. .patchAndFetchById(certificate.id, {
  766. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  767. });
  768. })
  769. .then((updated_certificate) => {
  770. // Add to audit log
  771. return internalAuditLog.add(access, {
  772. action: 'renewed',
  773. object_type: 'certificate',
  774. object_id: updated_certificate.id,
  775. meta: updated_certificate
  776. })
  777. .then(() => {
  778. return updated_certificate;
  779. });
  780. });
  781. } else {
  782. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  783. }
  784. });
  785. },
  786. /**
  787. * @param {Object} certificate the certificate row
  788. * @returns {Promise}
  789. */
  790. renewLetsEncryptSsl: (certificate) => {
  791. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  792. let cmd = certbot_command + ' renew --non-interactive ' +
  793. '--config "' + le_config + '" ' +
  794. '--cert-name "npm-' + certificate.id + '" ' +
  795. '--preferred-challenges "dns,http" ' +
  796. '--disable-hook-validation ' +
  797. (le_staging ? '--staging' : '');
  798. if (debug_mode) {
  799. logger.info('Command:', cmd);
  800. }
  801. return utils.exec(cmd)
  802. .then((result) => {
  803. logger.info(result);
  804. return result;
  805. });
  806. },
  807. /**
  808. * @param {Object} certificate the certificate row
  809. * @returns {Promise}
  810. */
  811. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  812. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  813. if(!dns_plugin){
  814. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`)
  815. }
  816. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  817. const credentials_loc = `/etc/letsencrypt/credentials-${certificate.id}`;
  818. const credentials_cmd = `echo '${certificate.meta.dns_provider_credentials.replace("'", "\'")}' > '${credentials_loc}' && chmod 600 '${credentials_loc}'`;
  819. const prepare_cmd = 'pip3 install ' + dns_plugin.package_name + '==' + dns_plugin.package_version;
  820. const main_cmd =
  821. certbot_command + ' renew --non-interactive ' +
  822. '--cert-name "npm-' + certificate.id + '" ' +
  823. '--disable-hook-validation' +
  824. (le_staging ? ' --staging' : '');
  825. const teardown_cmd = `rm '${credentials_loc}'`;
  826. if (debug_mode) {
  827. logger.info('Command:', `${credentials_cmd} && ${prepare_cmd} && ${main_cmd} && ${teardown_cmd}`);
  828. }
  829. return utils.exec(credentials_cmd)
  830. .then(() => {
  831. return utils.exec(prepare_cmd)
  832. .then(() => {
  833. return utils.exec(main_cmd)
  834. .then(async (result) => {
  835. await utils.exec(teardown_cmd);
  836. logger.info(result);
  837. return result;
  838. });
  839. });
  840. });
  841. },
  842. /**
  843. * @param {Object} certificate the certificate row
  844. * @param {Boolean} [throw_errors]
  845. * @returns {Promise}
  846. */
  847. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  848. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  849. let cmd = certbot_command + ' revoke --non-interactive ' +
  850. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  851. '--delete-after-revoke ' +
  852. (le_staging ? '--staging' : '');
  853. if (debug_mode) {
  854. logger.info('Command:', cmd);
  855. }
  856. return utils.exec(cmd)
  857. .then((result) => {
  858. if (debug_mode) {
  859. logger.info('Command:', cmd);
  860. }
  861. logger.info(result);
  862. return result;
  863. })
  864. .catch((err) => {
  865. if (debug_mode) {
  866. logger.error(err.message);
  867. }
  868. if (throw_errors) {
  869. throw err;
  870. }
  871. });
  872. },
  873. /**
  874. * @param {Object} certificate
  875. * @returns {Boolean}
  876. */
  877. hasLetsEncryptSslCerts: (certificate) => {
  878. let le_path = '/etc/letsencrypt/live/npm-' + certificate.id;
  879. return fs.existsSync(le_path + '/fullchain.pem') && fs.existsSync(le_path + '/privkey.pem');
  880. },
  881. /**
  882. * @param {Object} in_use_result
  883. * @param {Number} in_use_result.total_count
  884. * @param {Array} in_use_result.proxy_hosts
  885. * @param {Array} in_use_result.redirection_hosts
  886. * @param {Array} in_use_result.dead_hosts
  887. */
  888. disableInUseHosts: (in_use_result) => {
  889. if (in_use_result.total_count) {
  890. let promises = [];
  891. if (in_use_result.proxy_hosts.length) {
  892. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  893. }
  894. if (in_use_result.redirection_hosts.length) {
  895. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  896. }
  897. if (in_use_result.dead_hosts.length) {
  898. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  899. }
  900. return Promise.all(promises);
  901. } else {
  902. return Promise.resolve();
  903. }
  904. },
  905. /**
  906. * @param {Object} in_use_result
  907. * @param {Number} in_use_result.total_count
  908. * @param {Array} in_use_result.proxy_hosts
  909. * @param {Array} in_use_result.redirection_hosts
  910. * @param {Array} in_use_result.dead_hosts
  911. */
  912. enableInUseHosts: (in_use_result) => {
  913. if (in_use_result.total_count) {
  914. let promises = [];
  915. if (in_use_result.proxy_hosts.length) {
  916. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  917. }
  918. if (in_use_result.redirection_hosts.length) {
  919. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  920. }
  921. if (in_use_result.dead_hosts.length) {
  922. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  923. }
  924. return Promise.all(promises);
  925. } else {
  926. return Promise.resolve();
  927. }
  928. }
  929. };
  930. module.exports = internalCertificate;