certificate.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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. }).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. .omit(omissions())
  248. .patchAndFetchById(row.id, data)
  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 _.omit(saved_row, omissions());
  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. .allowEager('[owner]')
  288. .first();
  289. if (access_data.permission_visibility !== 'all') {
  290. query.andWhere('owner_user_id', access.token.getUserId(1));
  291. }
  292. // Custom omissions
  293. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  294. query.omit(data.omit);
  295. }
  296. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  297. query.eager('[' + data.expand.join(', ') + ']');
  298. }
  299. return query;
  300. })
  301. .then((row) => {
  302. if (row) {
  303. return _.omit(row, omissions());
  304. } else {
  305. throw new error.ItemNotFoundError(data.id);
  306. }
  307. });
  308. },
  309. /**
  310. * @param {Access} access
  311. * @param {Object} data
  312. * @param {Number} data.id
  313. * @param {String} [data.reason]
  314. * @returns {Promise}
  315. */
  316. delete: (access, data) => {
  317. return access.can('certificates:delete', data.id)
  318. .then(() => {
  319. return internalCertificate.get(access, {id: data.id});
  320. })
  321. .then((row) => {
  322. if (!row) {
  323. throw new error.ItemNotFoundError(data.id);
  324. }
  325. return certificateModel
  326. .query()
  327. .where('id', row.id)
  328. .patch({
  329. is_deleted: 1
  330. })
  331. .then(() => {
  332. // Add to audit log
  333. row.meta = internalCertificate.cleanMeta(row.meta);
  334. return internalAuditLog.add(access, {
  335. action: 'deleted',
  336. object_type: 'certificate',
  337. object_id: row.id,
  338. meta: _.omit(row, omissions())
  339. });
  340. })
  341. .then(() => {
  342. if (row.provider === 'letsencrypt') {
  343. // Revoke the cert
  344. return internalCertificate.revokeLetsEncryptSsl(row);
  345. }
  346. });
  347. })
  348. .then(() => {
  349. return true;
  350. });
  351. },
  352. /**
  353. * All Certs
  354. *
  355. * @param {Access} access
  356. * @param {Array} [expand]
  357. * @param {String} [search_query]
  358. * @returns {Promise}
  359. */
  360. getAll: (access, expand, search_query) => {
  361. return access.can('certificates:list')
  362. .then((access_data) => {
  363. let query = certificateModel
  364. .query()
  365. .where('is_deleted', 0)
  366. .groupBy('id')
  367. .omit(['is_deleted'])
  368. .allowEager('[owner]')
  369. .orderBy('nice_name', 'ASC');
  370. if (access_data.permission_visibility !== 'all') {
  371. query.andWhere('owner_user_id', access.token.getUserId(1));
  372. }
  373. // Query is used for searching
  374. if (typeof search_query === 'string') {
  375. query.where(function () {
  376. this.where('name', 'like', '%' + search_query + '%');
  377. });
  378. }
  379. if (typeof expand !== 'undefined' && expand !== null) {
  380. query.eager('[' + expand.join(', ') + ']');
  381. }
  382. return query;
  383. });
  384. },
  385. /**
  386. * Report use
  387. *
  388. * @param {Number} user_id
  389. * @param {String} visibility
  390. * @returns {Promise}
  391. */
  392. getCount: (user_id, visibility) => {
  393. let query = certificateModel
  394. .query()
  395. .count('id as count')
  396. .where('is_deleted', 0);
  397. if (visibility !== 'all') {
  398. query.andWhere('owner_user_id', user_id);
  399. }
  400. return query.first()
  401. .then((row) => {
  402. return parseInt(row.count, 10);
  403. });
  404. },
  405. /**
  406. * @param {Object} certificate
  407. * @returns {Promise}
  408. */
  409. writeCustomCert: (certificate) => {
  410. if (debug_mode) {
  411. logger.info('Writing Custom Certificate:', certificate);
  412. }
  413. let dir = '/data/custom_ssl/npm-' + certificate.id;
  414. return new Promise((resolve, reject) => {
  415. if (certificate.provider === 'letsencrypt') {
  416. reject(new Error('Refusing to write letsencrypt certs here'));
  417. return;
  418. }
  419. let cert_data = certificate.meta.certificate;
  420. if (typeof certificate.meta.intermediate_certificate !== 'undefined') {
  421. cert_data = cert_data + '\n' + certificate.meta.intermediate_certificate;
  422. }
  423. try {
  424. if (!fs.existsSync(dir)) {
  425. fs.mkdirSync(dir);
  426. }
  427. } catch (err) {
  428. reject(err);
  429. return;
  430. }
  431. fs.writeFile(dir + '/fullchain.pem', cert_data, function (err) {
  432. if (err) {
  433. reject(err);
  434. } else {
  435. resolve();
  436. }
  437. });
  438. })
  439. .then(() => {
  440. return new Promise((resolve, reject) => {
  441. fs.writeFile(dir + '/privkey.pem', certificate.meta.certificate_key, function (err) {
  442. if (err) {
  443. reject(err);
  444. } else {
  445. resolve();
  446. }
  447. });
  448. });
  449. });
  450. },
  451. /**
  452. * @param {Access} access
  453. * @param {Object} data
  454. * @param {Array} data.domain_names
  455. * @param {String} data.meta.letsencrypt_email
  456. * @param {Boolean} data.meta.letsencrypt_agree
  457. * @returns {Promise}
  458. */
  459. createQuickCertificate: (access, data) => {
  460. return internalCertificate.create(access, {
  461. provider: 'letsencrypt',
  462. domain_names: data.domain_names,
  463. meta: data.meta
  464. });
  465. },
  466. /**
  467. * Validates that the certs provided are good.
  468. * No access required here, nothing is changed or stored.
  469. *
  470. * @param {Object} data
  471. * @param {Object} data.files
  472. * @returns {Promise}
  473. */
  474. validate: (data) => {
  475. return new Promise((resolve) => {
  476. // Put file contents into an object
  477. let files = {};
  478. _.map(data.files, (file, name) => {
  479. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  480. files[name] = file.data.toString();
  481. }
  482. });
  483. resolve(files);
  484. })
  485. .then((files) => {
  486. // For each file, create a temp file and write the contents to it
  487. // Then test it depending on the file type
  488. let promises = [];
  489. _.map(files, (content, type) => {
  490. promises.push(new Promise((resolve) => {
  491. if (type === 'certificate_key') {
  492. resolve(internalCertificate.checkPrivateKey(content));
  493. } else {
  494. // this should handle `certificate` and intermediate certificate
  495. resolve(internalCertificate.getCertificateInfo(content, true));
  496. }
  497. }).then((res) => {
  498. return {[type]: res};
  499. }));
  500. });
  501. return Promise.all(promises)
  502. .then((files) => {
  503. let data = {};
  504. _.each(files, (file) => {
  505. data = _.assign({}, data, file);
  506. });
  507. return data;
  508. });
  509. });
  510. },
  511. /**
  512. * @param {Access} access
  513. * @param {Object} data
  514. * @param {Number} data.id
  515. * @param {Object} data.files
  516. * @returns {Promise}
  517. */
  518. upload: (access, data) => {
  519. return internalCertificate.get(access, {id: data.id})
  520. .then((row) => {
  521. if (row.provider !== 'other') {
  522. throw new error.ValidationError('Cannot upload certificates for this type of provider');
  523. }
  524. return internalCertificate.validate(data)
  525. .then((validations) => {
  526. if (typeof validations.certificate === 'undefined') {
  527. throw new error.ValidationError('Certificate file was not provided');
  528. }
  529. _.map(data.files, (file, name) => {
  530. if (internalCertificate.allowed_ssl_files.indexOf(name) !== -1) {
  531. row.meta[name] = file.data.toString();
  532. }
  533. });
  534. // TODO: This uses a mysql only raw function that won't translate to postgres
  535. return internalCertificate.update(access, {
  536. id: data.id,
  537. expires_on: moment(validations.certificate.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss'),
  538. domain_names: [validations.certificate.cn],
  539. meta: _.clone(row.meta) // Prevent the update method from changing this value that we'll use later
  540. })
  541. .then((certificate) => {
  542. console.log('ROWMETA:', row.meta);
  543. certificate.meta = row.meta;
  544. return internalCertificate.writeCustomCert(certificate);
  545. });
  546. })
  547. .then(() => {
  548. return _.pick(row.meta, internalCertificate.allowed_ssl_files);
  549. });
  550. });
  551. },
  552. /**
  553. * Uses the openssl command to validate the private key.
  554. * It will save the file to disk first, then run commands on it, then delete the file.
  555. *
  556. * @param {String} private_key This is the entire key contents as a string
  557. */
  558. checkPrivateKey: (private_key) => {
  559. return tempWrite(private_key, '/tmp')
  560. .then((filepath) => {
  561. let key_type = private_key.includes('-----BEGIN RSA') ? 'rsa' : 'ec';
  562. return utils.exec('openssl ' + key_type + ' -in ' + filepath + ' -check -noout 2>&1 ')
  563. .then((result) => {
  564. if (!result.toLowerCase().includes('key ok') && !result.toLowerCase().includes('key valid') ) {
  565. throw new error.ValidationError('Result Validation Error: ' + result);
  566. }
  567. fs.unlinkSync(filepath);
  568. return true;
  569. }).catch((err) => {
  570. fs.unlinkSync(filepath);
  571. throw new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err);
  572. });
  573. });
  574. },
  575. /**
  576. * Uses the openssl command to both validate and get info out of the certificate.
  577. * It will save the file to disk first, then run commands on it, then delete the file.
  578. *
  579. * @param {String} certificate This is the entire cert contents as a string
  580. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  581. */
  582. getCertificateInfo: (certificate, throw_expired) => {
  583. return tempWrite(certificate, '/tmp')
  584. .then((filepath) => {
  585. return internalCertificate.getCertificateInfoFromFile(filepath, throw_expired)
  586. .then((cert_data) => {
  587. fs.unlinkSync(filepath);
  588. return cert_data;
  589. }).catch((err) => {
  590. fs.unlinkSync(filepath);
  591. throw err;
  592. });
  593. });
  594. },
  595. /**
  596. * Uses the openssl command to both validate and get info out of the certificate.
  597. * It will save the file to disk first, then run commands on it, then delete the file.
  598. *
  599. * @param {String} certificate_file The file location on disk
  600. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  601. */
  602. getCertificateInfoFromFile: (certificate_file, throw_expired) => {
  603. let cert_data = {};
  604. return utils.exec('openssl x509 -in ' + certificate_file + ' -subject -noout')
  605. .then((result) => {
  606. // subject=CN = something.example.com
  607. let regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  608. let match = regex.exec(result);
  609. if (typeof match[1] === 'undefined') {
  610. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  611. }
  612. cert_data['cn'] = match[1];
  613. })
  614. .then(() => {
  615. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  616. })
  617. .then((result) => {
  618. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  619. let regex = /^(?:issuer=)?(.*)$/gim;
  620. let match = regex.exec(result);
  621. if (typeof match[1] === 'undefined') {
  622. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  623. }
  624. cert_data['issuer'] = match[1];
  625. })
  626. .then(() => {
  627. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  628. })
  629. .then((result) => {
  630. // notBefore=Jul 14 04:04:29 2018 GMT
  631. // notAfter=Oct 12 04:04:29 2018 GMT
  632. let valid_from = null;
  633. let valid_to = null;
  634. let lines = result.split('\n');
  635. lines.map(function (str) {
  636. let regex = /^(\S+)=(.*)$/gim;
  637. let match = regex.exec(str.trim());
  638. if (match && typeof match[2] !== 'undefined') {
  639. let date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  640. if (match[1].toLowerCase() === 'notbefore') {
  641. valid_from = date;
  642. } else if (match[1].toLowerCase() === 'notafter') {
  643. valid_to = date;
  644. }
  645. }
  646. });
  647. if (!valid_from || !valid_to) {
  648. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  649. }
  650. if (throw_expired && valid_to < parseInt(moment().format('X'), 10)) {
  651. throw new error.ValidationError('Certificate has expired');
  652. }
  653. cert_data['dates'] = {
  654. from: valid_from,
  655. to: valid_to
  656. };
  657. return cert_data;
  658. }).catch((err) => {
  659. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  660. });
  661. },
  662. /**
  663. * Cleans the ssl keys from the meta object and sets them to "true"
  664. *
  665. * @param {Object} meta
  666. * @param {Boolean} [remove]
  667. * @returns {Object}
  668. */
  669. cleanMeta: function (meta, remove) {
  670. internalCertificate.allowed_ssl_files.map((key) => {
  671. if (typeof meta[key] !== 'undefined' && meta[key]) {
  672. if (remove) {
  673. delete meta[key];
  674. } else {
  675. meta[key] = true;
  676. }
  677. }
  678. });
  679. return meta;
  680. },
  681. /**
  682. * @param {Object} certificate the certificate row
  683. * @returns {Promise}
  684. */
  685. requestLetsEncryptSsl: (certificate) => {
  686. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  687. let cmd = certbot_command + ' certonly --non-interactive ' +
  688. '--config "' + le_config + '" ' +
  689. '--cert-name "npm-' + certificate.id + '" ' +
  690. '--agree-tos ' +
  691. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  692. '--preferred-challenges "dns,http" ' +
  693. '--domains "' + certificate.domain_names.join(',') + '" ' +
  694. (le_staging ? '--staging' : '');
  695. if (debug_mode) {
  696. logger.info('Command:', cmd);
  697. }
  698. return utils.exec(cmd)
  699. .then((result) => {
  700. logger.success(result);
  701. return result;
  702. });
  703. },
  704. /**
  705. * @param {Object} certificate the certificate row
  706. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  707. * @param {String | null} credentials the content of this providers credentials file
  708. * @param {String} propagation_seconds the cloudflare api token
  709. * @returns {Promise}
  710. */
  711. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  712. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  713. if (!dns_plugin) {
  714. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  715. }
  716. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  717. const credentials_loc = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  718. const credentials_cmd = 'mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + certificate.meta.dns_provider_credentials.replace('\'', '\\\'') + '\' > \'' + credentials_loc + '\' && chmod 600 \'' + credentials_loc + '\'';
  719. const prepare_cmd = 'pip3 install ' + dns_plugin.package_name + '==' + dns_plugin.package_version + ' ' + dns_plugin.dependencies;
  720. // Whether the plugin has a --<name>-credentials argument
  721. const has_config_arg = certificate.meta.dns_provider !== 'route53';
  722. let main_cmd =
  723. certbot_command + ' certonly --non-interactive ' +
  724. '--cert-name "npm-' + certificate.id + '" ' +
  725. '--agree-tos ' +
  726. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  727. '--domains "' + certificate.domain_names.join(',') + '" ' +
  728. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  729. (
  730. has_config_arg
  731. ? '--' + dns_plugin.full_plugin_name + '-credentials "' + credentials_loc + '"'
  732. : ''
  733. ) +
  734. (
  735. certificate.meta.propagation_seconds !== undefined
  736. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  737. : ''
  738. ) +
  739. (le_staging ? ' --staging' : '');
  740. // Prepend the path to the credentials file as an environment variable
  741. if (certificate.meta.dns_provider === 'route53') {
  742. main_cmd = 'AWS_CONFIG_FILE=\'' + credentials_loc + '\' ' + main_cmd;
  743. }
  744. if (debug_mode) {
  745. logger.info('Command:', `${credentials_cmd} && ${prepare_cmd} && ${main_cmd}`);
  746. }
  747. return utils.exec(credentials_cmd)
  748. .then(() => {
  749. return utils.exec(prepare_cmd)
  750. .then(() => {
  751. return utils.exec(main_cmd)
  752. .then(async (result) => {
  753. logger.info(result);
  754. return result;
  755. });
  756. });
  757. }).catch(async (err) => {
  758. // Don't fail if file does not exist
  759. const delete_credentials_cmd = `rm -f '${credentials_loc}' || true`;
  760. await utils.exec(delete_credentials_cmd);
  761. throw err;
  762. });
  763. },
  764. /**
  765. * @param {Access} access
  766. * @param {Object} data
  767. * @param {Number} data.id
  768. * @returns {Promise}
  769. */
  770. renew: (access, data) => {
  771. return access.can('certificates:update', data)
  772. .then(() => {
  773. return internalCertificate.get(access, data);
  774. })
  775. .then((certificate) => {
  776. if (certificate.provider === 'letsencrypt') {
  777. let renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  778. return renewMethod(certificate)
  779. .then(() => {
  780. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  781. })
  782. .then((cert_info) => {
  783. return certificateModel
  784. .query()
  785. .patchAndFetchById(certificate.id, {
  786. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  787. });
  788. })
  789. .then((updated_certificate) => {
  790. // Add to audit log
  791. return internalAuditLog.add(access, {
  792. action: 'renewed',
  793. object_type: 'certificate',
  794. object_id: updated_certificate.id,
  795. meta: updated_certificate
  796. })
  797. .then(() => {
  798. return updated_certificate;
  799. });
  800. });
  801. } else {
  802. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  803. }
  804. });
  805. },
  806. /**
  807. * @param {Object} certificate the certificate row
  808. * @returns {Promise}
  809. */
  810. renewLetsEncryptSsl: (certificate) => {
  811. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  812. let cmd = certbot_command + ' renew --non-interactive ' +
  813. '--config "' + le_config + '" ' +
  814. '--cert-name "npm-' + certificate.id + '" ' +
  815. '--preferred-challenges "dns,http" ' +
  816. '--disable-hook-validation ' +
  817. (le_staging ? '--staging' : '');
  818. if (debug_mode) {
  819. logger.info('Command:', cmd);
  820. }
  821. return utils.exec(cmd)
  822. .then((result) => {
  823. logger.info(result);
  824. return result;
  825. });
  826. },
  827. /**
  828. * @param {Object} certificate the certificate row
  829. * @returns {Promise}
  830. */
  831. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  832. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  833. if (!dns_plugin) {
  834. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  835. }
  836. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  837. let main_cmd =
  838. certbot_command + ' renew --non-interactive ' +
  839. '--cert-name "npm-' + certificate.id + '" ' +
  840. '--disable-hook-validation' +
  841. (le_staging ? ' --staging' : '');
  842. // Prepend the path to the credentials file as an environment variable
  843. if (certificate.meta.dns_provider === 'route53') {
  844. const credentials_loc = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  845. main_cmd = 'AWS_CONFIG_FILE=\'' + credentials_loc + '\' ' + main_cmd;
  846. }
  847. if (debug_mode) {
  848. logger.info('Command:', main_cmd);
  849. }
  850. return utils.exec(main_cmd)
  851. .then(async (result) => {
  852. logger.info(result);
  853. return result;
  854. });
  855. },
  856. /**
  857. * @param {Object} certificate the certificate row
  858. * @param {Boolean} [throw_errors]
  859. * @returns {Promise}
  860. */
  861. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  862. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  863. const main_cmd = certbot_command + ' revoke --non-interactive ' +
  864. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  865. '--delete-after-revoke ' +
  866. (le_staging ? '--staging' : '');
  867. // Don't fail command if file does not exist
  868. const delete_credentials_cmd = `rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`;
  869. if (debug_mode) {
  870. logger.info('Command:', main_cmd + '; ' + delete_credentials_cmd);
  871. }
  872. return utils.exec(main_cmd)
  873. .then(async (result) => {
  874. await utils.exec(delete_credentials_cmd);
  875. logger.info(result);
  876. return result;
  877. })
  878. .catch((err) => {
  879. if (debug_mode) {
  880. logger.error(err.message);
  881. }
  882. if (throw_errors) {
  883. throw err;
  884. }
  885. });
  886. },
  887. /**
  888. * @param {Object} certificate
  889. * @returns {Boolean}
  890. */
  891. hasLetsEncryptSslCerts: (certificate) => {
  892. let le_path = '/etc/letsencrypt/live/npm-' + certificate.id;
  893. return fs.existsSync(le_path + '/fullchain.pem') && fs.existsSync(le_path + '/privkey.pem');
  894. },
  895. /**
  896. * @param {Object} in_use_result
  897. * @param {Number} in_use_result.total_count
  898. * @param {Array} in_use_result.proxy_hosts
  899. * @param {Array} in_use_result.redirection_hosts
  900. * @param {Array} in_use_result.dead_hosts
  901. */
  902. disableInUseHosts: (in_use_result) => {
  903. if (in_use_result.total_count) {
  904. let promises = [];
  905. if (in_use_result.proxy_hosts.length) {
  906. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  907. }
  908. if (in_use_result.redirection_hosts.length) {
  909. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  910. }
  911. if (in_use_result.dead_hosts.length) {
  912. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  913. }
  914. return Promise.all(promises);
  915. } else {
  916. return Promise.resolve();
  917. }
  918. },
  919. /**
  920. * @param {Object} in_use_result
  921. * @param {Number} in_use_result.total_count
  922. * @param {Array} in_use_result.proxy_hosts
  923. * @param {Array} in_use_result.redirection_hosts
  924. * @param {Array} in_use_result.dead_hosts
  925. */
  926. enableInUseHosts: (in_use_result) => {
  927. if (in_use_result.total_count) {
  928. let promises = [];
  929. if (in_use_result.proxy_hosts.length) {
  930. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  931. }
  932. if (in_use_result.redirection_hosts.length) {
  933. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  934. }
  935. if (in_use_result.dead_hosts.length) {
  936. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  937. }
  938. return Promise.all(promises);
  939. } else {
  940. return Promise.resolve();
  941. }
  942. }
  943. };
  944. module.exports = internalCertificate;