背景与价值
DNS重绑定通过变更解析结果绕过同源策略。统一Host与Origin治理并校验解析一致性可有效阻断。
统一规范
- Host白名单:仅允许受控Host与Origin。
- 解析一致性:解析结果不得落入私网或环回网段。
- 代理头治理:统一校验并优先可信代理头。
核心实现
白名单与解析
```ts
const allowHosts = new Set(['app.example.com','api.example.com'])
function hostAllowed(h: string): boolean { return allowHosts.has(h.toLowerCase()) }
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 inCidr(ip: string, cidr: string): boolean { const [b,p] = cidr.split('/'); const base = ipv4ToInt(b); const mask = (~0 << (32-Number(p)))>>>0; const v = ipv4ToInt(ip); if (base<0||v<0) return false; return (v & mask) === (base & 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']
```
一致性校验
```ts
type Req = { headers: Record

发表评论 取消回复