blob: b8c613124829f8de32620d5c5695c00687a520d0 [file] [log] [blame]
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -08001/*
2 * Copyright (C) 2019 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/bpf.h>
18#include <linux/if.h>
19#include <linux/if_ether.h>
20#include <linux/in.h>
21#include <linux/in6.h>
22#include <linux/ip.h>
23#include <linux/ipv6.h>
24#include <linux/pkt_cls.h>
25#include <linux/swab.h>
26#include <stdbool.h>
27#include <stdint.h>
28
29// bionic kernel uapi linux/udp.h header is munged...
30#define __kernel_udphdr udphdr
31#include <linux/udp.h>
32
Maciej Żenczykowskif7699522022-05-24 15:56:03 -070033// The resulting .o needs to load on the Android T beta 3 bpfloader
34#define BPFLOADER_MIN_VER BPFLOADER_T_BETA3_VERSION
Maciej Żenczykowskiacebffb2022-05-16 16:05:15 -070035
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -080036#include "bpf_helpers.h"
37#include "bpf_net_helpers.h"
38#include "bpf_shared.h"
Maciej Żenczykowskice9108f2022-06-15 02:02:21 -070039#include "clat_mark.h"
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -080040
Maciej Żenczykowskie0ddc472022-10-24 02:43:21 -070041// IP flags. (from kernel's include/net/ip.h)
42#define IP_CE 0x8000 // Flag: "Congestion" (really reserved 'evil bit')
43#define IP_DF 0x4000 // Flag: "Don't Fragment"
44#define IP_MF 0x2000 // Flag: "More Fragments"
45#define IP_OFFSET 0x1FFF // "Fragment Offset" part
46
47// from kernel's include/net/ipv6.h
48struct frag_hdr {
49 __u8 nexthdr;
50 __u8 reserved; // always zero
51 __be16 frag_off; // 13 bit offset, 2 bits zero, 1 bit "More Fragments"
52 __be32 identification;
53};
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -080054
55DEFINE_BPF_MAP_GRW(clat_ingress6_map, HASH, ClatIngress6Key, ClatIngress6Value, 16, AID_SYSTEM)
56
57static inline __always_inline int nat64(struct __sk_buff* skb, bool is_ethernet) {
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -080058 // Require ethernet dst mac address to be our unicast address.
59 if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
60
61 // Must be meta-ethernet IPv6 frame
62 if (skb->protocol != htons(ETH_P_IPV6)) return TC_ACT_PIPE;
63
Maciej Żenczykowski4b1e0f82022-04-07 16:53:02 -070064 const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
65
66 // Not clear if this is actually necessary considering we use DPA (Direct Packet Access),
67 // but we need to make sure we can read the IPv6 header reliably so that we can set
68 // skb->mark = 0xDeadC1a7 for packets we fail to offload.
Maciej Żenczykowski824fb292022-04-11 23:29:46 -070069 try_make_writable(skb, l2_header_size + sizeof(struct ipv6hdr));
Maciej Żenczykowski4b1e0f82022-04-07 16:53:02 -070070
71 void* data = (void*)(long)skb->data;
72 const void* data_end = (void*)(long)skb->data_end;
73 const struct ethhdr* const eth = is_ethernet ? data : NULL; // used iff is_ethernet
74 const struct ipv6hdr* const ip6 = is_ethernet ? (void*)(eth + 1) : data;
75
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -080076 // Must have (ethernet and) ipv6 header
77 if (data + l2_header_size + sizeof(*ip6) > data_end) return TC_ACT_PIPE;
78
79 // Ethertype - if present - must be IPv6
80 if (is_ethernet && (eth->h_proto != htons(ETH_P_IPV6))) return TC_ACT_PIPE;
81
82 // IP version must be 6
83 if (ip6->version != 6) return TC_ACT_PIPE;
84
85 // Maximum IPv6 payload length that can be translated to IPv4
86 if (ntohs(ip6->payload_len) > 0xFFFF - sizeof(struct iphdr)) return TC_ACT_PIPE;
87
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -080088 ClatIngress6Key k = {
89 .iif = skb->ifindex,
90 .pfx96.in6_u.u6_addr32 =
91 {
92 ip6->saddr.in6_u.u6_addr32[0],
93 ip6->saddr.in6_u.u6_addr32[1],
94 ip6->saddr.in6_u.u6_addr32[2],
95 },
96 .local6 = ip6->daddr,
97 };
98
99 ClatIngress6Value* v = bpf_clat_ingress6_map_lookup_elem(&k);
100
101 if (!v) return TC_ACT_PIPE;
102
Maciej Żenczykowski321321c2022-10-24 03:08:06 -0700103 __u8 proto = ip6->nexthdr;
104 __be16 ip_id = 0;
105 __be16 frag_off = htons(IP_DF);
Maciej Żenczykowskibe9685c2022-10-24 04:54:47 -0700106 __u16 tot_len = ntohs(ip6->payload_len) + sizeof(struct iphdr); // cannot overflow, see above
107
108 if (proto == IPPROTO_FRAGMENT) {
109 // Must have (ethernet and) ipv6 header and ipv6 fragment extension header
110 if (data + l2_header_size + sizeof(*ip6) + sizeof(struct frag_hdr) > data_end)
111 return TC_ACT_PIPE;
112 const struct frag_hdr *frag = (const struct frag_hdr *)(ip6 + 1);
113 proto = frag->nexthdr;
114 // Trivial hash of 32-bit IPv6 ID field into 16-bit IPv4 field.
115 ip_id = (frag->identification) ^ (frag->identification >> 16);
116 // Conversion of 16-bit IPv6 frag offset to 16-bit IPv4 frag offset field.
117 // IPv6 is '13 bits of offset in multiples of 8' + 2 zero bits + more fragment bit
118 // IPv4 is zero bit + don't frag bit + more frag bit + '13 bits of offset in multiples of 8'
119 frag_off = ntohs(frag->frag_off);
120 frag_off = ((frag_off & 1) << 13) | (frag_off >> 3);
121 frag_off = htons(frag_off);
122 // Note that by construction tot_len is guaranteed to not underflow here
123 tot_len -= sizeof(struct frag_hdr);
124 // This is a badly formed IPv6 packet with less payload than the size of an IPv6 Frag EH
125 if (tot_len < sizeof(struct iphdr)) return TC_ACT_PIPE;
126 }
Maciej Żenczykowski321321c2022-10-24 03:08:06 -0700127
128 switch (proto) {
Hungming Chen6c0b1e82022-04-01 19:51:56 +0800129 case IPPROTO_TCP: // For TCP & UDP the checksum neutrality of the chosen IPv6
130 case IPPROTO_UDP: // address means there is no need to update their checksums.
131 case IPPROTO_GRE: // We do not need to bother looking at GRE/ESP headers,
132 case IPPROTO_ESP: // since there is never a checksum to update.
133 break;
134
135 default: // do not know how to handle anything else
136 // Mark ingress non-offloaded clat packet for dropping in ip6tables bw_raw_PREROUTING.
137 // Non-offloaded clat packet is going to be handled by clat daemon and ip6tables. The
138 // duplicate one in ip6tables is not necessary.
139 skb->mark = CLAT_MARK;
140 return TC_ACT_PIPE;
141 }
142
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800143 struct ethhdr eth2; // used iff is_ethernet
144 if (is_ethernet) {
145 eth2 = *eth; // Copy over the ethernet header (src/dst mac)
146 eth2.h_proto = htons(ETH_P_IP); // But replace the ethertype
147 }
148
149 struct iphdr ip = {
150 .version = 4, // u4
151 .ihl = sizeof(struct iphdr) / sizeof(__u32), // u4
152 .tos = (ip6->priority << 4) + (ip6->flow_lbl[0] >> 4), // u8
Maciej Żenczykowskibe9685c2022-10-24 04:54:47 -0700153 .tot_len = htons(tot_len), // be16
Maciej Żenczykowski321321c2022-10-24 03:08:06 -0700154 .id = ip_id, // be16
155 .frag_off = frag_off, // be16
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800156 .ttl = ip6->hop_limit, // u8
Maciej Żenczykowski321321c2022-10-24 03:08:06 -0700157 .protocol = proto, // u8
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800158 .check = 0, // u16
Maciej Żenczykowski321321c2022-10-24 03:08:06 -0700159 .saddr = ip6->saddr.in6_u.u6_addr32[3], // be32
160 .daddr = v->local4.s_addr, // be32
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800161 };
162
163 // Calculate the IPv4 one's complement checksum of the IPv4 header.
164 __wsum sum4 = 0;
165 for (int i = 0; i < sizeof(ip) / sizeof(__u16); ++i) {
166 sum4 += ((__u16*)&ip)[i];
167 }
168 // Note that sum4 is guaranteed to be non-zero by virtue of ip.version == 4
169 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE
170 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16
171 ip.check = (__u16)~sum4; // sum4 cannot be zero, so this is never 0xFFFF
172
173 // Calculate the *negative* IPv6 16-bit one's complement checksum of the IPv6 header.
174 __wsum sum6 = 0;
175 // We'll end up with a non-zero sum due to ip6->version == 6 (which has '0' bits)
176 for (int i = 0; i < sizeof(*ip6) / sizeof(__u16); ++i) {
177 sum6 += ~((__u16*)ip6)[i]; // note the bitwise negation
178 }
179
180 // Note that there is no L4 checksum update: we are relying on the checksum neutrality
181 // of the ipv6 address chosen by netd's ClatdController.
182
183 // Packet mutations begin - point of no return, but if this first modification fails
184 // the packet is probably still pristine, so let clatd handle it.
Hungming Chen6c0b1e82022-04-01 19:51:56 +0800185 if (bpf_skb_change_proto(skb, htons(ETH_P_IP), 0)) {
186 // Mark ingress non-offloaded clat packet for dropping in ip6tables bw_raw_PREROUTING.
187 // Non-offloaded clat packet is going to be handled by clat daemon and ip6tables. The
188 // duplicate one in ip6tables is not necessary.
189 skb->mark = CLAT_MARK;
190 return TC_ACT_PIPE;
191 }
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800192
193 // This takes care of updating the skb->csum field for a CHECKSUM_COMPLETE packet.
194 //
195 // In such a case, skb->csum is a 16-bit one's complement sum of the entire payload,
196 // thus we need to subtract out the ipv6 header's sum, and add in the ipv4 header's sum.
197 // However, by construction of ip.check above the checksum of an ipv4 header is zero.
198 // Thus we only need to subtract the ipv6 header's sum, which is the same as adding
199 // in the sum of the bitwise negation of the ipv6 header.
200 //
201 // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
202 // (-ENOTSUPP) if it isn't. So we just ignore the return code.
203 //
204 // if (skb->ip_summed == CHECKSUM_COMPLETE)
205 // return (skb->csum = csum_add(skb->csum, csum));
206 // else
207 // return -ENOTSUPP;
208 bpf_csum_update(skb, sum6);
209
Maciej Żenczykowskibe9685c2022-10-24 04:54:47 -0700210 if (frag_off != htons(IP_DF)) {
211 // If we're converting an IPv6 Fragment, we need to trim off 8 more bytes
212 // We're beyond recovery on error here... but hard to imagine how this could fail.
213 if (bpf_skb_adjust_room(skb, -(__s32)sizeof(struct frag_hdr), BPF_ADJ_ROOM_NET, /*flags*/0))
214 return TC_ACT_SHOT;
215 }
216
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800217 // bpf_skb_change_proto() invalidates all pointers - reload them.
218 data = (void*)(long)skb->data;
219 data_end = (void*)(long)skb->data_end;
220
221 // I cannot think of any valid way for this error condition to trigger, however I do
222 // believe the explicit check is required to keep the in kernel ebpf verifier happy.
223 if (data + l2_header_size + sizeof(struct iphdr) > data_end) return TC_ACT_SHOT;
224
225 if (is_ethernet) {
226 struct ethhdr* new_eth = data;
227
228 // Copy over the updated ethernet header
229 *new_eth = eth2;
230
231 // Copy over the new ipv4 header.
232 *(struct iphdr*)(new_eth + 1) = ip;
233 } else {
234 // Copy over the new ipv4 header without an ethernet header.
235 *(struct iphdr*)data = ip;
236 }
237
238 // Redirect, possibly back to same interface, so tcpdump sees packet twice.
239 if (v->oif) return bpf_redirect(v->oif, BPF_F_INGRESS);
240
241 // Just let it through, tcpdump will not see IPv4 packet.
242 return TC_ACT_PIPE;
243}
244
245DEFINE_BPF_PROG("schedcls/ingress6/clat_ether", AID_ROOT, AID_SYSTEM, sched_cls_ingress6_clat_ether)
246(struct __sk_buff* skb) {
247 return nat64(skb, true);
248}
249
250DEFINE_BPF_PROG("schedcls/ingress6/clat_rawip", AID_ROOT, AID_SYSTEM, sched_cls_ingress6_clat_rawip)
251(struct __sk_buff* skb) {
252 return nat64(skb, false);
253}
254
255DEFINE_BPF_MAP_GRW(clat_egress4_map, HASH, ClatEgress4Key, ClatEgress4Value, 16, AID_SYSTEM)
256
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800257DEFINE_BPF_PROG("schedcls/egress4/clat_rawip", AID_ROOT, AID_SYSTEM, sched_cls_egress4_clat_rawip)
258(struct __sk_buff* skb) {
Maciej Żenczykowski4b1e0f82022-04-07 16:53:02 -0700259 // Must be meta-ethernet IPv4 frame
260 if (skb->protocol != htons(ETH_P_IP)) return TC_ACT_PIPE;
261
262 // Possibly not needed, but for consistency with nat64 up above
Maciej Żenczykowski824fb292022-04-11 23:29:46 -0700263 try_make_writable(skb, sizeof(struct iphdr));
Maciej Żenczykowski4b1e0f82022-04-07 16:53:02 -0700264
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800265 void* data = (void*)(long)skb->data;
266 const void* data_end = (void*)(long)skb->data_end;
267 const struct iphdr* const ip4 = data;
268
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800269 // Must have ipv4 header
270 if (data + sizeof(*ip4) > data_end) return TC_ACT_PIPE;
271
272 // IP version must be 4
273 if (ip4->version != 4) return TC_ACT_PIPE;
274
275 // We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header
276 if (ip4->ihl != 5) return TC_ACT_PIPE;
277
278 // Calculate the IPv4 one's complement checksum of the IPv4 header.
279 __wsum sum4 = 0;
280 for (int i = 0; i < sizeof(*ip4) / sizeof(__u16); ++i) {
281 sum4 += ((__u16*)ip4)[i];
282 }
283 // Note that sum4 is guaranteed to be non-zero by virtue of ip4->version == 4
284 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE
285 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16
286 // for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF
287 if (sum4 != 0xFFFF) return TC_ACT_PIPE;
288
289 // Minimum IPv4 total length is the size of the header
290 if (ntohs(ip4->tot_len) < sizeof(*ip4)) return TC_ACT_PIPE;
291
292 // We are incapable of dealing with IPv4 fragments
293 if (ip4->frag_off & ~htons(IP_DF)) return TC_ACT_PIPE;
294
295 switch (ip4->protocol) {
296 case IPPROTO_TCP: // For TCP & UDP the checksum neutrality of the chosen IPv6
297 case IPPROTO_GRE: // address means there is no need to update their checksums.
298 case IPPROTO_ESP: // We do not need to bother looking at GRE/ESP headers,
299 break; // since there is never a checksum to update.
300
301 case IPPROTO_UDP: // See above comment, but must also have UDP header...
302 if (data + sizeof(*ip4) + sizeof(struct udphdr) > data_end) return TC_ACT_PIPE;
303 const struct udphdr* uh = (const struct udphdr*)(ip4 + 1);
304 // If IPv4/UDP checksum is 0 then fallback to clatd so it can calculate the
305 // checksum. Otherwise the network or more likely the NAT64 gateway might
306 // drop the packet because in most cases IPv6/UDP packets with a zero checksum
307 // are invalid. See RFC 6935. TODO: calculate checksum via bpf_csum_diff()
308 if (!uh->check) return TC_ACT_PIPE;
309 break;
310
311 default: // do not know how to handle anything else
312 return TC_ACT_PIPE;
313 }
314
315 ClatEgress4Key k = {
316 .iif = skb->ifindex,
317 .local4.s_addr = ip4->saddr,
318 };
319
320 ClatEgress4Value* v = bpf_clat_egress4_map_lookup_elem(&k);
321
322 if (!v) return TC_ACT_PIPE;
323
324 // Translating without redirecting doesn't make sense.
325 if (!v->oif) return TC_ACT_PIPE;
326
327 // This implementation is currently limited to rawip.
328 if (v->oifIsEthernet) return TC_ACT_PIPE;
329
330 struct ipv6hdr ip6 = {
331 .version = 6, // __u8:4
332 .priority = ip4->tos >> 4, // __u8:4
333 .flow_lbl = {(ip4->tos & 0xF) << 4, 0, 0}, // __u8[3]
334 .payload_len = htons(ntohs(ip4->tot_len) - 20), // __be16
335 .nexthdr = ip4->protocol, // __u8
336 .hop_limit = ip4->ttl, // __u8
337 .saddr = v->local6, // struct in6_addr
338 .daddr = v->pfx96, // struct in6_addr
339 };
340 ip6.daddr.in6_u.u6_addr32[3] = ip4->daddr;
341
342 // Calculate the IPv6 16-bit one's complement checksum of the IPv6 header.
343 __wsum sum6 = 0;
344 // We'll end up with a non-zero sum due to ip6.version == 6
345 for (int i = 0; i < sizeof(ip6) / sizeof(__u16); ++i) {
346 sum6 += ((__u16*)&ip6)[i];
347 }
348
349 // Note that there is no L4 checksum update: we are relying on the checksum neutrality
350 // of the ipv6 address chosen by netd's ClatdController.
351
352 // Packet mutations begin - point of no return, but if this first modification fails
353 // the packet is probably still pristine, so let clatd handle it.
354 if (bpf_skb_change_proto(skb, htons(ETH_P_IPV6), 0)) return TC_ACT_PIPE;
355
356 // This takes care of updating the skb->csum field for a CHECKSUM_COMPLETE packet.
357 //
358 // In such a case, skb->csum is a 16-bit one's complement sum of the entire payload,
359 // thus we need to subtract out the ipv4 header's sum, and add in the ipv6 header's sum.
360 // However, we've already verified the ipv4 checksum is correct and thus 0.
361 // Thus we only need to add the ipv6 header's sum.
362 //
363 // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
364 // (-ENOTSUPP) if it isn't. So we just ignore the return code (see above for more details).
365 bpf_csum_update(skb, sum6);
366
367 // bpf_skb_change_proto() invalidates all pointers - reload them.
368 data = (void*)(long)skb->data;
369 data_end = (void*)(long)skb->data_end;
370
371 // I cannot think of any valid way for this error condition to trigger, however I do
372 // believe the explicit check is required to keep the in kernel ebpf verifier happy.
373 if (data + sizeof(ip6) > data_end) return TC_ACT_SHOT;
374
375 // Copy over the new ipv6 header without an ethernet header.
376 *(struct ipv6hdr*)data = ip6;
377
378 // Redirect to non v4-* interface. Tcpdump only sees packet after this redirect.
379 return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
380}
381
382LICENSE("Apache 2.0");
Maciej Żenczykowskic41e35d2022-08-04 13:58:46 +0000383CRITICAL("Connectivity");