blob: 55165b103662c4bdf90ffecca46e9e5339683b2b [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
33#include "bpf_helpers.h"
34#include "bpf_net_helpers.h"
35#include "bpf_shared.h"
36
37// From kernel:include/net/ip.h
38#define IP_DF 0x4000 // Flag: "Don't Fragment"
39
Hungming Chen6c0b1e82022-04-01 19:51:56 +080040// Used for iptables drops ingress clat packet. Beware of clat mark change may break the device
41// which is using the old clat mark in netd platform code. The reason is that the clat mark is a
42// mainline constant since T+ but netd iptable rules (ex: bandwidth control, firewall, and so on)
43// are set in stone.
44#define CLAT_MARK 0xdeadc1a7
45
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -080046DEFINE_BPF_MAP_GRW(clat_ingress6_map, HASH, ClatIngress6Key, ClatIngress6Value, 16, AID_SYSTEM)
47
48static inline __always_inline int nat64(struct __sk_buff* skb, bool is_ethernet) {
49 const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
50 void* data = (void*)(long)skb->data;
51 const void* data_end = (void*)(long)skb->data_end;
52 const struct ethhdr* const eth = is_ethernet ? data : NULL; // used iff is_ethernet
53 const struct ipv6hdr* const ip6 = is_ethernet ? (void*)(eth + 1) : data;
54
55 // Require ethernet dst mac address to be our unicast address.
56 if (is_ethernet && (skb->pkt_type != PACKET_HOST)) return TC_ACT_PIPE;
57
58 // Must be meta-ethernet IPv6 frame
59 if (skb->protocol != htons(ETH_P_IPV6)) return TC_ACT_PIPE;
60
61 // Must have (ethernet and) ipv6 header
62 if (data + l2_header_size + sizeof(*ip6) > data_end) return TC_ACT_PIPE;
63
64 // Ethertype - if present - must be IPv6
65 if (is_ethernet && (eth->h_proto != htons(ETH_P_IPV6))) return TC_ACT_PIPE;
66
67 // IP version must be 6
68 if (ip6->version != 6) return TC_ACT_PIPE;
69
70 // Maximum IPv6 payload length that can be translated to IPv4
71 if (ntohs(ip6->payload_len) > 0xFFFF - sizeof(struct iphdr)) return TC_ACT_PIPE;
72
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -080073 ClatIngress6Key k = {
74 .iif = skb->ifindex,
75 .pfx96.in6_u.u6_addr32 =
76 {
77 ip6->saddr.in6_u.u6_addr32[0],
78 ip6->saddr.in6_u.u6_addr32[1],
79 ip6->saddr.in6_u.u6_addr32[2],
80 },
81 .local6 = ip6->daddr,
82 };
83
84 ClatIngress6Value* v = bpf_clat_ingress6_map_lookup_elem(&k);
85
86 if (!v) return TC_ACT_PIPE;
87
Hungming Chen6c0b1e82022-04-01 19:51:56 +080088 switch (ip6->nexthdr) {
89 case IPPROTO_TCP: // For TCP & UDP the checksum neutrality of the chosen IPv6
90 case IPPROTO_UDP: // address means there is no need to update their checksums.
91 case IPPROTO_GRE: // We do not need to bother looking at GRE/ESP headers,
92 case IPPROTO_ESP: // since there is never a checksum to update.
93 break;
94
95 default: // do not know how to handle anything else
96 // Mark ingress non-offloaded clat packet for dropping in ip6tables bw_raw_PREROUTING.
97 // Non-offloaded clat packet is going to be handled by clat daemon and ip6tables. The
98 // duplicate one in ip6tables is not necessary.
99 skb->mark = CLAT_MARK;
100 return TC_ACT_PIPE;
101 }
102
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800103 struct ethhdr eth2; // used iff is_ethernet
104 if (is_ethernet) {
105 eth2 = *eth; // Copy over the ethernet header (src/dst mac)
106 eth2.h_proto = htons(ETH_P_IP); // But replace the ethertype
107 }
108
109 struct iphdr ip = {
110 .version = 4, // u4
111 .ihl = sizeof(struct iphdr) / sizeof(__u32), // u4
112 .tos = (ip6->priority << 4) + (ip6->flow_lbl[0] >> 4), // u8
113 .tot_len = htons(ntohs(ip6->payload_len) + sizeof(struct iphdr)), // u16
114 .id = 0, // u16
115 .frag_off = htons(IP_DF), // u16
116 .ttl = ip6->hop_limit, // u8
117 .protocol = ip6->nexthdr, // u8
118 .check = 0, // u16
119 .saddr = ip6->saddr.in6_u.u6_addr32[3], // u32
120 .daddr = v->local4.s_addr, // u32
121 };
122
123 // Calculate the IPv4 one's complement checksum of the IPv4 header.
124 __wsum sum4 = 0;
125 for (int i = 0; i < sizeof(ip) / sizeof(__u16); ++i) {
126 sum4 += ((__u16*)&ip)[i];
127 }
128 // Note that sum4 is guaranteed to be non-zero by virtue of ip.version == 4
129 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE
130 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16
131 ip.check = (__u16)~sum4; // sum4 cannot be zero, so this is never 0xFFFF
132
133 // Calculate the *negative* IPv6 16-bit one's complement checksum of the IPv6 header.
134 __wsum sum6 = 0;
135 // We'll end up with a non-zero sum due to ip6->version == 6 (which has '0' bits)
136 for (int i = 0; i < sizeof(*ip6) / sizeof(__u16); ++i) {
137 sum6 += ~((__u16*)ip6)[i]; // note the bitwise negation
138 }
139
140 // Note that there is no L4 checksum update: we are relying on the checksum neutrality
141 // of the ipv6 address chosen by netd's ClatdController.
142
143 // Packet mutations begin - point of no return, but if this first modification fails
144 // the packet is probably still pristine, so let clatd handle it.
Hungming Chen6c0b1e82022-04-01 19:51:56 +0800145 if (bpf_skb_change_proto(skb, htons(ETH_P_IP), 0)) {
146 // Mark ingress non-offloaded clat packet for dropping in ip6tables bw_raw_PREROUTING.
147 // Non-offloaded clat packet is going to be handled by clat daemon and ip6tables. The
148 // duplicate one in ip6tables is not necessary.
149 skb->mark = CLAT_MARK;
150 return TC_ACT_PIPE;
151 }
Maciej Żenczykowski849b3aa2022-01-20 20:58:34 -0800152
153 // This takes care of updating the skb->csum field for a CHECKSUM_COMPLETE packet.
154 //
155 // In such a case, skb->csum is a 16-bit one's complement sum of the entire payload,
156 // thus we need to subtract out the ipv6 header's sum, and add in the ipv4 header's sum.
157 // However, by construction of ip.check above the checksum of an ipv4 header is zero.
158 // Thus we only need to subtract the ipv6 header's sum, which is the same as adding
159 // in the sum of the bitwise negation of the ipv6 header.
160 //
161 // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
162 // (-ENOTSUPP) if it isn't. So we just ignore the return code.
163 //
164 // if (skb->ip_summed == CHECKSUM_COMPLETE)
165 // return (skb->csum = csum_add(skb->csum, csum));
166 // else
167 // return -ENOTSUPP;
168 bpf_csum_update(skb, sum6);
169
170 // bpf_skb_change_proto() invalidates all pointers - reload them.
171 data = (void*)(long)skb->data;
172 data_end = (void*)(long)skb->data_end;
173
174 // I cannot think of any valid way for this error condition to trigger, however I do
175 // believe the explicit check is required to keep the in kernel ebpf verifier happy.
176 if (data + l2_header_size + sizeof(struct iphdr) > data_end) return TC_ACT_SHOT;
177
178 if (is_ethernet) {
179 struct ethhdr* new_eth = data;
180
181 // Copy over the updated ethernet header
182 *new_eth = eth2;
183
184 // Copy over the new ipv4 header.
185 *(struct iphdr*)(new_eth + 1) = ip;
186 } else {
187 // Copy over the new ipv4 header without an ethernet header.
188 *(struct iphdr*)data = ip;
189 }
190
191 // Redirect, possibly back to same interface, so tcpdump sees packet twice.
192 if (v->oif) return bpf_redirect(v->oif, BPF_F_INGRESS);
193
194 // Just let it through, tcpdump will not see IPv4 packet.
195 return TC_ACT_PIPE;
196}
197
198DEFINE_BPF_PROG("schedcls/ingress6/clat_ether", AID_ROOT, AID_SYSTEM, sched_cls_ingress6_clat_ether)
199(struct __sk_buff* skb) {
200 return nat64(skb, true);
201}
202
203DEFINE_BPF_PROG("schedcls/ingress6/clat_rawip", AID_ROOT, AID_SYSTEM, sched_cls_ingress6_clat_rawip)
204(struct __sk_buff* skb) {
205 return nat64(skb, false);
206}
207
208DEFINE_BPF_MAP_GRW(clat_egress4_map, HASH, ClatEgress4Key, ClatEgress4Value, 16, AID_SYSTEM)
209
210DEFINE_BPF_PROG("schedcls/egress4/clat_ether", AID_ROOT, AID_SYSTEM, sched_cls_egress4_clat_ether)
211(struct __sk_buff* skb) {
212 return TC_ACT_PIPE;
213}
214
215DEFINE_BPF_PROG("schedcls/egress4/clat_rawip", AID_ROOT, AID_SYSTEM, sched_cls_egress4_clat_rawip)
216(struct __sk_buff* skb) {
217 void* data = (void*)(long)skb->data;
218 const void* data_end = (void*)(long)skb->data_end;
219 const struct iphdr* const ip4 = data;
220
221 // Must be meta-ethernet IPv4 frame
222 if (skb->protocol != htons(ETH_P_IP)) return TC_ACT_PIPE;
223
224 // Must have ipv4 header
225 if (data + sizeof(*ip4) > data_end) return TC_ACT_PIPE;
226
227 // IP version must be 4
228 if (ip4->version != 4) return TC_ACT_PIPE;
229
230 // We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header
231 if (ip4->ihl != 5) return TC_ACT_PIPE;
232
233 // Calculate the IPv4 one's complement checksum of the IPv4 header.
234 __wsum sum4 = 0;
235 for (int i = 0; i < sizeof(*ip4) / sizeof(__u16); ++i) {
236 sum4 += ((__u16*)ip4)[i];
237 }
238 // Note that sum4 is guaranteed to be non-zero by virtue of ip4->version == 4
239 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE
240 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16
241 // for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF
242 if (sum4 != 0xFFFF) return TC_ACT_PIPE;
243
244 // Minimum IPv4 total length is the size of the header
245 if (ntohs(ip4->tot_len) < sizeof(*ip4)) return TC_ACT_PIPE;
246
247 // We are incapable of dealing with IPv4 fragments
248 if (ip4->frag_off & ~htons(IP_DF)) return TC_ACT_PIPE;
249
250 switch (ip4->protocol) {
251 case IPPROTO_TCP: // For TCP & UDP the checksum neutrality of the chosen IPv6
252 case IPPROTO_GRE: // address means there is no need to update their checksums.
253 case IPPROTO_ESP: // We do not need to bother looking at GRE/ESP headers,
254 break; // since there is never a checksum to update.
255
256 case IPPROTO_UDP: // See above comment, but must also have UDP header...
257 if (data + sizeof(*ip4) + sizeof(struct udphdr) > data_end) return TC_ACT_PIPE;
258 const struct udphdr* uh = (const struct udphdr*)(ip4 + 1);
259 // If IPv4/UDP checksum is 0 then fallback to clatd so it can calculate the
260 // checksum. Otherwise the network or more likely the NAT64 gateway might
261 // drop the packet because in most cases IPv6/UDP packets with a zero checksum
262 // are invalid. See RFC 6935. TODO: calculate checksum via bpf_csum_diff()
263 if (!uh->check) return TC_ACT_PIPE;
264 break;
265
266 default: // do not know how to handle anything else
267 return TC_ACT_PIPE;
268 }
269
270 ClatEgress4Key k = {
271 .iif = skb->ifindex,
272 .local4.s_addr = ip4->saddr,
273 };
274
275 ClatEgress4Value* v = bpf_clat_egress4_map_lookup_elem(&k);
276
277 if (!v) return TC_ACT_PIPE;
278
279 // Translating without redirecting doesn't make sense.
280 if (!v->oif) return TC_ACT_PIPE;
281
282 // This implementation is currently limited to rawip.
283 if (v->oifIsEthernet) return TC_ACT_PIPE;
284
285 struct ipv6hdr ip6 = {
286 .version = 6, // __u8:4
287 .priority = ip4->tos >> 4, // __u8:4
288 .flow_lbl = {(ip4->tos & 0xF) << 4, 0, 0}, // __u8[3]
289 .payload_len = htons(ntohs(ip4->tot_len) - 20), // __be16
290 .nexthdr = ip4->protocol, // __u8
291 .hop_limit = ip4->ttl, // __u8
292 .saddr = v->local6, // struct in6_addr
293 .daddr = v->pfx96, // struct in6_addr
294 };
295 ip6.daddr.in6_u.u6_addr32[3] = ip4->daddr;
296
297 // Calculate the IPv6 16-bit one's complement checksum of the IPv6 header.
298 __wsum sum6 = 0;
299 // We'll end up with a non-zero sum due to ip6.version == 6
300 for (int i = 0; i < sizeof(ip6) / sizeof(__u16); ++i) {
301 sum6 += ((__u16*)&ip6)[i];
302 }
303
304 // Note that there is no L4 checksum update: we are relying on the checksum neutrality
305 // of the ipv6 address chosen by netd's ClatdController.
306
307 // Packet mutations begin - point of no return, but if this first modification fails
308 // the packet is probably still pristine, so let clatd handle it.
309 if (bpf_skb_change_proto(skb, htons(ETH_P_IPV6), 0)) return TC_ACT_PIPE;
310
311 // This takes care of updating the skb->csum field for a CHECKSUM_COMPLETE packet.
312 //
313 // In such a case, skb->csum is a 16-bit one's complement sum of the entire payload,
314 // thus we need to subtract out the ipv4 header's sum, and add in the ipv6 header's sum.
315 // However, we've already verified the ipv4 checksum is correct and thus 0.
316 // Thus we only need to add the ipv6 header's sum.
317 //
318 // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error
319 // (-ENOTSUPP) if it isn't. So we just ignore the return code (see above for more details).
320 bpf_csum_update(skb, sum6);
321
322 // bpf_skb_change_proto() invalidates all pointers - reload them.
323 data = (void*)(long)skb->data;
324 data_end = (void*)(long)skb->data_end;
325
326 // I cannot think of any valid way for this error condition to trigger, however I do
327 // believe the explicit check is required to keep the in kernel ebpf verifier happy.
328 if (data + sizeof(ip6) > data_end) return TC_ACT_SHOT;
329
330 // Copy over the new ipv6 header without an ethernet header.
331 *(struct ipv6hdr*)data = ip6;
332
333 // Redirect to non v4-* interface. Tcpdump only sees packet after this redirect.
334 return bpf_redirect(v->oif, 0 /* this is effectively BPF_F_EGRESS */);
335}
336
337LICENSE("Apache 2.0");
338CRITICAL("netd");