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