certificate.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. let key_type = private_key.includes('-----BEGIN RSA') ? 'rsa' : 'ec';
  556. return utils.exec('openssl ' + key_type + ' -in ' + filepath + ' -check -noout 2>&1 ')
  557. .then((result) => {
  558. if (!result.toLowerCase().includes('key ok') && !result.toLowerCase().includes('key valid') ) {
  559. throw new error.ValidationError('Result Validation Error: ' + result);
  560. }
  561. fs.unlinkSync(filepath);
  562. return true;
  563. }).catch((err) => {
  564. fs.unlinkSync(filepath);
  565. throw new error.ValidationError('Certificate Key is not valid (' + err.message + ')', err);
  566. });
  567. });
  568. },
  569. /**
  570. * Uses the openssl command to both validate and get info out of the certificate.
  571. * It will save the file to disk first, then run commands on it, then delete the file.
  572. *
  573. * @param {String} certificate This is the entire cert contents as a string
  574. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  575. */
  576. getCertificateInfo: (certificate, throw_expired) => {
  577. return tempWrite(certificate, '/tmp')
  578. .then((filepath) => {
  579. return internalCertificate.getCertificateInfoFromFile(filepath, throw_expired)
  580. .then((cert_data) => {
  581. fs.unlinkSync(filepath);
  582. return cert_data;
  583. }).catch((err) => {
  584. fs.unlinkSync(filepath);
  585. throw err;
  586. });
  587. });
  588. },
  589. /**
  590. * Uses the openssl command to both validate and get info out of the certificate.
  591. * It will save the file to disk first, then run commands on it, then delete the file.
  592. *
  593. * @param {String} certificate_file The file location on disk
  594. * @param {Boolean} [throw_expired] Throw when the certificate is out of date
  595. */
  596. getCertificateInfoFromFile: (certificate_file, throw_expired) => {
  597. let cert_data = {};
  598. return utils.exec('openssl x509 -in ' + certificate_file + ' -subject -noout')
  599. .then((result) => {
  600. // subject=CN = something.example.com
  601. let regex = /(?:subject=)?[^=]+=\s+(\S+)/gim;
  602. let match = regex.exec(result);
  603. if (typeof match[1] === 'undefined') {
  604. throw new error.ValidationError('Could not determine subject from certificate: ' + result);
  605. }
  606. cert_data['cn'] = match[1];
  607. })
  608. .then(() => {
  609. return utils.exec('openssl x509 -in ' + certificate_file + ' -issuer -noout');
  610. })
  611. .then((result) => {
  612. // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
  613. let regex = /^(?:issuer=)?(.*)$/gim;
  614. let match = regex.exec(result);
  615. if (typeof match[1] === 'undefined') {
  616. throw new error.ValidationError('Could not determine issuer from certificate: ' + result);
  617. }
  618. cert_data['issuer'] = match[1];
  619. })
  620. .then(() => {
  621. return utils.exec('openssl x509 -in ' + certificate_file + ' -dates -noout');
  622. })
  623. .then((result) => {
  624. // notBefore=Jul 14 04:04:29 2018 GMT
  625. // notAfter=Oct 12 04:04:29 2018 GMT
  626. let valid_from = null;
  627. let valid_to = null;
  628. let lines = result.split('\n');
  629. lines.map(function (str) {
  630. let regex = /^(\S+)=(.*)$/gim;
  631. let match = regex.exec(str.trim());
  632. if (match && typeof match[2] !== 'undefined') {
  633. let date = parseInt(moment(match[2], 'MMM DD HH:mm:ss YYYY z').format('X'), 10);
  634. if (match[1].toLowerCase() === 'notbefore') {
  635. valid_from = date;
  636. } else if (match[1].toLowerCase() === 'notafter') {
  637. valid_to = date;
  638. }
  639. }
  640. });
  641. if (!valid_from || !valid_to) {
  642. throw new error.ValidationError('Could not determine dates from certificate: ' + result);
  643. }
  644. if (throw_expired && valid_to < parseInt(moment().format('X'), 10)) {
  645. throw new error.ValidationError('Certificate has expired');
  646. }
  647. cert_data['dates'] = {
  648. from: valid_from,
  649. to: valid_to
  650. };
  651. return cert_data;
  652. }).catch((err) => {
  653. throw new error.ValidationError('Certificate is not valid (' + err.message + ')', err);
  654. });
  655. },
  656. /**
  657. * Cleans the ssl keys from the meta object and sets them to "true"
  658. *
  659. * @param {Object} meta
  660. * @param {Boolean} [remove]
  661. * @returns {Object}
  662. */
  663. cleanMeta: function (meta, remove) {
  664. internalCertificate.allowed_ssl_files.map((key) => {
  665. if (typeof meta[key] !== 'undefined' && meta[key]) {
  666. if (remove) {
  667. delete meta[key];
  668. } else {
  669. meta[key] = true;
  670. }
  671. }
  672. });
  673. return meta;
  674. },
  675. /**
  676. * @param {Object} certificate the certificate row
  677. * @returns {Promise}
  678. */
  679. requestLetsEncryptSsl: (certificate) => {
  680. logger.info('Requesting Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  681. let cmd = certbot_command + ' certonly --non-interactive ' +
  682. '--config "' + le_config + '" ' +
  683. '--cert-name "npm-' + certificate.id + '" ' +
  684. '--agree-tos ' +
  685. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  686. '--preferred-challenges "dns,http" ' +
  687. '--domains "' + certificate.domain_names.join(',') + '" ' +
  688. (le_staging ? '--staging' : '');
  689. if (debug_mode) {
  690. logger.info('Command:', cmd);
  691. }
  692. return utils.exec(cmd)
  693. .then((result) => {
  694. logger.success(result);
  695. return result;
  696. });
  697. },
  698. /**
  699. * @param {Object} certificate the certificate row
  700. * @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.js`)
  701. * @param {String | null} credentials the content of this providers credentials file
  702. * @param {String} propagation_seconds the cloudflare api token
  703. * @returns {Promise}
  704. */
  705. requestLetsEncryptSslWithDnsChallenge: (certificate) => {
  706. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  707. if (!dns_plugin) {
  708. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  709. }
  710. logger.info(`Requesting Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  711. const credentials_loc = '/etc/letsencrypt/credentials-' + certificate.id;
  712. const credentials_cmd = 'echo \'' + certificate.meta.dns_provider_credentials.replace('\'', '\\\'') + '\' > \'' + credentials_loc + '\' && chmod 600 \'' + credentials_loc + '\'';
  713. const prepare_cmd = 'pip3 install ' + dns_plugin.package_name + '==' + dns_plugin.package_version;
  714. // Whether the plugin has a --<name>-credentials argument
  715. const has_config_arg = certificate.meta.dns_provider !== 'route53';
  716. let main_cmd =
  717. certbot_command + ' certonly --non-interactive ' +
  718. '--cert-name "npm-' + certificate.id + '" ' +
  719. '--agree-tos ' +
  720. '--email "' + certificate.meta.letsencrypt_email + '" ' +
  721. '--domains "' + certificate.domain_names.join(',') + '" ' +
  722. '--authenticator ' + dns_plugin.full_plugin_name + ' ' +
  723. (
  724. has_config_arg
  725. ? '--' + dns_plugin.full_plugin_name + '-credentials "' + credentials_loc + '"'
  726. : ''
  727. ) +
  728. (
  729. certificate.meta.propagation_seconds !== undefined
  730. ? ' --' + dns_plugin.full_plugin_name + '-propagation-seconds ' + certificate.meta.propagation_seconds
  731. : ''
  732. ) +
  733. (le_staging ? ' --staging' : '');
  734. // Prepend the path to the credentials file as an environment variable
  735. if (certificate.meta.dns_provider === 'route53') {
  736. main_cmd = 'AWS_CONFIG_FILE=\'' + credentials_loc + '\' ' + main_cmd;
  737. }
  738. const teardown_cmd = `rm '${credentials_loc}'`;
  739. if (debug_mode) {
  740. logger.info('Command:', `${credentials_cmd} && ${prepare_cmd} && ${main_cmd} && ${teardown_cmd}`);
  741. }
  742. return utils.exec(credentials_cmd)
  743. .then(() => {
  744. return utils.exec(prepare_cmd)
  745. .then(() => {
  746. return utils.exec(main_cmd)
  747. .then(async (result) => {
  748. await utils.exec(teardown_cmd);
  749. logger.info(result);
  750. return result;
  751. });
  752. });
  753. });
  754. },
  755. /**
  756. * @param {Access} access
  757. * @param {Object} data
  758. * @param {Number} data.id
  759. * @returns {Promise}
  760. */
  761. renew: (access, data) => {
  762. return access.can('certificates:update', data)
  763. .then(() => {
  764. return internalCertificate.get(access, data);
  765. })
  766. .then((certificate) => {
  767. if (certificate.provider === 'letsencrypt') {
  768. let renewMethod = certificate.meta.dns_challenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge : internalCertificate.renewLetsEncryptSsl;
  769. return renewMethod(certificate)
  770. .then(() => {
  771. return internalCertificate.getCertificateInfoFromFile('/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem');
  772. })
  773. .then((cert_info) => {
  774. return certificateModel
  775. .query()
  776. .patchAndFetchById(certificate.id, {
  777. expires_on: moment(cert_info.dates.to, 'X').format('YYYY-MM-DD HH:mm:ss')
  778. });
  779. })
  780. .then((updated_certificate) => {
  781. // Add to audit log
  782. return internalAuditLog.add(access, {
  783. action: 'renewed',
  784. object_type: 'certificate',
  785. object_id: updated_certificate.id,
  786. meta: updated_certificate
  787. })
  788. .then(() => {
  789. return updated_certificate;
  790. });
  791. });
  792. } else {
  793. throw new error.ValidationError('Only Let\'sEncrypt certificates can be renewed');
  794. }
  795. });
  796. },
  797. /**
  798. * @param {Object} certificate the certificate row
  799. * @returns {Promise}
  800. */
  801. renewLetsEncryptSsl: (certificate) => {
  802. logger.info('Renewing Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  803. let cmd = certbot_command + ' renew --non-interactive ' +
  804. '--config "' + le_config + '" ' +
  805. '--cert-name "npm-' + certificate.id + '" ' +
  806. '--preferred-challenges "dns,http" ' +
  807. '--disable-hook-validation ' +
  808. (le_staging ? '--staging' : '');
  809. if (debug_mode) {
  810. logger.info('Command:', cmd);
  811. }
  812. return utils.exec(cmd)
  813. .then((result) => {
  814. logger.info(result);
  815. return result;
  816. });
  817. },
  818. /**
  819. * @param {Object} certificate the certificate row
  820. * @returns {Promise}
  821. */
  822. renewLetsEncryptSslWithDnsChallenge: (certificate) => {
  823. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  824. if (!dns_plugin) {
  825. throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
  826. }
  827. logger.info(`Renewing Let'sEncrypt certificates via ${dns_plugin.display_name} for Cert #${certificate.id}: ${certificate.domain_names.join(', ')}`);
  828. const credentials_loc = '/etc/letsencrypt/credentials-' + certificate.id;
  829. const credentials_cmd = 'echo \'' + certificate.meta.dns_provider_credentials.replace('\'', '\\\'') + '\' > \'' + credentials_loc + '\' && chmod 600 \'' + credentials_loc + '\'';
  830. const prepare_cmd = 'pip3 install ' + dns_plugin.package_name + '==' + dns_plugin.package_version;
  831. let main_cmd =
  832. certbot_command + ' renew --non-interactive ' +
  833. '--cert-name "npm-' + certificate.id + '" ' +
  834. '--disable-hook-validation' +
  835. (le_staging ? ' --staging' : '');
  836. // Prepend the path to the credentials file as an environment variable
  837. if (certificate.meta.dns_provider === 'route53') {
  838. main_cmd = 'AWS_CONFIG_FILE=\'' + credentials_loc + '\' ' + main_cmd;
  839. }
  840. const teardown_cmd = `rm '${credentials_loc}'`;
  841. if (debug_mode) {
  842. logger.info('Command:', `${credentials_cmd} && ${prepare_cmd} && ${main_cmd} && ${teardown_cmd}`);
  843. }
  844. return utils.exec(credentials_cmd)
  845. .then(() => {
  846. return utils.exec(prepare_cmd)
  847. .then(() => {
  848. return utils.exec(main_cmd)
  849. .then(async (result) => {
  850. await utils.exec(teardown_cmd);
  851. logger.info(result);
  852. return result;
  853. });
  854. });
  855. });
  856. },
  857. /**
  858. * @param {Object} certificate the certificate row
  859. * @param {Boolean} [throw_errors]
  860. * @returns {Promise}
  861. */
  862. revokeLetsEncryptSsl: (certificate, throw_errors) => {
  863. logger.info('Revoking Let\'sEncrypt certificates for Cert #' + certificate.id + ': ' + certificate.domain_names.join(', '));
  864. let cmd = certbot_command + ' revoke --non-interactive ' +
  865. '--cert-path "/etc/letsencrypt/live/npm-' + certificate.id + '/fullchain.pem" ' +
  866. '--delete-after-revoke ' +
  867. (le_staging ? '--staging' : '');
  868. if (debug_mode) {
  869. logger.info('Command:', cmd);
  870. }
  871. return utils.exec(cmd)
  872. .then((result) => {
  873. if (debug_mode) {
  874. logger.info('Command:', cmd);
  875. }
  876. logger.info(result);
  877. return result;
  878. })
  879. .catch((err) => {
  880. if (debug_mode) {
  881. logger.error(err.message);
  882. }
  883. if (throw_errors) {
  884. throw err;
  885. }
  886. });
  887. },
  888. /**
  889. * @param {Object} certificate
  890. * @returns {Boolean}
  891. */
  892. hasLetsEncryptSslCerts: (certificate) => {
  893. let le_path = '/etc/letsencrypt/live/npm-' + certificate.id;
  894. return fs.existsSync(le_path + '/fullchain.pem') && fs.existsSync(le_path + '/privkey.pem');
  895. },
  896. /**
  897. * @param {Object} in_use_result
  898. * @param {Number} in_use_result.total_count
  899. * @param {Array} in_use_result.proxy_hosts
  900. * @param {Array} in_use_result.redirection_hosts
  901. * @param {Array} in_use_result.dead_hosts
  902. */
  903. disableInUseHosts: (in_use_result) => {
  904. if (in_use_result.total_count) {
  905. let promises = [];
  906. if (in_use_result.proxy_hosts.length) {
  907. promises.push(internalNginx.bulkDeleteConfigs('proxy_host', in_use_result.proxy_hosts));
  908. }
  909. if (in_use_result.redirection_hosts.length) {
  910. promises.push(internalNginx.bulkDeleteConfigs('redirection_host', in_use_result.redirection_hosts));
  911. }
  912. if (in_use_result.dead_hosts.length) {
  913. promises.push(internalNginx.bulkDeleteConfigs('dead_host', in_use_result.dead_hosts));
  914. }
  915. return Promise.all(promises);
  916. } else {
  917. return Promise.resolve();
  918. }
  919. },
  920. /**
  921. * @param {Object} in_use_result
  922. * @param {Number} in_use_result.total_count
  923. * @param {Array} in_use_result.proxy_hosts
  924. * @param {Array} in_use_result.redirection_hosts
  925. * @param {Array} in_use_result.dead_hosts
  926. */
  927. enableInUseHosts: (in_use_result) => {
  928. if (in_use_result.total_count) {
  929. let promises = [];
  930. if (in_use_result.proxy_hosts.length) {
  931. promises.push(internalNginx.bulkGenerateConfigs('proxy_host', in_use_result.proxy_hosts));
  932. }
  933. if (in_use_result.redirection_hosts.length) {
  934. promises.push(internalNginx.bulkGenerateConfigs('redirection_host', in_use_result.redirection_hosts));
  935. }
  936. if (in_use_result.dead_hosts.length) {
  937. promises.push(internalNginx.bulkGenerateConfigs('dead_host', in_use_result.dead_hosts));
  938. }
  939. return Promise.all(promises);
  940. } else {
  941. return Promise.resolve();
  942. }
  943. }
  944. };
  945. module.exports = internalCertificate;