diff --git a/backend/internal/certificate.js b/backend/internal/certificate.js index 401c560..d8330b4 100644 --- a/backend/internal/certificate.js +++ b/backend/internal/certificate.js @@ -1,5 +1,6 @@ const _ = require('lodash'); const fs = require('fs'); +const https = require('https'); const tempWrite = require('temp-write'); const moment = require('moment'); const logger = require('../logger').ssl; @@ -15,6 +16,7 @@ const letsencryptConfig = '/etc/letsencrypt.ini'; const certbotCommand = 'certbot'; const archiver = require('archiver'); const path = require('path'); +const { isArray } = require('lodash'); function omissions() { return ['is_deleted']; @@ -1119,6 +1121,87 @@ const internalCertificate = { } else { return Promise.resolve(); } + }, + + testHttpsChallenge: async (access, domains) => { + await access.can('certificates:list'); + + if (!isArray(domains)) { + throw new error.InternalValidationError('Domains must be an array of strings'); + } + if (domains.length === 0) { + throw new error.InternalValidationError('No domains provided'); + } + + // Create a test challenge file + const testChallengeDir = '/data/letsencrypt-acme-challenge/.well-known/acme-challenge'; + const testChallengeFile = testChallengeDir + '/test-challenge'; + fs.mkdirSync(testChallengeDir, {recursive: true}); + fs.writeFileSync(testChallengeFile, 'Success', {encoding: 'utf8'}); + + async function performTestForDomain (domain) { + logger.info('Testing http challenge for ' + domain); + const url = `http://${domain}/.well-known/acme-challenge/test-challenge`; + const formBody = `method=G&url=${encodeURI(url)}&bodytype=T&requestbody=&headername=User-Agent&headervalue=None&locationid=1&ch=false&cc=false`; + const options = { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': Buffer.byteLength(formBody) + } + }; + + const result = await new Promise((resolve) => { + + const req = https.request('https://www.site24x7.com/tools/restapi-tester', options, function (res) { + let responseBody = ''; + + res.on('data', (chunk) => responseBody = responseBody + chunk); + res.on('end', function () { + const parsedBody = JSON.parse(responseBody + ''); + if (res.statusCode !== 200) { + logger.warn(`Failed to test HTTP challenge for domain ${domain}`, res); + resolve(undefined); + } + resolve(parsedBody); + }); + }); + + // Make sure to write the request body. + req.write(formBody); + req.end(); + req.on('error', function (e) { logger.warn(`Failed to test HTTP challenge for domain ${domain}`, e); + resolve(undefined); }); + }); + + if (!result) { + // Some error occurred while trying to get the data + return 'failed'; + } else if (`${result.responsecode}` === '200' && result.htmlresponse === 'Success') { + // Server exists and has responded with the correct data + return 'ok'; + } else if (`${result.responsecode}` === '404') { + // Server exists but responded with a 404 + return '404'; + } else if (`${result.responsecode}` === '0' || result.reason.toLowerCase() === 'host unavailable') { + // Server does not exist at domain + return 'no-host'; + } else { + // Other errors + return `other:${result.responsecode}`; + } + } + + const results = {}; + + for (const domain of domains){ + results[domain] = await performTestForDomain(domain); + } + + // Remove the test challenge file + fs.unlinkSync(testChallengeFile); + + return results; } }; diff --git a/backend/routes/api/nginx/certificates.js b/backend/routes/api/nginx/certificates.js index 32995c5..ad5b563 100644 --- a/backend/routes/api/nginx/certificates.js +++ b/backend/routes/api/nginx/certificates.js @@ -68,6 +68,32 @@ router .catch(next); }); +/** + * Test HTTP challenge for domains + * + * /api/nginx/certificates/test-http + */ + router + .route('/test-http') + .options((req, res) => { + res.sendStatus(204); + }) + .all(jwtdecode()) + +/** + * GET /api/nginx/certificates/test-http + * + * Test HTTP challenge for domains + */ + .get((req, res, next) => { + internalCertificate.testHttpsChallenge(res.locals.access, JSON.parse(req.query.domains)) + .then((result) => { + res.status(200) + .send(result); + }) + .catch(next); + }); + /** * Specific certificate * @@ -209,7 +235,6 @@ router .catch(next); }); - /** * Download LE Certs * diff --git a/backend/schema/endpoints/certificates.json b/backend/schema/endpoints/certificates.json index 49fd6a7..955ca75 100644 --- a/backend/schema/endpoints/certificates.json +++ b/backend/schema/endpoints/certificates.json @@ -157,6 +157,17 @@ "targetSchema": { "type": "boolean" } + }, + { + "title": "Test HTTP Challenge", + "description": "Tests whether the HTTP challenge should work", + "href": "/nginx/certificates/{definitions.identity.example}/test-http", + "access": "private", + "method": "GET", + "rel": "info", + "http_header": { + "$ref": "../examples.json#/definitions/auth_header" + } } ] } diff --git a/frontend/js/app/api.js b/frontend/js/app/api.js index 2511a78..6e33a6d 100644 --- a/frontend/js/app/api.js +++ b/frontend/js/app/api.js @@ -685,6 +685,16 @@ module.exports = { return fetch('post', 'nginx/certificates/' + id + '/renew', undefined, {timeout}); }, + /** + * @param {Number} id + * @returns {Promise} + */ + testHttpChallenge: function (domains) { + return fetch('get', 'nginx/certificates/test-http?' + new URLSearchParams({ + domains: JSON.stringify(domains), + })); + }, + /** * @param {Number} id * @returns {Promise} diff --git a/frontend/js/app/controller.js b/frontend/js/app/controller.js index 902659b..ccb2978 100644 --- a/frontend/js/app/controller.js +++ b/frontend/js/app/controller.js @@ -366,6 +366,19 @@ module.exports = { } }, + /** + * Certificate Test Reachability + * + * @param model + */ + showNginxCertificateTestReachability: function (model) { + if (Cache.User.isAdmin() || Cache.User.canManage('certificates')) { + require(['./main', './nginx/certificates/test'], function (App, View) { + App.UI.showModalDialog(new View({model: model})); + }); + } + }, + /** * Audit Log */ diff --git a/frontend/js/app/nginx/certificates/form.ejs b/frontend/js/app/nginx/certificates/form.ejs index c8b1369..7fc1278 100644 --- a/frontend/js/app/nginx/certificates/form.ejs +++ b/frontend/js/app/nginx/certificates/form.ejs @@ -18,6 +18,14 @@
${domain}: ${App.i18n('certificates', 'reachability-ok')}
`; + } else { + allOk = false; + if (status === 'no-host') { + text += `${domain}: ${App.i18n('certificates', 'reachability-not-resolved')}
`; + } else if (status === 'failed') { + text += `${domain}: ${App.i18n('certificates', 'reachability-failed-to-check')}
`; + } else if (status === '404') { + text += `${domain}: ${App.i18n('certificates', 'reachability-404')}
`; + } else if (status.startsWith('other:')) { + const code = status.substring(6); + text += `${domain}: ${App.i18n('certificates', 'reachability-other', {code})}
`; + } else { + // This should never happen + text += `${domain}: ?
`; + } + } + } + + this.ui.waiting.hide(); + if (allOk) { + this.ui.success.html(text).show(); + } else { + this.ui.error.html(text).show(); + } + this.ui.close.prop('disabled', false); + }) + .catch((e) => { + console.error(e); + this.ui.waiting.hide(); + this.ui.error.text(App.i18n('certificates', 'reachability-failed-to-reach-api')).show(); + this.ui.close.prop('disabled', false); + }); + } +}); diff --git a/frontend/js/i18n/messages.json b/frontend/js/i18n/messages.json index 1e00ef7..f231de5 100644 --- a/frontend/js/i18n/messages.json +++ b/frontend/js/i18n/messages.json @@ -188,6 +188,15 @@ "other-certificate-key": "Certificate Key", "other-intermediate-certificate": "Intermediate Certificate", "force-renew": "Renew Now", + "test-reachability": "Test Server Reachability", + "reachability-title": "Test Server Reachability", + "reachability-info": "Test whether the domains are reachable from the public internet using Site24x7. This is not necessary when using the DNS Challenge.", + "reachability-failed-to-reach-api": "Communication with the API failed, is NPM running correctly?", + "reachability-failed-to-check": "Failed to check the reachability due to a communication error with site24x7.com.", + "reachability-ok": "Your server is reachable and creating certificates should be possible.", + "reachability-404": "There is a server found at this domain but it does not seem to be Nginx Proxy Manager. Please make sure your domain points to the IP where your NPM instance is running.", + "reachability-not-resolved": "There is no server available at this domain. Please make sure your domain exists and points to the IP where your NPM instance is running and if necessary port 80 is forwarded in your router.", + "reachability-other": "There is a server found at this domain but it returned an unexpected status code {code}. Is it the NPM server? Please make sure your domain points to the IP where your NPM instance is running.", "download": "Download", "renew-title": "Renew Let'sEncrypt Certificate" },