Pre-fix: POST /api/v1/site accepted upstreams matching /^[a-z0-9.-]+:\d{1,5}$/i
with no private-IP gate. POST /api/v1/site/external called validateURL()
WITHOUT blockPrivate:true. An authenticated dashboard operator (TOTP + CSRF)
could register upstream=10.0.0.1:80 and have Caddy reverse_proxy public
traffic to an internal host. Caddy runs on DNS2, same network as the targets —
the SSRF lands.
Post-fix: new module helper validateUpstream() in fleet-validation.js
reuses the existing resolveAndCheckAddress() private-range gate (14 IPv4
reserved CIDR ranges, 6 IPv6 reserved ranges including CGNAT/multicast/
IMDS). Async, lastIndexOf(':')-split for bracketed IPv6, port 1..65535
validation, DNS resolution with rebinding defense. Opt-in via
SITES_ALLOW_PRIVATE_UPSTREAMS=true for operators who intentionally proxy
to private targets.
Routes sites.js:184 and :250 throw ValidationError [DC-074] BEFORE
caddy.read()/caddy.modify() is called. 60/60 new tests pass (helper unit,
route integration per private range, regression on canonical SSRF payloads,
helper exports unchanged). Full repo npm test: 4 unrelated billing suites
fail due to missing pdfkit module — pre-existing, not caused by this diff.
325 lines
14 KiB
JavaScript
325 lines
14 KiB
JavaScript
const express = require('express');
|
|
const fs = require('fs');
|
|
const { CADDY, REGEX, LIMITS } = require('../src/utilities/constants');
|
|
const { ValidationError, ConflictError, NotFoundError } = require('../src/utilities/errors');
|
|
const { validateURL } = require('../src/security/input-validator');
|
|
const { ok, successMessage } = require('../src/utils/responses');
|
|
// DC-074: SSRF defense — reject upstream hosts that resolve to
|
|
// private/reserved ranges before they reach the Caddyfile.
|
|
const { validateUpstream } = require('../src/utilities/fleet-validation');
|
|
|
|
/**
|
|
* Sites route factory
|
|
* @param {Object} deps - Explicit dependencies
|
|
* @param {Function} deps.asyncHandler - Async route handler wrapper
|
|
* @param {Object} deps.caddy - Caddy manager
|
|
* @param {Object} deps.dns - DNS manager
|
|
* @param {Function} deps.fetchT - Fetch with timeout
|
|
* @param {Function} deps.buildDomain - Domain builder function
|
|
* @param {Function} deps.addServiceToConfig - Service config adder
|
|
* @param {Object} deps.siteConfig - Site configuration
|
|
* @param {Object} deps.log - Logger instance
|
|
* @returns {express.Router}
|
|
*/
|
|
module.exports = function({ asyncHandler, ok, caddy, dns, fetchT, buildDomain, addServiceToConfig, siteConfig, log }) {
|
|
const router = express.Router();
|
|
|
|
// Get Caddyfile contents
|
|
router.get('/caddyfile', asyncHandler(async (req, res) => {
|
|
const content = await caddy.read();
|
|
ok(res, { content });
|
|
}, 'caddyfile-get'));
|
|
|
|
// Get current Caddy config (from admin API)
|
|
router.get('/caddy/config', asyncHandler(async (req, res) => {
|
|
const response = await fetchT(`${caddy.adminUrl}/config/`);
|
|
const config = await response.json();
|
|
ok(res, { config });
|
|
}, 'caddy-config'));
|
|
|
|
// Reload Caddy configuration via admin API
|
|
router.post('/caddy/reload', asyncHandler(async (req, res) => {
|
|
const caddyfileContent = await caddy.read();
|
|
|
|
const response = await fetchT(`${caddy.adminUrl}/load`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': CADDY.CONTENT_TYPE },
|
|
body: caddyfileContent
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log.error('caddy', new Error(`Caddy reload failed: ${errorText.slice(0, 500)}`));
|
|
throw new Error('Caddy reload failed. Check server logs for details.');
|
|
}
|
|
|
|
successMessage(res, 'Caddy configuration reloaded successfully');
|
|
}, 'caddy-reload'));
|
|
|
|
// Get Certificate Authorities from Caddyfile
|
|
router.get('/caddy/cas', asyncHandler(async (req, res) => {
|
|
const content = await caddy.read();
|
|
const cas = [];
|
|
|
|
const pkiRegex = /pki\s*\{([^}]*(?:\{[^}]*\}[^}]*)*)\}/gs;
|
|
let pkiMatch;
|
|
while ((pkiMatch = pkiRegex.exec(content)) !== null) {
|
|
const pkiBlock = pkiMatch[1];
|
|
let caMatch;
|
|
const caBlockRegex = /ca\s+(\S+)\s*\{([^}]*(?:\{[^}]*\}[^}]*)*)\}/gs;
|
|
while ((caMatch = caBlockRegex.exec(pkiBlock)) !== null) {
|
|
const caName = caMatch[1];
|
|
const caBlock = caMatch[2];
|
|
const ca = { id: caName, name: caName, root: {}, intermediate: {} };
|
|
|
|
const nameMatch = /name\s+"([^"]+)"/.exec(caBlock);
|
|
if (nameMatch) ca.name = nameMatch[1];
|
|
|
|
const rootCnMatch = /root_cn\s+"([^"]+)"/.exec(caBlock);
|
|
const intCnMatch = /intermediate_cn\s+"([^"]+)"/.exec(caBlock);
|
|
if (rootCnMatch) ca.root_cn = rootCnMatch[1];
|
|
if (intCnMatch) ca.intermediate_cn = intCnMatch[1];
|
|
|
|
const rootMatch = /root\s*\{([^}]*)\}/s.exec(caBlock);
|
|
if (rootMatch) {
|
|
const rootBlock = rootMatch[1];
|
|
const certMatch = /cert\s+(\S+)/.exec(rootBlock);
|
|
const keyMatch = /key\s+(\S+)/.exec(rootBlock);
|
|
if (certMatch) ca.root.cert = certMatch[1];
|
|
if (keyMatch) ca.root.key = keyMatch[1];
|
|
}
|
|
|
|
const intMatch = /intermediate\s*\{([^}]*)\}/s.exec(caBlock);
|
|
if (intMatch) {
|
|
const intBlock = intMatch[1];
|
|
const certMatch = /cert\s+(\S+)/.exec(intBlock);
|
|
const keyMatch = /key\s+(\S+)/.exec(intBlock);
|
|
if (certMatch) ca.intermediate.cert = certMatch[1];
|
|
if (keyMatch) ca.intermediate.key = keyMatch[1];
|
|
}
|
|
|
|
cas.push(ca);
|
|
}
|
|
}
|
|
|
|
const tlsGlobalRegex = /\{\s*acme_ca\s+(\S+)/g;
|
|
let tlsMatch;
|
|
while ((tlsMatch = tlsGlobalRegex.exec(content)) !== null) {
|
|
cas.push({ name: 'acme', url: tlsMatch[1], type: 'acme' });
|
|
}
|
|
|
|
const siteBlocks = content.match(/[\w.-]+\s*\{[^}]*tls\s+[^}]*\}/gs) || [];
|
|
const tlsInternalCAs = new Set();
|
|
for (const block of siteBlocks) {
|
|
const tlsInternalMatch = /tls\s+internal\s*\{[^}]*ca\s+(\S+)/s.exec(block);
|
|
if (tlsInternalMatch) tlsInternalCAs.add(tlsInternalMatch[1]);
|
|
if (/tls\s+internal(?:\s|$)/.test(block) && !/tls\s+internal\s*\{/.test(block)) {
|
|
tlsInternalCAs.add('local');
|
|
}
|
|
}
|
|
for (const caName of tlsInternalCAs) {
|
|
if (!cas.find(c => c.name === caName)) {
|
|
cas.push({ name: caName, type: 'internal', note: 'Referenced in tls directive' });
|
|
}
|
|
}
|
|
if (cas.length === 0 && /tls\s+internal/.test(content)) {
|
|
cas.push({ name: 'local', type: 'internal', note: 'Default Caddy internal CA' });
|
|
}
|
|
|
|
const caList = cas.map(ca => ({
|
|
id: ca.id || ca.name,
|
|
name: ca.name,
|
|
displayName: ca.name !== (ca.id || ca.name) ? `${ca.name} (${ca.id || ca.name})` : ca.name
|
|
}));
|
|
ok(res, { cas: caList });
|
|
}, 'caddy-get-cas'));
|
|
|
|
// Remove a site from Caddyfile
|
|
router.delete('/site/:domain', asyncHandler(async (req, res) => {
|
|
const { domain } = req.params;
|
|
if (!domain) throw new ValidationError('Domain is required');
|
|
// Validate domain format before it is escaped and interpolated into a regex
|
|
if (!REGEX.DOMAIN.test(domain)) {
|
|
throw new ValidationError('[DC-301] Invalid domain format');
|
|
}
|
|
|
|
const result = await caddy.modify((content) => {
|
|
const escapedDomain = domain.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
const siteBlockRegex = new RegExp(
|
|
`\\n?${escapedDomain}\\s*\\{[^{}]*(?:\\{[^{}]*(?:\\{[^{}]*\\}[^{}]*)*\\}[^{}]*)*\\}\\s*`, 'g'
|
|
);
|
|
const modified = content.replace(siteBlockRegex, '\n');
|
|
if (modified.length === content.length) return null;
|
|
return modified.replace(/\n{3,}/g, '\n\n');
|
|
});
|
|
|
|
if (!result.success) {
|
|
if (result.rolledBack) {
|
|
throw new Error( `Removed "${domain}" but Caddy reload failed (rolled back): ${result.error}`);
|
|
}
|
|
throw new NotFoundError(`Site block for "" in Caddyfile`);
|
|
}
|
|
|
|
successMessage(res, `Site "${domain}" removed from Caddyfile and Caddy reloaded`);
|
|
}, 'site-delete'));
|
|
|
|
// Add a new site to Caddyfile and reload
|
|
router.post('/site', asyncHandler(async (req, res) => {
|
|
const { domain, upstream, config } = req.body;
|
|
if (!domain || !upstream) throw new ValidationError('Domain and upstream are required');
|
|
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
|
|
|
// DC-074: SSRF defense — reject upstreams that resolve to private/
|
|
// reserved ranges BEFORE we write them into the Caddyfile. Without
|
|
// this, an authenticated dashboard operator can call POST /api/v1/site
|
|
// with `upstream: '10.0.0.1:80'` and end up with a Caddy site block
|
|
// that proxies public traffic to an internal host. Caddy runs on
|
|
// DNS2 (same network as the targets), so the SSRF lands.
|
|
//
|
|
// The existing upstreamRegex /^[a-z0-9.-]+:\d{1,5}$/i only checks
|
|
// charset — it happily accepts 192.168.1.1:80 and 169.254.169.254:80
|
|
// (the AWS metadata IP). validateUpstream() also does a DNS lookup
|
|
// for hostnames so a malicious operator can't sneak a public-looking
|
|
// domain past the gate and have it resolve to a private IP later.
|
|
const upstreamCheck = await validateUpstream(upstream);
|
|
if (!upstreamCheck.ok) {
|
|
// Don't echo attacker-supplied hostnames in the audit log; keep the
|
|
// canonical code + message but never write the raw value.
|
|
log?.warn?.('site', 'POST /site rejected by SSRF gate', { code: upstreamCheck.code });
|
|
throw new ValidationError(`[DC-074] ${upstreamCheck.message} (set SITES_ALLOW_PRIVATE_UPSTREAMS=true to opt in)`);
|
|
}
|
|
|
|
const content = await caddy.read();
|
|
const escapedDomain = domain.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
const siteBlockRegex = new RegExp(`\\n?${escapedDomain}\\s*\\{`, 'g');
|
|
if (siteBlockRegex.test(content)) {
|
|
throw new ConflictError(`Site block for "" already exists in Caddyfile`);
|
|
}
|
|
|
|
// Always generate structured config — never allow raw Caddy config injection
|
|
const newSiteBlock = `\n${domain} {\n reverse_proxy ${upstream}\n tls internal\n}\n`;
|
|
|
|
const result = await caddy.modify(c => c + newSiteBlock);
|
|
if (!result.success) {
|
|
throw new Error( `[DC-303] Site added to Caddyfile but reload failed: ${result.error}`,
|
|
result.rolledBack ? { note: 'Caddyfile was rolled back to previous state' } : {});
|
|
}
|
|
|
|
successMessage(res, `Site "${domain}" added to Caddyfile and Caddy reloaded successfully`);
|
|
}, 'site-add'));
|
|
|
|
// Add external service reverse proxy to Caddyfile
|
|
router.post('/site/external', asyncHandler(async (req, res) => {
|
|
const { subdomain, externalUrl, preserveHost, followRedirects, sslType, caddyfilePath, reloadCaddy: shouldReload, createDns, serviceName, logo } = req.body;
|
|
|
|
if (!subdomain || !externalUrl) {
|
|
throw new ValidationError('Subdomain and externalUrl are required');
|
|
}
|
|
if (!REGEX.SUBDOMAIN.test(subdomain)) {
|
|
throw new ValidationError('[DC-301] Invalid subdomain format');
|
|
}
|
|
|
|
// DC-074: SSRF defense — validate the URL syntax via validateURL() (catches
|
|
// non-http(s) schemes, malformed URLs) AND validateUpstream() (catches
|
|
// every private/reserved range including CGNAT, multicast, TEST-NET
|
|
// ranges that validateURL's isPrivateIP() regex misses).
|
|
//
|
|
// We intentionally do NOT pass `blockPrivate: true` to validateURL()
|
|
// here — that's handled by validateUpstream() below, which honors the
|
|
// SITES_ALLOW_PRIVATE_UPSTREAMS opt-in. validateURL's blockPrivate path
|
|
// is a hard reject with no escape hatch, which would force operators
|
|
// who intentionally proxy to a private target to remove validation
|
|
// entirely.
|
|
try {
|
|
validateURL(externalUrl);
|
|
} catch (validationErr) {
|
|
throw new ValidationError(validationErr.message);
|
|
}
|
|
|
|
// DC-074: validateUpstream() does the same rigorous private-IP check
|
|
// fleet-validation shipped for DC-068, with full CGNAT / multicast /
|
|
// broadcast / 0.0.0.0 / TEST-NET / benchmark range coverage and a DNS
|
|
// resolution step for hostnames (rebinding defense).
|
|
let parsedExternalUrl;
|
|
try {
|
|
parsedExternalUrl = new URL(externalUrl);
|
|
} catch (_) {
|
|
// validateURL() above already gates URL syntax — unreachable.
|
|
throw new ValidationError('Invalid external URL');
|
|
}
|
|
const externalCheck = await validateUpstream(`${parsedExternalUrl.hostname}:${parsedExternalUrl.port || (parsedExternalUrl.protocol === 'https:' ? '443' : '80')}`);
|
|
if (!externalCheck.ok) {
|
|
log?.warn?.('site', 'POST /site/external rejected by SSRF gate', { code: externalCheck.code });
|
|
throw new ValidationError(`[DC-074] ${externalCheck.message} (set SITES_ALLOW_PRIVATE_UPSTREAMS=true to opt in)`);
|
|
}
|
|
|
|
const domain = buildDomain(subdomain);
|
|
let dnsWarning = null;
|
|
|
|
if (createDns) {
|
|
try {
|
|
await dns.universalCreateRecord(subdomain, siteConfig.dnsServerIp);
|
|
log.info('dns', 'DNS record created for external proxy', { domain, ip: siteConfig.dnsServerIp });
|
|
} catch (dnsError) {
|
|
dnsWarning = `DNS creation failed: ${dnsError.message}. You may need to create the DNS record manually.`;
|
|
log.warn('dns', 'DNS creation failed for external proxy', { domain, error: dnsError.message });
|
|
}
|
|
}
|
|
|
|
const sslConfig = sslType === 'letsencrypt' ? '' : 'tls internal';
|
|
const hostHeader = preserveHost ? `\n header_up Host {upstream_hostport}` : '';
|
|
|
|
const urlObj = new URL(externalUrl);
|
|
|
|
// Validate URL components are safe for Caddyfile syntax
|
|
const unsafeCaddyChars = /[{}\n\r]/;
|
|
if (unsafeCaddyChars.test(urlObj.host) || unsafeCaddyChars.test(urlObj.pathname)) {
|
|
throw new ValidationError('External URL contains characters not safe for Caddy configuration');
|
|
}
|
|
|
|
const baseUrl = `${urlObj.protocol}//${urlObj.host}`;
|
|
const urlPath = urlObj.pathname.replace(/\/$/, '');
|
|
|
|
let proxyConfig = '';
|
|
if (urlPath && urlPath !== '') {
|
|
proxyConfig = `\n${domain} {\n ${sslConfig}\n\n handle_path ${urlPath}/* {\n reverse_proxy ${baseUrl} {\n transport http {\n tls\n tls_server_name ${urlObj.host}\n }\n }\n }\n\n handle {\n redir ${urlPath}/ permanent\n }\n}\n`;
|
|
} else {
|
|
proxyConfig = `\n${domain} {\n ${sslConfig}\n\n reverse_proxy ${externalUrl} {${hostHeader}\n transport http {\n tls\n }\n }\n}\n`;
|
|
}
|
|
|
|
const caddyResult = await caddy.modify(c => {
|
|
const escapedDomain = domain.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
if (new RegExp(`\\n?${escapedDomain}\\s*\\{`, 'g').test(c)) return null;
|
|
return c + proxyConfig;
|
|
});
|
|
|
|
if (!caddyResult.success && !caddyResult.rolledBack) {
|
|
throw new ConflictError(`Site block for "" already exists in Caddyfile`);
|
|
}
|
|
if (!caddyResult.success) {
|
|
throw new Error( `[DC-303] External proxy added but Caddy reload failed (rolled back): ${caddyResult.error}`);
|
|
}
|
|
|
|
if (serviceName && logo) {
|
|
try {
|
|
await addServiceToConfig({
|
|
id: subdomain, name: serviceName, logo,
|
|
isExternal: true, externalUrl,
|
|
deployedAt: new Date().toISOString()
|
|
});
|
|
log.info('deploy', 'Service added to dashboard', { subdomain });
|
|
} catch (serviceError) {
|
|
log.warn('deploy', 'Failed to add service to dashboard', { subdomain, error: serviceError.message });
|
|
}
|
|
}
|
|
|
|
const data = {
|
|
message: `External service proxy for ${domain} -> ${externalUrl} created${shouldReload ? ' and Caddy reloaded' : ''}`
|
|
};
|
|
if (dnsWarning) data.warning = dnsWarning;
|
|
ok(res, data);
|
|
}, 'site-external'));
|
|
|
|
return router;
|
|
};
|