• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 // The resulting .o needs to load on Android S+
18 #define BPFLOADER_MIN_VER BPFLOADER_MAINLINE_S_VERSION
19 
20 #include "bpf_net_helpers.h"
21 #include "offload.h"
22 
23 // ----- Tethering Error Counters -----
24 
25 // Note that pre-T devices with Mediatek chipsets may have a kernel bug (bad patch
26 // "[ALPS05162612] bpf: fix ubsan error") making it impossible to write to non-zero
27 // offset of bpf map ARRAYs.  This file (offload.o) loads on S+, but luckily this
28 // array is only written by bpf code, and only read by userspace.
DEFINE_BPF_MAP_RO(tether_error_map,ARRAY,uint32_t,uint32_t,BPF_TETHER_ERR__MAX,AID_NETWORK_STACK)29 DEFINE_BPF_MAP_RO(tether_error_map, ARRAY, uint32_t, uint32_t, BPF_TETHER_ERR__MAX, AID_NETWORK_STACK)
30 
31 #define COUNT_AND_RETURN(counter, ret) do {                     \
32     uint32_t code = BPF_TETHER_ERR_ ## counter;                 \
33     uint32_t *count = bpf_tether_error_map_lookup_elem(&code);  \
34     if (count) __sync_fetch_and_add(count, 1);                  \
35     return ret;                                                 \
36 } while(0)
37 
38 #define TC_DROP(counter) COUNT_AND_RETURN(counter, TC_ACT_SHOT)
39 #define TC_PUNT(counter) COUNT_AND_RETURN(counter, TC_ACT_PIPE)
40 
41 #define XDP_DROP(counter) COUNT_AND_RETURN(counter, XDP_DROP)
42 #define XDP_PUNT(counter) COUNT_AND_RETURN(counter, XDP_PASS)
43 
44 // ----- Tethering Data Stats and Limits -----
45 
46 // Tethering stats, indexed by upstream interface.
47 DEFINE_BPF_MAP_GRW(tether_stats_map, HASH, TetherStatsKey, TetherStatsValue, 16, AID_NETWORK_STACK)
48 
49 // Tethering data limit, indexed by upstream interface.
50 // (tethering allowed when stats[iif].rxBytes + stats[iif].txBytes < limit[iif])
51 DEFINE_BPF_MAP_GRW(tether_limit_map, HASH, TetherLimitKey, TetherLimitValue, 16, AID_NETWORK_STACK)
52 
53 // ----- IPv6 Support -----
54 
55 DEFINE_BPF_MAP_GRW(tether_downstream6_map, HASH, TetherDownstream6Key, Tether6Value, 64,
56                    AID_NETWORK_STACK)
57 
58 DEFINE_BPF_MAP_GRW(tether_downstream64_map, HASH, TetherDownstream64Key, TetherDownstream64Value,
59                    1024, AID_NETWORK_STACK)
60 
61 DEFINE_BPF_MAP_GRW(tether_upstream6_map, HASH, TetherUpstream6Key, Tether6Value, 64,
62                    AID_NETWORK_STACK)
63 
64 static inline __always_inline int do_forward6(struct __sk_buff* skb,
65                                               const struct rawip_bool rawip,
66                                               const struct stream_bool stream,
67                                               __unused const struct kver_uint kver) {
68     const bool is_ethernet = !rawip.rawip;
69 
70     // Must be meta-ethernet IPv6 frame
71     if (skb->protocol != htons(ETH_P_IPV6)) return TC_ACT_PIPE;
72 
73     // Require ethernet dst mac address to be our unicast address.
74     if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
75 
76     const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
77 
78     // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
79     // not trigger and thus we need to manually make sure we can read packet headers via DPA.
80     // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
81     if (bpf_skb_pull_data(skb, l2_header_size + IP6_HLEN)) return TC_ACT_PIPE;
82 
83     void* data = (void*)(long)skb->data;
84     const void* data_end = (void*)(long)skb->data_end;
85     struct ethhdr* eth = is_ethernet ? data : NULL;  // used iff is_ethernet
86     struct ipv6hdr* ip6 = is_ethernet ? (void*)(eth + 1) : data;
87 
88     // Must have (ethernet and) ipv6 header
89     if (data + l2_header_size + sizeof(*ip6) > data_end) return TC_ACT_PIPE;
90 
91     // Ethertype - if present - must be IPv6
92     if (is_ethernet && (eth->h_proto != htons(ETH_P_IPV6))) return TC_ACT_PIPE;
93 
94     // IP version must be 6
95     if (ip6->version != 6) TC_PUNT(INVALID_IPV6_VERSION);
96 
97     // Cannot decrement during forward if already zero or would be zero,
98     // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
99     if (ip6->hop_limit <= 1) TC_PUNT(LOW_TTL);
100 
101     // If hardware offload is running and programming flows based on conntrack entries,
102     // try not to interfere with it.
103     if (ip6->nexthdr == IPPROTO_TCP) {
104         // don't need to check return code, as it's effectively checked in the next 'if' below
105         bpf_skb_pull_data(skb, l2_header_size + IP6_HLEN + TCP_HLEN);
106 
107         data = (void*)(long)skb->data;
108         data_end = (void*)(long)skb->data_end;
109         eth = is_ethernet ? data : NULL;  // used iff is_ethernet
110         ip6 = is_ethernet ? (void*)(eth + 1) : data;
111 
112         struct tcphdr* tcph = (void*)(ip6 + 1);
113 
114         // Make sure we can get at the tcp header
115         if (data + l2_header_size + sizeof(*ip6) + sizeof(*tcph) > data_end)
116             TC_PUNT(INVALID_TCP_HEADER);
117 
118         // Do not offload TCP packets with any one of the SYN/FIN/RST flags
119         if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCPV6_CONTROL_PACKET);
120     }
121 
122     // Protect against forwarding packets sourced from ::1 or fe80::/64 or other weirdness.
123     __be32 src32 = ip6->saddr.s6_addr32[0];
124     if (src32 != htonl(0x0064ff9b) &&                        // 64:ff9b:/32 incl. XLAT464 WKP
125         (src32 & htonl(0xe0000000)) != htonl(0x20000000))    // 2000::/3 Global Unicast
126         TC_PUNT(NON_GLOBAL_SRC);
127 
128     // Protect against forwarding packets destined to ::1 or fe80::/64 or other weirdness.
129     __be32 dst32 = ip6->daddr.s6_addr32[0];
130     if (dst32 != htonl(0x0064ff9b) &&                        // 64:ff9b:/32 incl. XLAT464 WKP
131         (dst32 & htonl(0xe0000000)) != htonl(0x20000000))    // 2000::/3 Global Unicast
132         TC_PUNT(NON_GLOBAL_DST);
133 
134     // In the upstream direction do not forward traffic within the same /64 subnet.
135     if (!stream.down && (src32 == dst32) && (ip6->saddr.s6_addr32[1] == ip6->daddr.s6_addr32[1]))
136         TC_PUNT(LOCAL_SRC_DST);
137 
138     TetherDownstream6Key kd = {
139             .iif = skb->ifindex,
140             .neigh6 = ip6->daddr,
141     };
142 
143     TetherUpstream6Key ku = {
144             .iif = skb->ifindex,
145             // Retrieve the first 64 bits of the source IPv6 address in network order
146             .src64 = *(uint64_t*)&(ip6->saddr.s6_addr32[0]),
147     };
148     if (is_ethernet) __builtin_memcpy(stream.down ? kd.dstMac : ku.dstMac, eth->h_dest, ETH_ALEN);
149 
150     Tether6Value* v = stream.down ? bpf_tether_downstream6_map_lookup_elem(&kd)
151                                   : bpf_tether_upstream6_map_lookup_elem(&ku);
152 
153     // If we don't find any offload information then simply let the core stack handle it...
154     if (!v) return TC_ACT_PIPE;
155 
156     uint32_t stat_and_limit_k = stream.down ? skb->ifindex : v->oif;
157 
158     TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
159 
160     // If we don't have anywhere to put stats, then abort...
161     if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
162 
163     uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
164 
165     // If we don't have a limit, then abort...
166     if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
167 
168     // Required IPv6 minimum mtu is 1280, below that not clear what we should do, abort...
169     if (v->pmtu < IPV6_MIN_MTU) TC_PUNT(BELOW_IPV6_MTU);
170 
171     // Approximate handling of TCP/IPv6 overhead for incoming LRO/GRO packets: default
172     // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
173     // undercount, which is still better then not accounting for this overhead at all.
174     // Note: this really shouldn't be device/path mtu at all, but rather should be
175     // derived from this particular connection's mss (ie. from gro segment size).
176     // This would require a much newer kernel with newer ebpf accessors.
177     // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
178     uint64_t packets = 1;
179     uint64_t L3_bytes = skb->len - l2_header_size;
180     if (L3_bytes > v->pmtu) {
181         const int tcp6_overhead = sizeof(struct ipv6hdr) + sizeof(struct tcphdr) + 12;
182         const int mss = v->pmtu - tcp6_overhead;
183         const uint64_t payload = L3_bytes - tcp6_overhead;
184         packets = (payload + mss - 1) / mss;
185         L3_bytes = tcp6_overhead * packets + payload;
186     }
187 
188     // Are we past the limit?  If so, then abort...
189     // Note: will not overflow since u64 is 936 years even at 5Gbps.
190     // Do not drop here.  Offload is just that, whenever we fail to handle
191     // a packet we let the core stack deal with things.
192     // (The core stack needs to handle limits correctly anyway,
193     // since we don't offload all traffic in both directions)
194     if (stat_v->rxBytes + stat_v->txBytes + L3_bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
195 
196     if (!is_ethernet) {
197         // Try to inject an ethernet header, and simply return if we fail.
198         // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
199         // because this is easier and the kernel will strip extraneous ethernet header.
200         if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
201             __sync_fetch_and_add(stream.down ? &stat_v->rxErrors : &stat_v->txErrors, 1);
202             TC_PUNT(CHANGE_HEAD_FAILED);
203         }
204 
205         // bpf_skb_change_head() invalidates all pointers - reload them
206         data = (void*)(long)skb->data;
207         data_end = (void*)(long)skb->data_end;
208         eth = data;
209         ip6 = (void*)(eth + 1);
210 
211         // I do not believe this can ever happen, but keep the verifier happy...
212         if (data + sizeof(struct ethhdr) + sizeof(*ip6) > data_end) {
213             __sync_fetch_and_add(stream.down ? &stat_v->rxErrors : &stat_v->txErrors, 1);
214             TC_DROP(TOO_SHORT);
215         }
216     };
217 
218     // At this point we always have an ethernet header - which will get stripped by the
219     // kernel during transmit through a rawip interface.  ie. 'eth' pointer is valid.
220     // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
221 
222     // CHECKSUM_COMPLETE is a 16-bit one's complement sum,
223     // thus corrections for it need to be done in 16-byte chunks at even offsets.
224     // IPv6 nexthdr is at offset 6, while hop limit is at offset 7
225     uint8_t old_hl = ip6->hop_limit;
226     --ip6->hop_limit;
227     uint8_t new_hl = ip6->hop_limit;
228 
229     // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
230     // (-ENOTSUPP) if it isn't.
231     bpf_csum_update(skb, 0xFFFF - ntohs(old_hl) + ntohs(new_hl));
232 
233     __sync_fetch_and_add(stream.down ? &stat_v->rxPackets : &stat_v->txPackets, packets);
234     __sync_fetch_and_add(stream.down ? &stat_v->rxBytes : &stat_v->txBytes, L3_bytes);
235 
236     // Overwrite any mac header with the new one
237     // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
238     *eth = v->macHeader;
239 
240     // Redirect to forwarded interface.
241     //
242     // Note that bpf_redirect() cannot fail unless you pass invalid flags.
243     // The redirect actually happens after the ebpf program has already terminated,
244     // and can fail for example for mtu reasons at that point in time, but there's nothing
245     // we can do about it here.
246     return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
247 }
248 
249 DEFINE_BPF_PROG("schedcls/tether_downstream6_ether", AID_ROOT, AID_NETWORK_STACK,
250                 sched_cls_tether_downstream6_ether)
251 (struct __sk_buff* skb) {
252     return do_forward6(skb, ETHER, DOWNSTREAM, KVER_NONE);
253 }
254 
255 DEFINE_BPF_PROG("schedcls/tether_upstream6_ether", AID_ROOT, AID_NETWORK_STACK,
256                 sched_cls_tether_upstream6_ether)
257 (struct __sk_buff* skb) {
258     return do_forward6(skb, ETHER, UPSTREAM, KVER_NONE);
259 }
260 
261 // Note: section names must be unique to prevent programs from appending to each other,
262 // so instead the bpf loader will strip everything past the final $ symbol when actually
263 // pinning the program into the filesystem.
264 //
265 // bpf_skb_change_head() is only present on 4.14+ and 2 trivial kernel patches are needed:
266 //   ANDROID: net: bpf: Allow TC programs to call BPF_FUNC_skb_change_head
267 //   ANDROID: net: bpf: permit redirect from ingress L3 to egress L2 devices at near max mtu
268 // (the first of those has already been upstreamed)
269 //
270 // These were added to 4.14+ Android Common Kernel in R (including the original release of ACK 5.4)
271 // and there is a test in kernel/tests/net/test/bpf_test.py testSkbChangeHead()
272 // and in system/netd/tests/binder_test.cpp NetdBinderTest TetherOffloadForwarding.
273 //
274 // Hence, these mandatory (must load successfully) implementations for 4.14+ kernels:
275 DEFINE_BPF_PROG_KVER("schedcls/tether_downstream6_rawip$4_14", AID_ROOT, AID_NETWORK_STACK,
276                      sched_cls_tether_downstream6_rawip_4_14, KVER_4_14)
277 (struct __sk_buff* skb) {
278     return do_forward6(skb, RAWIP, DOWNSTREAM, KVER_4_14);
279 }
280 
281 DEFINE_BPF_PROG_KVER("schedcls/tether_upstream6_rawip$4_14", AID_ROOT, AID_NETWORK_STACK,
282                      sched_cls_tether_upstream6_rawip_4_14, KVER_4_14)
283 (struct __sk_buff* skb) {
284     return do_forward6(skb, RAWIP, UPSTREAM, KVER_4_14);
285 }
286 
287 // and define no-op stubs for pre-4.14 kernels.
288 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream6_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
289                            sched_cls_tether_downstream6_rawip_stub, KVER_NONE, KVER_4_14)
290 (__unused struct __sk_buff* skb) {
291     return TC_ACT_PIPE;
292 }
293 
294 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream6_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
295                            sched_cls_tether_upstream6_rawip_stub, KVER_NONE, KVER_4_14)
296 (__unused struct __sk_buff* skb) {
297     return TC_ACT_PIPE;
298 }
299 
300 // ----- IPv4 Support -----
301 
302 DEFINE_BPF_MAP_GRW(tether_downstream4_map, HASH, Tether4Key, Tether4Value, 1024, AID_NETWORK_STACK)
303 
304 DEFINE_BPF_MAP_GRW(tether_upstream4_map, HASH, Tether4Key, Tether4Value, 1024, AID_NETWORK_STACK)
305 
do_forward4_bottom(struct __sk_buff * skb,const int l2_header_size,void * data,const void * data_end,struct ethhdr * eth,struct iphdr * ip,const struct rawip_bool rawip,const struct stream_bool stream,const struct updatetime_bool updatetime,const bool is_tcp,__unused const struct kver_uint kver)306 static inline __always_inline int do_forward4_bottom(struct __sk_buff* skb,
307         const int l2_header_size, void* data, const void* data_end,
308         struct ethhdr* eth, struct iphdr* ip, const struct rawip_bool rawip,
309         const struct stream_bool stream, const struct updatetime_bool updatetime,
310         const bool is_tcp, __unused const struct kver_uint kver) {
311     const bool is_ethernet = !rawip.rawip;
312     struct tcphdr* tcph = is_tcp ? (void*)(ip + 1) : NULL;
313     struct udphdr* udph = is_tcp ? NULL : (void*)(ip + 1);
314 
315     if (is_tcp) {
316         // Make sure we can get at the tcp header
317         if (data + l2_header_size + sizeof(*ip) + sizeof(*tcph) > data_end)
318             TC_PUNT(SHORT_TCP_HEADER);
319 
320         // If hardware offload is running and programming flows based on conntrack entries, try not
321         // to interfere with it, so do not offload TCP packets with any one of the SYN/FIN/RST flags
322         if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCPV4_CONTROL_PACKET);
323     } else { // UDP
324         // Make sure we can get at the udp header
325         if (data + l2_header_size + sizeof(*ip) + sizeof(*udph) > data_end)
326             TC_PUNT(SHORT_UDP_HEADER);
327 
328         // Skip handling of CHECKSUM_COMPLETE packets with udp checksum zero due to need for
329         // additional updating of skb->csum (this could be fixed up manually with more effort).
330         //
331         // Note that the in-kernel implementation of 'int64_t bpf_csum_update(skb, u32 csum)' is:
332         //   if (skb->ip_summed == CHECKSUM_COMPLETE)
333         //     return (skb->csum = csum_add(skb->csum, csum));
334         //   else
335         //     return -ENOTSUPP;
336         //
337         // So this will punt any CHECKSUM_COMPLETE packet with a zero UDP checksum,
338         // and leave all other packets unaffected (since it just at most adds zero to skb->csum).
339         //
340         // In practice this should almost never trigger because most nics do not generate
341         // CHECKSUM_COMPLETE packets on receive - especially so for nics/drivers on a phone.
342         //
343         // Additionally since we're forwarding, in most cases the value of the skb->csum field
344         // shouldn't matter (it's not used by physical nic egress).
345         //
346         // It only matters if we're ingressing through a CHECKSUM_COMPLETE capable nic
347         // and egressing through a virtual interface looping back to the kernel itself
348         // (ie. something like veth) where the CHECKSUM_COMPLETE/skb->csum can get reused
349         // on ingress.
350         //
351         // If we were in the kernel we'd simply probably call
352         //   void skb_checksum_complete_unset(struct sk_buff *skb) {
353         //     if (skb->ip_summed == CHECKSUM_COMPLETE) skb->ip_summed = CHECKSUM_NONE;
354         //   }
355         // here instead.  Perhaps there should be a bpf helper for that?
356         if (!udph->check && (bpf_csum_update(skb, 0) >= 0)) TC_PUNT(UDP_CSUM_ZERO);
357     }
358 
359     Tether4Key k = {
360             .iif = skb->ifindex,
361             .l4Proto = ip->protocol,
362             .src4.s_addr = ip->saddr,
363             .dst4.s_addr = ip->daddr,
364             .srcPort = is_tcp ? tcph->source : udph->source,
365             .dstPort = is_tcp ? tcph->dest : udph->dest,
366     };
367     if (is_ethernet) __builtin_memcpy(k.dstMac, eth->h_dest, ETH_ALEN);
368 
369     Tether4Value* v = stream.down ? bpf_tether_downstream4_map_lookup_elem(&k)
370                                   : bpf_tether_upstream4_map_lookup_elem(&k);
371 
372     // If we don't find any offload information then simply let the core stack handle it...
373     if (!v) return TC_ACT_PIPE;
374 
375     uint32_t stat_and_limit_k = stream.down ? skb->ifindex : v->oif;
376 
377     TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
378 
379     // If we don't have anywhere to put stats, then abort...
380     if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
381 
382     uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
383 
384     // If we don't have a limit, then abort...
385     if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
386 
387     // Required IPv4 minimum mtu is 68, below that not clear what we should do, abort...
388     if (v->pmtu < 68) TC_PUNT(BELOW_IPV4_MTU);
389 
390     // Approximate handling of TCP/IPv4 overhead for incoming LRO/GRO packets: default
391     // outbound path mtu of 1500 is not necessarily correct, but worst case we simply
392     // undercount, which is still better then not accounting for this overhead at all.
393     // Note: this really shouldn't be device/path mtu at all, but rather should be
394     // derived from this particular connection's mss (ie. from gro segment size).
395     // This would require a much newer kernel with newer ebpf accessors.
396     // (This is also blindly assuming 12 bytes of tcp timestamp option in tcp header)
397     uint64_t packets = 1;
398     uint64_t L3_bytes = skb->len - l2_header_size;
399     if (L3_bytes > v->pmtu) {
400         const int tcp4_overhead = sizeof(struct iphdr) + sizeof(struct tcphdr) + 12;
401         const int mss = v->pmtu - tcp4_overhead;
402         const uint64_t payload = L3_bytes - tcp4_overhead;
403         packets = (payload + mss - 1) / mss;
404         L3_bytes = tcp4_overhead * packets + payload;
405     }
406 
407     // Are we past the limit?  If so, then abort...
408     // Note: will not overflow since u64 is 936 years even at 5Gbps.
409     // Do not drop here.  Offload is just that, whenever we fail to handle
410     // a packet we let the core stack deal with things.
411     // (The core stack needs to handle limits correctly anyway,
412     // since we don't offload all traffic in both directions)
413     if (stat_v->rxBytes + stat_v->txBytes + L3_bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
414 
415     if (!is_ethernet) {
416         // Try to inject an ethernet header, and simply return if we fail.
417         // We do this even if TX interface is RAWIP and thus does not need an ethernet header,
418         // because this is easier and the kernel will strip extraneous ethernet header.
419         if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
420             __sync_fetch_and_add(stream.down ? &stat_v->rxErrors : &stat_v->txErrors, 1);
421             TC_PUNT(CHANGE_HEAD_FAILED);
422         }
423 
424         // bpf_skb_change_head() invalidates all pointers - reload them
425         data = (void*)(long)skb->data;
426         data_end = (void*)(long)skb->data_end;
427         eth = data;
428         ip = (void*)(eth + 1);
429         tcph = is_tcp ? (void*)(ip + 1) : NULL;
430         udph = is_tcp ? NULL : (void*)(ip + 1);
431 
432         // I do not believe this can ever happen, but keep the verifier happy...
433         if (data + sizeof(struct ethhdr) + sizeof(*ip) + (is_tcp ? sizeof(*tcph) : sizeof(*udph)) > data_end) {
434             __sync_fetch_and_add(stream.down ? &stat_v->rxErrors : &stat_v->txErrors, 1);
435             TC_DROP(TOO_SHORT);
436         }
437     };
438 
439     // At this point we always have an ethernet header - which will get stripped by the
440     // kernel during transmit through a rawip interface.  ie. 'eth' pointer is valid.
441     // Additionally note that 'is_ethernet' and 'l2_header_size' are no longer correct.
442 
443     // Overwrite any mac header with the new one
444     // For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
445     *eth = v->macHeader;
446 
447     // Decrement the IPv4 TTL, we already know it's greater than 1.
448     // u8 TTL field is followed by u8 protocol to make a u16 for ipv4 header checksum update.
449     // Since we're keeping the ipv4 checksum valid (which means the checksum of the entire
450     // ipv4 header remains 0), the overall checksum of the entire packet does not change.
451     const int sz2 = sizeof(__be16);
452     const __be16 old_ttl_proto = *(__be16 *)&ip->ttl;
453     const __be16 new_ttl_proto = old_ttl_proto - htons(0x0100);
454     bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_ttl_proto, new_ttl_proto, sz2);
455     bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(ttl), &new_ttl_proto, sz2, 0);
456 
457     const int l4_offs_csum = is_tcp ? ETH_IP4_TCP_OFFSET(check) : ETH_IP4_UDP_OFFSET(check);
458     const int sz4 = sizeof(__be32);
459     // UDP 0 is special and stored as FFFF (this flag also causes a csum of 0 to be unmodified)
460     const int l4_flags = is_tcp ? 0 : BPF_F_MARK_MANGLED_0;
461     const __be32 old_daddr = k.dst4.s_addr;
462     const __be32 old_saddr = k.src4.s_addr;
463     const __be32 new_daddr = v->dst46.s6_addr32[3];
464     const __be32 new_saddr = v->src46.s6_addr32[3];
465 
466     bpf_l4_csum_replace(skb, l4_offs_csum, old_daddr, new_daddr, sz4 | BPF_F_PSEUDO_HDR | l4_flags);
467     bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_daddr, new_daddr, sz4);
468     bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(daddr), &new_daddr, sz4, 0);
469 
470     bpf_l4_csum_replace(skb, l4_offs_csum, old_saddr, new_saddr, sz4 | BPF_F_PSEUDO_HDR | l4_flags);
471     bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_saddr, new_saddr, sz4);
472     bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(saddr), &new_saddr, sz4, 0);
473 
474     // The offsets for TCP and UDP ports: source (u16 @ L4 offset 0) & dest (u16 @ L4 offset 2) are
475     // actually the same, so the compiler should just optimize them both down to a constant.
476     bpf_l4_csum_replace(skb, l4_offs_csum, k.srcPort, v->srcPort, sz2 | l4_flags);
477     bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(source) : ETH_IP4_UDP_OFFSET(source),
478                         &v->srcPort, sz2, 0);
479 
480     bpf_l4_csum_replace(skb, l4_offs_csum, k.dstPort, v->dstPort, sz2 | l4_flags);
481     bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(dest) : ETH_IP4_UDP_OFFSET(dest),
482                         &v->dstPort, sz2, 0);
483 
484     // This requires the bpf_ktime_get_boot_ns() helper which was added in 5.8,
485     // and backported to all Android Common Kernel 4.14+ trees.
486     if (updatetime.updatetime) v->last_used = bpf_ktime_get_boot_ns();
487 
488     __sync_fetch_and_add(stream.down ? &stat_v->rxPackets : &stat_v->txPackets, packets);
489     __sync_fetch_and_add(stream.down ? &stat_v->rxBytes : &stat_v->txBytes, L3_bytes);
490 
491     // Redirect to forwarded interface.
492     //
493     // Note that bpf_redirect() cannot fail unless you pass invalid flags.
494     // The redirect actually happens after the ebpf program has already terminated,
495     // and can fail for example for mtu reasons at that point in time, but there's nothing
496     // we can do about it here.
497     return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
498 }
499 
do_forward4(struct __sk_buff * skb,const struct rawip_bool rawip,const struct stream_bool stream,const struct updatetime_bool updatetime,const struct kver_uint kver)500 static inline __always_inline int do_forward4(struct __sk_buff* skb,
501                                               const struct rawip_bool rawip,
502                                               const struct stream_bool stream,
503                                               const struct updatetime_bool updatetime,
504                                               const struct kver_uint kver) {
505     const bool is_ethernet = !rawip.rawip;
506 
507     // Require ethernet dst mac address to be our unicast address.
508     if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
509 
510     // Must be meta-ethernet IPv4 frame
511     if (skb->protocol != htons(ETH_P_IP)) return TC_ACT_PIPE;
512 
513     const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
514 
515     // Since the program never writes via DPA (direct packet access) auto-pull/unclone logic does
516     // not trigger and thus we need to manually make sure we can read packet headers via DPA.
517     // Note: this is a blind best effort pull, which may fail or pull less - this doesn't matter.
518     // It has to be done early cause it will invalidate any skb->data/data_end derived pointers.
519     try_make_writable(skb, l2_header_size + IP4_HLEN + TCP_HLEN);
520 
521     void* data = (void*)(long)skb->data;
522     const void* data_end = (void*)(long)skb->data_end;
523     struct ethhdr* eth = is_ethernet ? data : NULL;  // used iff is_ethernet
524     struct iphdr* ip = is_ethernet ? (void*)(eth + 1) : data;
525 
526     // Must have (ethernet and) ipv4 header
527     if (data + l2_header_size + sizeof(*ip) > data_end) return TC_ACT_PIPE;
528 
529     // Ethertype - if present - must be IPv4
530     if (is_ethernet && (eth->h_proto != htons(ETH_P_IP))) return TC_ACT_PIPE;
531 
532     // IP version must be 4
533     if (ip->version != 4) TC_PUNT(INVALID_IPV4_VERSION);
534 
535     // We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header
536     if (ip->ihl != 5) TC_PUNT(HAS_IP_OPTIONS);
537 
538     // Calculate the IPv4 one's complement checksum of the IPv4 header.
539     __wsum sum4 = 0;
540     for (unsigned i = 0; i < sizeof(*ip) / sizeof(__u16); ++i) {
541         sum4 += ((__u16*)ip)[i];
542     }
543     // Note that sum4 is guaranteed to be non-zero by virtue of ip4->version == 4
544     sum4 = (sum4 & 0xFFFF) + (sum4 >> 16);  // collapse u32 into range 1 .. 0x1FFFE
545     sum4 = (sum4 & 0xFFFF) + (sum4 >> 16);  // collapse any potential carry into u16
546     // for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF
547     if (sum4 != 0xFFFF) TC_PUNT(CHECKSUM);
548 
549     // Minimum IPv4 total length is the size of the header
550     if (ntohs(ip->tot_len) < sizeof(*ip)) TC_PUNT(TRUNCATED_IPV4);
551 
552     // We are incapable of dealing with IPv4 fragments
553     if (ip->frag_off & ~htons(IP_DF)) TC_PUNT(IS_IP_FRAG);
554 
555     // Cannot decrement during forward if already zero or would be zero,
556     // Let the kernel's stack handle these cases and generate appropriate ICMP errors.
557     if (ip->ttl <= 1) TC_PUNT(LOW_TTL);
558 
559     // If we cannot update the 'last_used' field due to lack of bpf_ktime_get_boot_ns() helper,
560     // then it is not safe to offload UDP due to the small conntrack timeouts, as such,
561     // in such a situation we can only support TCP.  This also has the added nice benefit of
562     // using a separate error counter, and thus making it obvious which version of the program
563     // is loaded.
564     if (!updatetime.updatetime && ip->protocol != IPPROTO_TCP) TC_PUNT(NON_TCP);
565 
566     // We do not support offloading anything besides IPv4 TCP and UDP, due to need for NAT,
567     // but no need to check this if !updatetime due to check immediately above.
568     if (updatetime.updatetime && (ip->protocol != IPPROTO_TCP) && (ip->protocol != IPPROTO_UDP))
569         TC_PUNT(NON_TCP_UDP);
570 
571     // We want to make sure that the compiler will, in the !updatetime case, entirely optimize
572     // out all the non-tcp logic.  Also note that at this point is_udp === !is_tcp.
573     const bool is_tcp = !updatetime.updatetime || (ip->protocol == IPPROTO_TCP);
574 
575     // This is a bit of a hack to make things easier on the bpf verifier.
576     // (In particular I believe the Linux 4.14 kernel's verifier can get confused later on about
577     // what offsets into the packet are valid and can spuriously reject the program, this is
578     // because it fails to realize that is_tcp && !is_tcp is impossible)
579     //
580     // For both TCP & UDP we'll need to read and modify the src/dst ports, which so happen to
581     // always be in the first 4 bytes of the L4 header.  Additionally for UDP we'll need access
582     // to the checksum field which is in bytes 7 and 8.  While for TCP we'll need to read the
583     // TCP flags (at offset 13) and access to the checksum field (2 bytes at offset 16).
584     // As such we *always* need access to at least 8 bytes.
585     if (data + l2_header_size + sizeof(*ip) + 8 > data_end) TC_PUNT(SHORT_L4_HEADER);
586 
587     // We're forcing the compiler to emit two copies of the following code, optimized
588     // separately for is_tcp being true or false.  This simplifies the resulting bpf
589     // byte code sufficiently that the 4.14 bpf verifier is able to keep track of things.
590     // Without this (updatetime == true) case would fail to bpf verify on 4.14 even
591     // if the underlying requisite kernel support (bpf_ktime_get_boot_ns) was backported.
592     if (is_tcp) {
593       return do_forward4_bottom(skb, l2_header_size, data, data_end, eth, ip,
594                                 rawip, stream, updatetime, /* is_tcp */ true, kver);
595     } else {
596       return do_forward4_bottom(skb, l2_header_size, data, data_end, eth, ip,
597                                 rawip, stream, updatetime, /* is_tcp */ false, kver);
598     }
599 }
600 
601 // Full featured (required) implementations for 5.8+ kernels (these are S+ by definition)
602 
603 DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_rawip$5_8", AID_ROOT, AID_NETWORK_STACK,
604                      sched_cls_tether_downstream4_rawip_5_8, KVER_5_10)
605 (struct __sk_buff* skb) {
606     return do_forward4(skb, RAWIP, DOWNSTREAM, UPDATETIME, KVER_5_10);
607 }
608 
609 DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_rawip$5_8", AID_ROOT, AID_NETWORK_STACK,
610                      sched_cls_tether_upstream4_rawip_5_8, KVER_5_10)
611 (struct __sk_buff* skb) {
612     return do_forward4(skb, RAWIP, UPSTREAM, UPDATETIME, KVER_5_10);
613 }
614 
615 DEFINE_BPF_PROG_KVER("schedcls/tether_downstream4_ether$5_8", AID_ROOT, AID_NETWORK_STACK,
616                      sched_cls_tether_downstream4_ether_5_8, KVER_5_10)
617 (struct __sk_buff* skb) {
618     return do_forward4(skb, ETHER, DOWNSTREAM, UPDATETIME, KVER_5_10);
619 }
620 
621 DEFINE_BPF_PROG_KVER("schedcls/tether_upstream4_ether$5_8", AID_ROOT, AID_NETWORK_STACK,
622                      sched_cls_tether_upstream4_ether_5_8, KVER_5_10)
623 (struct __sk_buff* skb) {
624     return do_forward4(skb, ETHER, UPSTREAM, UPDATETIME, KVER_5_10);
625 }
626 
627 // Full featured (optional) implementations for 4.14-S, 4.19-S & 5.4-S kernels
628 // (optional, because we need to be able to fallback for 4.14/4.19/5.4 pre-S kernels)
629 
630 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$opt",
631                                     AID_ROOT, AID_NETWORK_STACK,
632                                     sched_cls_tether_downstream4_rawip_opt,
633                                     KVER_4_14, KVER_5_10)
634 (struct __sk_buff* skb) {
635     return do_forward4(skb, RAWIP, DOWNSTREAM, UPDATETIME, KVER_4_14);
636 }
637 
638 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$opt",
639                                     AID_ROOT, AID_NETWORK_STACK,
640                                     sched_cls_tether_upstream4_rawip_opt,
641                                     KVER_4_14, KVER_5_10)
642 (struct __sk_buff* skb) {
643     return do_forward4(skb, RAWIP, UPSTREAM, UPDATETIME, KVER_4_14);
644 }
645 
646 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$opt",
647                                     AID_ROOT, AID_NETWORK_STACK,
648                                     sched_cls_tether_downstream4_ether_opt,
649                                     KVER_4_14, KVER_5_10)
650 (struct __sk_buff* skb) {
651     return do_forward4(skb, ETHER, DOWNSTREAM, UPDATETIME, KVER_4_14);
652 }
653 
654 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$opt",
655                                     AID_ROOT, AID_NETWORK_STACK,
656                                     sched_cls_tether_upstream4_ether_opt,
657                                     KVER_4_14, KVER_5_10)
658 (struct __sk_buff* skb) {
659     return do_forward4(skb, ETHER, UPSTREAM, UPDATETIME, KVER_4_14);
660 }
661 
662 // Partial (TCP-only: will not update 'last_used' field) implementations for 4.14+ kernels.
663 // These will be loaded only if the above optional ones failed (loading of *these* must succeed
664 // for 5.4+, since that is always an R patched kernel).
665 //
666 // [Note: as a result TCP connections will not have their conntrack timeout refreshed, however,
667 // since /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established defaults to 432000 (seconds),
668 // this in practice means they'll break only after 5 days.  This seems an acceptable trade-off.
669 //
670 // Additionally kernel/tests change "net-test: add bpf_ktime_get_ns / bpf_ktime_get_boot_ns tests"
671 // which enforces and documents the required kernel cherrypicks will make it pretty unlikely that
672 // many devices upgrading to S will end up relying on these fallback programs.
673 
674 // RAWIP: Required for 5.4-R kernels -- which always support bpf_skb_change_head().
675 
676 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
677                            sched_cls_tether_downstream4_rawip_5_4, KVER_5_4, KVER_5_10)
678 (struct __sk_buff* skb) {
679     return do_forward4(skb, RAWIP, DOWNSTREAM, NO_UPDATETIME, KVER_5_4);
680 }
681 
682 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$5_4", AID_ROOT, AID_NETWORK_STACK,
683                            sched_cls_tether_upstream4_rawip_5_4, KVER_5_4, KVER_5_10)
684 (struct __sk_buff* skb) {
685     return do_forward4(skb, RAWIP, UPSTREAM, NO_UPDATETIME, KVER_5_4);
686 }
687 
688 // RAWIP: Optional for 4.14/4.19 (R) kernels -- which support bpf_skb_change_head().
689 // [Note: fallback for 4.14/4.19 (P/Q) kernels is below in stub section]
690 
691 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$4_14",
692                                     AID_ROOT, AID_NETWORK_STACK,
693                                     sched_cls_tether_downstream4_rawip_4_14,
694                                     KVER_4_14, KVER_5_4)
695 (struct __sk_buff* skb) {
696     return do_forward4(skb, RAWIP, DOWNSTREAM, NO_UPDATETIME, KVER_4_14);
697 }
698 
699 DEFINE_OPTIONAL_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$4_14",
700                                     AID_ROOT, AID_NETWORK_STACK,
701                                     sched_cls_tether_upstream4_rawip_4_14,
702                                     KVER_4_14, KVER_5_4)
703 (struct __sk_buff* skb) {
704     return do_forward4(skb, RAWIP, UPSTREAM, NO_UPDATETIME, KVER_4_14);
705 }
706 
707 // ETHER: Required for 4.14-Q/R, 4.19-Q/R & 5.4-R kernels.
708 
709 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$4_14", AID_ROOT, AID_NETWORK_STACK,
710                            sched_cls_tether_downstream4_ether_4_14, KVER_4_14, KVER_5_10)
711 (struct __sk_buff* skb) {
712     return do_forward4(skb, ETHER, DOWNSTREAM, NO_UPDATETIME, KVER_4_14);
713 }
714 
715 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$4_14", AID_ROOT, AID_NETWORK_STACK,
716                            sched_cls_tether_upstream4_ether_4_14, KVER_4_14, KVER_5_10)
717 (struct __sk_buff* skb) {
718     return do_forward4(skb, ETHER, UPSTREAM, NO_UPDATETIME, KVER_4_14);
719 }
720 
721 // Placeholder (no-op) implementations for older Q kernels
722 
723 // RAWIP: 4.9-P/Q, 4.14-P/Q & 4.19-Q kernels -- without bpf_skb_change_head() for tc programs
724 
725 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
726                            sched_cls_tether_downstream4_rawip_stub, KVER_NONE, KVER_5_4)
727 (__unused struct __sk_buff* skb) {
728     return TC_ACT_PIPE;
729 }
730 
731 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_rawip$stub", AID_ROOT, AID_NETWORK_STACK,
732                            sched_cls_tether_upstream4_rawip_stub, KVER_NONE, KVER_5_4)
733 (__unused struct __sk_buff* skb) {
734     return TC_ACT_PIPE;
735 }
736 
737 // ETHER: 4.9-P/Q kernel
738 
739 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_downstream4_ether$stub", AID_ROOT, AID_NETWORK_STACK,
740                            sched_cls_tether_downstream4_ether_stub, KVER_NONE, KVER_4_14)
741 (__unused struct __sk_buff* skb) {
742     return TC_ACT_PIPE;
743 }
744 
745 DEFINE_BPF_PROG_KVER_RANGE("schedcls/tether_upstream4_ether$stub", AID_ROOT, AID_NETWORK_STACK,
746                            sched_cls_tether_upstream4_ether_stub, KVER_NONE, KVER_4_14)
747 (__unused struct __sk_buff* skb) {
748     return TC_ACT_PIPE;
749 }
750 
751 // ----- XDP Support -----
752 
753 DEFINE_BPF_MAP_GRW(tether_dev_map, DEVMAP_HASH, uint32_t, uint32_t, 64, AID_NETWORK_STACK)
754 
do_xdp_forward6(__unused struct xdp_md * ctx,__unused const struct rawip_bool rawip,__unused const struct stream_bool stream)755 static inline __always_inline int do_xdp_forward6(__unused struct xdp_md *ctx,
756         __unused const struct rawip_bool rawip, __unused const struct stream_bool stream) {
757     return XDP_PASS;
758 }
759 
do_xdp_forward4(__unused struct xdp_md * ctx,__unused const struct rawip_bool rawip,__unused const struct stream_bool stream)760 static inline __always_inline int do_xdp_forward4(__unused struct xdp_md *ctx,
761         __unused const struct rawip_bool rawip, __unused const struct stream_bool stream) {
762     return XDP_PASS;
763 }
764 
do_xdp_forward_ether(struct xdp_md * ctx,const struct stream_bool stream)765 static inline __always_inline int do_xdp_forward_ether(struct xdp_md *ctx,
766                                                        const struct stream_bool stream) {
767     const void* data = (void*)(long)ctx->data;
768     const void* data_end = (void*)(long)ctx->data_end;
769     const struct ethhdr* eth = data;
770 
771     // Make sure we actually have an ethernet header
772     if ((void*)(eth + 1) > data_end) return XDP_PASS;
773 
774     if (eth->h_proto == htons(ETH_P_IPV6))
775         return do_xdp_forward6(ctx, ETHER, stream);
776     if (eth->h_proto == htons(ETH_P_IP))
777         return do_xdp_forward4(ctx, ETHER, stream);
778 
779     // Anything else we don't know how to handle...
780     return XDP_PASS;
781 }
782 
do_xdp_forward_rawip(struct xdp_md * ctx,const struct stream_bool stream)783 static inline __always_inline int do_xdp_forward_rawip(struct xdp_md *ctx,
784                                                        const struct stream_bool stream) {
785     const void* data = (void*)(long)ctx->data;
786     const void* data_end = (void*)(long)ctx->data_end;
787 
788     // The top nibble of both IPv4 and IPv6 headers is the IP version.
789     if (data_end - data < 1) return XDP_PASS;
790     const uint8_t v = (*(uint8_t*)data) >> 4;
791 
792     if (v == 6) return do_xdp_forward6(ctx, RAWIP, stream);
793     if (v == 4) return do_xdp_forward4(ctx, RAWIP, stream);
794 
795     // Anything else we don't know how to handle...
796     return XDP_PASS;
797 }
798 
799 #define DEFINE_XDP_PROG(str, func) \
800     DEFINE_BPF_PROG_KVER(str, AID_ROOT, AID_NETWORK_STACK, func, KVER_5_10)(struct xdp_md *ctx)
801 
802 DEFINE_XDP_PROG("xdp/tether_downstream_ether",
803                  xdp_tether_downstream_ether) {
804     return do_xdp_forward_ether(ctx, DOWNSTREAM);
805 }
806 
807 DEFINE_XDP_PROG("xdp/tether_downstream_rawip",
808                  xdp_tether_downstream_rawip) {
809     return do_xdp_forward_rawip(ctx, DOWNSTREAM);
810 }
811 
812 DEFINE_XDP_PROG("xdp/tether_upstream_ether",
813                  xdp_tether_upstream_ether) {
814     return do_xdp_forward_ether(ctx, UPSTREAM);
815 }
816 
817 DEFINE_XDP_PROG("xdp/tether_upstream_rawip",
818                  xdp_tether_upstream_rawip) {
819     return do_xdp_forward_rawip(ctx, UPSTREAM);
820 }
821 
822 LICENSE("Apache 2.0");
823 CRITICAL("Connectivity (Tethering)");
824