blob: 4eb1e8d72872c02620d13483b0e2597718457277 [file] [log] [blame]
Hungming Chen56c632c2020-09-10 15:42:58 +08001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <linux/if.h>
18#include <linux/ip.h>
19#include <linux/ipv6.h>
20#include <linux/pkt_cls.h>
21#include <linux/tcp.h>
22
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -080023// bionic kernel uapi linux/udp.h header is munged...
24#define __kernel_udphdr udphdr
25#include <linux/udp.h>
26
Maciej Żenczykowski07d30132022-04-23 12:33:32 -070027#ifdef BTF
28// BTF is incompatible with bpfloaders < v0.10, hence for S (v0.2) we must
29// ship a different file than for later versions, but we need bpfloader v0.25+
30// for obj@ver.o support
31#define BPFLOADER_MIN_VER BPFLOADER_OBJ_AT_VER_VERSION
32#else /* BTF */
Maciej Żenczykowskif7699522022-05-24 15:56:03 -070033// The resulting .o needs to load on the Android S bpfloader
34#define BPFLOADER_MIN_VER BPFLOADER_S_VERSION
Maciej Żenczykowski07d30132022-04-23 12:33:32 -070035#define BPFLOADER_MAX_VER BPFLOADER_OBJ_AT_VER_VERSION
36#endif /* BTF */
Maciej Żenczykowskia457bf72021-10-22 21:41:25 -070037
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -070038// Warning: values other than AID_ROOT don't work for map uid on BpfLoader < v0.21
39#define TETHERING_UID AID_ROOT
40
41#ifdef INPROCESS
42#define DEFAULT_BPF_MAP_SELINUX_CONTEXT "fs_bpf_net_shared"
43#define DEFAULT_BPF_PROG_SELINUX_CONTEXT "fs_bpf_net_shared"
44#define TETHERING_GID AID_SYSTEM
45#else
46#define TETHERING_GID AID_NETWORK_STACK
47#endif
48
Hungming Chen56c632c2020-09-10 15:42:58 +080049#include "bpf_helpers.h"
50#include "bpf_net_helpers.h"
Lorenzo Colittib81584d2021-02-06 00:00:58 +090051#include "bpf_tethering.h"
Hungming Chen56c632c2020-09-10 15:42:58 +080052
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -080053// From kernel:include/net/ip.h
54#define IP_DF 0x4000 // Flag: "Don't Fragment"
55
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -080056// ----- Helper functions for offsets to fields -----
57
58// They all assume simple IP packets:
59// - no VLAN ethernet tags
60// - no IPv4 options (see IPV4_HLEN/TCP4_OFFSET/UDP4_OFFSET)
61// - no IPv6 extension headers
62// - no TCP options (see TCP_HLEN)
63
64//#define ETH_HLEN sizeof(struct ethhdr)
65#define IP4_HLEN sizeof(struct iphdr)
66#define IP6_HLEN sizeof(struct ipv6hdr)
67#define TCP_HLEN sizeof(struct tcphdr)
68#define UDP_HLEN sizeof(struct udphdr)
69
70// Offsets from beginning of L4 (TCP/UDP) header
71#define TCP_OFFSET(field) offsetof(struct tcphdr, field)
72#define UDP_OFFSET(field) offsetof(struct udphdr, field)
73
74// Offsets from beginning of L3 (IPv4) header
75#define IP4_OFFSET(field) offsetof(struct iphdr, field)
76#define IP4_TCP_OFFSET(field) (IP4_HLEN + TCP_OFFSET(field))
77#define IP4_UDP_OFFSET(field) (IP4_HLEN + UDP_OFFSET(field))
78
79// Offsets from beginning of L3 (IPv6) header
80#define IP6_OFFSET(field) offsetof(struct ipv6hdr, field)
81#define IP6_TCP_OFFSET(field) (IP6_HLEN + TCP_OFFSET(field))
82#define IP6_UDP_OFFSET(field) (IP6_HLEN + UDP_OFFSET(field))
83
84// Offsets from beginning of L2 (ie. Ethernet) header (which must be present)
85#define ETH_IP4_OFFSET(field) (ETH_HLEN + IP4_OFFSET(field))
86#define ETH_IP4_TCP_OFFSET(field) (ETH_HLEN + IP4_TCP_OFFSET(field))
87#define ETH_IP4_UDP_OFFSET(field) (ETH_HLEN + IP4_UDP_OFFSET(field))
88#define ETH_IP6_OFFSET(field) (ETH_HLEN + IP6_OFFSET(field))
89#define ETH_IP6_TCP_OFFSET(field) (ETH_HLEN + IP6_TCP_OFFSET(field))
90#define ETH_IP6_UDP_OFFSET(field) (ETH_HLEN + IP6_UDP_OFFSET(field))
91
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080092// ----- Tethering Error Counters -----
93
94DEFINE_BPF_MAP_GRW(tether_error_map, ARRAY, uint32_t, uint32_t, BPF_TETHER_ERR__MAX,
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -070095 TETHERING_GID)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080096
Maciej Żenczykowski3f32a832021-03-17 19:27:23 -070097#define COUNT_AND_RETURN(counter, ret) do { \
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080098 uint32_t code = BPF_TETHER_ERR_ ## counter; \
99 uint32_t *count = bpf_tether_error_map_lookup_elem(&code); \
Maciej Żenczykowski3f32a832021-03-17 19:27:23 -0700100 if (count) __sync_fetch_and_add(count, 1); \
101 return ret; \
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800102} while(0)
103
104#define TC_DROP(counter) COUNT_AND_RETURN(counter, TC_ACT_SHOT)
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700105#define TC_PUNT(counter) COUNT_AND_RETURN(counter, TC_ACT_PIPE)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800106
107#define XDP_DROP(counter) COUNT_AND_RETURN(counter, XDP_DROP)
108#define XDP_PUNT(counter) COUNT_AND_RETURN(counter, XDP_PASS)
109
110// ----- Tethering Data Stats and Limits -----
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800111
Hungming Chen56c632c2020-09-10 15:42:58 +0800112// Tethering stats, indexed by upstream interface.
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700113DEFINE_BPF_MAP_GRW(tether_stats_map, HASH, TetherStatsKey, TetherStatsValue, 16, TETHERING_GID)
Hungming Chen56c632c2020-09-10 15:42:58 +0800114
115// Tethering data limit, indexed by upstream interface.
116// (tethering allowed when stats[iif].rxBytes + stats[iif].txBytes < limit[iif])
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700117DEFINE_BPF_MAP_GRW(tether_limit_map, HASH, TetherLimitKey, TetherLimitValue, 16, TETHERING_GID)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800118
119// ----- IPv6 Support -----
120
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800121DEFINE_BPF_MAP_GRW(tether_downstream6_map, HASH, TetherDownstream6Key, Tether6Value, 64,
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700122 TETHERING_GID)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800123
124DEFINE_BPF_MAP_GRW(tether_downstream64_map, HASH, TetherDownstream64Key, TetherDownstream64Value,
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700125 1024, TETHERING_GID)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800126
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800127DEFINE_BPF_MAP_GRW(tether_upstream6_map, HASH, TetherUpstream6Key, Tether6Value, 64,
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700128 TETHERING_GID)
Hungming Chen56c632c2020-09-10 15:42:58 +0800129
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800130static inline __always_inline int do_forward6(struct __sk_buff* skb, const bool is_ethernet,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800131 const bool downstream) {
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800132 // Must be meta-ethernet IPv6 frame
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700133 if (skb->protocol != htons(ETH_P_IPV6)) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800134
Maciej Żenczykowski18552e82021-01-24 19:59:05 -0800135 // Require ethernet dst mac address to be our unicast address.
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700136 if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
Maciej Żenczykowski18552e82021-01-24 19:59:05 -0800137
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800138 const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
139
140 // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
141 // not trigger and thus we need to manually make sure we can read packet headers via DPA.
142 // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
143 // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
Maciej Żenczykowski824fb292022-04-11 23:29:46 -0700144 try_make_writable(skb, l2_header_size + IP6_HLEN + TCP_HLEN);
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800145
146 void* data = (void*)(long)skb->data;
147 const void* data_end = (void*)(long)skb->data_end;
148 struct ethhdr* eth = is_ethernet ? data : NULL; // used iff is_ethernet
149 struct ipv6hdr* ip6 = is_ethernet ? (void*)(eth + 1) : data;
Hungming Chen56c632c2020-09-10 15:42:58 +0800150
151 // Must have (ethernet and) ipv6 header
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700152 if (data + l2_header_size + sizeof(*ip6) > data_end) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800153
154 // Ethertype - if present - must be IPv6
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700155 if (is_ethernet && (eth->h_proto != htons(ETH_P_IPV6))) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800156
157 // IP version must be 6
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800158 if (ip6->version != 6) TC_PUNT(INVALID_IP_VERSION);
Hungming Chen56c632c2020-09-10 15:42:58 +0800159
160 // Cannot decrement during forward if already zero or would be zero,
161 // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800162 if (ip6->hop_limit <= 1) TC_PUNT(LOW_TTL);
Hungming Chen56c632c2020-09-10 15:42:58 +0800163
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800164 // If hardware offload is running and programming flows based on conntrack entries,
165 // try not to interfere with it.
166 if (ip6->nexthdr == IPPROTO_TCP) {
167 struct tcphdr* tcph = (void*)(ip6 + 1);
168
169 // Make sure we can get at the tcp header
Lorenzo Colittib81584d2021-02-06 00:00:58 +0900170 if (data + l2_header_size + sizeof(*ip6) + sizeof(*tcph) > data_end)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800171 TC_PUNT(INVALID_TCP_HEADER);
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800172
173 // Do not offload TCP packets with any one of the SYN/FIN/RST flags
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800174 if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCP_CONTROL_PACKET);
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800175 }
176
Hungming Chen56c632c2020-09-10 15:42:58 +0800177 // Protect against forwarding packets sourced from ::1 or fe80::/64 or other weirdness.
178 __be32 src32 = ip6->saddr.s6_addr32[0];
179 if (src32 != htonl(0x0064ff9b) && // 64:ff9b:/32 incl. XLAT464 WKP
180 (src32 & htonl(0xe0000000)) != htonl(0x20000000)) // 2000::/3 Global Unicast
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800181 TC_PUNT(NON_GLOBAL_SRC);
Hungming Chen56c632c2020-09-10 15:42:58 +0800182
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800183 // Protect against forwarding packets destined to ::1 or fe80::/64 or other weirdness.
184 __be32 dst32 = ip6->daddr.s6_addr32[0];
185 if (dst32 != htonl(0x0064ff9b) && // 64:ff9b:/32 incl. XLAT464 WKP
186 (dst32 & htonl(0xe0000000)) != htonl(0x20000000)) // 2000::/3 Global Unicast
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800187 TC_PUNT(NON_GLOBAL_DST);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800188
189 // In the upstream direction do not forward traffic within the same /64 subnet.
190 if (!downstream && (src32 == dst32) && (ip6->saddr.s6_addr32[1] == ip6->daddr.s6_addr32[1]))
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800191 TC_PUNT(LOCAL_SRC_DST);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800192
193 TetherDownstream6Key kd = {
Hungming Chen56c632c2020-09-10 15:42:58 +0800194 .iif = skb->ifindex,
195 .neigh6 = ip6->daddr,
196 };
197
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800198 TetherUpstream6Key ku = {
199 .iif = skb->ifindex,
200 };
Maciej Żenczykowski62733f52021-04-01 21:51:41 -0700201 if (is_ethernet) __builtin_memcpy(downstream ? kd.dstMac : ku.dstMac, eth->h_dest, ETH_ALEN);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800202
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800203 Tether6Value* v = downstream ? bpf_tether_downstream6_map_lookup_elem(&kd)
204 : bpf_tether_upstream6_map_lookup_elem(&ku);
Hungming Chen56c632c2020-09-10 15:42:58 +0800205
206 // If we don't find any offload information then simply let the core stack handle it...
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700207 if (!v) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800208
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800209 uint32_t stat_and_limit_k = downstream ? skb->ifindex : v->oif;
Hungming Chen56c632c2020-09-10 15:42:58 +0800210
211 TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
212
213 // If we don't have anywhere to put stats, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800214 if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
Hungming Chen56c632c2020-09-10 15:42:58 +0800215
216 uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
217
218 // If we don't have a limit, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800219 if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
Hungming Chen56c632c2020-09-10 15:42:58 +0800220
221 // Required IPv6 minimum mtu is 1280, below that not clear what we should do, abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800222 if (v->pmtu < IPV6_MIN_MTU) TC_PUNT(BELOW_IPV6_MTU);
Hungming Chen56c632c2020-09-10 15:42:58 +0800223
224 // Approximate handling of TCP/IPv6 overhead for incoming LRO/GRO packets: default
225 // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
226 // undercount, which is still better then not accounting for this overhead at all.
227 // Note: this really shouldn't be device/path mtu at all, but rather should be
228 // derived from this particular connection's mss (ie. from gro segment size).
229 // This would require a much newer kernel with newer ebpf accessors.
230 // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
231 uint64_t packets = 1;
232 uint64_t bytes = skb->len;
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800233 if (bytes > v->pmtu) {
Hungming Chen56c632c2020-09-10 15:42:58 +0800234 const int tcp_overhead = sizeof(struct ipv6hdr) + sizeof(struct tcphdr) + 12;
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800235 const int mss = v->pmtu - tcp_overhead;
Hungming Chen56c632c2020-09-10 15:42:58 +0800236 const uint64_t payload = bytes - tcp_overhead;
237 packets = (payload + mss - 1) / mss;
238 bytes = tcp_overhead * packets + payload;
239 }
240
241 // Are we past the limit? If so, then abort...
242 // Note: will not overflow since u64 is 936 years even at 5Gbps.
243 // Do not drop here. Offload is just that, whenever we fail to handle
244 // a packet we let the core stack deal with things.
245 // (The core stack needs to handle limits correctly anyway,
246 // since we don't offload all traffic in both directions)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800247 if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
Hungming Chen56c632c2020-09-10 15:42:58 +0800248
249 if (!is_ethernet) {
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800250 // Try to inject an ethernet header, and simply return if we fail.
251 // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
252 // because this is easier and the kernel will strip extraneous ethernet header.
253 if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
254 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800255 TC_PUNT(CHANGE_HEAD_FAILED);
Hungming Chen56c632c2020-09-10 15:42:58 +0800256 }
257
258 // bpf_skb_change_head() invalidates all pointers - reload them
259 data = (void*)(long)skb->data;
260 data_end = (void*)(long)skb->data_end;
261 eth = data;
262 ip6 = (void*)(eth + 1);
263
264 // I do not believe this can ever happen, but keep the verifier happy...
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800265 if (data + sizeof(struct ethhdr) + sizeof(*ip6) > data_end) {
266 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800267 TC_DROP(TOO_SHORT);
Hungming Chen56c632c2020-09-10 15:42:58 +0800268 }
269 };
270
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800271 // At this point we always have an ethernet header - which will get stripped by the
272 // kernel during transmit through a rawip interface. ie. 'eth' pointer is valid.
273 // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
274
Hungming Chen56c632c2020-09-10 15:42:58 +0800275 // CHECKSUM_COMPLETE is a 16-bit one's complement sum,
276 // thus corrections for it need to be done in 16-byte chunks at even offsets.
277 // IPv6 nexthdr is at offset 6, while hop limit is at offset 7
278 uint8_t old_hl = ip6->hop_limit;
279 --ip6->hop_limit;
280 uint8_t new_hl = ip6->hop_limit;
281
282 // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
283 // (-ENOTSUPP) if it isn't.
284 bpf_csum_update(skb, 0xFFFF - ntohs(old_hl) + ntohs(new_hl));
285
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800286 __sync_fetch_and_add(downstream ? &stat_v->rxPackets : &stat_v->txPackets, packets);
287 __sync_fetch_and_add(downstream ? &stat_v->rxBytes : &stat_v->txBytes, bytes);
Hungming Chen56c632c2020-09-10 15:42:58 +0800288
289 // Overwrite any mac header with the new one
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800290 // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800291 *eth = v->macHeader;
Hungming Chen56c632c2020-09-10 15:42:58 +0800292
293 // Redirect to forwarded interface.
294 //
295 // Note that bpf_redirect() cannot fail unless you pass invalid flags.
296 // The redirect actually happens after the ebpf program has already terminated,
297 // and can fail for example for mtu reasons at that point in time, but there's nothing
298 // we can do about it here.
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800299 return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
Hungming Chen56c632c2020-09-10 15:42:58 +0800300}
301
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700302DEFINE_BPF_PROG("schedcls/tether_downstream6_ether", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800303 sched_cls_tether_downstream6_ether)
Maciej Żenczykowski6b7829f2021-01-18 00:03:37 -0800304(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800305 return do_forward6(skb, /* is_ethernet */ true, /* downstream */ true);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800306}
307
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700308DEFINE_BPF_PROG("schedcls/tether_upstream6_ether", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800309 sched_cls_tether_upstream6_ether)
310(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800311 return do_forward6(skb, /* is_ethernet */ true, /* downstream */ false);
Hungming Chen56c632c2020-09-10 15:42:58 +0800312}
313
314// Note: section names must be unique to prevent programs from appending to each other,
315// so instead the bpf loader will strip everything past the final $ symbol when actually
316// pinning the program into the filesystem.
317//
318// bpf_skb_change_head() is only present on 4.14+ and 2 trivial kernel patches are needed:
319// ANDROID: net: bpf: Allow TC programs to call BPF_FUNC_skb_change_head
320// ANDROID: net: bpf: permit redirect from ingress L3 to egress L2 devices at near max mtu
321// (the first of those has already been upstreamed)
322//
323// 5.4 kernel support was only added to Android Common Kernel in R,
324// and thus a 5.4 kernel always supports this.
325//
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800326// Hence, these mandatory (must load successfully) implementations for 5.4+ kernels:
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700327DEFINE_BPF_PROG_KVER("schedcls/tether_downstream6_rawip$5_4", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800328 sched_cls_tether_downstream6_rawip_5_4, KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800329(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800330 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ true);
Hungming Chen56c632c2020-09-10 15:42:58 +0800331}
332
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700333DEFINE_BPF_PROG_KVER("schedcls/tether_upstream6_rawip$5_4", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800334 sched_cls_tether_upstream6_rawip_5_4, KVER(5, 4, 0))
335(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800336 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ false);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800337}
338
339// and these identical optional (may fail to load) implementations for [4.14..5.4) patched kernels:
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800340DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream6_rawip$4_14",
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700341 TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800342 sched_cls_tether_downstream6_rawip_4_14,
343 KVER(4, 14, 0), KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800344(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800345 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ true);
Hungming Chen56c632c2020-09-10 15:42:58 +0800346}
347
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800348DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream6_rawip$4_14",
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700349 TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800350 sched_cls_tether_upstream6_rawip_4_14,
351 KVER(4, 14, 0), KVER(5, 4, 0))
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800352(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800353 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ false);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800354}
355
356// and define no-op stubs for [4.9,4.14) and unpatched [4.14,5.4) kernels.
Hungming Chen56c632c2020-09-10 15:42:58 +0800357// (if the above real 4.14+ program loaded successfully, then bpfloader will have already pinned
358// it at the same location this one would be pinned at and will thus skip loading this stub)
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700359DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream6_rawip$stub", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800360 sched_cls_tether_downstream6_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800361(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700362 return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800363}
364
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700365DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream6_rawip$stub", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800366 sched_cls_tether_upstream6_rawip_stub, KVER_NONE, KVER(5, 4, 0))
367(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700368 return TC_ACT_PIPE;
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800369}
370
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800371// ----- IPv4 Support -----
372
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700373DEFINE_BPF_MAP_GRW(tether_downstream4_map, HASH, Tether4Key, Tether4Value, 1024, TETHERING_GID)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800374
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700375DEFINE_BPF_MAP_GRW(tether_upstream4_map, HASH, Tether4Key, Tether4Value, 1024, TETHERING_GID)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800376
Maciej Żenczykowskif72c8aa2022-04-28 02:02:45 -0700377static inline __always_inline int do_forward4_bottom(struct __sk_buff* skb,
378 const int l2_header_size, void* data, const void* data_end,
379 struct ethhdr* eth, struct iphdr* ip, const bool is_ethernet,
380 const bool downstream, const bool updatetime, const bool is_tcp) {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800381 struct tcphdr* tcph = is_tcp ? (void*)(ip + 1) : NULL;
382 struct udphdr* udph = is_tcp ? NULL : (void*)(ip + 1);
383
384 if (is_tcp) {
385 // Make sure we can get at the tcp header
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800386 if (data + l2_header_size + sizeof(*ip) + sizeof(*tcph) > data_end)
387 TC_PUNT(SHORT_TCP_HEADER);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800388
389 // If hardware offload is running and programming flows based on conntrack entries, try not
390 // to interfere with it, so do not offload TCP packets with any one of the SYN/FIN/RST flags
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800391 if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCP_CONTROL_PACKET);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800392 } else { // UDP
393 // Make sure we can get at the udp header
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800394 if (data + l2_header_size + sizeof(*ip) + sizeof(*udph) > data_end)
395 TC_PUNT(SHORT_UDP_HEADER);
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800396
397 // Skip handling of CHECKSUM_COMPLETE packets with udp checksum zero due to need for
398 // additional updating of skb->csum (this could be fixed up manually with more effort).
399 //
400 // Note that the in-kernel implementation of 'int64_t bpf_csum_update(skb, u32 csum)' is:
401 // if (skb->ip_summed == CHECKSUM_COMPLETE)
402 // return (skb->csum = csum_add(skb->csum, csum));
403 // else
404 // return -ENOTSUPP;
405 //
406 // So this will punt any CHECKSUM_COMPLETE packet with a zero UDP checksum,
407 // and leave all other packets unaffected (since it just at most adds zero to skb->csum).
408 //
409 // In practice this should almost never trigger because most nics do not generate
410 // CHECKSUM_COMPLETE packets on receive - especially so for nics/drivers on a phone.
411 //
412 // Additionally since we're forwarding, in most cases the value of the skb->csum field
413 // shouldn't matter (it's not used by physical nic egress).
414 //
415 // It only matters if we're ingressing through a CHECKSUM_COMPLETE capable nic
416 // and egressing through a virtual interface looping back to the kernel itself
417 // (ie. something like veth) where the CHECKSUM_COMPLETE/skb->csum can get reused
418 // on ingress.
419 //
420 // If we were in the kernel we'd simply probably call
421 // void skb_checksum_complete_unset(struct sk_buff *skb) {
422 // if (skb->ip_summed == CHECKSUM_COMPLETE) skb->ip_summed = CHECKSUM_NONE;
423 // }
424 // here instead. Perhaps there should be a bpf helper for that?
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800425 if (!udph->check && (bpf_csum_update(skb, 0) >= 0)) TC_PUNT(UDP_CSUM_ZERO);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800426 }
427
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800428 Tether4Key k = {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800429 .iif = skb->ifindex,
430 .l4Proto = ip->protocol,
431 .src4.s_addr = ip->saddr,
432 .dst4.s_addr = ip->daddr,
433 .srcPort = is_tcp ? tcph->source : udph->source,
434 .dstPort = is_tcp ? tcph->dest : udph->dest,
435 };
Maciej Żenczykowski62733f52021-04-01 21:51:41 -0700436 if (is_ethernet) __builtin_memcpy(k.dstMac, eth->h_dest, ETH_ALEN);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800437
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800438 Tether4Value* v = downstream ? bpf_tether_downstream4_map_lookup_elem(&k)
439 : bpf_tether_upstream4_map_lookup_elem(&k);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800440
441 // If we don't find any offload information then simply let the core stack handle it...
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700442 if (!v) return TC_ACT_PIPE;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800443
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800444 uint32_t stat_and_limit_k = downstream ? skb->ifindex : v->oif;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800445
446 TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
447
448 // If we don't have anywhere to put stats, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800449 if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800450
451 uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
452
453 // If we don't have a limit, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800454 if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800455
456 // Required IPv4 minimum mtu is 68, below that not clear what we should do, abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800457 if (v->pmtu < 68) TC_PUNT(BELOW_IPV4_MTU);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800458
459 // Approximate handling of TCP/IPv4 overhead for incoming LRO/GRO packets: default
460 // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
461 // undercount, which is still better then not accounting for this overhead at all.
462 // Note: this really shouldn't be device/path mtu at all, but rather should be
463 // derived from this particular connection's mss (ie. from gro segment size).
464 // This would require a much newer kernel with newer ebpf accessors.
465 // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
466 uint64_t packets = 1;
467 uint64_t bytes = skb->len;
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800468 if (bytes > v->pmtu) {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800469 const int tcp_overhead = sizeof(struct iphdr) + sizeof(struct tcphdr) + 12;
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800470 const int mss = v->pmtu - tcp_overhead;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800471 const uint64_t payload = bytes - tcp_overhead;
472 packets = (payload + mss - 1) / mss;
473 bytes = tcp_overhead * packets + payload;
474 }
475
476 // Are we past the limit? If so, then abort...
477 // Note: will not overflow since u64 is 936 years even at 5Gbps.
478 // Do not drop here. Offload is just that, whenever we fail to handle
479 // a packet we let the core stack deal with things.
480 // (The core stack needs to handle limits correctly anyway,
481 // since we don't offload all traffic in both directions)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800482 if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800483
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800484 if (!is_ethernet) {
485 // Try to inject an ethernet header, and simply return if we fail.
486 // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
487 // because this is easier and the kernel will strip extraneous ethernet header.
488 if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
489 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800490 TC_PUNT(CHANGE_HEAD_FAILED);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800491 }
492
493 // bpf_skb_change_head() invalidates all pointers - reload them
494 data = (void*)(long)skb->data;
495 data_end = (void*)(long)skb->data_end;
496 eth = data;
497 ip = (void*)(eth + 1);
498 tcph = is_tcp ? (void*)(ip + 1) : NULL;
499 udph = is_tcp ? NULL : (void*)(ip + 1);
500
501 // I do not believe this can ever happen, but keep the verifier happy...
502 if (data + sizeof(struct ethhdr) + sizeof(*ip) + (is_tcp ? sizeof(*tcph) : sizeof(*udph)) > data_end) {
503 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800504 TC_DROP(TOO_SHORT);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800505 }
506 };
507
508 // At this point we always have an ethernet header - which will get stripped by the
509 // kernel during transmit through a rawip interface. ie. 'eth' pointer is valid.
510 // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
511
512 // Overwrite any mac header with the new one
513 // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
514 *eth = v->macHeader;
515
Maciej Żenczykowskic29af792021-07-02 01:54:04 -0700516 // Decrement the IPv4 TTL, we already know it's greater than 1.
517 // u8 TTL field is followed by u8 protocol to make a u16 for ipv4 header checksum update.
518 // Since we're keeping the ipv4 checksum valid (which means the checksum of the entire
519 // ipv4 header remains 0), the overall checksum of the entire packet does not change.
520 const int sz2 = sizeof(__be16);
521 const __be16 old_ttl_proto = *(__be16 *)&ip->ttl;
522 const __be16 new_ttl_proto = old_ttl_proto - htons(0x0100);
523 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_ttl_proto, new_ttl_proto, sz2);
524 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(ttl), &new_ttl_proto, sz2, 0);
525
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800526 const int l4_offs_csum = is_tcp ? ETH_IP4_TCP_OFFSET(check) : ETH_IP4_UDP_OFFSET(check);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800527 const int sz4 = sizeof(__be32);
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800528 // UDP 0 is special and stored as FFFF (this flag also causes a csum of 0 to be unmodified)
529 const int l4_flags = is_tcp ? 0 : BPF_F_MARK_MANGLED_0;
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800530 const __be32 old_daddr = k.dst4.s_addr;
531 const __be32 old_saddr = k.src4.s_addr;
532 const __be32 new_daddr = v->dst46.s6_addr32[3];
533 const __be32 new_saddr = v->src46.s6_addr32[3];
534
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800535 bpf_l4_csum_replace(skb, l4_offs_csum, old_daddr, new_daddr, sz4 | BPF_F_PSEUDO_HDR | l4_flags);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800536 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_daddr, new_daddr, sz4);
537 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(daddr), &new_daddr, sz4, 0);
538
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800539 bpf_l4_csum_replace(skb, l4_offs_csum, old_saddr, new_saddr, sz4 | BPF_F_PSEUDO_HDR | l4_flags);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800540 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_saddr, new_saddr, sz4);
541 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(saddr), &new_saddr, sz4, 0);
542
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800543 // The offsets for TCP and UDP ports: source (u16 @ L4 offset 0) & dest (u16 @ L4 offset 2) are
544 // actually the same, so the compiler should just optimize them both down to a constant.
545 bpf_l4_csum_replace(skb, l4_offs_csum, k.srcPort, v->srcPort, sz2 | l4_flags);
546 bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(source) : ETH_IP4_UDP_OFFSET(source),
547 &v->srcPort, sz2, 0);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800548
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800549 bpf_l4_csum_replace(skb, l4_offs_csum, k.dstPort, v->dstPort, sz2 | l4_flags);
550 bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(dest) : ETH_IP4_UDP_OFFSET(dest),
551 &v->dstPort, sz2, 0);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800552
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800553 // This requires the bpf_ktime_get_boot_ns() helper which was added in 5.8,
554 // and backported to all Android Common Kernel 4.14+ trees.
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800555 if (updatetime) v->last_used = bpf_ktime_get_boot_ns();
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800556
557 __sync_fetch_and_add(downstream ? &stat_v->rxPackets : &stat_v->txPackets, packets);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800558 __sync_fetch_and_add(downstream ? &stat_v->rxBytes : &stat_v->txBytes, bytes);
559
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800560 // Redirect to forwarded interface.
561 //
562 // Note that bpf_redirect() cannot fail unless you pass invalid flags.
563 // The redirect actually happens after the ebpf program has already terminated,
564 // and can fail for example for mtu reasons at that point in time, but there's nothing
565 // we can do about it here.
566 return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800567}
568
Maciej Żenczykowskif72c8aa2022-04-28 02:02:45 -0700569static inline __always_inline int do_forward4(struct __sk_buff* skb, const bool is_ethernet,
570 const bool downstream, const bool updatetime) {
571 // Require ethernet dst mac address to be our unicast address.
572 if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
573
574 // Must be meta-ethernet IPv4 frame
575 if (skb->protocol != htons(ETH_P_IP)) return TC_ACT_PIPE;
576
577 const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
578
579 // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
580 // not trigger and thus we need to manually make sure we can read packet headers via DPA.
581 // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
582 // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
583 try_make_writable(skb, l2_header_size + IP4_HLEN + TCP_HLEN);
584
585 void* data = (void*)(long)skb->data;
586 const void* data_end = (void*)(long)skb->data_end;
587 struct ethhdr* eth = is_ethernet ? data : NULL; // used iff is_ethernet
588 struct iphdr* ip = is_ethernet ? (void*)(eth + 1) : data;
589
590 // Must have (ethernet and) ipv4 header
591 if (data + l2_header_size + sizeof(*ip) > data_end) return TC_ACT_PIPE;
592
593 // Ethertype - if present - must be IPv4
594 if (is_ethernet && (eth->h_proto != htons(ETH_P_IP))) return TC_ACT_PIPE;
595
596 // IP version must be 4
597 if (ip->version != 4) TC_PUNT(INVALID_IP_VERSION);
598
599 // We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header
600 if (ip->ihl != 5) TC_PUNT(HAS_IP_OPTIONS);
601
602 // Calculate the IPv4 one's complement checksum of the IPv4 header.
603 __wsum sum4 = 0;
604 for (int i = 0; i < sizeof(*ip) / sizeof(__u16); ++i) {
605 sum4 += ((__u16*)ip)[i];
606 }
607 // Note that sum4 is guaranteed to be non-zero by virtue of ip4->version == 4
608 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE
609 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16
610 // for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF
611 if (sum4 != 0xFFFF) TC_PUNT(CHECKSUM);
612
613 // Minimum IPv4 total length is the size of the header
614 if (ntohs(ip->tot_len) < sizeof(*ip)) TC_PUNT(TRUNCATED_IPV4);
615
616 // We are incapable of dealing with IPv4 fragments
617 if (ip->frag_off & ~htons(IP_DF)) TC_PUNT(IS_IP_FRAG);
618
619 // Cannot decrement during forward if already zero or would be zero,
620 // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
621 if (ip->ttl <= 1) TC_PUNT(LOW_TTL);
622
623 // If we cannot update the 'last_used' field due to lack of bpf_ktime_get_boot_ns() helper,
624 // then it is not safe to offload UDP due to the small conntrack timeouts, as such,
625 // in such a situation we can only support TCP. This also has the added nice benefit of
626 // using a separate error counter, and thus making it obvious which version of the program
627 // is loaded.
628 if (!updatetime && ip->protocol != IPPROTO_TCP) TC_PUNT(NON_TCP);
629
630 // We do not support offloading anything besides IPv4 TCP and UDP, due to need for NAT,
631 // but no need to check this if !updatetime due to check immediately above.
632 if (updatetime && (ip->protocol != IPPROTO_TCP) && (ip->protocol != IPPROTO_UDP))
633 TC_PUNT(NON_TCP_UDP);
634
635 // We want to make sure that the compiler will, in the !updatetime case, entirely optimize
636 // out all the non-tcp logic. Also note that at this point is_udp === !is_tcp.
637 const bool is_tcp = !updatetime || (ip->protocol == IPPROTO_TCP);
638
639 // This is a bit of a hack to make things easier on the bpf verifier.
640 // (In particular I believe the Linux 4.14 kernel's verifier can get confused later on about
641 // what offsets into the packet are valid and can spuriously reject the program, this is
642 // because it fails to realize that is_tcp && !is_tcp is impossible)
643 //
644 // For both TCP & UDP we'll need to read and modify the src/dst ports, which so happen to
645 // always be in the first 4 bytes of the L4 header. Additionally for UDP we'll need access
646 // to the checksum field which is in bytes 7 and 8. While for TCP we'll need to read the
647 // TCP flags (at offset 13) and access to the checksum field (2 bytes at offset 16).
648 // As such we *always* need access to at least 8 bytes.
649 if (data + l2_header_size + sizeof(*ip) + 8 > data_end) TC_PUNT(SHORT_L4_HEADER);
650
651 // We're forcing the compiler to emit two copies of the following code, optimized
652 // separately for is_tcp being true or false. This simplifies the resulting bpf
653 // byte code sufficiently that the 4.14 bpf verifier is able to keep track of things.
654 // Without this (updatetime == true) case would fail to bpf verify on 4.14 even
655 // if the underlying requisite kernel support (bpf_ktime_get_boot_ns) was backported.
656 if (is_tcp) {
657 return do_forward4_bottom(skb, l2_header_size, data, data_end, eth, ip,
658 is_ethernet, downstream, updatetime, /* is_tcp */ true);
659 } else {
660 return do_forward4_bottom(skb, l2_header_size, data, data_end, eth, ip,
661 is_ethernet, downstream, updatetime, /* is_tcp */ false);
662 }
663}
664
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800665// Full featured (required) implementations for 5.8+ kernels (these are S+ by definition)
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800666
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700667DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_rawip$5_8", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskib0ac41f2021-02-14 21:34:03 -0800668 sched_cls_tether_downstream4_rawip_5_8, KVER(5, 8, 0))
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800669(struct __sk_buff* skb) {
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800670 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ true);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800671}
672
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700673DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_rawip$5_8", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskib0ac41f2021-02-14 21:34:03 -0800674 sched_cls_tether_upstream4_rawip_5_8, KVER(5, 8, 0))
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800675(struct __sk_buff* skb) {
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800676 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ true);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800677}
678
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700679DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_ether$5_8", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800680 sched_cls_tether_downstream4_ether_5_8, KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800681(struct __sk_buff* skb) {
682 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ true);
683}
684
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700685DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_ether$5_8", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800686 sched_cls_tether_upstream4_ether_5_8, KVER(5, 8, 0))
687(struct __sk_buff* skb) {
688 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ true);
689}
690
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800691// Full featured (optional) implementations for 4.14-S, 4.19-S & 5.4-S kernels
692// (optional, because we need to be able to fallback for 4.14/4.19/5.4 pre-S kernels)
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800693
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800694DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$opt",
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700695 TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800696 sched_cls_tether_downstream4_rawip_opt,
697 KVER(4, 14, 0), KVER(5, 8, 0))
698(struct __sk_buff* skb) {
699 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ true);
700}
701
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800702DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$opt",
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700703 TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800704 sched_cls_tether_upstream4_rawip_opt,
705 KVER(4, 14, 0), KVER(5, 8, 0))
706(struct __sk_buff* skb) {
707 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ true);
708}
709
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800710DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$opt",
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700711 TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800712 sched_cls_tether_downstream4_ether_opt,
713 KVER(4, 14, 0), KVER(5, 8, 0))
714(struct __sk_buff* skb) {
715 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ true);
716}
717
718DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$opt",
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700719 TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800720 sched_cls_tether_upstream4_ether_opt,
721 KVER(4, 14, 0), KVER(5, 8, 0))
722(struct __sk_buff* skb) {
723 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ true);
724}
725
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800726// Partial (TCP-only: will not update 'last_used' field) implementations for 4.14+ kernels.
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800727// These will be loaded only if the above optional ones failed (loading of *these* must succeed
728// for 5.4+, since that is always an R patched kernel).
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800729//
730// [Note: as a result TCP connections will not have their conntrack timeout refreshed, however,
731// since /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established defaults to 432000 (seconds),
732// this in practice means they'll break only after 5 days. This seems an acceptable trade-off.
733//
734// Additionally kernel/tests change "net-test: add bpf_ktime_get_ns / bpf_ktime_get_boot_ns tests"
735// which enforces and documents the required kernel cherrypicks will make it pretty unlikely that
736// many devices upgrading to S will end up relying on these fallback programs.
737
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800738// RAWIP: Required for 5.4-R kernels -- which always support bpf_skb_change_head().
739
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700740DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$5_4", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800741 sched_cls_tether_downstream4_rawip_5_4, KVER(5, 4, 0), KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800742(struct __sk_buff* skb) {
743 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ false);
744}
745
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700746DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$5_4", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800747 sched_cls_tether_upstream4_rawip_5_4, KVER(5, 4, 0), KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800748(struct __sk_buff* skb) {
749 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ false);
750}
751
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800752// RAWIP: Optional for 4.14/4.19 (R) kernels -- which support bpf_skb_change_head().
753// [Note: fallback for 4.14/4.19 (P/Q) kernels is below in stub section]
754
755DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$4_14",
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700756 TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800757 sched_cls_tether_downstream4_rawip_4_14,
758 KVER(4, 14, 0), KVER(5, 4, 0))
759(struct __sk_buff* skb) {
760 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ false);
761}
762
763DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$4_14",
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700764 TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800765 sched_cls_tether_upstream4_rawip_4_14,
766 KVER(4, 14, 0), KVER(5, 4, 0))
767(struct __sk_buff* skb) {
768 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ false);
769}
770
771// ETHER: Required for 4.14-Q/R, 4.19-Q/R & 5.4-R kernels.
772
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700773DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$4_14", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800774 sched_cls_tether_downstream4_ether_4_14, KVER(4, 14, 0), KVER(5, 8, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800775(struct __sk_buff* skb) {
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800776 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ false);
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800777}
778
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700779DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$4_14", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800780 sched_cls_tether_upstream4_ether_4_14, KVER(4, 14, 0), KVER(5, 8, 0))
781(struct __sk_buff* skb) {
782 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ false);
783}
784
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800785// Placeholder (no-op) implementations for older Q kernels
786
787// RAWIP: 4.9-P/Q, 4.14-P/Q & 4.19-Q kernels -- without bpf_skb_change_head() for tc programs
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800788
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700789DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$stub", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800790 sched_cls_tether_downstream4_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800791(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700792 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800793}
794
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700795DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$stub", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800796 sched_cls_tether_upstream4_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800797(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700798 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800799}
800
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800801// ETHER: 4.9-P/Q kernel
802
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700803DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$stub", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800804 sched_cls_tether_downstream4_ether_stub, KVER_NONE, KVER(4, 14, 0))
805(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700806 return TC_ACT_PIPE;
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800807}
808
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700809DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$stub", TETHERING_UID, TETHERING_GID,
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800810 sched_cls_tether_upstream4_ether_stub, KVER_NONE, KVER(4, 14, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800811(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700812 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800813}
814
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800815// ----- XDP Support -----
816
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700817DEFINE_BPF_MAP_GRW(tether_dev_map, DEVMAP_HASH, uint32_t, uint32_t, 64, TETHERING_GID)
Maciej Żenczykowskidb2cff52021-03-01 21:22:49 -0800818
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800819static inline __always_inline int do_xdp_forward6(struct xdp_md *ctx, const bool is_ethernet,
820 const bool downstream) {
821 return XDP_PASS;
822}
823
824static inline __always_inline int do_xdp_forward4(struct xdp_md *ctx, const bool is_ethernet,
825 const bool downstream) {
826 return XDP_PASS;
827}
828
829static inline __always_inline int do_xdp_forward_ether(struct xdp_md *ctx, const bool downstream) {
830 const void* data = (void*)(long)ctx->data;
831 const void* data_end = (void*)(long)ctx->data_end;
832 const struct ethhdr* eth = data;
833
834 // Make sure we actually have an ethernet header
835 if ((void*)(eth + 1) > data_end) return XDP_PASS;
836
837 if (eth->h_proto == htons(ETH_P_IPV6))
838 return do_xdp_forward6(ctx, /* is_ethernet */ true, downstream);
839 if (eth->h_proto == htons(ETH_P_IP))
840 return do_xdp_forward4(ctx, /* is_ethernet */ true, downstream);
841
842 // Anything else we don't know how to handle...
843 return XDP_PASS;
844}
845
846static inline __always_inline int do_xdp_forward_rawip(struct xdp_md *ctx, const bool downstream) {
847 const void* data = (void*)(long)ctx->data;
848 const void* data_end = (void*)(long)ctx->data_end;
849
850 // The top nibble of both IPv4 and IPv6 headers is the IP version.
851 if (data_end - data < 1) return XDP_PASS;
852 const uint8_t v = (*(uint8_t*)data) >> 4;
853
854 if (v == 6) return do_xdp_forward6(ctx, /* is_ethernet */ false, downstream);
855 if (v == 4) return do_xdp_forward4(ctx, /* is_ethernet */ false, downstream);
856
857 // Anything else we don't know how to handle...
858 return XDP_PASS;
859}
860
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800861#define DEFINE_XDP_PROG(str, func) \
Maciej Żenczykowskiccce4a32022-07-17 01:28:38 -0700862 DEFINE_BPF_PROG_KVER(str, TETHERING_UID, TETHERING_GID, func, KVER(5, 9, 0))(struct xdp_md *ctx)
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800863
864DEFINE_XDP_PROG("xdp/tether_downstream_ether",
865 xdp_tether_downstream_ether) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800866 return do_xdp_forward_ether(ctx, /* downstream */ true);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800867}
868
869DEFINE_XDP_PROG("xdp/tether_downstream_rawip",
870 xdp_tether_downstream_rawip) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800871 return do_xdp_forward_rawip(ctx, /* downstream */ true);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800872}
873
874DEFINE_XDP_PROG("xdp/tether_upstream_ether",
875 xdp_tether_upstream_ether) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800876 return do_xdp_forward_ether(ctx, /* downstream */ false);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800877}
878
879DEFINE_XDP_PROG("xdp/tether_upstream_rawip",
880 xdp_tether_upstream_rawip) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800881 return do_xdp_forward_rawip(ctx, /* downstream */ false);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800882}
883
Hungming Chen56c632c2020-09-10 15:42:58 +0800884LICENSE("Apache 2.0");
Maciej Żenczykowski607d6dd2021-02-25 19:09:47 -0800885CRITICAL("tethering");