CubeSandbox icon indicating copy to clipboard operation
CubeSandbox copied to clipboard

CubeVS: Skip network policy check for established connections

Open chenhengqi opened this issue 4 months ago • 3 comments

This PR fixes connections broken by DNS TTL expiry.

CubeEgress sessions

DNS response TTL is recorded in allow_out_v2 map, and the userspace DNS reaper periodically removes stale entries. CubeVS relies on these records to enforce egress network policies.

If a DNS record expires (removed by the reaper) while a connection is still open, subsequent packets will be rejected by the policy check, even though the TCP session already exists. This causes active connections to break when the DNS TTL elapses.

Fix this by checking whether a TCP socket already exists for the connection (bpf_skc_lookup_tcp) before enforcing the egress network policy. If a socket is found, the traffic is from an already-established session, so the policy check is skipped and the packet is redirected directly to CubeEgress.

NAT sessions

Move the egress network policy gate off the sandbox egress fast path and into the shared create_nat_session() helper so TCP, UDP and ICMP all funnel through a single enforcement point at session creation time.

Previously, from_cube() called check_net_policy() on every packet before NAT. That call site is now removed; the check runs once per new NAT session and its result is cached in the session record's lifetime. Packets that hit an existing session are not re-evaluated so that an established connection survived even when DNS record expired.

To preserve the TCP "RST on policy deny" behavior, create_nat_session() receives the skb and communicates the deny reason back to callers via skb->cb[0]. do_tcp_nat() translates NAT_CB_DENIED_BY_POLICY into TCP_NAT_RESET, which the caller already dispatches to tcp_reply_reset(). UDP and ICMP drops stay silent, matching their previous behavior.

should_redirect_to_l7_proxy() no longer takes a plumbed policy_value. It performs its own allow_out_v2 lookup — cheap since the branch only fires for TCP dports 80/443.

chenhengqi avatar Jul 06 '26 11:07 chenhengqi

PR #780 Review: CubeVS — Skip policy check for established CubeEgress sessions

Overview: Adds BPF-level TCP socket lookup (bpf_skc_lookup_tcp) to bypass egress policy enforcement for established TCP connections on ports 80/443 whose DNS-learned policy entries may have expired.

Files changed: CubeNet/src/cubevs.h (+3), CubeNet/src/mvmtap.bpf.c (+16)


1. Missing L2 MAC rewrite may produce malformed packets on the bypass path

File: CubeNet/src/mvmtap.bpf.c, line 1029

The bypass path redirects to cubegw0_ifindex with BPF_F_INGRESS without updating the Ethernet MAC addresses. Every other code path that redirects elsewhere (e.g., snat_tcp at line 1011 which calls set_mac_pair via the NAT helper) properly rewrites L2 before redirect. The packet arrives at cubegw0 with the original VM/TAP MAC addresses — verify whether cubegw0 requires a specific MAC pair for ingress traffic or handles this internally.


2. bpf_skc_lookup_tcp matches sockets in any TCP state (including TIME_WAIT)

File: CubeNet/src/mvmtap.bpf.c, line 1026

bpf_skc_lookup_tcp returns sockets in any TCP state — ESTABLISHED, TIME_WAIT, LISTEN, SYN_SENT, etc. After a connection closes, the socket persists in TIME_WAIT for 2×MSL (~60s). During this window, traffic matching the same 5-tuple bypasses egress policy without re-evaluation.

The kernel provides bpf_sk_lookup_tcp which returns only full sockets (excluding timewait_sock and request_sock entries). If the intent is to match only fully established connections, bpf_sk_lookup_tcp would be the tighter fit:

sk = bpf_sk_lookup_tcp(skb, &tuple, sizeof(tuple.ipv4), BPF_F_CURRENT_NETNS, 0);

3. Redundant __pull_headers call on ALL TCP traffic

File: CubeNet/src/mvmtap.bpf.c, line 1020

The new block calls __pull_headers(skb, &l2, &l3, &l4) as part of its guard condition. Because proto == IPPROTO_TCP is true and short-circuit && evaluation means __pull_headers runs before the port check, this executes for every TCP packet (not just ports 80/443). For TCP traffic to other ports, this is a fully redundant operation — headers were already pulled at line 1001-1002 and no skb-modifying helper was called in between (bpf_map_lookup_elem at line 1006 is read-only).

