security(tunnels,proxy): dual-mode isolated proxy origin, direct SSH dialing, HTTPS upstream, SOCKS5 & TTL tunnels
This commit is contained in:
parent
838e69ba4e
commit
ca67c85fbf
7 changed files with 1243 additions and 135 deletions
|
|
@ -10,7 +10,7 @@ import {
|
|||
requireAuth,
|
||||
requireCsrf,
|
||||
} from '../../security/guards.js';
|
||||
import type { TunnelManager } from '../../ssh/tunnel-manager.js';
|
||||
import { ProxyIsolationError, type TunnelManager } from '../../ssh/tunnel-manager.js';
|
||||
|
||||
export interface TunnelsRouterDeps {
|
||||
authService: AuthService;
|
||||
|
|
@ -180,6 +180,46 @@ export function createTunnelsRouter(deps: TunnelsRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
// Issue single-use isolated-origin launch ticket (allowed in Safe Mode for read-only viewing)
|
||||
router.post(
|
||||
'/:serverId/:tunnelId/proxy-ticket',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
(req, res) => {
|
||||
const serverId = String(req.params.serverId ?? '');
|
||||
const tunnelId = String(req.params.tunnelId ?? '');
|
||||
try {
|
||||
const result = tunnelManager.issueProxyTicket(
|
||||
req.authSession!.idHash,
|
||||
serverId,
|
||||
tunnelId,
|
||||
{
|
||||
host: req.headers.host,
|
||||
protocol: req.protocol,
|
||||
},
|
||||
);
|
||||
auditService.log({
|
||||
action: 'tunnel.proxy_ticket',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: `${serverId}:${tunnelId}`,
|
||||
status: 'ok',
|
||||
details: { mode: result.mode },
|
||||
});
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
if (err instanceof ProxyIsolationError) {
|
||||
res.status(403).json({ error: err.code, message: err.message });
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'PROXY_TICKET_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to issue proxy ticket',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ export class WsHub {
|
|||
private readonly clients = new Set<WsClientMeta>();
|
||||
private readonly pingTimer: NodeJS.Timeout;
|
||||
private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = [];
|
||||
private readonly hostUpgradeHandlers: Array<(req: IncomingMessage, socket: Duplex, head: Buffer) => boolean> = [];
|
||||
private readonly subscribeListeners = new Set<WsSubscribeListener>();
|
||||
private ptyHandlers: WsPtyHandlers | null = null;
|
||||
private aiHandlers: WsAiHandlers | null = null;
|
||||
|
|
@ -119,6 +120,12 @@ export class WsHub {
|
|||
this.upgradeHandlers.push({ prefix, handler });
|
||||
}
|
||||
|
||||
registerHostUpgradeHandler(
|
||||
matcherHandler: (req: IncomingMessage, socket: Duplex, head: Buffer) => boolean,
|
||||
): void {
|
||||
this.hostUpgradeHandlers.push(matcherHandler);
|
||||
}
|
||||
|
||||
onChannelSubscribe(listener: WsSubscribeListener): () => void {
|
||||
this.subscribeListeners.add(listener);
|
||||
return () => {
|
||||
|
|
@ -181,6 +188,11 @@ export class WsHub {
|
|||
socket: Duplex,
|
||||
head: Buffer,
|
||||
): void {
|
||||
for (const matcher of this.hostUpgradeHandlers) {
|
||||
if (matcher(req, socket, head)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const urlPath = (req.url ?? '').split('?')[0] ?? '';
|
||||
for (const entry of this.upgradeHandlers) {
|
||||
if (urlPath.startsWith(entry.prefix)) {
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ import { KnownHostsService } from './ssh/known-hosts.js';
|
|||
import { PTYManager } from './ssh/pty-manager.js';
|
||||
import { SftpService } from './ssh/sftp-service.js';
|
||||
import { SSHPool } from './ssh/ssh-pool.js';
|
||||
import { TunnelManager } from './ssh/tunnel-manager.js';
|
||||
import { TunnelManager, extractSubdomainTunnel } from './ssh/tunnel-manager.js';
|
||||
import { CustomSystemsEngine } from './systems/systems-engine.js';
|
||||
import { createAiRouter } from './api/routes/ai.routes.js';
|
||||
import { createAlertsRouter } from './api/routes/alerts.routes.js';
|
||||
|
|
@ -97,6 +97,7 @@ export interface GCoordinatorInstance {
|
|||
aiService: AiService;
|
||||
wsHub: WsHub;
|
||||
port: number;
|
||||
proxyPort?: number;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
|
|
@ -179,7 +180,13 @@ export async function createGCoordinatorServer(
|
|||
const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService);
|
||||
const ptyManager = new PTYManager(sshPool, configManager, wsHub, getRuntimeLimits);
|
||||
const sftpService = new SftpService(sshPool);
|
||||
const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService);
|
||||
const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService, {
|
||||
getRuntimeLimits,
|
||||
allowLanTunnels: options.allowLanTunnels,
|
||||
proxyBaseDomain: options.proxyBaseDomain,
|
||||
proxyPort: options.proxyPort,
|
||||
trustCloudflare,
|
||||
});
|
||||
const customSystemsEngine = new CustomSystemsEngine(
|
||||
sshPool,
|
||||
configManager,
|
||||
|
|
@ -243,6 +250,12 @@ export async function createGCoordinatorServer(
|
|||
getRuntimeLimits,
|
||||
);
|
||||
|
||||
wsHub.registerHostUpgradeHandler((req, socket, head) => {
|
||||
const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain);
|
||||
if (!tunnelSub) return false;
|
||||
tunnelManager.handleSubdomainProxyWs(req, socket, head, tunnelSub);
|
||||
return true;
|
||||
});
|
||||
wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => {
|
||||
tunnelManager.handleWsProxyUpgrade(req, socket, head);
|
||||
});
|
||||
|
|
@ -299,6 +312,15 @@ export async function createGCoordinatorServer(
|
|||
}
|
||||
});
|
||||
|
||||
app.use((req, res, next) => {
|
||||
const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain);
|
||||
if (tunnelSub) {
|
||||
tunnelManager.handleSubdomainProxyHttp(req, res, tunnelSub);
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
app.use((req, res, next) => {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
|
|
@ -331,6 +353,7 @@ export async function createGCoordinatorServer(
|
|||
|
||||
const jsonParser = express.json({ limit: '2mb' });
|
||||
const backupJsonParser = express.json({ limit: '16mb' });
|
||||
|
||||
app.use((req, res, next) => {
|
||||
if (req.path.endsWith('/sftp/upload')) {
|
||||
next();
|
||||
|
|
@ -621,6 +644,8 @@ export async function createGCoordinatorServer(
|
|||
}
|
||||
});
|
||||
|
||||
await tunnelManager.startProxyServer();
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
httpServer.once('error', reject);
|
||||
httpServer.listen(options.port, options.host ?? '0.0.0.0', () => {
|
||||
|
|
@ -659,6 +684,7 @@ export async function createGCoordinatorServer(
|
|||
aiService,
|
||||
wsHub,
|
||||
port: actualPort,
|
||||
proxyPort: tunnelManager.actualProxyPort,
|
||||
async close() {
|
||||
aiService.close();
|
||||
backupScheduler.close();
|
||||
|
|
@ -668,6 +694,7 @@ export async function createGCoordinatorServer(
|
|||
monitoringService.close();
|
||||
customSystemsEngine.close();
|
||||
tunnelManager.stopAll();
|
||||
await tunnelManager.stopProxyServer();
|
||||
ptyManager.close();
|
||||
sshPool.closeAll('shutdown');
|
||||
authService.close();
|
||||
|
|
|
|||
|
|
@ -758,7 +758,11 @@ export class AuthService {
|
|||
|
||||
getSessionByToken(sessionToken: string | undefined): AuthSession | null {
|
||||
if (!sessionToken || sessionToken.length < 16) return null;
|
||||
const idHash = sha256Hex(sessionToken);
|
||||
return this.getSessionByHash(sha256Hex(sessionToken));
|
||||
}
|
||||
|
||||
getSessionByHash(idHash: string | undefined): AuthSession | null {
|
||||
if (!idHash || idHash.length < 16) return null;
|
||||
const row = this.db
|
||||
.prepare('SELECT * FROM sessions WHERE id_hash = ?')
|
||||
.get(idHash) as SessionRow | undefined;
|
||||
|
|
|
|||
|
|
@ -167,10 +167,14 @@ export function isBlockedByDefaultIp(rawIp: string): boolean {
|
|||
return false;
|
||||
}
|
||||
|
||||
export async function assertEgressHostAllowed(
|
||||
/**
|
||||
* Validate `rawHost` against Zero-Trust egress CIDR rules and return all
|
||||
* permitted resolved IP addresses in lookup order.
|
||||
*/
|
||||
export async function resolveAllowedEgressIps(
|
||||
rawHost: string,
|
||||
allowedCidrs: string[] = [],
|
||||
): Promise<void> {
|
||||
): Promise<string[]> {
|
||||
const { ip: cleanHost } = stripZoneAndBrackets(rawHost);
|
||||
if (!cleanHost) {
|
||||
throw new EgressBlockedError('Empty egress destination host');
|
||||
|
|
@ -182,7 +186,7 @@ export async function assertEgressHostAllowed(
|
|||
`Egress to non-public IP "${cleanHost}" is blocked by Zero-Trust egress policy`,
|
||||
);
|
||||
}
|
||||
return;
|
||||
return [cleanHost];
|
||||
}
|
||||
|
||||
let records: dns.LookupAddress[];
|
||||
|
|
@ -198,13 +202,23 @@ export async function assertEgressHostAllowed(
|
|||
throw new EgressBlockedError(`Egress host "${cleanHost}" resolved to no addresses`);
|
||||
}
|
||||
|
||||
const ips: string[] = [];
|
||||
for (const rec of records) {
|
||||
if (isBlockedByDefaultIp(rec.address) && !isIpInCidrs(rec.address, allowedCidrs)) {
|
||||
throw new EgressBlockedError(
|
||||
`Egress host "${cleanHost}" resolved to blocked address ${rec.address}`,
|
||||
);
|
||||
}
|
||||
ips.push(rec.address);
|
||||
}
|
||||
return ips;
|
||||
}
|
||||
|
||||
export async function assertEgressHostAllowed(
|
||||
rawHost: string,
|
||||
allowedCidrs: string[] = [],
|
||||
): Promise<void> {
|
||||
await resolveAllowedEgressIps(rawHost, allowedCidrs);
|
||||
}
|
||||
|
||||
export async function assertEgressUrlAllowed(
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -97,6 +97,7 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC
|
|||
dataDir,
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
proxyPort: 0,
|
||||
publicDir: path.resolve('dist/public'),
|
||||
watchConfig: false,
|
||||
});
|
||||
|
|
@ -210,6 +211,46 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC
|
|||
const unauthProxy = await fetch(`${baseUrl}/proxy/web-ui/hello`);
|
||||
expect(unauthProxy.status).toBe(401);
|
||||
|
||||
// Same-origin /proxy is blocked with 403 by default; test isolated proxyPort ticket flow first!
|
||||
const blockedSameOrigin = await api('/proxy/web-ui/hello');
|
||||
expect(blockedSameOrigin.status).toBe(403);
|
||||
expect(blockedSameOrigin.data.error).toBe('PROXY_ORIGIN_ISOLATION_REQUIRED');
|
||||
|
||||
const ticketRes = await api('/api/tunnels/app1/web-ui/proxy-ticket', {
|
||||
method: 'POST',
|
||||
body: {},
|
||||
});
|
||||
expect(ticketRes.status).toBe(200);
|
||||
expect(ticketRes.data.mode).toBe('port');
|
||||
const launchUrl = String(ticketRes.data.launchUrl);
|
||||
const proxyBaseUrl = `http://127.0.0.1:${server.proxyPort}`;
|
||||
|
||||
// Redeem single-use ticket on isolated proxy origin to receive scoped gcoord_proxy_sid cookie
|
||||
const proxyJar = new CookieJar();
|
||||
const ticketHit = await fetch(launchUrl, { redirect: 'manual' });
|
||||
expect(ticketHit.status).toBe(302);
|
||||
proxyJar.updateFrom(ticketHit);
|
||||
expect(proxyJar.header()).toContain('gcoord_proxy_sid=');
|
||||
|
||||
const isoHello = await fetch(`${proxyBaseUrl}/proxy/web-ui/hello`, {
|
||||
headers: { Cookie: proxyJar.header() },
|
||||
});
|
||||
expect(isoHello.status).toBe(200);
|
||||
const isoHelloData = (await isoHello.json()) as { ok: boolean };
|
||||
expect(isoHelloData.ok).toBe(true);
|
||||
expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_sid');
|
||||
expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_proxy_sid');
|
||||
|
||||
// Also enable allowSameOriginProxy explicitly to test same-origin backwards compatibility
|
||||
expect(
|
||||
(
|
||||
await api('/api/auth/security-policy', {
|
||||
method: 'PUT',
|
||||
body: { allowSameOriginProxy: true },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
|
||||
// Authenticated GET & POST JSON stream through proxy without exposing hub session cookies
|
||||
const authedHello = await api('/proxy/web-ui/hello');
|
||||
expect(authedHello.status).toBe(200);
|
||||
|
|
@ -304,7 +345,35 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC
|
|||
expect(localHttp.status).toBe(200);
|
||||
expect(((await localHttp.json()) as { ok: boolean }).ok).toBe(true);
|
||||
|
||||
// 3. Remote TCP (R) tunnel via forwardIn
|
||||
// 3. Remote TCP (R) tunnel targets 127.0.0.1 -> blocked by Zero-Trust egress guard unless allowlisted
|
||||
const blockedRemoteTcp = await api('/api/tunnels', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
serverId: 'app1',
|
||||
tunnel: {
|
||||
id: 'tcp-remote',
|
||||
name: 'Remote TCP Reverse',
|
||||
mode: 'remote-tcp',
|
||||
bindHost: '127.0.0.1',
|
||||
targetHost: '127.0.0.1',
|
||||
targetPort: upstream.port,
|
||||
autoStart: false,
|
||||
},
|
||||
start: true,
|
||||
},
|
||||
});
|
||||
expect(blockedRemoteTcp.data.startError).toBeTruthy();
|
||||
|
||||
// Allow 127.0.0.1/32 in egressAllowedCidrs -> Remote TCP (R) starts and forwards cleanly
|
||||
expect(
|
||||
(
|
||||
await api('/api/auth/security-policy', {
|
||||
method: 'PUT',
|
||||
body: { egressAllowedCidrs: ['127.0.0.1/32'] },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
|
||||
const remoteTcpRes = await api('/api/tunnels', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue