blob: 92a774cefe7f13dbd4a8ce9c2c6f373b0ebd1ac0 [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 Żenczykowskia457bf72021-10-22 21:41:25 -070027// The resulting .o needs to load on the Android S bpfloader v0.2
28#define BPFLOADER_MIN_VER 2u
29
Hungming Chen56c632c2020-09-10 15:42:58 +080030#include "bpf_helpers.h"
31#include "bpf_net_helpers.h"
Lorenzo Colittib81584d2021-02-06 00:00:58 +090032#include "bpf_tethering.h"
Hungming Chen56c632c2020-09-10 15:42:58 +080033
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -080034// From kernel:include/net/ip.h
35#define IP_DF 0x4000 // Flag: "Don't Fragment"
36
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -080037// ----- Helper functions for offsets to fields -----
38
39// They all assume simple IP packets:
40// - no VLAN ethernet tags
41// - no IPv4 options (see IPV4_HLEN/TCP4_OFFSET/UDP4_OFFSET)
42// - no IPv6 extension headers
43// - no TCP options (see TCP_HLEN)
44
45//#define ETH_HLEN sizeof(struct ethhdr)
46#define IP4_HLEN sizeof(struct iphdr)
47#define IP6_HLEN sizeof(struct ipv6hdr)
48#define TCP_HLEN sizeof(struct tcphdr)
49#define UDP_HLEN sizeof(struct udphdr)
50
51// Offsets from beginning of L4 (TCP/UDP) header
52#define TCP_OFFSET(field) offsetof(struct tcphdr, field)
53#define UDP_OFFSET(field) offsetof(struct udphdr, field)
54
55// Offsets from beginning of L3 (IPv4) header
56#define IP4_OFFSET(field) offsetof(struct iphdr, field)
57#define IP4_TCP_OFFSET(field) (IP4_HLEN + TCP_OFFSET(field))
58#define IP4_UDP_OFFSET(field) (IP4_HLEN + UDP_OFFSET(field))
59
60// Offsets from beginning of L3 (IPv6) header
61#define IP6_OFFSET(field) offsetof(struct ipv6hdr, field)
62#define IP6_TCP_OFFSET(field) (IP6_HLEN + TCP_OFFSET(field))
63#define IP6_UDP_OFFSET(field) (IP6_HLEN + UDP_OFFSET(field))
64
65// Offsets from beginning of L2 (ie. Ethernet) header (which must be present)
66#define ETH_IP4_OFFSET(field) (ETH_HLEN + IP4_OFFSET(field))
67#define ETH_IP4_TCP_OFFSET(field) (ETH_HLEN + IP4_TCP_OFFSET(field))
68#define ETH_IP4_UDP_OFFSET(field) (ETH_HLEN + IP4_UDP_OFFSET(field))
69#define ETH_IP6_OFFSET(field) (ETH_HLEN + IP6_OFFSET(field))
70#define ETH_IP6_TCP_OFFSET(field) (ETH_HLEN + IP6_TCP_OFFSET(field))
71#define ETH_IP6_UDP_OFFSET(field) (ETH_HLEN + IP6_UDP_OFFSET(field))
72
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080073// ----- Tethering Error Counters -----
74
75DEFINE_BPF_MAP_GRW(tether_error_map, ARRAY, uint32_t, uint32_t, BPF_TETHER_ERR__MAX,
76 AID_NETWORK_STACK)
77
Maciej Żenczykowski3f32a832021-03-17 19:27:23 -070078#define COUNT_AND_RETURN(counter, ret) do { \
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080079 uint32_t code = BPF_TETHER_ERR_ ## counter; \
80 uint32_t *count = bpf_tether_error_map_lookup_elem(&code); \
Maciej Żenczykowski3f32a832021-03-17 19:27:23 -070081 if (count) __sync_fetch_and_add(count, 1); \
82 return ret; \
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080083} while(0)
84
85#define TC_DROP(counter) COUNT_AND_RETURN(counter, TC_ACT_SHOT)
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -070086#define TC_PUNT(counter) COUNT_AND_RETURN(counter, TC_ACT_PIPE)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -080087
88#define XDP_DROP(counter) COUNT_AND_RETURN(counter, XDP_DROP)
89#define XDP_PUNT(counter) COUNT_AND_RETURN(counter, XDP_PASS)
90
91// ----- Tethering Data Stats and Limits -----
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -080092
Hungming Chen56c632c2020-09-10 15:42:58 +080093// Tethering stats, indexed by upstream interface.
Maciej Żenczykowski088fe192021-01-20 13:34:17 -080094DEFINE_BPF_MAP_GRW(tether_stats_map, HASH, TetherStatsKey, TetherStatsValue, 16, AID_NETWORK_STACK)
Hungming Chen56c632c2020-09-10 15:42:58 +080095
96// Tethering data limit, indexed by upstream interface.
97// (tethering allowed when stats[iif].rxBytes + stats[iif].txBytes < limit[iif])
Maciej Żenczykowski088fe192021-01-20 13:34:17 -080098DEFINE_BPF_MAP_GRW(tether_limit_map, HASH, TetherLimitKey, TetherLimitValue, 16, AID_NETWORK_STACK)
99
100// ----- IPv6 Support -----
101
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800102DEFINE_BPF_MAP_GRW(tether_downstream6_map, HASH, TetherDownstream6Key, Tether6Value, 64,
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800103 AID_NETWORK_STACK)
104
105DEFINE_BPF_MAP_GRW(tether_downstream64_map, HASH, TetherDownstream64Key, TetherDownstream64Value,
Maciej Żenczykowski8549af92021-02-25 19:11:34 -0800106 1024, AID_NETWORK_STACK)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800107
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800108DEFINE_BPF_MAP_GRW(tether_upstream6_map, HASH, TetherUpstream6Key, Tether6Value, 64,
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800109 AID_NETWORK_STACK)
Hungming Chen56c632c2020-09-10 15:42:58 +0800110
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800111static inline __always_inline int do_forward6(struct __sk_buff* skb, const bool is_ethernet,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800112 const bool downstream) {
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800113 // Must be meta-ethernet IPv6 frame
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700114 if (skb->protocol != htons(ETH_P_IPV6)) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800115
Maciej Żenczykowski18552e82021-01-24 19:59:05 -0800116 // Require ethernet dst mac address to be our unicast address.
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700117 if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
Maciej Żenczykowski18552e82021-01-24 19:59:05 -0800118
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800119 const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
120
121 // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
122 // not trigger and thus we need to manually make sure we can read packet headers via DPA.
123 // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
124 // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
Maciej Żenczykowski824fb292022-04-11 23:29:46 -0700125 try_make_writable(skb, l2_header_size + IP6_HLEN + TCP_HLEN);
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800126
127 void* data = (void*)(long)skb->data;
128 const void* data_end = (void*)(long)skb->data_end;
129 struct ethhdr* eth = is_ethernet ? data : NULL; // used iff is_ethernet
130 struct ipv6hdr* ip6 = is_ethernet ? (void*)(eth + 1) : data;
Hungming Chen56c632c2020-09-10 15:42:58 +0800131
132 // Must have (ethernet and) ipv6 header
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700133 if (data + l2_header_size + sizeof(*ip6) > data_end) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800134
135 // Ethertype - if present - must be IPv6
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700136 if (is_ethernet && (eth->h_proto != htons(ETH_P_IPV6))) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800137
138 // IP version must be 6
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800139 if (ip6->version != 6) TC_PUNT(INVALID_IP_VERSION);
Hungming Chen56c632c2020-09-10 15:42:58 +0800140
141 // Cannot decrement during forward if already zero or would be zero,
142 // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800143 if (ip6->hop_limit <= 1) TC_PUNT(LOW_TTL);
Hungming Chen56c632c2020-09-10 15:42:58 +0800144
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800145 // If hardware offload is running and programming flows based on conntrack entries,
146 // try not to interfere with it.
147 if (ip6->nexthdr == IPPROTO_TCP) {
148 struct tcphdr* tcph = (void*)(ip6 + 1);
149
150 // Make sure we can get at the tcp header
Lorenzo Colittib81584d2021-02-06 00:00:58 +0900151 if (data + l2_header_size + sizeof(*ip6) + sizeof(*tcph) > data_end)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800152 TC_PUNT(INVALID_TCP_HEADER);
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800153
154 // Do not offload TCP packets with any one of the SYN/FIN/RST flags
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800155 if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCP_CONTROL_PACKET);
Maciej Żenczykowskifc4f6542021-01-22 22:19:45 -0800156 }
157
Hungming Chen56c632c2020-09-10 15:42:58 +0800158 // Protect against forwarding packets sourced from ::1 or fe80::/64 or other weirdness.
159 __be32 src32 = ip6->saddr.s6_addr32[0];
160 if (src32 != htonl(0x0064ff9b) && // 64:ff9b:/32 incl. XLAT464 WKP
161 (src32 & htonl(0xe0000000)) != htonl(0x20000000)) // 2000::/3 Global Unicast
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800162 TC_PUNT(NON_GLOBAL_SRC);
Hungming Chen56c632c2020-09-10 15:42:58 +0800163
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800164 // Protect against forwarding packets destined to ::1 or fe80::/64 or other weirdness.
165 __be32 dst32 = ip6->daddr.s6_addr32[0];
166 if (dst32 != htonl(0x0064ff9b) && // 64:ff9b:/32 incl. XLAT464 WKP
167 (dst32 & htonl(0xe0000000)) != htonl(0x20000000)) // 2000::/3 Global Unicast
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800168 TC_PUNT(NON_GLOBAL_DST);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800169
170 // In the upstream direction do not forward traffic within the same /64 subnet.
171 if (!downstream && (src32 == dst32) && (ip6->saddr.s6_addr32[1] == ip6->daddr.s6_addr32[1]))
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800172 TC_PUNT(LOCAL_SRC_DST);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800173
174 TetherDownstream6Key kd = {
Hungming Chen56c632c2020-09-10 15:42:58 +0800175 .iif = skb->ifindex,
176 .neigh6 = ip6->daddr,
177 };
178
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800179 TetherUpstream6Key ku = {
180 .iif = skb->ifindex,
181 };
Maciej Żenczykowski62733f52021-04-01 21:51:41 -0700182 if (is_ethernet) __builtin_memcpy(downstream ? kd.dstMac : ku.dstMac, eth->h_dest, ETH_ALEN);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800183
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800184 Tether6Value* v = downstream ? bpf_tether_downstream6_map_lookup_elem(&kd)
185 : bpf_tether_upstream6_map_lookup_elem(&ku);
Hungming Chen56c632c2020-09-10 15:42:58 +0800186
187 // If we don't find any offload information then simply let the core stack handle it...
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700188 if (!v) return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800189
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800190 uint32_t stat_and_limit_k = downstream ? skb->ifindex : v->oif;
Hungming Chen56c632c2020-09-10 15:42:58 +0800191
192 TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
193
194 // If we don't have anywhere to put stats, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800195 if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
Hungming Chen56c632c2020-09-10 15:42:58 +0800196
197 uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
198
199 // If we don't have a limit, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800200 if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
Hungming Chen56c632c2020-09-10 15:42:58 +0800201
202 // Required IPv6 minimum mtu is 1280, below that not clear what we should do, abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800203 if (v->pmtu < IPV6_MIN_MTU) TC_PUNT(BELOW_IPV6_MTU);
Hungming Chen56c632c2020-09-10 15:42:58 +0800204
205 // Approximate handling of TCP/IPv6 overhead for incoming LRO/GRO packets: default
206 // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
207 // undercount, which is still better then not accounting for this overhead at all.
208 // Note: this really shouldn't be device/path mtu at all, but rather should be
209 // derived from this particular connection's mss (ie. from gro segment size).
210 // This would require a much newer kernel with newer ebpf accessors.
211 // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
212 uint64_t packets = 1;
213 uint64_t bytes = skb->len;
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800214 if (bytes > v->pmtu) {
Hungming Chen56c632c2020-09-10 15:42:58 +0800215 const int tcp_overhead = sizeof(struct ipv6hdr) + sizeof(struct tcphdr) + 12;
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800216 const int mss = v->pmtu - tcp_overhead;
Hungming Chen56c632c2020-09-10 15:42:58 +0800217 const uint64_t payload = bytes - tcp_overhead;
218 packets = (payload + mss - 1) / mss;
219 bytes = tcp_overhead * packets + payload;
220 }
221
222 // Are we past the limit? If so, then abort...
223 // Note: will not overflow since u64 is 936 years even at 5Gbps.
224 // Do not drop here. Offload is just that, whenever we fail to handle
225 // a packet we let the core stack deal with things.
226 // (The core stack needs to handle limits correctly anyway,
227 // since we don't offload all traffic in both directions)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800228 if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
Hungming Chen56c632c2020-09-10 15:42:58 +0800229
230 if (!is_ethernet) {
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800231 // Try to inject an ethernet header, and simply return if we fail.
232 // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
233 // because this is easier and the kernel will strip extraneous ethernet header.
234 if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
235 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800236 TC_PUNT(CHANGE_HEAD_FAILED);
Hungming Chen56c632c2020-09-10 15:42:58 +0800237 }
238
239 // bpf_skb_change_head() invalidates all pointers - reload them
240 data = (void*)(long)skb->data;
241 data_end = (void*)(long)skb->data_end;
242 eth = data;
243 ip6 = (void*)(eth + 1);
244
245 // I do not believe this can ever happen, but keep the verifier happy...
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800246 if (data + sizeof(struct ethhdr) + sizeof(*ip6) > data_end) {
247 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800248 TC_DROP(TOO_SHORT);
Hungming Chen56c632c2020-09-10 15:42:58 +0800249 }
250 };
251
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800252 // At this point we always have an ethernet header - which will get stripped by the
253 // kernel during transmit through a rawip interface. ie. 'eth' pointer is valid.
254 // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
255
Hungming Chen56c632c2020-09-10 15:42:58 +0800256 // CHECKSUM_COMPLETE is a 16-bit one's complement sum,
257 // thus corrections for it need to be done in 16-byte chunks at even offsets.
258 // IPv6 nexthdr is at offset 6, while hop limit is at offset 7
259 uint8_t old_hl = ip6->hop_limit;
260 --ip6->hop_limit;
261 uint8_t new_hl = ip6->hop_limit;
262
263 // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
264 // (-ENOTSUPP) if it isn't.
265 bpf_csum_update(skb, 0xFFFF - ntohs(old_hl) + ntohs(new_hl));
266
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800267 __sync_fetch_and_add(downstream ? &stat_v->rxPackets : &stat_v->txPackets, packets);
268 __sync_fetch_and_add(downstream ? &stat_v->rxBytes : &stat_v->txBytes, bytes);
Hungming Chen56c632c2020-09-10 15:42:58 +0800269
270 // Overwrite any mac header with the new one
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800271 // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800272 *eth = v->macHeader;
Hungming Chen56c632c2020-09-10 15:42:58 +0800273
274 // Redirect to forwarded interface.
275 //
276 // Note that bpf_redirect() cannot fail unless you pass invalid flags.
277 // The redirect actually happens after the ebpf program has already terminated,
278 // and can fail for example for mtu reasons at that point in time, but there's nothing
279 // we can do about it here.
Maciej Żenczykowski7dfbcf52021-01-26 16:08:57 -0800280 return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
Hungming Chen56c632c2020-09-10 15:42:58 +0800281}
282
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800283DEFINE_BPF_PROG("schedcls/tether_downstream6_ether", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800284 sched_cls_tether_downstream6_ether)
Maciej Żenczykowski6b7829f2021-01-18 00:03:37 -0800285(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800286 return do_forward6(skb, /* is_ethernet */ true, /* downstream */ true);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800287}
288
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800289DEFINE_BPF_PROG("schedcls/tether_upstream6_ether", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800290 sched_cls_tether_upstream6_ether)
291(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800292 return do_forward6(skb, /* is_ethernet */ true, /* downstream */ false);
Hungming Chen56c632c2020-09-10 15:42:58 +0800293}
294
295// Note: section names must be unique to prevent programs from appending to each other,
296// so instead the bpf loader will strip everything past the final $ symbol when actually
297// pinning the program into the filesystem.
298//
299// bpf_skb_change_head() is only present on 4.14+ and 2 trivial kernel patches are needed:
300// ANDROID: net: bpf: Allow TC programs to call BPF_FUNC_skb_change_head
301// ANDROID: net: bpf: permit redirect from ingress L3 to egress L2 devices at near max mtu
302// (the first of those has already been upstreamed)
303//
304// 5.4 kernel support was only added to Android Common Kernel in R,
305// and thus a 5.4 kernel always supports this.
306//
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800307// Hence, these mandatory (must load successfully) implementations for 5.4+ kernels:
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800308DEFINE_BPF_PROG_KVER("schedcls/tether_downstream6_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800309 sched_cls_tether_downstream6_rawip_5_4, KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800310(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800311 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ true);
Hungming Chen56c632c2020-09-10 15:42:58 +0800312}
313
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800314DEFINE_BPF_PROG_KVER("schedcls/tether_upstream6_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800315 sched_cls_tether_upstream6_rawip_5_4, KVER(5, 4, 0))
316(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800317 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ false);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800318}
319
320// and these identical optional (may fail to load) implementations for [4.14..5.4) patched kernels:
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800321DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream6_rawip$4_14",
322 AID_ROOT, AID_NETWORK_STACK,
323 sched_cls_tether_downstream6_rawip_4_14,
324 KVER(4, 14, 0), KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800325(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800326 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ true);
Hungming Chen56c632c2020-09-10 15:42:58 +0800327}
328
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800329DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream6_rawip$4_14",
330 AID_ROOT, AID_NETWORK_STACK,
331 sched_cls_tether_upstream6_rawip_4_14,
332 KVER(4, 14, 0), KVER(5, 4, 0))
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800333(struct __sk_buff* skb) {
Maciej Żenczykowskibf8ec1a2021-01-24 19:56:39 -0800334 return do_forward6(skb, /* is_ethernet */ false, /* downstream */ false);
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800335}
336
337// and define no-op stubs for [4.9,4.14) and unpatched [4.14,5.4) kernels.
Hungming Chen56c632c2020-09-10 15:42:58 +0800338// (if the above real 4.14+ program loaded successfully, then bpfloader will have already pinned
339// 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 -0800340DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream6_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowski770e0a72021-01-18 20:14:03 -0800341 sched_cls_tether_downstream6_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Hungming Chen56c632c2020-09-10 15:42:58 +0800342(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700343 return TC_ACT_PIPE;
Hungming Chen56c632c2020-09-10 15:42:58 +0800344}
345
Maciej Żenczykowski5b00fbd2021-01-19 23:37:51 -0800346DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream6_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800347 sched_cls_tether_upstream6_rawip_stub, KVER_NONE, KVER(5, 4, 0))
348(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700349 return TC_ACT_PIPE;
Maciej Żenczykowskibca0c852021-01-19 01:22:17 -0800350}
351
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800352// ----- IPv4 Support -----
353
Maciej Żenczykowski8549af92021-02-25 19:11:34 -0800354DEFINE_BPF_MAP_GRW(tether_downstream4_map, HASH, Tether4Key, Tether4Value, 1024, AID_NETWORK_STACK)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800355
Maciej Żenczykowski8549af92021-02-25 19:11:34 -0800356DEFINE_BPF_MAP_GRW(tether_upstream4_map, HASH, Tether4Key, Tether4Value, 1024, AID_NETWORK_STACK)
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800357
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800358static inline __always_inline int do_forward4(struct __sk_buff* skb, const bool is_ethernet,
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800359 const bool downstream, const bool updatetime) {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800360 // Require ethernet dst mac address to be our unicast address.
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700361 if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800362
363 // Must be meta-ethernet IPv4 frame
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700364 if (skb->protocol != htons(ETH_P_IP)) return TC_ACT_PIPE;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800365
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800366 const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
367
368 // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
369 // not trigger and thus we need to manually make sure we can read packet headers via DPA.
370 // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
371 // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
Maciej Żenczykowski824fb292022-04-11 23:29:46 -0700372 try_make_writable(skb, l2_header_size + IP4_HLEN + TCP_HLEN);
Maciej Żenczykowski8e69ec12021-03-07 07:06:13 -0800373
374 void* data = (void*)(long)skb->data;
375 const void* data_end = (void*)(long)skb->data_end;
376 struct ethhdr* eth = is_ethernet ? data : NULL; // used iff is_ethernet
377 struct iphdr* ip = is_ethernet ? (void*)(eth + 1) : data;
378
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800379 // Must have (ethernet and) ipv4 header
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700380 if (data + l2_header_size + sizeof(*ip) > data_end) return TC_ACT_PIPE;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800381
382 // Ethertype - if present - must be IPv4
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700383 if (is_ethernet && (eth->h_proto != htons(ETH_P_IP))) return TC_ACT_PIPE;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800384
385 // IP version must be 4
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800386 if (ip->version != 4) TC_PUNT(INVALID_IP_VERSION);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800387
388 // We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800389 if (ip->ihl != 5) TC_PUNT(HAS_IP_OPTIONS);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800390
391 // Calculate the IPv4 one's complement checksum of the IPv4 header.
392 __wsum sum4 = 0;
393 for (int i = 0; i < sizeof(*ip) / sizeof(__u16); ++i) {
394 sum4 += ((__u16*)ip)[i];
395 }
396 // Note that sum4 is guaranteed to be non-zero by virtue of ip4->version == 4
397 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE
398 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16
399 // for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800400 if (sum4 != 0xFFFF) TC_PUNT(CHECKSUM);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800401
402 // Minimum IPv4 total length is the size of the header
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800403 if (ntohs(ip->tot_len) < sizeof(*ip)) TC_PUNT(TRUNCATED_IPV4);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800404
405 // We are incapable of dealing with IPv4 fragments
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800406 if (ip->frag_off & ~htons(IP_DF)) TC_PUNT(IS_IP_FRAG);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800407
408 // Cannot decrement during forward if already zero or would be zero,
409 // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800410 if (ip->ttl <= 1) TC_PUNT(LOW_TTL);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800411
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800412 // If we cannot update the 'last_used' field due to lack of bpf_ktime_get_boot_ns() helper,
413 // then it is not safe to offload UDP due to the small conntrack timeouts, as such,
414 // in such a situation we can only support TCP. This also has the added nice benefit of
415 // using a separate error counter, and thus making it obvious which version of the program
416 // is loaded.
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800417 if (!updatetime && ip->protocol != IPPROTO_TCP) TC_PUNT(NON_TCP);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800418
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800419 // We do not support offloading anything besides IPv4 TCP and UDP, due to need for NAT,
420 // but no need to check this if !updatetime due to check immediately above.
421 if (updatetime && (ip->protocol != IPPROTO_TCP) && (ip->protocol != IPPROTO_UDP))
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800422 TC_PUNT(NON_TCP_UDP);
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800423
424 // We want to make sure that the compiler will, in the !updatetime case, entirely optimize
425 // out all the non-tcp logic. Also note that at this point is_udp === !is_tcp.
426 const bool is_tcp = !updatetime || (ip->protocol == IPPROTO_TCP);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800427
Maciej Żenczykowski82ee26b2021-02-16 16:10:08 -0800428 // This is a bit of a hack to make things easier on the bpf verifier.
429 // (In particular I believe the Linux 4.14 kernel's verifier can get confused later on about
430 // what offsets into the packet are valid and can spuriously reject the program, this is
431 // because it fails to realize that is_tcp && !is_tcp is impossible)
432 //
433 // For both TCP & UDP we'll need to read and modify the src/dst ports, which so happen to
434 // always be in the first 4 bytes of the L4 header. Additionally for UDP we'll need access
435 // to the checksum field which is in bytes 7 and 8. While for TCP we'll need to read the
436 // TCP flags (at offset 13) and access to the checksum field (2 bytes at offset 16).
437 // As such we *always* need access to at least 8 bytes.
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800438 if (data + l2_header_size + sizeof(*ip) + 8 > data_end) TC_PUNT(SHORT_L4_HEADER);
Maciej Żenczykowski82ee26b2021-02-16 16:10:08 -0800439
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800440 struct tcphdr* tcph = is_tcp ? (void*)(ip + 1) : NULL;
441 struct udphdr* udph = is_tcp ? NULL : (void*)(ip + 1);
442
443 if (is_tcp) {
444 // Make sure we can get at the tcp header
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800445 if (data + l2_header_size + sizeof(*ip) + sizeof(*tcph) > data_end)
446 TC_PUNT(SHORT_TCP_HEADER);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800447
448 // If hardware offload is running and programming flows based on conntrack entries, try not
449 // 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 -0800450 if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCP_CONTROL_PACKET);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800451 } else { // UDP
452 // Make sure we can get at the udp header
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800453 if (data + l2_header_size + sizeof(*ip) + sizeof(*udph) > data_end)
454 TC_PUNT(SHORT_UDP_HEADER);
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800455
456 // Skip handling of CHECKSUM_COMPLETE packets with udp checksum zero due to need for
457 // additional updating of skb->csum (this could be fixed up manually with more effort).
458 //
459 // Note that the in-kernel implementation of 'int64_t bpf_csum_update(skb, u32 csum)' is:
460 // if (skb->ip_summed == CHECKSUM_COMPLETE)
461 // return (skb->csum = csum_add(skb->csum, csum));
462 // else
463 // return -ENOTSUPP;
464 //
465 // So this will punt any CHECKSUM_COMPLETE packet with a zero UDP checksum,
466 // and leave all other packets unaffected (since it just at most adds zero to skb->csum).
467 //
468 // In practice this should almost never trigger because most nics do not generate
469 // CHECKSUM_COMPLETE packets on receive - especially so for nics/drivers on a phone.
470 //
471 // Additionally since we're forwarding, in most cases the value of the skb->csum field
472 // shouldn't matter (it's not used by physical nic egress).
473 //
474 // It only matters if we're ingressing through a CHECKSUM_COMPLETE capable nic
475 // and egressing through a virtual interface looping back to the kernel itself
476 // (ie. something like veth) where the CHECKSUM_COMPLETE/skb->csum can get reused
477 // on ingress.
478 //
479 // If we were in the kernel we'd simply probably call
480 // void skb_checksum_complete_unset(struct sk_buff *skb) {
481 // if (skb->ip_summed == CHECKSUM_COMPLETE) skb->ip_summed = CHECKSUM_NONE;
482 // }
483 // here instead. Perhaps there should be a bpf helper for that?
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800484 if (!udph->check && (bpf_csum_update(skb, 0) >= 0)) TC_PUNT(UDP_CSUM_ZERO);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800485 }
486
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800487 Tether4Key k = {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800488 .iif = skb->ifindex,
489 .l4Proto = ip->protocol,
490 .src4.s_addr = ip->saddr,
491 .dst4.s_addr = ip->daddr,
492 .srcPort = is_tcp ? tcph->source : udph->source,
493 .dstPort = is_tcp ? tcph->dest : udph->dest,
494 };
Maciej Żenczykowski62733f52021-04-01 21:51:41 -0700495 if (is_ethernet) __builtin_memcpy(k.dstMac, eth->h_dest, ETH_ALEN);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800496
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800497 Tether4Value* v = downstream ? bpf_tether_downstream4_map_lookup_elem(&k)
498 : bpf_tether_upstream4_map_lookup_elem(&k);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800499
500 // If we don't find any offload information then simply let the core stack handle it...
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700501 if (!v) return TC_ACT_PIPE;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800502
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800503 uint32_t stat_and_limit_k = downstream ? skb->ifindex : v->oif;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800504
505 TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
506
507 // If we don't have anywhere to put stats, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800508 if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800509
510 uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
511
512 // If we don't have a limit, then abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800513 if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800514
515 // Required IPv4 minimum mtu is 68, below that not clear what we should do, abort...
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800516 if (v->pmtu < 68) TC_PUNT(BELOW_IPV4_MTU);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800517
518 // Approximate handling of TCP/IPv4 overhead for incoming LRO/GRO packets: default
519 // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
520 // undercount, which is still better then not accounting for this overhead at all.
521 // Note: this really shouldn't be device/path mtu at all, but rather should be
522 // derived from this particular connection's mss (ie. from gro segment size).
523 // This would require a much newer kernel with newer ebpf accessors.
524 // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
525 uint64_t packets = 1;
526 uint64_t bytes = skb->len;
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800527 if (bytes > v->pmtu) {
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800528 const int tcp_overhead = sizeof(struct iphdr) + sizeof(struct tcphdr) + 12;
Maciej Żenczykowski1feb8b42021-01-25 12:01:31 -0800529 const int mss = v->pmtu - tcp_overhead;
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800530 const uint64_t payload = bytes - tcp_overhead;
531 packets = (payload + mss - 1) / mss;
532 bytes = tcp_overhead * packets + payload;
533 }
534
535 // Are we past the limit? If so, then abort...
536 // Note: will not overflow since u64 is 936 years even at 5Gbps.
537 // Do not drop here. Offload is just that, whenever we fail to handle
538 // a packet we let the core stack deal with things.
539 // (The core stack needs to handle limits correctly anyway,
540 // since we don't offload all traffic in both directions)
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800541 if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800542
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800543 if (!is_ethernet) {
544 // Try to inject an ethernet header, and simply return if we fail.
545 // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
546 // because this is easier and the kernel will strip extraneous ethernet header.
547 if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
548 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800549 TC_PUNT(CHANGE_HEAD_FAILED);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800550 }
551
552 // bpf_skb_change_head() invalidates all pointers - reload them
553 data = (void*)(long)skb->data;
554 data_end = (void*)(long)skb->data_end;
555 eth = data;
556 ip = (void*)(eth + 1);
557 tcph = is_tcp ? (void*)(ip + 1) : NULL;
558 udph = is_tcp ? NULL : (void*)(ip + 1);
559
560 // I do not believe this can ever happen, but keep the verifier happy...
561 if (data + sizeof(struct ethhdr) + sizeof(*ip) + (is_tcp ? sizeof(*tcph) : sizeof(*udph)) > data_end) {
562 __sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
Maciej Żenczykowskie982f092021-02-04 20:26:26 -0800563 TC_DROP(TOO_SHORT);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800564 }
565 };
566
567 // At this point we always have an ethernet header - which will get stripped by the
568 // kernel during transmit through a rawip interface. ie. 'eth' pointer is valid.
569 // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
570
571 // Overwrite any mac header with the new one
572 // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
573 *eth = v->macHeader;
574
Maciej Żenczykowskic29af792021-07-02 01:54:04 -0700575 // Decrement the IPv4 TTL, we already know it's greater than 1.
576 // u8 TTL field is followed by u8 protocol to make a u16 for ipv4 header checksum update.
577 // Since we're keeping the ipv4 checksum valid (which means the checksum of the entire
578 // ipv4 header remains 0), the overall checksum of the entire packet does not change.
579 const int sz2 = sizeof(__be16);
580 const __be16 old_ttl_proto = *(__be16 *)&ip->ttl;
581 const __be16 new_ttl_proto = old_ttl_proto - htons(0x0100);
582 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_ttl_proto, new_ttl_proto, sz2);
583 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(ttl), &new_ttl_proto, sz2, 0);
584
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800585 const int l4_offs_csum = is_tcp ? ETH_IP4_TCP_OFFSET(check) : ETH_IP4_UDP_OFFSET(check);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800586 const int sz4 = sizeof(__be32);
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800587 // UDP 0 is special and stored as FFFF (this flag also causes a csum of 0 to be unmodified)
588 const int l4_flags = is_tcp ? 0 : BPF_F_MARK_MANGLED_0;
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800589 const __be32 old_daddr = k.dst4.s_addr;
590 const __be32 old_saddr = k.src4.s_addr;
591 const __be32 new_daddr = v->dst46.s6_addr32[3];
592 const __be32 new_saddr = v->src46.s6_addr32[3];
593
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800594 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 -0800595 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_daddr, new_daddr, sz4);
596 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(daddr), &new_daddr, sz4, 0);
597
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800598 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 -0800599 bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_saddr, new_saddr, sz4);
600 bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(saddr), &new_saddr, sz4, 0);
601
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800602 // The offsets for TCP and UDP ports: source (u16 @ L4 offset 0) & dest (u16 @ L4 offset 2) are
603 // actually the same, so the compiler should just optimize them both down to a constant.
604 bpf_l4_csum_replace(skb, l4_offs_csum, k.srcPort, v->srcPort, sz2 | l4_flags);
605 bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(source) : ETH_IP4_UDP_OFFSET(source),
606 &v->srcPort, sz2, 0);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800607
Maciej Żenczykowskie4a726a2021-02-16 17:27:34 -0800608 bpf_l4_csum_replace(skb, l4_offs_csum, k.dstPort, v->dstPort, sz2 | l4_flags);
609 bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(dest) : ETH_IP4_UDP_OFFSET(dest),
610 &v->dstPort, sz2, 0);
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800611
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800612 // This requires the bpf_ktime_get_boot_ns() helper which was added in 5.8,
613 // and backported to all Android Common Kernel 4.14+ trees.
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800614 if (updatetime) v->last_used = bpf_ktime_get_boot_ns();
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800615
616 __sync_fetch_and_add(downstream ? &stat_v->rxPackets : &stat_v->txPackets, packets);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800617 __sync_fetch_and_add(downstream ? &stat_v->rxBytes : &stat_v->txBytes, bytes);
618
Maciej Żenczykowskiec5f67d2021-01-25 02:32:01 -0800619 // Redirect to forwarded interface.
620 //
621 // Note that bpf_redirect() cannot fail unless you pass invalid flags.
622 // The redirect actually happens after the ebpf program has already terminated,
623 // and can fail for example for mtu reasons at that point in time, but there's nothing
624 // we can do about it here.
625 return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800626}
627
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800628// Full featured (required) implementations for 5.8+ kernels (these are S+ by definition)
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800629
Maciej Żenczykowskib0ac41f2021-02-14 21:34:03 -0800630DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_rawip$5_8", AID_ROOT, AID_NETWORK_STACK,
631 sched_cls_tether_downstream4_rawip_5_8, KVER(5, 8, 0))
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800632(struct __sk_buff* skb) {
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800633 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ true);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800634}
635
Maciej Żenczykowskib0ac41f2021-02-14 21:34:03 -0800636DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_rawip$5_8", AID_ROOT, AID_NETWORK_STACK,
637 sched_cls_tether_upstream4_rawip_5_8, KVER(5, 8, 0))
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800638(struct __sk_buff* skb) {
Maciej Żenczykowskiaefa0952021-02-14 23:15:19 -0800639 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ true);
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800640}
641
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800642DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_ether$5_8", AID_ROOT, AID_NETWORK_STACK,
643 sched_cls_tether_downstream4_ether_5_8, KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800644(struct __sk_buff* skb) {
645 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ true);
646}
647
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800648DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_ether$5_8", AID_ROOT, AID_NETWORK_STACK,
649 sched_cls_tether_upstream4_ether_5_8, KVER(5, 8, 0))
650(struct __sk_buff* skb) {
651 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ true);
652}
653
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800654// Full featured (optional) implementations for 4.14-S, 4.19-S & 5.4-S kernels
655// (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 -0800656
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800657DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$opt",
658 AID_ROOT, AID_NETWORK_STACK,
659 sched_cls_tether_downstream4_rawip_opt,
660 KVER(4, 14, 0), KVER(5, 8, 0))
661(struct __sk_buff* skb) {
662 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ true);
663}
664
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800665DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$opt",
666 AID_ROOT, AID_NETWORK_STACK,
667 sched_cls_tether_upstream4_rawip_opt,
668 KVER(4, 14, 0), KVER(5, 8, 0))
669(struct __sk_buff* skb) {
670 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ true);
671}
672
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800673DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$opt",
674 AID_ROOT, AID_NETWORK_STACK,
675 sched_cls_tether_downstream4_ether_opt,
676 KVER(4, 14, 0), KVER(5, 8, 0))
677(struct __sk_buff* skb) {
678 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ true);
679}
680
681DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$opt",
682 AID_ROOT, AID_NETWORK_STACK,
683 sched_cls_tether_upstream4_ether_opt,
684 KVER(4, 14, 0), KVER(5, 8, 0))
685(struct __sk_buff* skb) {
686 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ true);
687}
688
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800689// Partial (TCP-only: will not update 'last_used' field) implementations for 4.14+ kernels.
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800690// These will be loaded only if the above optional ones failed (loading of *these* must succeed
691// for 5.4+, since that is always an R patched kernel).
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800692//
693// [Note: as a result TCP connections will not have their conntrack timeout refreshed, however,
694// since /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established defaults to 432000 (seconds),
695// this in practice means they'll break only after 5 days. This seems an acceptable trade-off.
696//
697// Additionally kernel/tests change "net-test: add bpf_ktime_get_ns / bpf_ktime_get_boot_ns tests"
698// which enforces and documents the required kernel cherrypicks will make it pretty unlikely that
699// many devices upgrading to S will end up relying on these fallback programs.
700
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800701// RAWIP: Required for 5.4-R kernels -- which always support bpf_skb_change_head().
702
703DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
704 sched_cls_tether_downstream4_rawip_5_4, KVER(5, 4, 0), KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800705(struct __sk_buff* skb) {
706 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ false);
707}
708
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800709DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
710 sched_cls_tether_upstream4_rawip_5_4, KVER(5, 4, 0), KVER(5, 8, 0))
Maciej Żenczykowski36867352021-02-15 01:53:17 -0800711(struct __sk_buff* skb) {
712 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ false);
713}
714
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800715// RAWIP: Optional for 4.14/4.19 (R) kernels -- which support bpf_skb_change_head().
716// [Note: fallback for 4.14/4.19 (P/Q) kernels is below in stub section]
717
718DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$4_14",
719 AID_ROOT, AID_NETWORK_STACK,
720 sched_cls_tether_downstream4_rawip_4_14,
721 KVER(4, 14, 0), KVER(5, 4, 0))
722(struct __sk_buff* skb) {
723 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ true, /* updatetime */ false);
724}
725
726DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$4_14",
727 AID_ROOT, AID_NETWORK_STACK,
728 sched_cls_tether_upstream4_rawip_4_14,
729 KVER(4, 14, 0), KVER(5, 4, 0))
730(struct __sk_buff* skb) {
731 return do_forward4(skb, /* is_ethernet */ false, /* downstream */ false, /* updatetime */ false);
732}
733
734// ETHER: Required for 4.14-Q/R, 4.19-Q/R & 5.4-R kernels.
735
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800736DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$4_14", AID_ROOT, AID_NETWORK_STACK,
737 sched_cls_tether_downstream4_ether_4_14, KVER(4, 14, 0), KVER(5, 8, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800738(struct __sk_buff* skb) {
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800739 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ true, /* updatetime */ false);
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800740}
741
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800742DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$4_14", AID_ROOT, AID_NETWORK_STACK,
743 sched_cls_tether_upstream4_ether_4_14, KVER(4, 14, 0), KVER(5, 8, 0))
744(struct __sk_buff* skb) {
745 return do_forward4(skb, /* is_ethernet */ true, /* downstream */ false, /* updatetime */ false);
746}
747
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800748// Placeholder (no-op) implementations for older Q kernels
749
750// 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 -0800751
Maciej Żenczykowskic2b01462021-01-24 21:01:29 -0800752DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800753 sched_cls_tether_downstream4_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800754(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700755 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800756}
757
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800758DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800759 sched_cls_tether_upstream4_rawip_stub, KVER_NONE, KVER(5, 4, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800760(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700761 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800762}
763
Maciej Żenczykowskiacddd4f2021-03-09 21:43:48 -0800764// ETHER: 4.9-P/Q kernel
765
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800766DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$stub", AID_ROOT, AID_NETWORK_STACK,
767 sched_cls_tether_downstream4_ether_stub, KVER_NONE, KVER(4, 14, 0))
768(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700769 return TC_ACT_PIPE;
Maciej Żenczykowski2278aed2021-03-09 21:19:52 -0800770}
771
772DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$stub", AID_ROOT, AID_NETWORK_STACK,
773 sched_cls_tether_upstream4_ether_stub, KVER_NONE, KVER(4, 14, 0))
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800774(struct __sk_buff* skb) {
Maciej Żenczykowski6e66a362021-08-24 15:43:15 -0700775 return TC_ACT_PIPE;
Maciej Żenczykowski088fe192021-01-20 13:34:17 -0800776}
777
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800778// ----- XDP Support -----
779
Hungming Chen3feb7822021-05-11 21:07:18 +0800780DEFINE_BPF_MAP_GRW(tether_dev_map, DEVMAP_HASH, uint32_t, uint32_t, 64, AID_NETWORK_STACK)
Maciej Żenczykowskidb2cff52021-03-01 21:22:49 -0800781
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800782static inline __always_inline int do_xdp_forward6(struct xdp_md *ctx, const bool is_ethernet,
783 const bool downstream) {
784 return XDP_PASS;
785}
786
787static inline __always_inline int do_xdp_forward4(struct xdp_md *ctx, const bool is_ethernet,
788 const bool downstream) {
789 return XDP_PASS;
790}
791
792static inline __always_inline int do_xdp_forward_ether(struct xdp_md *ctx, const bool downstream) {
793 const void* data = (void*)(long)ctx->data;
794 const void* data_end = (void*)(long)ctx->data_end;
795 const struct ethhdr* eth = data;
796
797 // Make sure we actually have an ethernet header
798 if ((void*)(eth + 1) > data_end) return XDP_PASS;
799
800 if (eth->h_proto == htons(ETH_P_IPV6))
801 return do_xdp_forward6(ctx, /* is_ethernet */ true, downstream);
802 if (eth->h_proto == htons(ETH_P_IP))
803 return do_xdp_forward4(ctx, /* is_ethernet */ true, downstream);
804
805 // Anything else we don't know how to handle...
806 return XDP_PASS;
807}
808
809static inline __always_inline int do_xdp_forward_rawip(struct xdp_md *ctx, const bool downstream) {
810 const void* data = (void*)(long)ctx->data;
811 const void* data_end = (void*)(long)ctx->data_end;
812
813 // The top nibble of both IPv4 and IPv6 headers is the IP version.
814 if (data_end - data < 1) return XDP_PASS;
815 const uint8_t v = (*(uint8_t*)data) >> 4;
816
817 if (v == 6) return do_xdp_forward6(ctx, /* is_ethernet */ false, downstream);
818 if (v == 4) return do_xdp_forward4(ctx, /* is_ethernet */ false, downstream);
819
820 // Anything else we don't know how to handle...
821 return XDP_PASS;
822}
823
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800824#define DEFINE_XDP_PROG(str, func) \
825 DEFINE_BPF_PROG_KVER(str, AID_ROOT, AID_NETWORK_STACK, func, KVER(5, 9, 0))(struct xdp_md *ctx)
826
827DEFINE_XDP_PROG("xdp/tether_downstream_ether",
828 xdp_tether_downstream_ether) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800829 return do_xdp_forward_ether(ctx, /* downstream */ true);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800830}
831
832DEFINE_XDP_PROG("xdp/tether_downstream_rawip",
833 xdp_tether_downstream_rawip) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800834 return do_xdp_forward_rawip(ctx, /* downstream */ true);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800835}
836
837DEFINE_XDP_PROG("xdp/tether_upstream_ether",
838 xdp_tether_upstream_ether) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800839 return do_xdp_forward_ether(ctx, /* downstream */ false);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800840}
841
842DEFINE_XDP_PROG("xdp/tether_upstream_rawip",
843 xdp_tether_upstream_rawip) {
Maciej Żenczykowski90b81ac2021-03-07 06:48:26 -0800844 return do_xdp_forward_rawip(ctx, /* downstream */ false);
Maciej Żenczykowskib1997422021-01-20 14:31:50 -0800845}
846
Hungming Chen56c632c2020-09-10 15:42:58 +0800847LICENSE("Apache 2.0");
Maciej Żenczykowski607d6dd2021-02-25 19:09:47 -0800848CRITICAL("tethering");