blob: c71e8812324e29ba4bab0ff311a05fe6daa4028c [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
Hungming Chen56c632c2020-09-10 15:42:58 +080038#include "bpf_helpers.h"
39#include "bpf_net_helpers.h"
Lorenzo Colittib81584d2021-02-06 00:00:58 +090040#include "bpf_tethering.h"
Hungming Chen56c632c2020-09-10 15:42:58 +080041
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -080042// From kernel:include/net/ip.h
43#define IP_DF 0x4000 // Flag: "Don't Fragment"
44
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -080045// ----- Helper functions for offsets to fields -----
46
47// They all assume simple IP packets:
48// - no VLAN ethernet tags
49// - no IPv4 options (see IPV4_HLEN/TCP4_OFFSET/UDP4_OFFSET)
50// - no IPv6 extension headers
51// - no TCP options (see TCP_HLEN)
52
53//#define ETH_HLEN sizeof(struct ethhdr)
54#define IP4_HLEN sizeof(struct iphdr)
55#define IP6_HLEN sizeof(struct ipv6hdr)
56#define TCP_HLEN sizeof(struct tcphdr)
57#define UDP_HLEN sizeof(struct udphdr)
58
59// Offsets from beginning of L4 (TCP/UDP) header
60#define TCP_OFFSET(field) offsetof(struct tcphdr, field)
61#define UDP_OFFSET(field) offsetof(struct udphdr, field)
62
63// Offsets from beginning of L3 (IPv4) header
64#define IP4_OFFSET(field) offsetof(struct iphdr, field)
65#define IP4_TCP_OFFSET(field) (IP4_HLEN + TCP_OFFSET(field))
66#define IP4_UDP_OFFSET(field) (IP4_HLEN + UDP_OFFSET(field))
67
68// Offsets from beginning of L3 (IPv6) header
69#define IP6_OFFSET(field) offsetof(struct ipv6hdr, field)
70#define IP6_TCP_OFFSET(field) (IP6_HLEN + TCP_OFFSET(field))
71#define IP6_UDP_OFFSET(field) (IP6_HLEN + UDP_OFFSET(field))
72
73// Offsets from beginning of L2 (ie. Ethernet) header (which must be present)
74#define ETH_IP4_OFFSET(field) (ETH_HLEN + IP4_OFFSET(field))
75#define ETH_IP4_TCP_OFFSET(field) (ETH_HLEN + IP4_TCP_OFFSET(field))
76#define ETH_IP4_UDP_OFFSET(field) (ETH_HLEN + IP4_UDP_OFFSET(field))
77#define ETH_IP6_OFFSET(field) (ETH_HLEN + IP6_OFFSET(field))
78#define ETH_IP6_TCP_OFFSET(field) (ETH_HLEN + IP6_TCP_OFFSET(field))
79#define ETH_IP6_UDP_OFFSET(field) (ETH_HLEN + IP6_UDP_OFFSET(field))
80
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080081// ----- Tethering Error Counters -----
82
83DEFINE_BPF_MAP_GRW(tether_error_map, ARRAY, uint32_t, uint32_t, BPF_TETHER_ERR__MAX,
84 AID_NETWORK_STACK)
85
Maciej Żenczykowski3f32a832021-03-17 19:27:23 -070086#define COUNT_AND_RETURN(counter, ret) do { \
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080087 uint32_t code = BPF_TETHER_ERR_ ## counter; \
88 uint32_t *count = bpf_tether_error_map_lookup_elem(&code); \
Maciej Żenczykowski3f32a832021-03-17 19:27:23 -070089 if (count) __sync_fetch_and_add(count, 1); \
90 return ret; \
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080091} while(0)
92
93#define TC_DROP(counter) COUNT_AND_RETURN(counter, TC_ACT_SHOT)
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -070094#define TC_PUNT(counter) COUNT_AND_RETURN(counter, TC_ACT_PIPE)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080095
96#define XDP_DROP(counter) COUNT_AND_RETURN(counter, XDP_DROP)
97#define XDP_PUNT(counter) COUNT_AND_RETURN(counter, XDP_PASS)
98
99// ----- Tethering Data Stats and Limits -----
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800100
Hungming Chen56c632c2020-09-10 15:42:58 +0800101// Tethering stats, indexed by upstream interface.
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800102DEFINE_BPF_MAP_GRW(tether_stats_map, HASH, TetherStatsKey, TetherStatsValue, 16, AID_NETWORK_STACK)
Hungming Chen56c632c2020-09-10 15:42:58 +0800103
104// Tethering data limit, indexed by upstream interface.
105// (tethering allowed when stats[iif].rxBytes + stats[iif].txBytes < limit[iif])
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800106DEFINE_BPF_MAP_GRW(tether_limit_map, HASH, TetherLimitKey, TetherLimitValue, 16, AID_NETWORK_STACK)
107
108// ----- IPv6 Support -----
109
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800110DEFINE_BPF_MAP_GRW(tether_downstream6_map, HASH, TetherDownstream6Key, Tether6Value, 64,
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800111 AID_NETWORK_STACK)
112
113DEFINE_BPF_MAP_GRW(tether_downstream64_map, HASH, TetherDownstream64Key, TetherDownstream64Value,
Maciej Żenczykowski8549af92021-02-25 19:11:34 -0800114 1024, AID_NETWORK_STACK)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800115
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800116DEFINE_BPF_MAP_GRW(tether_upstream6_map, HASH, TetherUpstream6Key, Tether6Value, 64,
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800117 AID_NETWORK_STACK)
Hungming Chen56c632c2020-09-10 15:42:58 +0800118
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800119static inline __always_inline int do_forward6(struct __sk_buff* skb, const bool is_ethernet,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800120 const bool downstream) {
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800121 // Must be meta-ethernet IPv6 frame
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700122 if (skb->protocol != htons(ETH_P_IPV6)) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800123
Maciej Żenczykowski18552e82021-01-24 19:59:05 -0800124 // Require ethernet dst mac address to be our unicast address.
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700125 if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
Maciej Żenczykowski18552e82021-01-24 19:59:05 -0800126
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800127 const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
128
129 // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
130 // not trigger and thus we need to manually make sure we can read packet headers via DPA.
131 // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
132 // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
Maciej Żenczykowski824fb292022-04-11 23:29:46 -0700133 try_make_writable(skb, l2_header_size + IP6_HLEN + TCP_HLEN);
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800134
135 void* data = (void*)(long)skb->data;
136 const void* data_end = (void*)(long)skb->data_end;
137 struct ethhdr* eth = is_ethernet ? data : NULL; // used iff is_ethernet
138 struct ipv6hdr* ip6 = is_ethernet ? (void*)(eth + 1) : data;
Hungming Chen56c632c2020-09-10 15:42:58 +0800139
140 // Must have (ethernet and) ipv6 header
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700141 if (data + l2_header_size + sizeof(*ip6) > data_end) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800142
143 // Ethertype - if present - must be IPv6
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700144 if (is_ethernet && (eth->h_proto != htons(ETH_P_IPV6))) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800145
146 // IP version must be 6
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800147 if (ip6->version != 6) TC_PUNT(INVALID_IP_VERSION);
Hungming Chen56c632c2020-09-10 15:42:58 +0800148
149 // Cannot decrement during forward if already zero or would be zero,
150 // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800151 if (ip6->hop_limit <= 1) TC_PUNT(LOW_TTL);
Hungming Chen56c632c2020-09-10 15:42:58 +0800152
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800153 // If hardware offload is running and programming flows based on conntrack entries,
154 // try not to interfere with it.
155 if (ip6->nexthdr == IPPROTO_TCP) {
156 struct tcphdr* tcph = (void*)(ip6 + 1);
157
158 // Make sure we can get at the tcp header
Lorenzo Colittib81584d2021-02-06 00:00:58 +0900159 if (data + l2_header_size + sizeof(*ip6) + sizeof(*tcph) > data_end)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800160 TC_PUNT(INVALID_TCP_HEADER);
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800161
162 // Do not offload TCP packets with any one of the SYN/FIN/RST flags
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800163 if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCP_CONTROL_PACKET);
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800164 }
165
Hungming Chen56c632c2020-09-10 15:42:58 +0800166 // Protect against forwarding packets sourced from ::1 or fe80::/64 or other weirdness.
167 __be32 src32 = ip6->saddr.s6_addr32[0];
168 if (src32 != htonl(0x0064ff9b) && // 64:ff9b:/32 incl. XLAT464 WKP
169 (src32 & htonl(0xe0000000)) != htonl(0x20000000)) // 2000::/3 Global Unicast
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800170 TC_PUNT(NON_GLOBAL_SRC);
Hungming Chen56c632c2020-09-10 15:42:58 +0800171
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800172 // Protect against forwarding packets destined to ::1 or fe80::/64 or other weirdness.
173 __be32 dst32 = ip6->daddr.s6_addr32[0];
174 if (dst32 != htonl(0x0064ff9b) && // 64:ff9b:/32 incl. XLAT464 WKP
175 (dst32 & htonl(0xe0000000)) != htonl(0x20000000)) // 2000::/3 Global Unicast
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800176 TC_PUNT(NON_GLOBAL_DST);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800177
178 // In the upstream direction do not forward traffic within the same /64 subnet.
179 if (!downstream && (src32 == dst32) && (ip6->saddr.s6_addr32[1] == ip6->daddr.s6_addr32[1]))
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800180 TC_PUNT(LOCAL_SRC_DST);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800181
182 TetherDownstream6Key kd = {
Hungming Chen56c632c2020-09-10 15:42:58 +0800183 .iif = skb->ifindex,
184 .neigh6 = ip6->daddr,
185 };
186
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800187 TetherUpstream6Key ku = {
188 .iif = skb->ifindex,
189 };
Maciej Żenczykowski62733f52021-04-01 21:51:41 -0700190 if (is_ethernet) __builtin_memcpy(downstream ? kd.dstMac : ku.dstMac, eth->h_dest, ETH_ALEN);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800191
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800192 Tether6Value* v = downstream ? bpf_tether_downstream6_map_lookup_elem(&kd)
193 : bpf_tether_upstream6_map_lookup_elem(&ku);
Hungming Chen56c632c2020-09-10 15:42:58 +0800194
195 // If we don't find any offload information then simply let the core stack handle it...
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700196 if (!v) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800197
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800198 uint32_t stat_and_limit_k = downstream ? skb->ifindex : v->oif;
Hungming Chen56c632c2020-09-10 15:42:58 +0800199
200 TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
201
202 // If we don't have anywhere to put stats, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800203 if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
Hungming Chen56c632c2020-09-10 15:42:58 +0800204
205 uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
206
207 // If we don't have a limit, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800208 if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
Hungming Chen56c632c2020-09-10 15:42:58 +0800209
210 // Required IPv6 minimum mtu is 1280, below that not clear what we should do, abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800211 if (v->pmtu < IPV6_MIN_MTU) TC_PUNT(BELOW_IPV6_MTU);
Hungming Chen56c632c2020-09-10 15:42:58 +0800212
213 // Approximate handling of TCP/IPv6 overhead for incoming LRO/GRO packets: default
214 // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
215 // undercount, which is still better then not accounting for this overhead at all.
216 // Note: this really shouldn't be device/path mtu at all, but rather should be
217 // derived from this particular connection's mss (ie. from gro segment size).
218 // This would require a much newer kernel with newer ebpf accessors.
219 // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
220 uint64_t packets = 1;
221 uint64_t bytes = skb->len;
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800222 if (bytes > v->pmtu) {
Hungming Chen56c632c2020-09-10 15:42:58 +0800223 const int tcp_overhead = sizeof(struct ipv6hdr) + sizeof(struct tcphdr) + 12;
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800224 const int mss = v->pmtu - tcp_overhead;
Hungming Chen56c632c2020-09-10 15:42:58 +0800225 const uint64_t payload = bytes - tcp_overhead;
226 packets = (payload + mss - 1) / mss;
227 bytes = tcp_overhead * packets + payload;
228 }
229
230 // Are we past the limit? If so, then abort...
231 // Note: will not overflow since u64 is 936 years even at 5Gbps.
232 // Do not drop here. Offload is just that, whenever we fail to handle
233 // a packet we let the core stack deal with things.
234 // (The core stack needs to handle limits correctly anyway,
235 // since we don't offload all traffic in both directions)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800236 if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
Hungming Chen56c632c2020-09-10 15:42:58 +0800237
238 if (!is_ethernet) {
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800239 // Try to inject an ethernet header, and simply return if we fail.
240 // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
241 // because this is easier and the kernel will strip extraneous ethernet header.
242 if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
243 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800244 TC_PUNT(CHANGE_HEAD_FAILED);
Hungming Chen56c632c2020-09-10 15:42:58 +0800245 }
246
247 // bpf_skb_change_head() invalidates all pointers - reload them
248 data = (void*)(long)skb->data;
249 data_end = (void*)(long)skb->data_end;
250 eth = data;
251 ip6 = (void*)(eth + 1);
252
253 // I do not believe this can ever happen, but keep the verifier happy...
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800254 if (data + sizeof(struct ethhdr) + sizeof(*ip6) > data_end) {
255 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800256 TC_DROP(TOO_SHORT);
Hungming Chen56c632c2020-09-10 15:42:58 +0800257 }
258 };
259
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800260 // At this point we always have an ethernet header - which will get stripped by the
261 // kernel during transmit through a rawip interface. ie. 'eth' pointer is valid.
262 // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
263
Hungming Chen56c632c2020-09-10 15:42:58 +0800264 // CHECKSUM_COMPLETE is a 16-bit one's complement sum,
265 // thus corrections for it need to be done in 16-byte chunks at even offsets.
266 // IPv6 nexthdr is at offset 6, while hop limit is at offset 7
267 uint8_t old_hl = ip6->hop_limit;
268 --ip6->hop_limit;
269 uint8_t new_hl = ip6->hop_limit;
270
271 // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
272 // (-ENOTSUPP) if it isn't.
273 bpf_csum_update(skb, 0xFFFF - ntohs(old_hl) + ntohs(new_hl));
274
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800275 __sync_fetch_and_add(downstream ? &stat_v->rxPackets : &stat_v->txPackets, packets);
276 __sync_fetch_and_add(downstream ? &stat_v->rxBytes : &stat_v->txBytes, bytes);
Hungming Chen56c632c2020-09-10 15:42:58 +0800277
278 // Overwrite any mac header with the new one
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800279 // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800280 *eth = v->macHeader;
Hungming Chen56c632c2020-09-10 15:42:58 +0800281
282 // Redirect to forwarded interface.
283 //
284 // Note that bpf_redirect() cannot fail unless you pass invalid flags.
285 // The redirect actually happens after the ebpf program has already terminated,
286 // and can fail for example for mtu reasons at that point in time, but there's nothing
287 // we can do about it here.
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800288 return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
Hungming Chen56c632c2020-09-10 15:42:58 +0800289}
290
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800291DEFINE_BPF_PROG("schedcls/tether_downstream6_ether", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800292 sched_cls_tether_downstream6_ether)
Maciej Żenczykowski6b7829f2021-01-18 00:03:37 -0800293(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800294 return do_forward6(skb, /* is_ethernet */ true, /* downstream */ true);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800295}
296
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800297DEFINE_BPF_PROG("schedcls/tether_upstream6_ether", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800298 sched_cls_tether_upstream6_ether)
299(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800300 return do_forward6(skb, /* is_ethernet */ true, /* downstream */ false);
Hungming Chen56c632c2020-09-10 15:42:58 +0800301}
302
303// Note: section names must be unique to prevent programs from appending to each other,
304// so instead the bpf loader will strip everything past the final $ symbol when actually
305// pinning the program into the filesystem.
306//
307// bpf_skb_change_head() is only present on 4.14+ and 2 trivial kernel patches are needed:
308// ANDROID: net: bpf: Allow TC programs to call BPF_FUNC_skb_change_head
309// ANDROID: net: bpf: permit redirect from ingress L3 to egress L2 devices at near max mtu
310// (the first of those has already been upstreamed)
311//
312// 5.4 kernel support was only added to Android Common Kernel in R,
313// and thus a 5.4 kernel always supports this.
314//
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800315// Hence, these mandatory (must load successfully) implementations for 5.4+ kernels:
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800316DEFINE_BPF_PROG_KVER("schedcls/tether_downstream6_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800317 sched_cls_tether_downstream6_rawip_5_4, KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800318(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800319 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ true);
Hungming Chen56c632c2020-09-10 15:42:58 +0800320}
321
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800322DEFINE_BPF_PROG_KVER("schedcls/tether_upstream6_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800323 sched_cls_tether_upstream6_rawip_5_4, KVER(5, 4, 0))
324(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800325 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ false);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800326}
327
328// and these identical optional (may fail to load) implementations for [4.14..5.4) patched kernels:
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800329DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream6_rawip$4_14",
330 AID_ROOT, AID_NETWORK_STACK,
331 sched_cls_tether_downstream6_rawip_4_14,
332 KVER(4, 14, 0), KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800333(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800334 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ true);
Hungming Chen56c632c2020-09-10 15:42:58 +0800335}
336
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800337DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream6_rawip$4_14",
338 AID_ROOT, AID_NETWORK_STACK,
339 sched_cls_tether_upstream6_rawip_4_14,
340 KVER(4, 14, 0), KVER(5, 4, 0))
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800341(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800342 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ false);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800343}
344
345// and define no-op stubs for [4.9,4.14) and unpatched [4.14,5.4) kernels.
Hungming Chen56c632c2020-09-10 15:42:58 +0800346// (if the above real 4.14+ program loaded successfully, then bpfloader will have already pinned
347// it at the same location this one would be pinned at and will thus skip loading this stub)
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800348DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream6_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800349 sched_cls_tether_downstream6_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800350(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700351 return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800352}
353
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800354DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream6_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800355 sched_cls_tether_upstream6_rawip_stub, KVER_NONE, KVER(5, 4, 0))
356(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700357 return TC_ACT_PIPE;
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800358}
359
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800360// ----- IPv4 Support -----
361
Maciej Żenczykowski8549af92021-02-25 19:11:34 -0800362DEFINE_BPF_MAP_GRW(tether_downstream4_map, HASH, Tether4Key, Tether4Value, 1024, AID_NETWORK_STACK)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800363
Maciej Żenczykowski8549af92021-02-25 19:11:34 -0800364DEFINE_BPF_MAP_GRW(tether_upstream4_map, HASH, Tether4Key, Tether4Value, 1024, AID_NETWORK_STACK)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800365
Maciej Żenczykowskif72c8aa2022-04-28 02:02:45 -0700366static inline __always_inline int do_forward4_bottom(struct __sk_buff* skb,
367 const int l2_header_size, void* data, const void* data_end,
368 struct ethhdr* eth, struct iphdr* ip, const bool is_ethernet,
369 const bool downstream, const bool updatetime, const bool is_tcp) {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800370 struct tcphdr* tcph = is_tcp ? (void*)(ip + 1) : NULL;
371 struct udphdr* udph = is_tcp ? NULL : (void*)(ip + 1);
372
373 if (is_tcp) {
374 // Make sure we can get at the tcp header
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800375 if (data + l2_header_size + sizeof(*ip) + sizeof(*tcph) > data_end)
376 TC_PUNT(SHORT_TCP_HEADER);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800377
378 // If hardware offload is running and programming flows based on conntrack entries, try not
379 // 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 -0800380 if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCP_CONTROL_PACKET);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800381 } else { // UDP
382 // Make sure we can get at the udp header
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800383 if (data + l2_header_size + sizeof(*ip) + sizeof(*udph) > data_end)
384 TC_PUNT(SHORT_UDP_HEADER);
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800385
386 // Skip handling of CHECKSUM_COMPLETE packets with udp checksum zero due to need for
387 // additional updating of skb->csum (this could be fixed up manually with more effort).
388 //
389 // Note that the in-kernel implementation of 'int64_t bpf_csum_update(skb, u32 csum)' is:
390 // if (skb->ip_summed == CHECKSUM_COMPLETE)
391 // return (skb->csum = csum_add(skb->csum, csum));
392 // else
393 // return -ENOTSUPP;
394 //
395 // So this will punt any CHECKSUM_COMPLETE packet with a zero UDP checksum,
396 // and leave all other packets unaffected (since it just at most adds zero to skb->csum).
397 //
398 // In practice this should almost never trigger because most nics do not generate
399 // CHECKSUM_COMPLETE packets on receive - especially so for nics/drivers on a phone.
400 //
401 // Additionally since we're forwarding, in most cases the value of the skb->csum field
402 // shouldn't matter (it's not used by physical nic egress).
403 //
404 // It only matters if we're ingressing through a CHECKSUM_COMPLETE capable nic
405 // and egressing through a virtual interface looping back to the kernel itself
406 // (ie. something like veth) where the CHECKSUM_COMPLETE/skb->csum can get reused
407 // on ingress.
408 //
409 // If we were in the kernel we'd simply probably call
410 // void skb_checksum_complete_unset(struct sk_buff *skb) {
411 // if (skb->ip_summed == CHECKSUM_COMPLETE) skb->ip_summed = CHECKSUM_NONE;
412 // }
413 // here instead. Perhaps there should be a bpf helper for that?
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800414 if (!udph->check && (bpf_csum_update(skb, 0) >= 0)) TC_PUNT(UDP_CSUM_ZERO);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800415 }
416
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800417 Tether4Key k = {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800418 .iif = skb->ifindex,
419 .l4Proto = ip->protocol,
420 .src4.s_addr = ip->saddr,
421 .dst4.s_addr = ip->daddr,
422 .srcPort = is_tcp ? tcph->source : udph->source,
423 .dstPort = is_tcp ? tcph->dest : udph->dest,
424 };
Maciej Żenczykowski62733f52021-04-01 21:51:41 -0700425 if (is_ethernet) __builtin_memcpy(k.dstMac, eth->h_dest, ETH_ALEN);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800426
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800427 Tether4Value* v = downstream ? bpf_tether_downstream4_map_lookup_elem(&k)
428 : bpf_tether_upstream4_map_lookup_elem(&k);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800429
430 // If we don't find any offload information then simply let the core stack handle it...
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700431 if (!v) return TC_ACT_PIPE;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800432
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800433 uint32_t stat_and_limit_k = downstream ? skb->ifindex : v->oif;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800434
435 TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
436
437 // If we don't have anywhere to put stats, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800438 if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800439
440 uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
441
442 // If we don't have a limit, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800443 if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800444
445 // Required IPv4 minimum mtu is 68, below that not clear what we should do, abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800446 if (v->pmtu < 68) TC_PUNT(BELOW_IPV4_MTU);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800447
448 // Approximate handling of TCP/IPv4 overhead for incoming LRO/GRO packets: default
449 // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
450 // undercount, which is still better then not accounting for this overhead at all.
451 // Note: this really shouldn't be device/path mtu at all, but rather should be
452 // derived from this particular connection's mss (ie. from gro segment size).
453 // This would require a much newer kernel with newer ebpf accessors.
454 // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
455 uint64_t packets = 1;
456 uint64_t bytes = skb->len;
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800457 if (bytes > v->pmtu) {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800458 const int tcp_overhead = sizeof(struct iphdr) + sizeof(struct tcphdr) + 12;
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800459 const int mss = v->pmtu - tcp_overhead;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800460 const uint64_t payload = bytes - tcp_overhead;
461 packets = (payload + mss - 1) / mss;
462 bytes = tcp_overhead * packets + payload;
463 }
464
465 // Are we past the limit? If so, then abort...
466 // Note: will not overflow since u64 is 936 years even at 5Gbps.
467 // Do not drop here. Offload is just that, whenever we fail to handle
468 // a packet we let the core stack deal with things.
469 // (The core stack needs to handle limits correctly anyway,
470 // since we don't offload all traffic in both directions)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800471 if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800472
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800473 if (!is_ethernet) {
474 // Try to inject an ethernet header, and simply return if we fail.
475 // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
476 // because this is easier and the kernel will strip extraneous ethernet header.
477 if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
478 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800479 TC_PUNT(CHANGE_HEAD_FAILED);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800480 }
481
482 // bpf_skb_change_head() invalidates all pointers - reload them
483 data = (void*)(long)skb->data;
484 data_end = (void*)(long)skb->data_end;
485 eth = data;
486 ip = (void*)(eth + 1);
487 tcph = is_tcp ? (void*)(ip + 1) : NULL;
488 udph = is_tcp ? NULL : (void*)(ip + 1);
489
490 // I do not believe this can ever happen, but keep the verifier happy...
491 if (data + sizeof(struct ethhdr) + sizeof(*ip) + (is_tcp ? sizeof(*tcph) : sizeof(*udph)) > data_end) {
492 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800493 TC_DROP(TOO_SHORT);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800494 }
495 };
496
497 // At this point we always have an ethernet header - which will get stripped by the
498 // kernel during transmit through a rawip interface. ie. 'eth' pointer is valid.
499 // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
500
501 // Overwrite any mac header with the new one
502 // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
503 *eth = v->macHeader;
504
Maciej Żenczykowskic29af792021-07-02 01:54:04 -0700505 // Decrement the IPv4 TTL, we already know it's greater than 1.
506 // u8 TTL field is followed by u8 protocol to make a u16 for ipv4 header checksum update.
507 // Since we're keeping the ipv4 checksum valid (which means the checksum of the entire
508 // ipv4 header remains 0), the overall checksum of the entire packet does not change.
509 const int sz2 = sizeof(__be16);
510 const __be16 old_ttl_proto = *(__be16 *)&ip->ttl;
511 const __be16 new_ttl_proto = old_ttl_proto - htons(0x0100);
512 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_ttl_proto, new_ttl_proto, sz2);
513 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(ttl), &new_ttl_proto, sz2, 0);
514
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800515 const int l4_offs_csum = is_tcp ? ETH_IP4_TCP_OFFSET(check) : ETH_IP4_UDP_OFFSET(check);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800516 const int sz4 = sizeof(__be32);
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800517 // UDP 0 is special and stored as FFFF (this flag also causes a csum of 0 to be unmodified)
518 const int l4_flags = is_tcp ? 0 : BPF_F_MARK_MANGLED_0;
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800519 const __be32 old_daddr = k.dst4.s_addr;
520 const __be32 old_saddr = k.src4.s_addr;
521 const __be32 new_daddr = v->dst46.s6_addr32[3];
522 const __be32 new_saddr = v->src46.s6_addr32[3];
523
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800524 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 -0800525 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_daddr, new_daddr, sz4);
526 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(daddr), &new_daddr, sz4, 0);
527
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800528 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 -0800529 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_saddr, new_saddr, sz4);
530 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(saddr), &new_saddr, sz4, 0);
531
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800532 // The offsets for TCP and UDP ports: source (u16 @ L4 offset 0) & dest (u16 @ L4 offset 2) are
533 // actually the same, so the compiler should just optimize them both down to a constant.
534 bpf_l4_csum_replace(skb, l4_offs_csum, k.srcPort, v->srcPort, sz2 | l4_flags);
535 bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(source) : ETH_IP4_UDP_OFFSET(source),
536 &v->srcPort, sz2, 0);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800537
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800538 bpf_l4_csum_replace(skb, l4_offs_csum, k.dstPort, v->dstPort, sz2 | l4_flags);
539 bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(dest) : ETH_IP4_UDP_OFFSET(dest),
540 &v->dstPort, sz2, 0);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800541
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800542 // This requires the bpf_ktime_get_boot_ns() helper which was added in 5.8,
543 // and backported to all Android Common Kernel 4.14+ trees.
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800544 if (updatetime) v->last_used = bpf_ktime_get_boot_ns();
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800545
546 __sync_fetch_and_add(downstream ? &stat_v->rxPackets : &stat_v->txPackets, packets);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800547 __sync_fetch_and_add(downstream ? &stat_v->rxBytes : &stat_v->txBytes, bytes);
548
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800549 // Redirect to forwarded interface.
550 //
551 // Note that bpf_redirect() cannot fail unless you pass invalid flags.
552 // The redirect actually happens after the ebpf program has already terminated,
553 // and can fail for example for mtu reasons at that point in time, but there's nothing
554 // we can do about it here.
555 return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800556}
557
Maciej Żenczykowskif72c8aa2022-04-28 02:02:45 -0700558static inline __always_inline int do_forward4(struct __sk_buff* skb, const bool is_ethernet,
559 const bool downstream, const bool updatetime) {
560 // Require ethernet dst mac address to be our unicast address.
561 if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
562
563 // Must be meta-ethernet IPv4 frame
564 if (skb->protocol != htons(ETH_P_IP)) return TC_ACT_PIPE;
565
566 const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
567
568 // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
569 // not trigger and thus we need to manually make sure we can read packet headers via DPA.
570 // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
571 // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
572 try_make_writable(skb, l2_header_size + IP4_HLEN + TCP_HLEN);
573
574 void* data = (void*)(long)skb->data;
575 const void* data_end = (void*)(long)skb->data_end;
576 struct ethhdr* eth = is_ethernet ? data : NULL; // used iff is_ethernet
577 struct iphdr* ip = is_ethernet ? (void*)(eth + 1) : data;
578
579 // Must have (ethernet and) ipv4 header
580 if (data + l2_header_size + sizeof(*ip) > data_end) return TC_ACT_PIPE;
581
582 // Ethertype - if present - must be IPv4
583 if (is_ethernet && (eth->h_proto != htons(ETH_P_IP))) return TC_ACT_PIPE;
584
585 // IP version must be 4
586 if (ip->version != 4) TC_PUNT(INVALID_IP_VERSION);
587
588 // We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header
589 if (ip->ihl != 5) TC_PUNT(HAS_IP_OPTIONS);
590
591 // Calculate the IPv4 one's complement checksum of the IPv4 header.
592 __wsum sum4 = 0;
593 for (int i = 0; i < sizeof(*ip) / sizeof(__u16); ++i) {
594 sum4 += ((__u16*)ip)[i];
595 }
596 // Note that sum4 is guaranteed to be non-zero by virtue of ip4->version == 4
597 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE
598 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16
599 // for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF
600 if (sum4 != 0xFFFF) TC_PUNT(CHECKSUM);
601
602 // Minimum IPv4 total length is the size of the header
603 if (ntohs(ip->tot_len) < sizeof(*ip)) TC_PUNT(TRUNCATED_IPV4);
604
605 // We are incapable of dealing with IPv4 fragments
606 if (ip->frag_off & ~htons(IP_DF)) TC_PUNT(IS_IP_FRAG);
607
608 // Cannot decrement during forward if already zero or would be zero,
609 // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
610 if (ip->ttl <= 1) TC_PUNT(LOW_TTL);
611
612 // If we cannot update the 'last_used' field due to lack of bpf_ktime_get_boot_ns() helper,
613 // then it is not safe to offload UDP due to the small conntrack timeouts, as such,
614 // in such a situation we can only support TCP. This also has the added nice benefit of
615 // using a separate error counter, and thus making it obvious which version of the program
616 // is loaded.
617 if (!updatetime && ip->protocol != IPPROTO_TCP) TC_PUNT(NON_TCP);
618
619 // We do not support offloading anything besides IPv4 TCP and UDP, due to need for NAT,
620 // but no need to check this if !updatetime due to check immediately above.
621 if (updatetime && (ip->protocol != IPPROTO_TCP) && (ip->protocol != IPPROTO_UDP))
622 TC_PUNT(NON_TCP_UDP);
623
624 // We want to make sure that the compiler will, in the !updatetime case, entirely optimize
625 // out all the non-tcp logic. Also note that at this point is_udp === !is_tcp.
626 const bool is_tcp = !updatetime || (ip->protocol == IPPROTO_TCP);
627
628 // This is a bit of a hack to make things easier on the bpf verifier.
629 // (In particular I believe the Linux 4.14 kernel's verifier can get confused later on about
630 // what offsets into the packet are valid and can spuriously reject the program, this is
631 // because it fails to realize that is_tcp && !is_tcp is impossible)
632 //
633 // For both TCP & UDP we'll need to read and modify the src/dst ports, which so happen to
634 // always be in the first 4 bytes of the L4 header. Additionally for UDP we'll need access
635 // to the checksum field which is in bytes 7 and 8. While for TCP we'll need to read the
636 // TCP flags (at offset 13) and access to the checksum field (2 bytes at offset 16).
637 // As such we *always* need access to at least 8 bytes.
638 if (data + l2_header_size + sizeof(*ip) + 8 > data_end) TC_PUNT(SHORT_L4_HEADER);
639
640 // We're forcing the compiler to emit two copies of the following code, optimized
641 // separately for is_tcp being true or false. This simplifies the resulting bpf
642 // byte code sufficiently that the 4.14 bpf verifier is able to keep track of things.
643 // Without this (updatetime == true) case would fail to bpf verify on 4.14 even
644 // if the underlying requisite kernel support (bpf_ktime_get_boot_ns) was backported.
645 if (is_tcp) {
646 return do_forward4_bottom(skb, l2_header_size, data, data_end, eth, ip,
647 is_ethernet, downstream, updatetime, /* is_tcp */ true);
648 } else {
649 return do_forward4_bottom(skb, l2_header_size, data, data_end, eth, ip,
650 is_ethernet, downstream, updatetime, /* is_tcp */ false);
651 }
652}
653
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800654// Full featured (required) implementations for 5.8+ kernels (these are S+ by definition)
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800655
Maciej Żenczykowskib0ac41f2021-02-14 21:34:03 -0800656DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_rawip$5_8", AID_ROOT, AID_NETWORK_STACK,
657 sched_cls_tether_downstream4_rawip_5_8, KVER(5, 8, 0))
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800658(struct __sk_buff* skb) {
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800659 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ true);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800660}
661
Maciej Żenczykowskib0ac41f2021-02-14 21:34:03 -0800662DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_rawip$5_8", AID_ROOT, AID_NETWORK_STACK,
663 sched_cls_tether_upstream4_rawip_5_8, KVER(5, 8, 0))
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800664(struct __sk_buff* skb) {
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800665 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ true);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800666}
667
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800668DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_ether$5_8", AID_ROOT, AID_NETWORK_STACK,
669 sched_cls_tether_downstream4_ether_5_8, KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800670(struct __sk_buff* skb) {
671 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ true);
672}
673
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800674DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_ether$5_8", AID_ROOT, AID_NETWORK_STACK,
675 sched_cls_tether_upstream4_ether_5_8, KVER(5, 8, 0))
676(struct __sk_buff* skb) {
677 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ true);
678}
679
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800680// Full featured (optional) implementations for 4.14-S, 4.19-S & 5.4-S kernels
681// (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 -0800682
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800683DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$opt",
684 AID_ROOT, AID_NETWORK_STACK,
685 sched_cls_tether_downstream4_rawip_opt,
686 KVER(4, 14, 0), KVER(5, 8, 0))
687(struct __sk_buff* skb) {
688 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ true);
689}
690
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800691DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$opt",
692 AID_ROOT, AID_NETWORK_STACK,
693 sched_cls_tether_upstream4_rawip_opt,
694 KVER(4, 14, 0), KVER(5, 8, 0))
695(struct __sk_buff* skb) {
696 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ true);
697}
698
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800699DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$opt",
700 AID_ROOT, AID_NETWORK_STACK,
701 sched_cls_tether_downstream4_ether_opt,
702 KVER(4, 14, 0), KVER(5, 8, 0))
703(struct __sk_buff* skb) {
704 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ true);
705}
706
707DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$opt",
708 AID_ROOT, AID_NETWORK_STACK,
709 sched_cls_tether_upstream4_ether_opt,
710 KVER(4, 14, 0), KVER(5, 8, 0))
711(struct __sk_buff* skb) {
712 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ true);
713}
714
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800715// Partial (TCP-only: will not update 'last_used' field) implementations for 4.14+ kernels.
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800716// These will be loaded only if the above optional ones failed (loading of *these* must succeed
717// for 5.4+, since that is always an R patched kernel).
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800718//
719// [Note: as a result TCP connections will not have their conntrack timeout refreshed, however,
720// since /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established defaults to 432000 (seconds),
721// this in practice means they'll break only after 5 days. This seems an acceptable trade-off.
722//
723// Additionally kernel/tests change "net-test: add bpf_ktime_get_ns / bpf_ktime_get_boot_ns tests"
724// which enforces and documents the required kernel cherrypicks will make it pretty unlikely that
725// many devices upgrading to S will end up relying on these fallback programs.
726
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800727// RAWIP: Required for 5.4-R kernels -- which always support bpf_skb_change_head().
728
729DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
730 sched_cls_tether_downstream4_rawip_5_4, KVER(5, 4, 0), KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800731(struct __sk_buff* skb) {
732 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ false);
733}
734
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800735DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
736 sched_cls_tether_upstream4_rawip_5_4, KVER(5, 4, 0), KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800737(struct __sk_buff* skb) {
738 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ false);
739}
740
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800741// RAWIP: Optional for 4.14/4.19 (R) kernels -- which support bpf_skb_change_head().
742// [Note: fallback for 4.14/4.19 (P/Q) kernels is below in stub section]
743
744DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$4_14",
745 AID_ROOT, AID_NETWORK_STACK,
746 sched_cls_tether_downstream4_rawip_4_14,
747 KVER(4, 14, 0), KVER(5, 4, 0))
748(struct __sk_buff* skb) {
749 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ false);
750}
751
752DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$4_14",
753 AID_ROOT, AID_NETWORK_STACK,
754 sched_cls_tether_upstream4_rawip_4_14,
755 KVER(4, 14, 0), KVER(5, 4, 0))
756(struct __sk_buff* skb) {
757 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ false);
758}
759
760// ETHER: Required for 4.14-Q/R, 4.19-Q/R & 5.4-R kernels.
761
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800762DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$4_14", AID_ROOT, AID_NETWORK_STACK,
763 sched_cls_tether_downstream4_ether_4_14, KVER(4, 14, 0), KVER(5, 8, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800764(struct __sk_buff* skb) {
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800765 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ false);
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800766}
767
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800768DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$4_14", AID_ROOT, AID_NETWORK_STACK,
769 sched_cls_tether_upstream4_ether_4_14, KVER(4, 14, 0), KVER(5, 8, 0))
770(struct __sk_buff* skb) {
771 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ false);
772}
773
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800774// Placeholder (no-op) implementations for older Q kernels
775
776// 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 -0800777
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800778DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800779 sched_cls_tether_downstream4_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800780(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700781 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800782}
783
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800784DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800785 sched_cls_tether_upstream4_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800786(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700787 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800788}
789
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800790// ETHER: 4.9-P/Q kernel
791
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800792DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$stub", AID_ROOT, AID_NETWORK_STACK,
793 sched_cls_tether_downstream4_ether_stub, KVER_NONE, KVER(4, 14, 0))
794(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700795 return TC_ACT_PIPE;
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800796}
797
798DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$stub", AID_ROOT, AID_NETWORK_STACK,
799 sched_cls_tether_upstream4_ether_stub, KVER_NONE, KVER(4, 14, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800800(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700801 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800802}
803
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800804// ----- XDP Support -----
805
Hungming Chen3feb7822021-05-11 21:07:18 +0800806DEFINE_BPF_MAP_GRW(tether_dev_map, DEVMAP_HASH, uint32_t, uint32_t, 64, AID_NETWORK_STACK)
Maciej Żenczykowskidb2cff52021-03-01 21:22:49 -0800807
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800808static inline __always_inline int do_xdp_forward6(struct xdp_md *ctx, const bool is_ethernet,
809 const bool downstream) {
810 return XDP_PASS;
811}
812
813static inline __always_inline int do_xdp_forward4(struct xdp_md *ctx, const bool is_ethernet,
814 const bool downstream) {
815 return XDP_PASS;
816}
817
818static inline __always_inline int do_xdp_forward_ether(struct xdp_md *ctx, const bool downstream) {
819 const void* data = (void*)(long)ctx->data;
820 const void* data_end = (void*)(long)ctx->data_end;
821 const struct ethhdr* eth = data;
822
823 // Make sure we actually have an ethernet header
824 if ((void*)(eth + 1) > data_end) return XDP_PASS;
825
826 if (eth->h_proto == htons(ETH_P_IPV6))
827 return do_xdp_forward6(ctx, /* is_ethernet */ true, downstream);
828 if (eth->h_proto == htons(ETH_P_IP))
829 return do_xdp_forward4(ctx, /* is_ethernet */ true, downstream);
830
831 // Anything else we don't know how to handle...
832 return XDP_PASS;
833}
834
835static inline __always_inline int do_xdp_forward_rawip(struct xdp_md *ctx, const bool downstream) {
836 const void* data = (void*)(long)ctx->data;
837 const void* data_end = (void*)(long)ctx->data_end;
838
839 // The top nibble of both IPv4 and IPv6 headers is the IP version.
840 if (data_end - data < 1) return XDP_PASS;
841 const uint8_t v = (*(uint8_t*)data) >> 4;
842
843 if (v == 6) return do_xdp_forward6(ctx, /* is_ethernet */ false, downstream);
844 if (v == 4) return do_xdp_forward4(ctx, /* is_ethernet */ false, downstream);
845
846 // Anything else we don't know how to handle...
847 return XDP_PASS;
848}
849
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800850#define DEFINE_XDP_PROG(str, func) \
851 DEFINE_BPF_PROG_KVER(str, AID_ROOT, AID_NETWORK_STACK, func, KVER(5, 9, 0))(struct xdp_md *ctx)
852
853DEFINE_XDP_PROG("xdp/tether_downstream_ether",
854 xdp_tether_downstream_ether) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800855 return do_xdp_forward_ether(ctx, /* downstream */ true);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800856}
857
858DEFINE_XDP_PROG("xdp/tether_downstream_rawip",
859 xdp_tether_downstream_rawip) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800860 return do_xdp_forward_rawip(ctx, /* downstream */ true);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800861}
862
863DEFINE_XDP_PROG("xdp/tether_upstream_ether",
864 xdp_tether_upstream_ether) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800865 return do_xdp_forward_ether(ctx, /* downstream */ false);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800866}
867
868DEFINE_XDP_PROG("xdp/tether_upstream_rawip",
869 xdp_tether_upstream_rawip) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800870 return do_xdp_forward_rawip(ctx, /* downstream */ false);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800871}
872
Hungming Chen56c632c2020-09-10 15:42:58 +0800873LICENSE("Apache 2.0");
Maciej Żenczykowski607d6dd2021-02-25 19:09:47 -0800874CRITICAL("tethering");