certificate.js 31 KB

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