309 lines
11 KiB
TypeScript
309 lines
11 KiB
TypeScript
import { isIP } from "node:net"
|
||
|
||
/** IP helpers for RIPEstat prefix cache and EvoBGP CIDR match. */
|
||
|
||
/**
|
||
* Host-семантика PostgreSQL `host(inet)`: снимает `/32` `/128`, `::ffff:`.
|
||
* IPFIX 5-tuple не меняем — только канонический вид адреса.
|
||
*/
|
||
export function canonicalIp(raw: string | undefined | null): string {
|
||
let t = String(raw ?? "").trim()
|
||
if (!t) return ""
|
||
const zone = t.indexOf("%")
|
||
if (zone >= 0) t = t.slice(0, zone)
|
||
const slash = t.lastIndexOf("/")
|
||
if (slash >= 0) {
|
||
const plen = t.slice(slash + 1)
|
||
if (/^\d+$/.test(plen)) t = t.slice(0, slash)
|
||
}
|
||
if (t.toLowerCase().startsWith("::ffff:") && isIP(t.slice(7)) === 4) t = t.slice(7)
|
||
else if (/(?:^|:)ffff:/i.test(t)) {
|
||
const n = ipv6ToInt(t)
|
||
if (n !== null && n >> 32n === 0xffffn) {
|
||
const v4 = Number(n & 0xffffffffn)
|
||
t = [v4 >>> 24, (v4 >>> 16) & 255, (v4 >>> 8) & 255, v4 & 255].join(".")
|
||
}
|
||
}
|
||
return t.trim()
|
||
}
|
||
|
||
export function ipv4ToInt(ip: string): number | null {
|
||
const parts = canonicalIp(ip).split(".")
|
||
if (parts.length !== 4) return null
|
||
let n = 0
|
||
for (const p of parts) {
|
||
if (!/^\d+$/.test(p)) return null
|
||
const o = Number(p)
|
||
if (o < 0 || o > 255) return null
|
||
n = ((n << 8) >>> 0) + o
|
||
}
|
||
return n >>> 0
|
||
}
|
||
|
||
export function parseCidrV4(cidr: string): { net: number; mask: number; prefixLen: number } | null {
|
||
const raw = String(cidr ?? "").trim()
|
||
const [ip, lenRaw] = raw.split("/")
|
||
const addr = ipv4ToInt(ip ?? "")
|
||
const prefixLen = Number.parseInt(lenRaw ?? "", 10)
|
||
if (addr == null || !Number.isFinite(prefixLen) || prefixLen < 0 || prefixLen > 32) return null
|
||
const mask = prefixLen === 0 ? 0 : (0xffffffff << (32 - prefixLen)) >>> 0
|
||
return { net: (addr & mask) >>> 0, mask, prefixLen }
|
||
}
|
||
|
||
export function ipInCidrV4(ip: string, cidr: string): boolean {
|
||
const addr = ipv4ToInt(ip)
|
||
const parsed = parseCidrV4(cidr)
|
||
if (addr == null || parsed == null) return false
|
||
return ((addr & parsed.mask) >>> 0) === parsed.net
|
||
}
|
||
|
||
// IPv4 ranges not globally reachable in the IANA special-purpose registry.
|
||
// Parse fixed ranges once: this predicate also runs for each flow endpoint.
|
||
const nonPublicV4Ranges = [
|
||
"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8",
|
||
"169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24",
|
||
"192.88.99.2/32", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24",
|
||
"203.0.113.0/24", "224.0.0.0/4", "240.0.0.0/4",
|
||
].map(cidr => parseCidrV4(cidr)!)
|
||
const publicProtocolAnycastV4 = new Set([0xc0000009, 0xc000000a]) // 192.0.0.9/10
|
||
|
||
// Only parse validated IPv6. Embedded IPv4 occupies the final two words.
|
||
export function ipv6ToInt(ip: string): bigint | null {
|
||
if (isIP(ip) !== 6) return null
|
||
let value = ip
|
||
if (value.includes(".")) {
|
||
const last = value.lastIndexOf(":")
|
||
const v4 = ipv4ToInt(value.slice(last + 1))!
|
||
value = value.slice(0, last + 1) + (v4 >>> 16).toString(16) + ":" + (v4 & 0xffff).toString(16)
|
||
}
|
||
const [left, right] = value.split("::")
|
||
const head = left ? left.split(":") : []
|
||
const tail = right ? right.split(":") : []
|
||
const words = right === undefined ? head : [...head, ...Array<string>(8 - head.length - tail.length).fill("0"), ...tail]
|
||
return words.reduce((n, word) => (n << 16n) | BigInt(parseInt(word, 16)), 0n)
|
||
}
|
||
|
||
function v6Range(cidr: string) {
|
||
const [ip, length] = cidr.split("/")
|
||
const shift = BigInt(128 - Number(length))
|
||
return { prefix: ipv6ToInt(ip!)! >> shift, shift }
|
||
}
|
||
|
||
export function parseCidrV6(cidr: string): { net: bigint; shift: bigint; prefixLen: number } | null {
|
||
const parts = cidr.split("/")
|
||
if (parts.length !== 2 || !/^\d+$/.test(parts[1]!)) return null
|
||
const prefixLen = Number(parts[1])
|
||
const addr = ipv6ToInt(parts[0]!)
|
||
if (addr === null || prefixLen < 0 || prefixLen > 128) return null
|
||
const shift = BigInt(128 - prefixLen)
|
||
return { net: addr >> shift, shift, prefixLen }
|
||
}
|
||
|
||
// IANA non-global assignments plus deprecated site-local and multicast.
|
||
// More-specific globally reachable allocations inside 2001::/23 take priority.
|
||
const nonPublicV6Ranges = [
|
||
"::/96", "64:ff9b:1::/48", "100::/64", "100:0:0:1::/64",
|
||
"2001::/23", "2001:db8::/32", "3fff::/20", "5f00::/16",
|
||
"fc00::/7", "fe80::/10", "fec0::/10", "ff00::/8",
|
||
].map(v6Range)
|
||
const publicProtocolV6Ranges = [
|
||
"2001::/32", // Teredo: IANA reachability is N/A, not non-global.
|
||
"2001:1::1/128", "2001:1::2/128", "2001:1::3/128",
|
||
"2001:3::/32", "2001:4:112::/48", "2001:20::/28", "2001:30::/28",
|
||
].map(v6Range)
|
||
|
||
export function isNonPublicIp(ip: string): boolean {
|
||
const trimmed = canonicalIp(ip)
|
||
if (!trimmed) return true
|
||
if (trimmed.includes(":")) {
|
||
const n = ipv6ToInt(trimmed)
|
||
if (n === null) return true
|
||
if (publicProtocolV6Ranges.some(({ prefix, shift }) => n >> shift === prefix)) return false
|
||
return nonPublicV6Ranges.some(({ prefix, shift }) => n >> shift === prefix)
|
||
}
|
||
const n = ipv4ToInt(trimmed)
|
||
if (n == null) return true
|
||
if (publicProtocolAnycastV4.has(n)) return false
|
||
return nonPublicV4Ranges.some(({ net, mask }) => ((n & mask) >>> 0) === net)
|
||
}
|
||
|
||
const PEER_WELL_KNOWN_PORTS = new Set([80, 443, 53, 853])
|
||
|
||
export function isUnspecifiedIp(ip: string): boolean {
|
||
const t = canonicalIp(ip)
|
||
if (!t) return true
|
||
const lower = t.toLowerCase()
|
||
return t === "0.0.0.0" || lower === "::" || lower === "::0"
|
||
|| (lower.includes(":") && !/[1-9a-f]/i.test(lower) && ipv6ToInt(lower) === 0n)
|
||
}
|
||
|
||
function usableIp(ip: string | undefined): string {
|
||
const t = canonicalIp(ip)
|
||
return isUnspecifiedIp(t) ? "" : t
|
||
}
|
||
|
||
export interface InternetDestCtx {
|
||
/** WAN IP узлов сети (EN/JH) — не интернет-назначение. */
|
||
ours?: ReadonlySet<string>
|
||
/** Ingress с bound GRE/WG клиента: dest = нелокальный IP, не ASN клиента. */
|
||
boundClient?: boolean
|
||
/** IPFIX postNAT (IANA 225/226). */
|
||
natSrc?: string
|
||
natDst?: string
|
||
/** IPFIX postNAPT ports (IANA 227/228). */
|
||
natSrcPort?: number
|
||
natDstPort?: number
|
||
}
|
||
|
||
export function isLocalIp(ip: string, ours?: ReadonlySet<string>): boolean {
|
||
const host = canonicalIp(ip)
|
||
if (isUnspecifiedIp(host) || isNonPublicIp(host)) return true
|
||
if (!ours || ours.size === 0) return false
|
||
if (ours.has(host) || ours.has(String(ip ?? "").trim())) return true
|
||
for (const o of ours) {
|
||
if (canonicalIp(o) === host) return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
/**
|
||
* Интернет-назначение потока для ASN/страны/сервиса.
|
||
* Пустая строка — dest нет (не GeoIP IP клиента / GRE-пира).
|
||
*
|
||
* boundClient: download CDN→overlay берём публичный src даже без :80/:443
|
||
* (googlevideo). Client-ISP → overlay:well-known — не dest (ASN клиента).
|
||
*/
|
||
export function pickInternetDest(
|
||
srcRaw: string,
|
||
dstRaw: string,
|
||
srcPort: number,
|
||
dstPort: number,
|
||
ctx?: InternetDestCtx,
|
||
): string {
|
||
const ours = ctx?.ours
|
||
const src = usableIp(srcRaw)
|
||
const dst = usableIp(dstRaw)
|
||
const natSrc = usableIp(ctx?.natSrc)
|
||
const natDst = usableIp(ctx?.natDst)
|
||
const internet = (ip: string) => Boolean(ip) && !isLocalIp(ip, ours)
|
||
const dstIp = internet(dst) ? dst : (internet(natDst) ? natDst : "")
|
||
const srcIp = internet(src) ? src : (internet(natSrc) ? natSrc : "")
|
||
const dstPortEff = internet(dst) ? dstPort : (internet(natDst) ? (ctx?.natDstPort || dstPort) : dstPort)
|
||
const srcPortEff = internet(src) ? srcPort : (internet(natSrc) ? (ctx?.natSrcPort || srcPort) : srcPort)
|
||
|
||
if (ctx?.boundClient) {
|
||
if (dstIp) return dstIp
|
||
if (srcIp) {
|
||
const srcWk = PEER_WELL_KNOWN_PORTS.has(srcPortEff)
|
||
const dstWk = PEER_WELL_KNOWN_PORTS.has(dstPortEff)
|
||
if (!srcWk && dstWk) return ""
|
||
return srcIp
|
||
}
|
||
return ""
|
||
}
|
||
|
||
if (srcIp && !dstIp) return srcIp
|
||
if (dstIp && !srcIp) return dstIp
|
||
if (srcIp && dstIp) {
|
||
const srcWk = PEER_WELL_KNOWN_PORTS.has(srcPortEff)
|
||
const dstWk = PEER_WELL_KNOWN_PORTS.has(dstPortEff)
|
||
if (srcWk && !dstWk) return srcIp
|
||
if (dstWk && !srcWk) return dstIp
|
||
return dstIp
|
||
}
|
||
|
||
if (src && dst && ours?.has(src) && ours.has(dst)) return ""
|
||
return dst
|
||
}
|
||
|
||
/**
|
||
* Dest для карты = тот же internet peer, что аналитика/факты.
|
||
* (исторически отдельный fallback без well-known trap — теперь в pickInternetDest.)
|
||
*/
|
||
export function pickMapInternetDest(
|
||
srcRaw: string,
|
||
dstRaw: string,
|
||
srcPort: number,
|
||
dstPort: number,
|
||
ctx?: InternetDestCtx,
|
||
): string {
|
||
return pickInternetDest(srcRaw, dstRaw, srcPort, dstPort, ctx)
|
||
}
|
||
|
||
/**
|
||
* Интернет-сторона потока без топологии: у IPFIX сервис часто в src (Google:443 → RFC1918).
|
||
*/
|
||
export function pickInternetPeer(src: string, dst: string, srcPort: number, dstPort: number): string {
|
||
return pickInternetDest(src, dst, srcPort, dstPort) || ""
|
||
}
|
||
|
||
export type FlowDirection = "to_client" | "from_client" | "transit"
|
||
|
||
export interface FlowEndpoints {
|
||
packetSrc: string
|
||
packetDst: string
|
||
internetPeer: string
|
||
peerPort: number
|
||
otherPort: number
|
||
clientIp: string
|
||
direction: FlowDirection
|
||
}
|
||
|
||
function sameHost(a: string, b: string | undefined): boolean {
|
||
const x = canonicalIp(a)
|
||
const y = canonicalIp(b)
|
||
return Boolean(x) && x === y
|
||
}
|
||
|
||
/** Роли концов IPFIX-пакета. 5-tuple не переворачивается. */
|
||
export function resolveFlowEndpoints(opts: {
|
||
src: string
|
||
dst: string
|
||
srcPort: number
|
||
dstPort: number
|
||
ctx?: InternetDestCtx
|
||
}): FlowEndpoints {
|
||
const packetSrc = usableIp(opts.src)
|
||
const packetDst = usableIp(opts.dst)
|
||
const internetPeer = pickInternetDest(opts.src, opts.dst, opts.srcPort, opts.dstPort, opts.ctx)
|
||
const ours = opts.ctx?.ours
|
||
const srcLocal = Boolean(packetSrc) && isLocalIp(packetSrc, ours)
|
||
const dstLocal = Boolean(packetDst) && isLocalIp(packetDst, ours)
|
||
|
||
let peerPort = 0
|
||
let otherPort = 0
|
||
if (internetPeer) {
|
||
if (sameHost(internetPeer, packetSrc) || sameHost(internetPeer, opts.ctx?.natSrc)) {
|
||
peerPort = opts.srcPort
|
||
otherPort = opts.dstPort
|
||
} else if (sameHost(internetPeer, packetDst) || sameHost(internetPeer, opts.ctx?.natDst)) {
|
||
peerPort = opts.dstPort
|
||
otherPort = opts.srcPort
|
||
} else {
|
||
peerPort = opts.ctx?.natDstPort || opts.dstPort
|
||
otherPort = opts.srcPort
|
||
}
|
||
}
|
||
|
||
let clientIp = ""
|
||
if (srcLocal && !dstLocal) clientIp = packetSrc
|
||
else if (dstLocal && !srcLocal) clientIp = packetDst
|
||
else if (srcLocal) clientIp = packetSrc
|
||
else if (dstLocal) clientIp = packetDst
|
||
|
||
let direction: FlowDirection = "transit"
|
||
if (internetPeer && clientIp) {
|
||
direction = sameHost(internetPeer, packetSrc) ? "to_client" : "from_client"
|
||
}
|
||
|
||
return {
|
||
packetSrc,
|
||
packetDst,
|
||
internetPeer,
|
||
peerPort,
|
||
otherPort,
|
||
clientIp,
|
||
direction,
|
||
}
|
||
}
|