fix(xdp): walk IPv6 extension headers and apply the blacklist to every protocol
IPv6 packets with any extension header, and IPv4 ICMP/GRE/ESP, returned XDP_PASS before the whitelist/blacklist were read. pkt_test gains phases for both (they fail on the previous filter). Explicit TCP header bounds checks keep the 5.15 verifier happy.
This commit is contained in:
parent
fb951ac225
commit
b670a69866
7 changed files with 177 additions and 19 deletions
10
CHANGELOG.md
10
CHANGELOG.md
|
|
@ -41,6 +41,16 @@
|
|||
|
||||
### Fixed
|
||||
|
||||
- **XDP: IPv6 с extension-заголовком обходил весь фильтр.** Любой заголовок hop-by-hop,
|
||||
routing, destination options или AH (стек ядра их обрабатывает) давал `XDP_PASS` до
|
||||
whitelist/blacklist/throttle/порт-гейта. Теперь цепочка (до 4 заголовков) разбирается до
|
||||
реального L4; более длинная цепочка и протоколы вне TCP/UDP проходят проверку blacklist.
|
||||
- **XDP: забаненный IPv4-источник проходил ICMP/GRE/ESP и т. п.** — `XDP_PASS` стоял до
|
||||
чтения списков. Теперь blacklist применяется ко всем протоколам, чистый трафик по-прежнему
|
||||
проходит. Также отбрасывается IPv4-пакет с `version != 4`.
|
||||
- XDP: для IPv4-mapped IPv6 длина TCP-payload считалась как `40 + payload_len` (всегда
|
||||
срезалась до конца кадра, то есть учитывала паддинг); теперь `payload_len` минус
|
||||
extension-заголовки.
|
||||
- **XDP: verifier на ядре 5.15 отвергал программу** (`invalid indirect read from stack`):
|
||||
неявный паддинг `struct throttle_entry` не обнулялся clang 14 — теперь явное поле `pad`
|
||||
(размер 16 и ABI прежние). Найдено прогоном на реальной KVM-ноде.
|
||||
|
|
|
|||
|
|
@ -42,8 +42,8 @@ client → eth0 → [XDP/eBPF] → kernel TCP → accept → Gateway → plugin
|
|||
|
||||
### 3.1 XDP (C, `xdp/core/`)
|
||||
|
||||
Stateless-фильтр на входе интерфейса. Разбирает Ethernet (VLAN/QinQ), IPv4/IPv6,
|
||||
L4; порт-гейт `[xdp] protected_port_start/end` отсекает нецелевой трафик до
|
||||
Stateless-фильтр на входе интерфейса. Разбирает Ethernet (VLAN/QinQ), IPv4/IPv6
|
||||
(для IPv6 — до 4 extension-заголовков до L4), L4; порт-гейт `[xdp] protected_port_start/end` отсекает нецелевой трафик до
|
||||
фильтра.
|
||||
|
||||
| Механизм | IPv4 | IPv6 |
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@
|
|||
| GeoIP/ASN reputation | P1 | idea | [v0.5-geoip-asn.md](v0.5-geoip-asn.md) |
|
||||
| gRPC protocol plugin | P2 | idea | [v0.5-grpc-plugin.md](v0.5-grpc-plugin.md) |
|
||||
| XDP: IPv6-паритет для L4 | P1 | idea | [v0.5-xdp-ipv6-parity.md](v0.5-xdp-ipv6-parity.md) |
|
||||
| Аудит XDP-фильтра и тесты без root | P1 | idea | [v0.5-xdp-filter-audit.md](v0.5-xdp-filter-audit.md) |
|
||||
| Аудит XDP-фильтра и тесты без root | P1 | in-progress | [v0.5-xdp-filter-audit.md](v0.5-xdp-filter-audit.md) |
|
||||
| Minecraft: гигиена handshake/login | P1 | idea | [v0.5-minecraft-handshake-hygiene.md](v0.5-minecraft-handshake-hygiene.md) |
|
||||
| Управление банами: теги, наборы, API | P2 | idea | [v0.5-control-plane-bans.md](v0.5-control-plane-bans.md) |
|
||||
| Пакеты и релизный процесс | P2 | idea | [v0.5-packaging-release.md](v0.5-packaging-release.md) |
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
| | |
|
||||
|---|---|
|
||||
| Milestone | v0.5 |
|
||||
| Status | idea |
|
||||
| Status | in-progress |
|
||||
| Priority | P1 |
|
||||
| Depends on | v0.4-xdp-ci-harness |
|
||||
|
||||
|
|
@ -40,6 +40,23 @@ XDP-Firewall (MIT) и Minecraft-XDP-eBPF (BSD-3) дал список конкр
|
|||
собранных буферах (приём XDP-Firewall `tests/packets.c`; альтернатива —
|
||||
`BPF_PROG_TEST_RUN` через libbpf-rs), плюс fuzz на тех же байтах.
|
||||
|
||||
## Результаты (часть 1, сделано)
|
||||
|
||||
Найдено и исправлено, подтверждено `scripts/xdp_pkt_test.sh` (на прежнем фильтре новые фазы
|
||||
падают, на исправленном проходят; ядро 5.15.0-204):
|
||||
|
||||
- [x] IPv6 extension headers обходили фильтр целиком → обход цепочки до 4 заголовков.
|
||||
- [x] ICMP/GRE и прочие протоколы вне TCP/UDP проходили до чтения blacklist → blacklist
|
||||
применяется ко всем протоколам.
|
||||
- [x] IPv4 `version != 4` → дроп.
|
||||
- [x] IPv4-mapped IPv6: длина L4 считалась неверно → `payload_len` минус extension-заголовки.
|
||||
- Урок для verifier: после появления переменного `l4_proto` потребовались явные проверки
|
||||
границ TCP-заголовка перед чтением флагов (verifier не коррелирует `l4_proto` с размером).
|
||||
|
||||
Осталось (пункты Scope выше без отметки): маска `/0`, байты ключа v6 в тесте загрузчика,
|
||||
per-CPU буферы по possible CPU, поведение при заполнении карт, тесты `size_of`, сверка
|
||||
с `detect_tcp_bypass`, rootless ASan/UBSan-тесты.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Линейные правила в горячем пути; переписывание XDP на Rust.
|
||||
|
|
|
|||
|
|
@ -67,17 +67,19 @@ ok "verifier принял программу, attach на $DEV0"
|
|||
discover_maps() {
|
||||
IDS=$(bpftool prog show pinned "$PIN" | grep -o 'map_ids [0-9,]*' | cut -d' ' -f2 | tr ',' ' ')
|
||||
B4=""
|
||||
B6=""
|
||||
CT=""
|
||||
ST=""
|
||||
for id in $IDS; do
|
||||
desc=$(bpftool map show id "$id" 2>/dev/null)
|
||||
case "$desc" in
|
||||
*"name blacklist_map"*) B4=$id ;;
|
||||
*"name blacklist6_map"*) B6=$id ;;
|
||||
*"name conntrack_map"*) CT=$id ;;
|
||||
*"name stats_map"*) ST=$id ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$B4" ] && [ -n "$CT" ] && [ -n "$ST" ]
|
||||
[ -n "$B4" ] && [ -n "$B6" ] && [ -n "$CT" ] && [ -n "$ST" ]
|
||||
}
|
||||
discover_maps || { echo "карты не найдены"; exit 1; }
|
||||
ok "blacklist_map id=$B4, conntrack_map id=$CT, stats_map id=$ST"
|
||||
|
|
@ -157,7 +159,36 @@ def tcp(args):
|
|||
emit(0x0800, ip4(6, hdr + data), 0, pad)
|
||||
|
||||
|
||||
{"udp": udp, "frag": frag, "tcp": tcp}[kind](sys.argv[5:])
|
||||
def other(args):
|
||||
# IPv4 with a protocol the filter does not inspect (ICMP 1, GRE 47, ...).
|
||||
proto = int(args[0], 0)
|
||||
emit(0x0800, ip4(proto, b"\0" * 16), 0, 0)
|
||||
|
||||
|
||||
SRC6 = bytes.fromhex("fd000088000000000000000000000002")
|
||||
DST6 = bytes.fromhex("fd000088000000000000000000000001")
|
||||
|
||||
|
||||
def ext_hdr(next_hdr):
|
||||
# 8 bytes: next header, length 0, PadN option filling the rest.
|
||||
return bytes([next_hdr, 0, 1, 4, 0, 0, 0, 0])
|
||||
|
||||
|
||||
def v6udp(args):
|
||||
# args: sport dport count-of-destination-options-headers
|
||||
sport, dport, n_ext = (int(a, 0) for a in args)
|
||||
udp = struct.pack("!HHHH", sport, dport, 16, 0) + b"w" * 8
|
||||
# Chain of n destination-options headers (60), then UDP (17).
|
||||
chain = b""
|
||||
for i in range(n_ext):
|
||||
chain += ext_hdr(60 if i < n_ext - 1 else 17)
|
||||
first = 60 if n_ext else 17
|
||||
payload = chain + udp
|
||||
hdr = struct.pack("!IHBB", 0x60000000, len(payload), first, 64) + SRC6 + DST6
|
||||
emit(0x86DD, hdr + payload, 0, 0)
|
||||
|
||||
|
||||
{"udp": udp, "frag": frag, "tcp": tcp, "other": other, "v6udp": v6udp}[kind](sys.argv[5:])
|
||||
PY
|
||||
|
||||
send() { ip netns exec "$NS" python3 "$WORK/send.py" "$DEV1" "$NS4" "$HOST4" "$@"; }
|
||||
|
|
@ -237,5 +268,49 @@ for e in json.load(sys.stdin):
|
|||
&& ok "expected_seq учёл 4 байта payload, а не 20 байт кадра (expected_seq=$got)" \
|
||||
|| fail "expected_seq=$got, ожидалось 1005 (паддинг попал в payload)"
|
||||
|
||||
[ "$PASS" = 1 ] && echo "PASS: VLAN/QinQ, фрагменты и паддинг обрабатываются корректно" || echo "FAIL"
|
||||
# Phase 5: protocols the filter cannot inspect (ICMP, GRE) are not a free pass for
|
||||
# a banned source; a clean source still passes.
|
||||
bpftool map update id "$B4" key hex $KEY4 value hex $BAN || fail "ban $NS4 (phase 5)"
|
||||
drop0=$(metric drop)
|
||||
send other 1
|
||||
send other 47
|
||||
sleep 0.3
|
||||
drop1=$(metric drop)
|
||||
[ "${drop1:-0}" -ge $((${drop0:-0} + 2)) ] \
|
||||
&& ok "ICMP/GRE от забаненного источника дропаются (drop $drop0 -> $drop1)" \
|
||||
|| fail "ICMP/GRE прошли мимо бана (drop $drop0 -> $drop1, $(stats))"
|
||||
bpftool map delete id "$B4" key hex $KEY4 || fail "unban $NS4 (phase 5)"
|
||||
pass0=$(metric pass)
|
||||
send other 1
|
||||
send other 47
|
||||
sleep 0.3
|
||||
pass1=$(metric pass)
|
||||
drop2=$(metric drop)
|
||||
[ "${pass1:-0}" -ge $((${pass0:-0} + 2)) ] && [ "${drop2:-0}" = "${drop1:-0}" ] \
|
||||
&& ok "ICMP/GRE от чистого источника проходят (pass $pass0 -> $pass1)" \
|
||||
|| fail "ICMP/GRE чистого источника не прошли (pass $pass0 -> $pass1, drop $drop1 -> $drop2)"
|
||||
|
||||
# Phase 6: IPv6 extension headers must not hide L4 from the filter. 0 headers is the
|
||||
# control; 1 and 2 are walked; 5 exceeds the walk limit (4) and must still hit the
|
||||
# source blacklist instead of being passed unseen.
|
||||
KEY6="80 00 00 00 fd 00 00 88 00 00 00 00 00 00 00 00 00 00 00 02"
|
||||
bpftool map update id "$B6" key hex $KEY6 value hex $BAN || fail "ban v6 source"
|
||||
drop0=$(metric drop)
|
||||
for n in 0 1 2 5; do send v6udp 5100 $PORT $n; done
|
||||
sleep 0.3
|
||||
drop1=$(metric drop)
|
||||
[ "${drop1:-0}" -ge $((${drop0:-0} + 4)) ] \
|
||||
&& ok "IPv6 (0/1/2/5 extension headers) от забаненного источника дропается (drop $drop0 -> $drop1)" \
|
||||
|| fail "IPv6 с extension headers прошёл мимо бана (drop $drop0 -> $drop1, $(stats))"
|
||||
bpftool map delete id "$B6" key hex $KEY6 || fail "unban v6 source"
|
||||
pass0=$(metric pass)
|
||||
for n in 0 1 2 5; do send v6udp 5101 $PORT $n; done
|
||||
sleep 0.3
|
||||
pass1=$(metric pass)
|
||||
drop2=$(metric drop)
|
||||
[ "${pass1:-0}" -ge $((${pass0:-0} + 4)) ] && [ "${drop2:-0}" = "${drop1:-0}" ] \
|
||||
&& ok "IPv6 с extension headers от чистого источника проходит (pass $pass0 -> $pass1)" \
|
||||
|| fail "IPv6 чистого источника с extension headers не прошёл (pass $pass0 -> $pass1, drop $drop1 -> $drop2)"
|
||||
|
||||
[ "$PASS" = 1 ] && echo "PASS: VLAN/QinQ, фрагменты, паддинг, ICMP/GRE и IPv6 extension headers обрабатываются корректно" || echo "FAIL"
|
||||
[ "$PASS" = 1 ]
|
||||
|
|
|
|||
|
|
@ -12,6 +12,13 @@
|
|||
#define IPPROTO_TCP 6
|
||||
#define IPPROTO_UDP 17
|
||||
#define IPPROTO_FRAGMENT 44
|
||||
#define IPPROTO_HOPOPTS 0
|
||||
#define IPPROTO_ROUTING 43
|
||||
#define IPPROTO_AH 51
|
||||
#define IPPROTO_DSTOPTS 60
|
||||
/* Extension headers walked before giving up; a longer chain is treated as
|
||||
* "L4 not found" (source blacklist only), never as a free pass. */
|
||||
#define RAMPART_V6_MAX_EXT 4
|
||||
#define IP_OFFSET 0x1FFF
|
||||
#define IP_MF 0x2000
|
||||
|
||||
|
|
@ -26,6 +33,15 @@ struct rampart_vlan_hdr {
|
|||
__u16 encap_proto; // EtherType of the next header
|
||||
};
|
||||
|
||||
/**
|
||||
* First two bytes shared by every IPv6 extension header that carries a length
|
||||
* (hop-by-hop, routing, destination options, AH).
|
||||
*/
|
||||
struct rampart_ipv6_ext {
|
||||
__u8 nexthdr;
|
||||
__u8 hdrlen; // 8-byte units minus 1 (AH: 4-byte units minus 2)
|
||||
};
|
||||
|
||||
/**
|
||||
* Protocol-agnostic TCP connection states.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -253,13 +253,19 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
__u8 is_ipv6 = 0;
|
||||
__u8 native_v6 = 0;
|
||||
__u8 is_fragment = 0;
|
||||
// Protocols the filter cannot inspect (ICMP, GRE, ESP, an IPv6 chain that
|
||||
// does not end in TCP/UDP): never a free pass, the source blacklist still
|
||||
// applies below. They used to return XDP_PASS before any list was read.
|
||||
__u8 l4_unfiltered = 0;
|
||||
__u16 v6_ext_len = 0;
|
||||
void *v6_l4 = NULL;
|
||||
__u8 src6[16];
|
||||
|
||||
if (eth_proto == bpf_htons(ETH_P_IP)) {
|
||||
struct iphdr *ip = l3;
|
||||
if ((void *)(ip + 1) > data_end)
|
||||
return XDP_PASS;
|
||||
if (ip->ihl < 5) {
|
||||
if (ip->version != 4 || ip->ihl < 5) {
|
||||
inc_drop();
|
||||
return XDP_DROP;
|
||||
}
|
||||
|
|
@ -275,7 +281,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
if (ip->frag_off & bpf_htons(IP_OFFSET | IP_MF)) {
|
||||
is_fragment = 1;
|
||||
} else if (ip->protocol != IPPROTO_TCP && ip->protocol != IPPROTO_UDP) {
|
||||
return XDP_PASS;
|
||||
l4_unfiltered = 1;
|
||||
}
|
||||
} else {
|
||||
struct ipv6hdr *ip6 = l3;
|
||||
|
|
@ -286,13 +292,34 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
// when it is IPv4-mapped; the low 32 bits are used for flow keys.
|
||||
__builtin_memcpy(src6, &ip6->saddr, 16);
|
||||
is_ipv6 = 1;
|
||||
l4_proto = ip6->nexthdr;
|
||||
// Walk hop-by-hop / routing / destination-options / AH headers to the
|
||||
// real L4 header. Returning XDP_PASS on the first extension header let
|
||||
// any IPv6 flood skip the blacklist, throttle and port gate by adding
|
||||
// one (kernel stacks process these headers normally).
|
||||
__u8 nh = ip6->nexthdr;
|
||||
void *ext = (void *)(ip6 + 1);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RAMPART_V6_MAX_EXT; i++) {
|
||||
if (nh != IPPROTO_HOPOPTS && nh != IPPROTO_ROUTING &&
|
||||
nh != IPPROTO_DSTOPTS && nh != IPPROTO_AH)
|
||||
break;
|
||||
struct rampart_ipv6_ext *eh = ext;
|
||||
if ((void *)(eh + 1) > data_end)
|
||||
return XDP_PASS;
|
||||
__u16 elen = (nh == IPPROTO_AH) ? ((__u16)eh->hdrlen + 2) * 4
|
||||
: ((__u16)eh->hdrlen + 1) * 8;
|
||||
nh = eh->nexthdr;
|
||||
ext = (void *)((__u8 *)ext + elen);
|
||||
}
|
||||
l4_proto = nh;
|
||||
v6_l4 = ext;
|
||||
v6_ext_len = (__u16)((__u8 *)ext - (__u8 *)(ip6 + 1));
|
||||
|
||||
// A fragment header hides the L4 header; same policy as IPv4.
|
||||
if (ip6->nexthdr == IPPROTO_FRAGMENT) {
|
||||
if (nh == IPPROTO_FRAGMENT) {
|
||||
is_fragment = 1;
|
||||
} else if (ip6->nexthdr != IPPROTO_TCP && ip6->nexthdr != IPPROTO_UDP) {
|
||||
return XDP_PASS; // extension headers not walked
|
||||
} else if (nh != IPPROTO_TCP && nh != IPPROTO_UDP) {
|
||||
l4_unfiltered = 1;
|
||||
}
|
||||
|
||||
// Use IPv4-mapped IPv6 address for flow key (::ffff:0:0/96)
|
||||
|
|
@ -337,7 +364,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
// Fragments: the L4 ports are missing or incomplete, so the stateful and
|
||||
// throttle logic cannot run. Apply the source blacklist and pass; the
|
||||
// dedicated counter keeps this deliberate bypass observable.
|
||||
if (is_fragment) {
|
||||
if (is_fragment || l4_unfiltered) {
|
||||
__u8 banned = native_v6 ? is_blacklisted6(src6, now)
|
||||
: is_blacklisted(src_ip, now);
|
||||
if (banned) {
|
||||
|
|
@ -347,7 +374,8 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
push_event(EVENT_BAN, src_ip, 0);
|
||||
return XDP_DROP;
|
||||
}
|
||||
inc_fragment_bypass();
|
||||
if (is_fragment)
|
||||
inc_fragment_bypass();
|
||||
inc_pass();
|
||||
return XDP_PASS;
|
||||
}
|
||||
|
|
@ -357,8 +385,7 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
void *l4;
|
||||
|
||||
if (is_ipv6) {
|
||||
struct ipv6hdr *ip6 = l3;
|
||||
l4 = (void *)(ip6 + 1);
|
||||
l4 = v6_l4;
|
||||
ip_hdr_len = sizeof(struct ipv6hdr);
|
||||
} else {
|
||||
struct iphdr *ip = l3;
|
||||
|
|
@ -416,7 +443,12 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
return XDP_PASS;
|
||||
}
|
||||
}
|
||||
// TCP: forged-flag combos are L4-generic, no state needed
|
||||
// TCP: forged-flag combos are L4-generic, no state needed. The full
|
||||
// TCP header must be in bounds: the earlier gate only proved the size
|
||||
// for the protocol class it saw, and the verifier cannot correlate the
|
||||
// two once l4_proto comes from the extension-header walk.
|
||||
if ((void *)l4 + sizeof(struct tcphdr) > data_end)
|
||||
return XDP_PASS;
|
||||
if (detect_tcp_bypass((struct tcphdr *)l4)) {
|
||||
inc_drop();
|
||||
return XDP_DROP;
|
||||
|
|
@ -467,6 +499,8 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
|
||||
// TCP path.
|
||||
struct tcphdr *tcp = l4;
|
||||
if ((void *)(tcp + 1) > data_end)
|
||||
return XDP_PASS;
|
||||
|
||||
// Malicious TCP flags
|
||||
if (detect_tcp_bypass(tcp)) {
|
||||
|
|
@ -500,7 +534,13 @@ int rampart_universal_filter(struct xdp_md *ctx)
|
|||
__u32 l4_len;
|
||||
if (is_ipv6) {
|
||||
struct ipv6hdr *ip6 = l3;
|
||||
l4_len = sizeof(struct ipv6hdr) + bpf_ntohs(ip6->payload_len);
|
||||
__u16 payload_len = bpf_ntohs(ip6->payload_len);
|
||||
if (payload_len < v6_ext_len) {
|
||||
inc_drop();
|
||||
return XDP_DROP;
|
||||
}
|
||||
// payload_len counts the extension headers; l4 starts after them.
|
||||
l4_len = payload_len - v6_ext_len;
|
||||
} else {
|
||||
struct iphdr *ip = l3;
|
||||
__u16 tot_len = bpf_ntohs(ip->tot_len);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue