security(tunnels,proxy): dual-mode isolated proxy origin, direct SSH dialing, HTTPS upstream, SOCKS5 & TTL tunnels

This commit is contained in:
tyuXX 2026-11-27 22:48:53 +00:00
parent 838e69ba4e
commit ca67c85fbf
7 changed files with 1243 additions and 135 deletions

View file

@ -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;
}

View file

@ -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)) {

View file

@ -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();

View file

@ -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;

View file

@ -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