diff --git a/src/server/api/routes/tunnels.routes.ts b/src/server/api/routes/tunnels.routes.ts index ca4df39..7d37b6d 100644 --- a/src/server/api/routes/tunnels.routes.ts +++ b/src/server/api/routes/tunnels.routes.ts @@ -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; } diff --git a/src/server/api/ws-hub.ts b/src/server/api/ws-hub.ts index 42f80e7..7a5ea04 100644 --- a/src/server/api/ws-hub.ts +++ b/src/server/api/ws-hub.ts @@ -57,6 +57,7 @@ export class WsHub { private readonly clients = new Set(); 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(); 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)) { diff --git a/src/server/app.ts b/src/server/app.ts index f5d5e0d..fb19dc9 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -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; } @@ -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((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(); diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index 0c33dd8..76c6928 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -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; diff --git a/src/server/security/egress-guard.ts b/src/server/security/egress-guard.ts index aae5c4b..adfec66 100644 --- a/src/server/security/egress-guard.ts +++ b/src/server/security/egress-guard.ts @@ -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 { +): Promise { 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 { + await resolveAllowedEgressIps(rawHost, allowedCidrs); } export async function assertEgressUrlAllowed( diff --git a/src/server/ssh/tunnel-manager.ts b/src/server/ssh/tunnel-manager.ts index 7da4a9c..dea4a30 100644 --- a/src/server/ssh/tunnel-manager.ts +++ b/src/server/ssh/tunnel-manager.ts @@ -1,15 +1,36 @@ +import crypto from 'node:crypto'; import http, { type IncomingMessage } from 'node:http'; import net, { type Socket } from 'node:net'; import type { Duplex } from 'node:stream'; +import tls from 'node:tls'; import type { Request, Response } from 'express'; import type { Client, TcpConnectionDetails } from 'ssh2'; import type { ServerTunnel } from '../../shared/schemas/server.schema.js'; import type { ConfigManager } from '../config/config-manager.js'; -import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; +import { SESSION_COOKIE_NAME, sha256Hex, type AuthService } from '../security/auth.js'; +import { + assertEgressHostAllowed, + resolveAllowedEgressIps, +} from '../security/egress-guard.js'; import { extractCookies } from '../security/guards.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from './ssh-pool.js'; +export const PROXY_SESSION_COOKIE_NAME = 'gcoord_proxy_sid'; + +export class ProxyIsolationError extends Error { + readonly code = 'PROXY_ISOLATION_NOT_CONFIGURED'; +} + +export interface TunnelManagerOptions { + getRuntimeLimits?: () => RuntimeLimits; + allowLanTunnels?: boolean; + proxyBaseDomain?: string; + proxyPort?: number; + trustCloudflare?: boolean; +} + export interface TunnelRuntimeInfo { key: string; serverId: string; @@ -19,6 +40,7 @@ export interface TunnelRuntimeInfo { localBoundPort?: number; remoteBoundPort?: number; proxyPath?: string; + expiresAt?: number; activeConnections: number; totalConnections: number; bytesIn: number; @@ -34,21 +56,45 @@ interface ActiveTunnelHandle { localBoundHost?: string; localBoundPort?: number; remoteBoundPort?: number; + httpProxyActive?: boolean; activeConnections: number; totalConnections: number; bytesIn: number; bytesOut: number; startedAt: number; + expiresAt?: number; lastError?: string; tcpServer?: net.Server; remoteClient?: Client; + remoteReconnectTimer?: NodeJS.Timeout; + ttlTimer?: NodeJS.Timeout; sockets: Set; + manuallyStopped?: boolean; +} + +interface PendingProxyTicket { + tunnelKey: string; + proxyId: string; + sessionIdHash: string; + expiresAt: number; +} + +interface IsolatedProxySession { + tunnelKey: string; + proxyId: string; + sessionIdHash: string; + expiresAt: number; } function makeTunnelKey(serverId: string, tunnelId: string): string { return `${serverId}--${tunnelId}`; } +function isLoopbackHost(host: string): boolean { + const clean = host.trim().toLowerCase().replace(/^\[|\]$/g, ''); + return clean === '127.0.0.1' || clean === '::1' || clean === 'localhost'; +} + function stripHubCookies(cookieHeader: string | string[] | undefined): string | undefined { if (!cookieHeader) return undefined; const raw = Array.isArray(cookieHeader) ? cookieHeader.join('; ') : cookieHeader; @@ -57,24 +103,186 @@ function stripHubCookies(cookieHeader: string | string[] | undefined): string | .map((part) => part.trim()) .filter((part) => { const name = part.split('=')[0]?.trim(); - return name && name !== SESSION_COOKIE_NAME && name !== 'gcoord_csrf'; + return ( + name && + name !== SESSION_COOKIE_NAME && + name !== 'gcoord_csrf' && + name !== PROXY_SESSION_COOKIE_NAME + ); }); return kept.length > 0 ? kept.join('; ') : undefined; } +function sanitizeOutgoingProxyHeaders( + rawHeaders: IncomingMessage['headers'], + targetHost: string, + targetPort: number, + extra: Record = {}, +): http.OutgoingHttpHeaders { + const headers: http.OutgoingHttpHeaders = {}; + for (const [hKey, hVal] of Object.entries(rawHeaders)) { + if (hVal === undefined) continue; + const lower = hKey.toLowerCase(); + if ( + lower === 'connection' || + lower === 'keep-alive' || + lower === 'transfer-encoding' || + lower === 'upgrade' || + lower === 'host' || + lower === 'proxy-connection' || + lower === 'proxy-authorization' || + lower === 'proxy-authenticate' || + lower === 'te' || + lower === 'trailers' + ) { + continue; + } + if (lower === 'cookie') { + const filtered = stripHubCookies(hVal); + if (filtered) headers.cookie = filtered; + continue; + } + headers[hKey] = hVal; + } + headers.host = `${targetHost}:${targetPort}`; + for (const [k, v] of Object.entries(extra)) { + headers[k] = v; + } + return headers; +} + +function rewriteSetCookieHeaders( + rawSetCookie: string | string[] | undefined, + baseMountPath: string, +): string[] | undefined { + if (!rawSetCookie) return undefined; + const list = Array.isArray(rawSetCookie) ? rawSetCookie : [rawSetCookie]; + const scopedPath = baseMountPath ? `${baseMountPath}/` : '/'; + return list.map((line) => { + const parts = line + .split(';') + .map((p) => p.trim()) + .filter((p) => !/^domain=/i.test(p) && !/^path=/i.test(p)); + parts.push(`Path=${scopedPath}`); + return parts.join('; '); + }); +} + +function rewriteRedirectLocation( + loc: string, + baseMountPath: string, + tunnel: ServerTunnel, +): string { + if (!baseMountPath) { + const originHttp = `http://${tunnel.targetHost}:${tunnel.targetPort}`; + const originHttps = `https://${tunnel.targetHost}:${tunnel.targetPort}`; + if (loc.startsWith(originHttp)) return loc.slice(originHttp.length) || '/'; + if (loc.startsWith(originHttps)) return loc.slice(originHttps.length) || '/'; + return loc; + } + if (loc.startsWith('/') && !loc.startsWith('//')) { + if (loc === baseMountPath || loc.startsWith(`${baseMountPath}/`)) { + return loc; + } + return `${baseMountPath}${loc}`; + } + const targetOrigin = `${tunnel.targetProtocol ?? 'http'}://${tunnel.targetHost}:${tunnel.targetPort}`; + if (loc.startsWith(targetOrigin)) { + const rest = loc.slice(targetOrigin.length) || '/'; + return `${baseMountPath}${rest.startsWith('/') ? rest : `/${rest}`}`; + } + return loc; +} + +export function extractSubdomainTunnel( + hostHeader: string | undefined, + proxyBaseDomain: string | undefined, +): string | null { + if (!hostHeader || !proxyBaseDomain) return null; + const base = proxyBaseDomain.trim().toLowerCase().replace(/^\./, ''); + if (!base) return null; + const hostOnly = hostHeader.trim().toLowerCase().split(':')[0] ?? ''; + const suffix = `.${base}`; + if (!hostOnly.endsWith(suffix)) return null; + const sub = hostOnly.slice(0, -suffix.length); + if (!sub || sub.includes('.') || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(sub)) { + return null; + } + return sub; +} + export class TunnelManager { private readonly active = new Map(); private readonly remoteDispatch = new WeakMap< Client, Map Duplex, reject: () => void) => void> >(); + private readonly pendingTickets = new Map(); + private readonly proxySessions = new Map(); + private proxyHttpServer: http.Server | null = null; + private boundProxyPort: number | undefined; + private readonly getRuntimeLimits?: () => RuntimeLimits; + private readonly allowLanTunnels: boolean; + private readonly proxyBaseDomain?: string; + private readonly configuredProxyPort?: number; + private readonly trustCloudflare: boolean; constructor( private readonly sshPool: SSHPool, private readonly configManager: ConfigManager, private readonly vaultService: VaultService, private readonly authService: AuthService, - ) {} + options: TunnelManagerOptions = {}, + ) { + this.getRuntimeLimits = options.getRuntimeLimits; + this.allowLanTunnels = Boolean(options.allowLanTunnels); + this.proxyBaseDomain = options.proxyBaseDomain?.trim().toLowerCase() || undefined; + this.configuredProxyPort = options.proxyPort; + this.trustCloudflare = Boolean(options.trustCloudflare); + } + + get actualProxyPort(): number | undefined { + return this.boundProxyPort; + } + + get baseDomain(): string | undefined { + return this.proxyBaseDomain; + } + + async startProxyServer(): Promise { + if (this.configuredProxyPort === undefined) return undefined; + if (this.proxyHttpServer) return this.boundProxyPort; + + const srv = http.createServer((req, res) => { + this.handleDedicatedProxyPortHttp(req, res); + }); + srv.on('upgrade', (req, socket, head) => { + this.handleDedicatedProxyPortWs(req, socket, head); + }); + + const bindHost = this.allowLanTunnels ? '0.0.0.0' : '127.0.0.1'; + await new Promise((resolve, reject) => { + srv.once('error', reject); + srv.listen(this.configuredProxyPort!, bindHost, () => { + srv.off('error', reject); + resolve(); + }); + }); + + this.proxyHttpServer = srv; + const addr = srv.address(); + this.boundProxyPort = + typeof addr === 'object' && addr ? addr.port : this.configuredProxyPort; + return this.boundProxyPort; + } + + async stopProxyServer(): Promise { + if (!this.proxyHttpServer) return; + const srv = this.proxyHttpServer; + this.proxyHttpServer = null; + this.boundProxyPort = undefined; + await new Promise((resolve) => srv.close(() => resolve())); + } listTunnels(): TunnelRuntimeInfo[] { const out: TunnelRuntimeInfo[] = []; @@ -134,13 +342,14 @@ export class TunnelManager { if (tunnel.mode === 'remote-tcp') { return this.startRemoteTunnel(serverId, tunnel); } - return this.startLocalListenerTunnel(serverId, tunnel); + return this.startLocalOrHttpTunnel(serverId, tunnel); } async stopTunnel(serverId: string, tunnelId: string): Promise { const key = makeTunnelKey(serverId, tunnelId); const handle = this.active.get(key); if (!handle) return false; + handle.manuallyStopped = true; this.active.delete(key); await this.teardownHandle(handle); return true; @@ -149,6 +358,7 @@ export class TunnelManager { stopServerTunnels(serverId: string): void { for (const [key, handle] of this.active.entries()) { if (handle.serverId === serverId) { + handle.manuallyStopped = true; this.active.delete(key); void this.teardownHandle(handle); } @@ -157,19 +367,22 @@ export class TunnelManager { stopAll(): void { for (const [key, handle] of this.active.entries()) { + handle.manuallyStopped = true; this.active.delete(key); void this.teardownHandle(handle); } + this.pendingTickets.clear(); + this.proxySessions.clear(); } resolveProxyTarget(idOrKey: string): TunnelRuntimeInfo | undefined { const direct = this.active.get(idOrKey); - if (direct && direct.tunnel.mode === 'http-proxy' && direct.localBoundPort) { + if (direct && direct.tunnel.mode === 'http-proxy' && direct.httpProxyActive) { return this.toRuntimeInfo(direct.serverId, direct.tunnel, direct); } const matches = [...this.active.values()].filter( - (h) => h.tunnel.mode === 'http-proxy' && h.localBoundPort && h.tunnel.id === idOrKey, + (h) => h.tunnel.mode === 'http-proxy' && h.httpProxyActive && h.tunnel.id === idOrKey, ); if (matches.length === 1) { const m = matches[0]!; @@ -178,9 +391,311 @@ export class TunnelManager { return undefined; } + issueProxyTicket( + sessionIdHash: string, + serverId: string, + tunnelId: string, + reqMeta: { host?: string; protocol?: string }, + ): { + ticket?: string; + launchUrl: string; + mode: 'subdomain' | 'port' | 'same-origin'; + expiresInSec: number; + } { + const key = makeTunnelKey(serverId, tunnelId); + const live = this.active.get(key); + if (!live || live.tunnel.mode !== 'http-proxy' || !live.httpProxyActive) { + throw new Error(`HTTP proxy tunnel "${tunnelId}" on "${serverId}" is not active`); + } + + this.sweepProxyAuthState(); + const proxyId = this.computeProxyId(serverId, live.tunnel); + const proto = reqMeta.protocol === 'https' || this.trustCloudflare ? 'https' : 'http'; + const rawHostOnly = (reqMeta.host ?? '127.0.0.1').split(':')[0]?.trim() || '127.0.0.1'; + + if (this.proxyBaseDomain) { + const ticket = crypto.randomBytes(24).toString('base64url'); + this.pendingTickets.set(sha256Hex(ticket), { + tunnelKey: key, + proxyId, + sessionIdHash, + expiresAt: Date.now() + 30_000, + }); + return { + ticket, + launchUrl: `${proto}://${proxyId}.${this.proxyBaseDomain}/__gcoord_ticket?ticket=${encodeURIComponent(ticket)}`, + mode: 'subdomain', + expiresInSec: 30, + }; + } + + if (this.boundProxyPort !== undefined) { + const ticket = crypto.randomBytes(24).toString('base64url'); + this.pendingTickets.set(sha256Hex(ticket), { + tunnelKey: key, + proxyId, + sessionIdHash, + expiresAt: Date.now() + 30_000, + }); + return { + ticket, + launchUrl: `http://${rawHostOnly}:${this.boundProxyPort}/__gcoord_ticket?ticket=${encodeURIComponent(ticket)}`, + mode: 'port', + expiresInSec: 30, + }; + } + + if (this.configManager.getSettings().security.allowSameOriginProxy) { + return { + launchUrl: `/proxy/${encodeURIComponent(proxyId)}/`, + mode: 'same-origin', + expiresInSec: 0, + }; + } + + throw new ProxyIsolationError( + 'Same-origin /proxy is disabled. Configure GCOORD_PROXY_BASE_DOMAIN or GCOORD_PROXY_PORT, or explicitly enable security.allowSameOriginProxy.', + ); + } + + private redeemTicket( + ticket: string, + expectedProxyId?: string, + ): { proxySid: string; redirectPath: string } | null { + this.sweepProxyAuthState(); + if (!ticket) return null; + const hash = sha256Hex(ticket); + const entry = this.pendingTickets.get(hash); + if (!entry) return null; + this.pendingTickets.delete(hash); + if (entry.expiresAt <= Date.now()) return null; + if (expectedProxyId && entry.proxyId !== expectedProxyId) return null; + if (!this.authService.getSessionByHash(entry.sessionIdHash)) return null; + + const proxySid = crypto.randomBytes(32).toString('base64url'); + this.proxySessions.set(sha256Hex(proxySid), { + tunnelKey: entry.tunnelKey, + proxyId: entry.proxyId, + sessionIdHash: entry.sessionIdHash, + expiresAt: Date.now() + 12 * 60 * 60 * 1000, + }); + return { + proxySid, + redirectPath: expectedProxyId ? '/' : `/proxy/${encodeURIComponent(entry.proxyId)}/`, + }; + } + + private resolveIsolatedSession( + req: IncomingMessage, + expectedProxyIdOrKey: string, + ): { safeMode: boolean; target: TunnelRuntimeInfo; live: ActiveTunnelHandle } | { errorStatus: number; code: string } { + this.sweepProxyAuthState(); + const cookies = extractCookies(req.headers.cookie); + const proxySid = cookies[PROXY_SESSION_COOKIE_NAME]; + if (!proxySid) { + return { errorStatus: 401, code: 'PROXY_AUTH_REQUIRED' }; + } + const sess = this.proxySessions.get(sha256Hex(proxySid)); + if (!sess || sess.expiresAt <= Date.now()) { + this.proxySessions.delete(sha256Hex(proxySid)); + return { errorStatus: 401, code: 'PROXY_SESSION_EXPIRED' }; + } + const authSess = this.authService.getSessionByHash(sess.sessionIdHash); + if (!authSess) { + this.proxySessions.delete(sha256Hex(proxySid)); + return { errorStatus: 401, code: 'HUB_SESSION_REVOKED' }; + } + const target = this.resolveProxyTarget(expectedProxyIdOrKey); + const live = target ? this.active.get(target.key) : undefined; + if (!target || !live || target.key !== sess.tunnelKey) { + return { errorStatus: 403, code: 'PROXY_TUNNEL_SCOPE_MISMATCH' }; + } + return { safeMode: authSess.safeMode, target, live }; + } + + private sweepProxyAuthState(): void { + const now = Date.now(); + for (const [k, v] of this.pendingTickets.entries()) { + if (v.expiresAt <= now) this.pendingTickets.delete(k); + } + if (this.pendingTickets.size > 500) { + for (const k of [...this.pendingTickets.keys()].slice(0, this.pendingTickets.size - 500)) { + this.pendingTickets.delete(k); + } + } + for (const [k, v] of this.proxySessions.entries()) { + if (v.expiresAt <= now) this.proxySessions.delete(k); + } + } + + private handleDedicatedProxyPortHttp(req: IncomingMessage, res: Response | http.ServerResponse): void { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('Referrer-Policy', 'no-referrer'); + const urlObj = new URL(req.url ?? '/', 'http://127.0.0.1'); + + if (urlObj.pathname === '/__gcoord_ticket' && req.method === 'GET') { + const redeemed = this.redeemTicket(urlObj.searchParams.get('ticket') ?? ''); + if (!redeemed) { + res.writeHead(401, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: 'INVALID_OR_EXPIRED_TICKET' })); + return; + } + res.writeHead(302, { + Location: redeemed.redirectPath, + 'Cache-Control': 'no-store', + 'Set-Cookie': `${PROXY_SESSION_COOKIE_NAME}=${redeemed.proxySid}; HttpOnly; SameSite=Lax; Path=/`, + }); + res.end(); + return; + } + + const match = /^\/proxy\/([^/]+)(\/.*)?$/.exec(urlObj.pathname); + if (!match) { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'NOT_FOUND' })); + return; + } + + const idOrKey = decodeURIComponent(match[1]!); + const authRes = this.resolveIsolatedSession(req, idOrKey); + if ('errorStatus' in authRes) { + res.writeHead(authRes.errorStatus, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: authRes.code })); + return; + } + + const method = (req.method ?? 'GET').toUpperCase(); + if (authRes.safeMode && method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') { + res.writeHead(423, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'SAFE_MODE_ACTIVE' })); + return; + } + + const subPath = `${match[2] || '/'}${urlObj.search}`; + void this.forwardHttpStream(req, res, authRes.target, authRes.live, subPath, `/proxy/${idOrKey}`); + } + + private handleDedicatedProxyPortWs(req: IncomingMessage, socket: Duplex, head: Buffer): void { + const urlObj = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`); + const origin = req.headers.origin; + const host = req.headers.host; + if (origin) { + try { + const u = new URL(origin); + if (!host || u.host !== host || (u.protocol !== 'http:' && u.protocol !== 'https:')) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } catch { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } + + const match = /^\/proxy\/([^/]+)(\/.*)?$/.exec(urlObj.pathname); + if (!match) { + socket.write('HTTP/1.1 404 Not Found\r\n\r\n'); + socket.destroy(); + return; + } + const idOrKey = decodeURIComponent(match[1]!); + const authRes = this.resolveIsolatedSession(req, idOrKey); + if ('errorStatus' in authRes) { + socket.write(`HTTP/1.1 ${authRes.errorStatus} Unauthorized\r\n\r\n`); + socket.destroy(); + return; + } + if (authRes.safeMode) { + socket.write('HTTP/1.1 423 Locked\r\n\r\n'); + socket.destroy(); + return; + } + const subPath = `${match[2] || '/'}${urlObj.search}`; + void this.forwardWsStream(req, socket, head, authRes.target, authRes.live, subPath); + } + + handleSubdomainProxyHttp(req: Request, res: Response, tunnelSub: string): void { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('Referrer-Policy', 'no-referrer'); + const urlObj = new URL(req.originalUrl, 'http://localhost'); + + if (urlObj.pathname === '/__gcoord_ticket' && req.method === 'GET') { + const redeemed = this.redeemTicket(urlObj.searchParams.get('ticket') ?? '', tunnelSub); + if (!redeemed) { + res.status(401).json({ error: 'INVALID_OR_EXPIRED_TICKET' }); + return; + } + const secure = Boolean(this.trustCloudflare || req.secure); + res.cookie(PROXY_SESSION_COOKIE_NAME, redeemed.proxySid, { + httpOnly: true, + sameSite: 'lax', + secure, + path: '/', + }); + res.redirect(302, '/'); + return; + } + + const authRes = this.resolveIsolatedSession(req, tunnelSub); + if ('errorStatus' in authRes) { + res.status(authRes.errorStatus).json({ error: authRes.code }); + return; + } + + const method = req.method.toUpperCase(); + if (authRes.safeMode && method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') { + res.status(423).json({ error: 'SAFE_MODE_ACTIVE' }); + return; + } + + void this.forwardHttpStream(req, res, authRes.target, authRes.live, req.originalUrl, ''); + } + + handleSubdomainProxyWs(req: IncomingMessage, socket: Duplex, head: Buffer, tunnelSub: string): void { + const origin = req.headers.origin; + const host = req.headers.host; + if (origin) { + try { + const u = new URL(origin); + if (!host || u.host !== host || (u.protocol !== 'http:' && u.protocol !== 'https:')) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } catch { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } + const authRes = this.resolveIsolatedSession(req, tunnelSub); + if ('errorStatus' in authRes) { + socket.write(`HTTP/1.1 ${authRes.errorStatus} Unauthorized\r\n\r\n`); + socket.destroy(); + return; + } + if (authRes.safeMode) { + socket.write('HTTP/1.1 423 Locked\r\n\r\n'); + socket.destroy(); + return; + } + void this.forwardWsStream(req, socket, head, authRes.target, authRes.live, req.url ?? '/'); + } + handleHttpProxy(req: Request, res: Response, idOrKey: string, subPath: string): void { + if (!this.configManager.getSettings().security.allowSameOriginProxy) { + res.status(403).json({ + error: 'PROXY_ORIGIN_ISOLATION_REQUIRED', + message: 'Same-origin /proxy is disabled by default; launch via /proxy-ticket or enable security.allowSameOriginProxy.', + }); + return; + } + const target = this.resolveProxyTarget(idOrKey); - if (!target || !target.localBoundPort) { + const live = target ? this.active.get(target.key) : undefined; + if (!target || !live || !live.httpProxyActive) { res.status(502).json({ error: 'TUNNEL_NOT_ACTIVE', message: `HTTP proxy tunnel "${idOrKey}" is not active`, @@ -188,64 +703,8 @@ export class TunnelManager { return; } - const live = this.active.get(target.key); - const qsIndex = req.originalUrl.indexOf('?'); - const qs = qsIndex >= 0 ? req.originalUrl.slice(qsIndex) : ''; - const upstreamPath = `${subPath.startsWith('/') ? subPath : `/${subPath}`}${qs}`; - - const headers: http.OutgoingHttpHeaders = {}; - for (const [hKey, hVal] of Object.entries(req.headers)) { - if (hVal === undefined) continue; - const lower = hKey.toLowerCase(); - if ( - lower === 'connection' || - lower === 'keep-alive' || - lower === 'transfer-encoding' || - lower === 'upgrade' || - lower === 'host' - ) { - continue; - } - if (lower === 'cookie') { - const filtered = stripHubCookies(hVal); - if (filtered) headers.cookie = filtered; - continue; - } - headers[hKey] = hVal; - } - headers.host = `${target.tunnel.targetHost}:${target.tunnel.targetPort}`; - headers['x-forwarded-host'] = req.headers.host ?? ''; - headers['x-forwarded-proto'] = req.protocol; - headers['x-forwarded-prefix'] = `/proxy/${idOrKey}`; - - const proxyReq = http.request( - { - host: '127.0.0.1', - port: target.localBoundPort, - method: req.method, - path: upstreamPath, - headers, - }, - (proxyRes) => { - const resHeaders: http.OutgoingHttpHeaders = { ...proxyRes.headers }; - if (typeof resHeaders.location === 'string' && resHeaders.location.startsWith('/')) { - resHeaders.location = `/proxy/${idOrKey}${resHeaders.location}`; - } - res.writeHead(proxyRes.statusCode ?? 502, resHeaders); - proxyRes.pipe(res); - }, - ); - - proxyReq.on('error', (err) => { - if (live) live.lastError = err.message; - if (!res.headersSent) { - res.status(502).json({ error: 'UPSTREAM_PROXY_ERROR', message: err.message }); - } else { - res.end(); - } - }); - - req.pipe(proxyReq); + const cleanSub = subPath.startsWith('/') ? subPath : `/${subPath}`; + void this.forwardHttpStream(req, res, target, live, cleanSub, `/proxy/${idOrKey}`); } handleWsProxyUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void { @@ -260,9 +719,14 @@ export class TunnelManager { const origin = req.headers.origin; const host = req.headers.host; - if (origin && host) { + if (origin) { try { - if (new URL(origin).host !== host) { + const originUrl = new URL(origin); + if ( + !host || + originUrl.host !== host || + (originUrl.protocol !== 'http:' && originUrl.protocol !== 'https:') + ) { socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); socket.destroy(); return; @@ -282,69 +746,337 @@ export class TunnelManager { return; } + if (!this.configManager.getSettings().security.allowSameOriginProxy) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + + if (session.safeMode) { + socket.write('HTTP/1.1 423 Locked\r\n\r\n'); + socket.destroy(); + return; + } + const idOrKey = decodeURIComponent(match[1]!); - const subPath = match[2] || '/'; + const subPath = `${match[2] || '/'}${parsedUrl.search}`; const target = this.resolveProxyTarget(idOrKey); const live = target ? this.active.get(target.key) : undefined; - if (!target || !live || !target.localBoundPort) { + if (!target || !live || !live.httpProxyActive) { socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.destroy(); return; } - const upstreamPath = `${subPath}${parsedUrl.search}`; - const upstream = net.connect(target.localBoundPort, '127.0.0.1', () => { - const headerLines: string[] = [ - `${req.method ?? 'GET'} ${upstreamPath} HTTP/1.1`, - `Host: ${target.tunnel.targetHost}:${target.tunnel.targetPort}`, - ]; - for (const [k, v] of Object.entries(req.headers)) { - if (v === undefined) continue; - const lower = k.toLowerCase(); - if (lower === 'host') continue; - if (lower === 'cookie') { - const filtered = stripHubCookies(v); - if (filtered) headerLines.push(`Cookie: ${filtered}`); - continue; - } - const vals = Array.isArray(v) ? v : [v]; - for (const item of vals) { - headerLines.push(`${k}: ${item}`); - } - } - upstream.write(`${headerLines.join('\r\n')}\r\n\r\n`); - if (head.length > 0) upstream.write(head); + void this.forwardWsStream(req, socket, head, target, live, subPath); + } - live.sockets.add(socket); - live.sockets.add(upstream); - socket.pipe(upstream); - upstream.pipe(socket); + private getGlobalActiveConnections(): number { + let total = 0; + for (const h of this.active.values()) total += h.activeConnections; + return total; + } + + private canAcceptSocket(handle: ActiveTunnelHandle): boolean { + const limits = this.getRuntimeLimits?.(); + const perTunnel = limits?.maxTunnelSocketsPerTunnel ?? 64; + const globalMax = limits?.maxGlobalTunnelSockets ?? 256; + return ( + handle.activeConnections < perTunnel && + this.getGlobalActiveConnections() < globalMax + ); + } + + private async forwardHttpStream( + req: IncomingMessage, + res: Response | http.ServerResponse, + target: TunnelRuntimeInfo, + live: ActiveTunnelHandle, + upstreamPath: string, + baseMountPath: string, + ): Promise { + if (!this.canAcceptSocket(live)) { + res.writeHead(503, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'TUNNEL_SOCKET_LIMIT_REACHED' })); + return; + } + + let sshStream: Duplex; + try { + sshStream = await this.sshPool.forwardOutStream( + live.serverId, + target.tunnel.targetHost, + target.tunnel.targetPort, + ); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + live.lastError = msg; + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'UPSTREAM_PROXY_ERROR', message: msg })); + } + return; + } + + live.activeConnections += 1; + live.totalConnections += 1; + live.sockets.add(sshStream); + + let decremented = false; + const markClosed = () => { + live.sockets.delete(sshStream); + if (!decremented) { + decremented = true; + live.activeConnections = Math.max(0, live.activeConnections - 1); + } + }; + sshStream.once('close', markClosed); + // Prevent unhandled 'error' events if raw SSH channel errors during TLS wrap or teardown. + sshStream.on('error', () => undefined); + + const headers = sanitizeOutgoingProxyHeaders( + req.headers, + target.tunnel.targetHost, + target.tunnel.targetPort, + { + 'x-forwarded-host': String(req.headers.host ?? ''), + 'x-forwarded-proto': this.trustCloudflare ? 'https' : 'http', + ...(baseMountPath ? { 'x-forwarded-prefix': baseMountPath } : {}), + }, + ); + + const useHttps = target.tunnel.targetProtocol === 'https'; + const serverName = + target.tunnel.tlsServerName || + (!net.isIP(target.tunnel.targetHost) ? target.tunnel.targetHost : undefined); + + const createConnection = (): Duplex => { + if (!useHttps) return sshStream; + const tlsSock = tls.connect({ + socket: sshStream, + servername: serverName, + rejectUnauthorized: target.tunnel.tlsRejectUnauthorized ?? true, + }); + live.sockets.add(tlsSock); + tlsSock.once('close', () => live.sockets.delete(tlsSock)); + return tlsSock; + }; + + const agent = new http.Agent({ keepAlive: false }); + (agent as unknown as { createConnection: () => Duplex }).createConnection = createConnection; + + const reqOpts: http.RequestOptions = { + method: req.method, + path: upstreamPath.startsWith('/') ? upstreamPath : `/${upstreamPath}`, + headers, + agent, + }; + + const proxyReq = http.request(reqOpts, (proxyRes) => { + const resHeaders: http.OutgoingHttpHeaders = { ...proxyRes.headers }; + delete resHeaders['proxy-authenticate']; + delete resHeaders['proxy-connection']; + if (typeof resHeaders.location === 'string') { + resHeaders.location = rewriteRedirectLocation( + resHeaders.location, + baseMountPath, + target.tunnel, + ); + } + const rewrittenCookies = rewriteSetCookieHeaders(resHeaders['set-cookie'], baseMountPath); + if (rewrittenCookies) { + resHeaders['set-cookie'] = rewrittenCookies; + } + + res.writeHead(proxyRes.statusCode ?? 502, resHeaders); + proxyRes.on('data', (chunk: Buffer) => { + live.bytesIn += chunk.length; + }); + proxyRes.pipe(res); }); + req.on('data', (chunk: Buffer) => { + live.bytesOut += chunk.length; + }); + + proxyReq.on('error', (err) => { + live.lastError = err.message; + markClosed(); + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'UPSTREAM_PROXY_ERROR', message: err.message })); + } else { + res.end(); + } + }); + + res.once('close', () => { + if (!res.writableEnded) { + proxyReq.destroy(); + sshStream.destroy(); + } + }); + + req.pipe(proxyReq); + } + + private async forwardWsStream( + req: IncomingMessage, + socket: Duplex, + head: Buffer, + target: TunnelRuntimeInfo, + live: ActiveTunnelHandle, + upstreamPath: string, + ): Promise { + if (!this.canAcceptSocket(live)) { + socket.write('HTTP/1.1 503 Service Unavailable\r\n\r\n'); + socket.destroy(); + return; + } + + let sshStream: Duplex; + try { + sshStream = await this.sshPool.forwardOutStream( + live.serverId, + target.tunnel.targetHost, + target.tunnel.targetPort, + ); + } catch (err) { + live.lastError = err instanceof Error ? err.message : String(err); + socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); + socket.destroy(); + return; + } + + let upstream: Duplex = sshStream; + if (target.tunnel.targetProtocol === 'https') { + const serverName = + target.tunnel.tlsServerName || + (!net.isIP(target.tunnel.targetHost) ? target.tunnel.targetHost : undefined); + try { + upstream = await new Promise((resolve, reject) => { + const tSock = tls.connect( + { + socket: sshStream, + servername: serverName, + rejectUnauthorized: target.tunnel.tlsRejectUnauthorized ?? true, + }, + () => resolve(tSock), + ); + tSock.once('error', reject); + }); + } catch (err) { + live.lastError = err instanceof Error ? err.message : String(err); + sshStream.destroy(); + socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); + socket.destroy(); + return; + } + } + + const headerLines: string[] = [ + `${req.method ?? 'GET'} ${upstreamPath} HTTP/1.1`, + `Host: ${target.tunnel.targetHost}:${target.tunnel.targetPort}`, + ]; + for (const [k, v] of Object.entries(req.headers)) { + if (v === undefined) continue; + const lower = k.toLowerCase(); + if ( + lower === 'host' || + lower === 'proxy-authorization' || + lower === 'proxy-connection' + ) { + continue; + } + if (lower === 'cookie') { + const filtered = stripHubCookies(v); + if (filtered) headerLines.push(`Cookie: ${filtered}`); + continue; + } + const vals = Array.isArray(v) ? v : [v]; + for (const item of vals) { + headerLines.push(`${k}: ${item}`); + } + } + + live.activeConnections += 1; + live.totalConnections += 1; + live.sockets.add(socket); + live.sockets.add(upstream); + + let cleaned = false; const cleanup = () => { + if (cleaned) return; + cleaned = true; live.sockets.delete(socket); live.sockets.delete(upstream); socket.destroy(); upstream.destroy(); + if (upstream !== sshStream) sshStream.destroy(); + live.activeConnections = Math.max(0, live.activeConnections - 1); }; + + socket.on('data', (c: Buffer) => { + live.bytesOut += c.length; + }); + upstream.on('data', (c: Buffer) => { + live.bytesIn += c.length; + }); + + upstream.write(`${headerLines.join('\r\n')}\r\n\r\n`); + if (head.length > 0) upstream.write(head); + + socket.pipe(upstream); + upstream.pipe(socket); upstream.on('error', cleanup); upstream.on('close', cleanup); socket.on('error', cleanup); socket.on('close', cleanup); } - private async startLocalListenerTunnel( + private scheduleTtl(handle: ActiveTunnelHandle): void { + if (!handle.tunnel.ttlSec) return; + const ttlMs = handle.tunnel.ttlSec * 1000; + handle.expiresAt = Date.now() + ttlMs; + handle.ttlTimer = setTimeout(() => { + void this.stopTunnel(handle.serverId, handle.tunnel.id); + }, ttlMs); + handle.ttlTimer.unref(); + } + + private async startLocalOrHttpTunnel( serverId: string, tunnel: ServerTunnel, ): Promise { - // Verify SSH reachability upfront so callers get immediate handshake/TOFU/vault feedback await this.sshPool.acquireClient(serverId); - - const bindHost = - tunnel.mode === 'http-proxy' ? '127.0.0.1' : tunnel.bindHost ?? '127.0.0.1'; - const bindPort = tunnel.mode === 'http-proxy' ? 0 : tunnel.bindPort ?? 0; const key = makeTunnelKey(serverId, tunnel.id); + if (tunnel.mode === 'http-proxy') { + const handle: ActiveTunnelHandle = { + key, + serverId, + tunnel, + httpProxyActive: true, + activeConnections: 0, + totalConnections: 0, + bytesIn: 0, + bytesOut: 0, + startedAt: Date.now(), + sockets: new Set(), + }; + this.scheduleTtl(handle); + this.active.set(key, handle); + return this.toRuntimeInfo(serverId, tunnel, handle); + } + + const bindHost = tunnel.bindHost ?? '127.0.0.1'; + if (!this.allowLanTunnels && !isLoopbackHost(bindHost)) { + throw new Error( + `Non-loopback bindHost "${bindHost}" requires GCOORD_ALLOW_LAN_TUNELS=true`, + ); + } + const bindPort = tunnel.bindPort ?? 0; + const handle: ActiveTunnelHandle = { key, serverId, @@ -359,7 +1091,11 @@ export class TunnelManager { }; const tcpServer = net.createServer((clientSocket: Socket) => { - this.bridgeLocalSocket(handle, clientSocket); + if (tunnel.mode === 'socks5') { + this.bridgeSocks5Socket(handle, clientSocket); + } else { + this.bridgeLocalSocket(handle, clientSocket); + } }); handle.tcpServer = tcpServer; @@ -379,11 +1115,163 @@ export class TunnelManager { handle.lastError = err.message; }); + this.scheduleTtl(handle); this.active.set(key, handle); return this.toRuntimeInfo(serverId, tunnel, handle); } + private bridgeSocks5Socket(handle: ActiveTunnelHandle, clientSocket: Socket): void { + if (!this.canAcceptSocket(handle)) { + clientSocket.destroy(); + return; + } + + handle.activeConnections += 1; + handle.totalConnections += 1; + handle.sockets.add(clientSocket); + + let decremented = false; + const closeSocket = () => { + handle.sockets.delete(clientSocket); + clientSocket.destroy(); + if (!decremented) { + decremented = true; + handle.activeConnections = Math.max(0, handle.activeConnections - 1); + } + }; + + let stage: 'greeting' | 'request' | 'connected' = 'greeting'; + let buf = Buffer.alloc(0); + + const sendSocksError = (rep: number) => { + try { + clientSocket.write(Buffer.from([0x05, rep, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); + } catch { + // Ignore write error + } + closeSocket(); + }; + + const onData = (chunk: Buffer) => { + if (stage === 'connected') return; + buf = Buffer.concat([buf, chunk]); + if (buf.length > 1024) { + closeSocket(); + return; + } + + if (stage === 'greeting') { + if (buf.length < 2) return; + const ver = buf[0]!; + const nMethods = buf[1]!; + if (ver !== 0x05) { + closeSocket(); + return; + } + if (buf.length < 2 + nMethods) return; + const methods = buf.subarray(2, 2 + nMethods); + buf = buf.subarray(2 + nMethods); + if (!methods.includes(0x00)) { + clientSocket.write(Buffer.from([0x05, 0xff])); + closeSocket(); + return; + } + clientSocket.write(Buffer.from([0x05, 0x00])); + stage = 'request'; + } + + if (stage === 'request') { + if (buf.length < 4) return; + const ver = buf[0]!; + const cmd = buf[1]!; + const atyp = buf[3]!; + if (ver !== 0x05 || cmd !== 0x01) { + sendSocksError(0x07); + return; + } + + let dstHost = ''; + let offset = 4; + if (atyp === 0x01) { + if (buf.length < offset + 4 + 2) return; + dstHost = `${buf[offset]!}.${buf[offset + 1]!}.${buf[offset + 2]!}.${buf[offset + 3]!}`; + offset += 4; + } else if (atyp === 0x03) { + if (buf.length < offset + 1) return; + const len = buf[offset]!; + offset += 1; + if (buf.length < offset + len + 2) return; + dstHost = buf.subarray(offset, offset + len).toString('utf8'); + offset += len; + } else if (atyp === 0x04) { + if (buf.length < offset + 16 + 2) return; + const parts: string[] = []; + for (let i = 0; i < 16; i += 2) { + parts.push(buf.readUInt16BE(offset + i).toString(16)); + } + dstHost = parts.join(':'); + offset += 16; + } else { + sendSocksError(0x08); + return; + } + + const dstPort = buf.readUInt16BE(offset); + const remaining = buf.subarray(offset + 2); + stage = 'connected'; + clientSocket.off('data', onData); + + this.sshPool + .forwardOutStream(handle.serverId, dstHost, dstPort) + .then((sshStream) => { + if (clientSocket.destroyed || !this.active.has(handle.key)) { + sshStream.destroy(); + closeSocket(); + return; + } + handle.sockets.add(sshStream); + clientSocket.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); + if (remaining.length > 0) { + sshStream.write(remaining); + handle.bytesOut += remaining.length; + } + clientSocket.on('data', (c: Buffer) => { + handle.bytesOut += c.length; + }); + sshStream.on('data', (c: Buffer) => { + handle.bytesIn += c.length; + }); + clientSocket.pipe(sshStream); + sshStream.pipe(clientSocket); + + const cleanup = () => { + handle.sockets.delete(sshStream); + sshStream.destroy(); + closeSocket(); + }; + sshStream.once('close', cleanup); + sshStream.once('error', cleanup); + clientSocket.once('close', cleanup); + clientSocket.once('error', cleanup); + }) + .catch((err) => { + handle.lastError = err instanceof Error ? err.message : String(err); + sendSocksError(0x05); + }); + } + }; + + clientSocket.on('data', onData); + clientSocket.once('error', closeSocket); + clientSocket.once('close', closeSocket); + } + private bridgeLocalSocket(handle: ActiveTunnelHandle, clientSocket: Socket): void { + if (!this.canAcceptSocket(handle)) { + clientSocket.destroy(); + return; + } + handle.activeConnections += 1; handle.totalConnections += 1; handle.sockets.add(clientSocket); @@ -440,6 +1328,9 @@ export class TunnelManager { serverId: string, tunnel: ServerTunnel, ): Promise { + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + await assertEgressHostAllowed(tunnel.targetHost, allowedCidrs); + const client = await this.sshPool.acquireClient(serverId); const bindHost = tunnel.bindHost ?? '127.0.0.1'; const bindPort = tunnel.bindPort ?? 0; @@ -484,47 +1375,92 @@ export class TunnelManager { }); handle.remoteBoundPort = actualPort; - portMap.set(actualPort, (_details, accept, _reject) => { + portMap.set(actualPort, (_details, accept, reject) => { + if (!this.canAcceptSocket(handle)) { + reject(); + return; + } + const channel = accept(); handle.activeConnections += 1; handle.totalConnections += 1; handle.sockets.add(channel); - const targetSock = net.connect(tunnel.targetPort, tunnel.targetHost); - handle.sockets.add(targetSock); - let decremented = false; - const cleanup = () => { + const cleanupBase = () => { handle.sockets.delete(channel); - handle.sockets.delete(targetSock); channel.destroy(); - targetSock.destroy(); if (!decremented) { decremented = true; handle.activeConnections = Math.max(0, handle.activeConnections - 1); } }; - channel.on('data', (chunk: Buffer) => { - handle.bytesIn += chunk.length; - }); - targetSock.on('data', (chunk: Buffer) => { - handle.bytesOut += chunk.length; - }); + const curCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + resolveAllowedEgressIps(tunnel.targetHost, curCidrs) + .then((resolvedIps: string[]) => { + if (!this.active.has(handle.key)) { + cleanupBase(); + return; + } + const targetSock = net.connect(tunnel.targetPort, resolvedIps[0]!); + handle.sockets.add(targetSock); - channel.pipe(targetSock); - targetSock.pipe(channel); - channel.once('close', cleanup); - channel.once('error', cleanup); - targetSock.once('close', cleanup); - targetSock.once('error', cleanup); + const cleanupAll = () => { + handle.sockets.delete(targetSock); + targetSock.destroy(); + cleanupBase(); + }; + + channel.on('data', (chunk: Buffer) => { + handle.bytesIn += chunk.length; + }); + targetSock.on('data', (chunk: Buffer) => { + handle.bytesOut += chunk.length; + }); + + channel.pipe(targetSock); + targetSock.pipe(channel); + channel.once('close', cleanupAll); + channel.once('error', cleanupAll); + targetSock.once('close', cleanupAll); + targetSock.once('error', cleanupAll); + }) + .catch((err: unknown) => { + handle.lastError = err instanceof Error ? err.message : String(err); + cleanupBase(); + }); }); + client.once('close', () => { + if (this.active.get(key) === handle && !handle.manuallyStopped) { + this.active.delete(key); + void this.teardownHandle(handle); + if (tunnel.autoStart && this.vaultService.isRuntimeReady) { + const timer = setTimeout(() => { + void this.startTunnel(serverId, tunnel.id).catch(() => undefined); + }, 5_000); + timer.unref(); + handle.remoteReconnectTimer = timer; + } + } + }); + + this.scheduleTtl(handle); this.active.set(key, handle); return this.toRuntimeInfo(serverId, tunnel, handle); } private async teardownHandle(handle: ActiveTunnelHandle): Promise { + if (handle.ttlTimer) { + clearTimeout(handle.ttlTimer); + handle.ttlTimer = undefined; + } + if (handle.remoteReconnectTimer) { + clearTimeout(handle.remoteReconnectTimer); + handle.remoteReconnectTimer = undefined; + } + for (const sock of handle.sockets) { try { sock.destroy(); @@ -550,17 +1486,22 @@ export class TunnelManager { } } + private computeProxyId(serverId: string, tunnel: ServerTunnel): string { + const key = makeTunnelKey(serverId, tunnel.id); + const sameIdCount = this.configManager + .listServers() + .flatMap((s) => s.tunnels) + .filter((t) => t.id === tunnel.id && t.mode === 'http-proxy').length; + return sameIdCount <= 1 ? tunnel.id : key; + } + private toRuntimeInfo( serverId: string, tunnel: ServerTunnel, live?: ActiveTunnelHandle, ): TunnelRuntimeInfo { const key = makeTunnelKey(serverId, tunnel.id); - const sameIdCount = this.configManager - .listServers() - .flatMap((s) => s.tunnels) - .filter((t) => t.id === tunnel.id && t.mode === 'http-proxy').length; - const proxyId = sameIdCount <= 1 ? tunnel.id : key; + const proxyId = this.computeProxyId(serverId, tunnel); return { key, serverId, @@ -570,9 +1511,10 @@ export class TunnelManager { localBoundPort: live?.localBoundPort, remoteBoundPort: live?.remoteBoundPort, proxyPath: - tunnel.mode === 'http-proxy' && live?.localBoundPort + tunnel.mode === 'http-proxy' && live?.httpProxyActive ? `/proxy/${proxyId}/` : undefined, + expiresAt: live?.expiresAt, activeConnections: live?.activeConnections ?? 0, totalConnections: live?.totalConnections ?? 0, bytesIn: live?.bytesIn ?? 0, diff --git a/tests/tunnels-and-proxy.test.ts b/tests/tunnels-and-proxy.test.ts index 9ae5a40..cc4bc20 100644 --- a/tests/tunnels-and-proxy.test.ts +++ b/tests/tunnels-and-proxy.test.ts @@ -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: {