Consider merging the port-80/443 check into the existing TCP block at lines 1000-1017 to reuse the already-valid l4 pointer and eliminate the duplicate __pull_headers:

if (proto == IPPROTO_TCP) {
    if (!__pull_headers(skb, &l2, &l3, &l4))
        return TC_ACT_SHOT;

    mvm_port.ifindex = ifindex;
    mvm_port.listen_port = l4->source;
    host_port = bpf_map_lookup_elem(&local_port_mapping, &mvm_port);
    if (host_port) {
        if (l4->syn && !l4->ack)
            return TC_ACT_SHOT;
        err = snat_tcp(skb, ifindex, l2, l3, l4, l4->source, *host_port);
        if (err)
            return TC_ACT_SHOT;
        return bpf_redirect(nodenic_ifindex, 0);
    }

    // Reuse already-pulled l4 for the socket-lookup fast-path
    if (l4->dest == bpf_htons(80) || l4->dest == bpf_htons(443)) {
        tuple.ipv4.saddr = daddr;
        tuple.ipv4.daddr = mvm_meta->ip;
        tuple.ipv4.sport = l4->dest;
        tuple.ipv4.dport = l4->source;
        sk = bpf_skc_lookup_tcp(skb, &tuple, sizeof(tuple.ipv4), BPF_F_CURRENT_NETNS, 0);
        if (sk) {
            bpf_sk_release(sk);
            return bpf_redirect(cubegw0_ifindex, BPF_F_INGRESS);
        }
    }
}

4. Missing explanatory comments

The new socket-lookup block at lines 1019-1031 has no comment explaining why policy is bypassed. Every other non-trivial block in from_cube has a brief comment (line 972: "Filter traffic to cubegw0"; line 1033: "Enforce egress network policy before NAT").

Similarly, the BPF_F_CURRENT_NETNS macro at cubevs.h:74 lacks the kernel-source citation that accompanies other kernel-UAPI redefines in that file.


5. No test coverage for the new code path

The from_cube() function (core of this change) has zero test coverage — no unit tests, BPF selftests, or integration tests. Existing Go tests (netpolicy_test.go, miscs_test.go) test only userspace struct layout and data validation.

Key test scenarios to cover:

  • Long-lived TCP connection to port 80/443 whose DNS-learned policy entry expires mid-connection — packets should still pass via the bypass
  • TCP SYN to an expired DNS-learned destination — should be blocked (no socket yet)
  • Non-80/443 TCP (e.g., port 8080) to an expired DNS destination — should still hit policy check
  • Non-TCP traffic (UDP, ICMP) to an expired DNS destination — should still hit policy check
  • Socket lookup miss — when bpf_skc_lookup_tcp returns NULL, fall through to policy check

Minor observations

  • No #ifndef guard on BPF_F_CURRENT_NETNS (cubevs.h:74): Kernel UAPI started providing this in 5.15. An #ifndef guard prevents redefinition errors with newer kernel headers. (Consistent with existing unguarded redefines in this file.)
  • Policy updates ineffective on established connections: The socket lookup permanently bypasses policy for the lifetime of the socket. If an operator adds a deny_out rule for a destination mid-connection, existing TCP flows continue unhindered until the socket closes. This is a design tradeoff worth documenting.

What was done well

  • Tuple correctly reversed (source↔destination) to match the server-side socket
  • daddr captured before snat() at line 968, preserving pre-NAT destination for lookup
  • Socket reference properly released with bpf_sk_release (no leak)
  • Block placement after local-port-mapping and before policy enforcement preserves correct processing priority
  • Follows existing __pull_headers and BPF coding conventions throughout

cubesandboxbot[bot] avatar Jul 06 '26 11:07 cubesandboxbot[bot]

The performance impact of querying the hash table for each package is significant, and in the future, if we need to support update_net_rules to completely block connections to certain domains, how should we do it?

kinwin-ustc avatar Jul 06 '26 23:07 kinwin-ustc

The performance impact of querying the hash table for each package is significant, and in the future, if we need to

I also hate that we have to do it. Currently this is limit to TCP 80/443 to mitigate the performance degrade.

support update_net_rules to completely block connections to certain domains, how should we do it?

As far as I can tell:

  • We will need to record IP <=> domain mapping in BPF side
  • Mark sessions as blocked or delete sessions on update_network() in userspace

chenhengqi avatar Jul 07 '26 09:07 chenhengqi