背景与价值SSRF常通过不受控的网络请求访问内部资源与云平台元数据端点。严格的协议、地址与端口治理可有效阻断攻击链。统一规范协议白名单:默认仅允许 `https`。地址黑名单:阻断私网、环回、链路本地与多播保留段。元数据防护:阻断云平台元数据域与地址。端口策略:仅允许业务需要的端口集合,默认 443。核心实现IPv4数值化与CIDR判定function ipv4ToInt(ip: string): number { const m = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/) if (!m) return -1 const n = m.slice(1).map(Number) for (const x of n) if (x < 0 || x > 255) return -1 return ((n[0] << 24) >>> 0) + (n[1] << 16) + (n[2] << 8) + n[3] } function parseCidr(cidr: string): { base: number; mask: number } | null { const m = cidr.match(/^([0-9.]+)\/(\d{1,2})$/) if (!m) return null const base = ipv4ToInt(m[1]) const p = Number(m[2]) if (base < 0 || p < 0 || p > 32) return null const mask = p === 0 ? 0 : (~0 << (32 - p)) >>> 0 return { base, mask } } function inCidr(ip: string, cidr: string): boolean { const v = ipv4ToInt(ip) const c = parseCidr(cidr) if (v < 0 || !c) return false return (v & c.mask) === (c.base & c.mask) } 保留与私网段集合const blockedCidrs = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.0/8', '169.254.0.0/16', '224.0.0.0/4' ] const metadataHosts = new Set([ '169.254.169.254', 'metadata.google.internal' ]) 协议与端口白名单const allowProtocols = new Set(['https']) const allowPorts = new Set([443]) function protocolAllowed(u: URL): boolean { return allowProtocols.has(u.protocol.replace(':','')) } function portAllowed(u: URL): boolean { const p = u.port ? Number(u.port) : (u.protocol === 'https:' ? 443 : 80); return allowPorts.has(p) } 出口校验function hostBlocked(host: string): boolean { if (metadataHosts.has(host)) return true if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) { for (const c of blockedCidrs) if (inCidr(host, c)) return true } if (host === 'localhost' || host.endsWith('.local')) return true return false } function validateOutbound(url: string): boolean { let u: URL try { u = new URL(url) } catch { return false } if (!protocolAllowed(u)) return false if (!portAllowed(u)) return false if (hostBlocked(u.hostname)) return false return true } 落地建议全链路使用 `https`,并在服务端与代理统一执行协议与端口白名单。阻断到私网、环回、链路本地与多播段的所有请求,覆盖IP字面量与保留域名。明确阻断云平台元数据端点与DNS劫持后的等效地址。将出口治理置于反向代理或服务网关,必要时进行域名解析后再判定归属网段。验证清单请求协议是否命中白名单,端口是否符合策略。目标主机是否在私网、环回或链路本地网段。是否命中云平台元数据端点与保留域名。

发表评论 取消回复