blob: 7876d534d74fbf1628d00fb50f21f95431e2b682 [file] [log] [blame]
Taoyu Liaa6238b2019-09-06 17:38:52 +09001// Copyright 2019 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/ndproxy.h"
Taoyu Liaa6238b2019-09-06 17:38:52 +09006
7#include <errno.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
Taoyu Lif0370c92019-09-18 15:04:37 +090011#include <sysexits.h>
Taoyu Liaa6238b2019-09-06 17:38:52 +090012#include <unistd.h>
13
14#include <arpa/inet.h>
Taoyu Lifbcda452019-09-11 16:57:25 +090015#include <linux/filter.h>
Taoyu Liaa6238b2019-09-06 17:38:52 +090016#include <linux/if_packet.h>
17#include <linux/in6.h>
Taoyu Li43f66882019-10-25 16:59:34 +090018#include <linux/netlink.h>
19#include <linux/rtnetlink.h>
Taoyu Liaa6238b2019-09-06 17:38:52 +090020#include <net/ethernet.h>
21#include <net/if.h>
22#include <sys/ioctl.h>
23#include <sys/socket.h>
24
25#include <string>
Taoyu Lif0370c92019-09-18 15:04:37 +090026#include <utility>
27
28#include <base/bind.h>
Taoyu Liaa6238b2019-09-06 17:38:52 +090029
Garrick Evans3388a032020-03-24 11:25:55 +090030#include "patchpanel/minijailed_process_runner.h"
31#include "patchpanel/net_util.h"
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090032
Garrick Evans3388a032020-03-24 11:25:55 +090033namespace patchpanel {
Taoyu Liaa6238b2019-09-06 17:38:52 +090034namespace {
Taoyu Lifbcda452019-09-11 16:57:25 +090035const unsigned char kBroadcastMacAddress[] = {0xff, 0xff, 0xff,
Taoyu Liaa6238b2019-09-06 17:38:52 +090036 0xff, 0xff, 0xff};
Taoyu Lifbcda452019-09-11 16:57:25 +090037
38sock_filter kNDFrameBpfInstructions[] = {
39 // Load ethernet type.
40 BPF_STMT(BPF_LD | BPF_H | BPF_ABS, offsetof(ether_header, ether_type)),
41 // Check if it equals IPv6, if not, then goto return 0.
42 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ETHERTYPE_IPV6, 0, 9),
43 // Move index to start of IPv6 header.
44 BPF_STMT(BPF_LDX | BPF_IMM, sizeof(ether_header)),
45 // Load IPv6 next header.
46 BPF_STMT(BPF_LD | BPF_B | BPF_IND, offsetof(ip6_hdr, ip6_nxt)),
47 // Check if equals ICMPv6, if not, then goto return 0.
48 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_ICMPV6, 0, 6),
49 // Move index to start of ICMPv6 header.
50 BPF_STMT(BPF_LDX | BPF_IMM, sizeof(ether_header) + sizeof(ip6_hdr)),
51 // Load ICMPv6 type.
52 BPF_STMT(BPF_LD | BPF_B | BPF_IND, offsetof(icmp6_hdr, icmp6_type)),
53 // Check if is ND ICMPv6 message.
54 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_ROUTER_SOLICIT, 4, 0),
55 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_ROUTER_ADVERT, 3, 0),
56 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_NEIGHBOR_SOLICIT, 2, 0),
57 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_NEIGHBOR_ADVERT, 1, 0),
58 // Return 0.
59 BPF_STMT(BPF_RET | BPF_K, 0),
60 // Return MAX.
61 BPF_STMT(BPF_RET | BPF_K, IP_MAXPACKET),
62};
63const sock_fprog kNDFrameBpfProgram = {
64 .len = sizeof(kNDFrameBpfInstructions) / sizeof(sock_filter),
65 .filter = kNDFrameBpfInstructions};
66
Taoyu Liaa6238b2019-09-06 17:38:52 +090067} // namespace
68
Taoyu Lie47df4a2019-11-08 12:48:57 +090069constexpr ssize_t NDProxy::kTranslateErrorNotICMPv6Frame;
70constexpr ssize_t NDProxy::kTranslateErrorNotNDFrame;
71constexpr ssize_t NDProxy::kTranslateErrorInsufficientLength;
72constexpr ssize_t NDProxy::kTranslateErrorBufferMisaligned;
73
74NDProxy::NDProxy()
75 : in_frame_buffer_(AlignFrameBuffer(in_frame_buffer_extended_)),
76 out_frame_buffer_(AlignFrameBuffer(out_frame_buffer_extended_)) {}
77
Taoyu Liba04fe32020-01-14 13:19:35 +090078base::ScopedFD NDProxy::PreparePacketSocket() {
79 base::ScopedFD fd(
80 socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC, htons(ETH_P_IPV6)));
81 if (!fd.is_valid()) {
82 PLOG(ERROR) << "socket() failed";
83 return base::ScopedFD();
84 }
85 if (setsockopt(fd.get(), SOL_SOCKET, SO_ATTACH_FILTER, &kNDFrameBpfProgram,
86 sizeof(kNDFrameBpfProgram))) {
87 PLOG(ERROR) << "setsockopt(SO_ATTACH_FILTER) failed";
88 return base::ScopedFD();
89 }
90 return fd;
91}
92
Taoyu Lie47df4a2019-11-08 12:48:57 +090093bool NDProxy::Init() {
94 rtnl_fd_ = base::ScopedFD(
95 socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE));
96 if (!rtnl_fd_.is_valid()) {
97 PLOG(ERROR) << "socket() failed for rtnetlink socket";
98 return false;
99 }
100 sockaddr_nl local = {
101 .nl_family = AF_NETLINK,
102 .nl_groups = 0,
103 };
104 if (bind(rtnl_fd_.get(), reinterpret_cast<sockaddr*>(&local), sizeof(local)) <
105 0) {
106 PLOG(ERROR) << "bind() failed on rtnetlink socket";
107 return false;
108 }
109
110 dummy_fd_ = base::ScopedFD(socket(AF_INET6, SOCK_DGRAM, 0));
111 if (!dummy_fd_.is_valid()) {
112 PLOG(ERROR) << "socket() failed for dummy socket";
113 return false;
114 }
115 return true;
116}
Taoyu Liaa6238b2019-09-06 17:38:52 +0900117
Taoyu Liaa6238b2019-09-06 17:38:52 +0900118// In an ICMPv6 Ethernet Frame *frame with length frame_len, replace the mac
119// address in option opt_type into *target_mac. nd_hdr_len indicates the length
120// of ICMPv6 ND message headers (so the first option starts after nd_hdr_len.)
121void NDProxy::ReplaceMacInIcmpOption(uint8_t* frame,
122 ssize_t frame_len,
123 size_t nd_hdr_len,
124 uint8_t opt_type,
Taoyu Lie47df4a2019-11-08 12:48:57 +0900125 const MacAddress& target_mac) {
Taoyu Liaa6238b2019-09-06 17:38:52 +0900126 nd_opt_hdr* opt;
127 nd_opt_hdr* end = reinterpret_cast<nd_opt_hdr*>(&frame[frame_len]);
128 for (opt = reinterpret_cast<nd_opt_hdr*>(frame + ETHER_HDR_LEN +
129 sizeof(ip6_hdr) + nd_hdr_len);
130 opt < end && opt->nd_opt_len > 0;
131 opt = reinterpret_cast<nd_opt_hdr*>(reinterpret_cast<uint64_t*>(opt) +
132 opt->nd_opt_len)) {
133 if (opt->nd_opt_type == opt_type) {
134 uint8_t* mac_in_opt =
135 reinterpret_cast<uint8_t*>(opt) + sizeof(nd_opt_hdr);
Taoyu Lie47df4a2019-11-08 12:48:57 +0900136 memcpy(mac_in_opt, target_mac.data(), ETHER_ADDR_LEN);
Taoyu Liaa6238b2019-09-06 17:38:52 +0900137 }
138 }
139}
140
141// RFC 4389
142// Read the input ICMPv6 frame and determine whether it should be proxied. If
143// so, fill out_frame buffer with proxied frame and return the length of proxied
144// frame (usually same with input frame length). Return a negative value if
145// proxy is not needed or error occured.
Taoyu Li18041fe2019-11-13 15:49:31 +0900146// in_frame: buffer containing input ethernet frame; needs special alignment
147// so that IP header is 4-bytes aligned;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900148// frame_len: the length of input frame;
149// local_mac_addr: MAC address of interface that will be used to send frame;
Taoyu Li18041fe2019-11-13 15:49:31 +0900150// out_frame: buffer for output frame; should have at least space of frame_len;
151// needs special alignment so that IP header is 4-bytes aligned.
Taoyu Liaa6238b2019-09-06 17:38:52 +0900152ssize_t NDProxy::TranslateNDFrame(const uint8_t* in_frame,
153 ssize_t frame_len,
Taoyu Lie47df4a2019-11-08 12:48:57 +0900154 const MacAddress& local_mac_addr,
Taoyu Liaa6238b2019-09-06 17:38:52 +0900155 uint8_t* out_frame) {
Taoyu Li18041fe2019-11-13 15:49:31 +0900156 if ((reinterpret_cast<uintptr_t>(in_frame + ETHER_HDR_LEN) & 0x3) != 0 ||
157 (reinterpret_cast<uintptr_t>(out_frame + ETHER_HDR_LEN) & 0x3) != 0) {
158 return kTranslateErrorBufferMisaligned;
159 }
Taoyu Licc621b22019-10-21 15:03:12 +0900160 if (frame_len < ETHER_HDR_LEN + sizeof(ip6_hdr) + sizeof(icmp6_hdr)) {
Taoyu Liaa6238b2019-09-06 17:38:52 +0900161 return kTranslateErrorInsufficientLength;
162 }
163 if (reinterpret_cast<const ethhdr*>(in_frame)->h_proto != htons(ETH_P_IPV6) ||
164 reinterpret_cast<const ip6_hdr*>(in_frame + ETHER_HDR_LEN)->ip6_nxt !=
165 IPPROTO_ICMPV6) {
166 return kTranslateErrorNotICMPv6Frame;
167 }
168
169 memcpy(out_frame, in_frame, frame_len);
170 ethhdr* eth = reinterpret_cast<ethhdr*>(out_frame);
171 ip6_hdr* ip6 = reinterpret_cast<ip6_hdr*>(out_frame + ETHER_HDR_LEN);
172 icmp6_hdr* icmp6 =
173 reinterpret_cast<icmp6_hdr*>(out_frame + ETHER_HDR_LEN + sizeof(ip6_hdr));
174
175 // If destination MAC is unicast (Individual/Group bit in MAC address == 0),
Taoyu Li43f66882019-10-25 16:59:34 +0900176 // it needs to be modified so guest OS L3 stack can see it.
Taoyu Liba04fe32020-01-14 13:19:35 +0900177 // For proxy cascading case, we also need to recheck if destination MAC is
178 // ff:ff:ff:ff:ff:ff (which must have been filled by an upstream proxy).
179 if (!(eth->h_dest[0] & 0x1) ||
180 memcmp(eth->h_dest, kBroadcastMacAddress, ETHER_ADDR_LEN) == 0) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900181 MacAddress neighbor_mac;
182 if (GetNeighborMac(ip6->ip6_dst, &neighbor_mac)) {
183 memcpy(eth->h_dest, neighbor_mac.data(), ETHER_ADDR_LEN);
184 } else {
Taoyu Li43f66882019-10-25 16:59:34 +0900185 // If we can't resolve the destination IP into MAC from kernel neighbor
186 // table, fill destination MAC with broadcast MAC instead.
187 memcpy(eth->h_dest, kBroadcastMacAddress, ETHER_ADDR_LEN);
188 }
Taoyu Liaa6238b2019-09-06 17:38:52 +0900189 }
190
191 switch (icmp6->icmp6_type) {
192 case ND_ROUTER_SOLICIT:
193 ReplaceMacInIcmpOption(out_frame, frame_len, sizeof(nd_router_solicit),
194 ND_OPT_SOURCE_LINKADDR, local_mac_addr);
195 break;
196 case ND_ROUTER_ADVERT: {
197 // RFC 4389 Section 4.1.3.3 - Set Proxy bit
198 nd_router_advert* ra = reinterpret_cast<nd_router_advert*>(icmp6);
199 if (ra->nd_ra_flags_reserved & 0x04) {
200 // According to RFC 4389, an RA packet with 'Proxy' bit set already
201 // should not be proxied again, in order to avoid loop. However, we'll
202 // need this form of proxy cascading in Crostini (Host->VM->Container)
203 // so we are ignoring the check here. Note that we know we are doing RA
204 // proxy in only one direction so there should be no loop.
205 }
206 ra->nd_ra_flags_reserved |= 0x04;
207
208 ReplaceMacInIcmpOption(out_frame, frame_len, sizeof(nd_router_advert),
209 ND_OPT_SOURCE_LINKADDR, local_mac_addr);
210 break;
211 }
212 case ND_NEIGHBOR_SOLICIT:
213 ReplaceMacInIcmpOption(out_frame, frame_len, sizeof(nd_neighbor_solicit),
214 ND_OPT_SOURCE_LINKADDR, local_mac_addr);
215 break;
216 case ND_NEIGHBOR_ADVERT:
217 ReplaceMacInIcmpOption(out_frame, frame_len, sizeof(nd_neighbor_advert),
218 ND_OPT_TARGET_LINKADDR, local_mac_addr);
219 break;
220 default:
221 return kTranslateErrorNotNDFrame;
222 }
223
224 // We need to clear the old checksum first so checksum calculation does not
225 // wrongly take old checksum into account.
226 icmp6->icmp6_cksum = 0;
227 icmp6->icmp6_cksum = Icmpv6Checksum(ip6, icmp6);
228
Taoyu Lie47df4a2019-11-08 12:48:57 +0900229 memcpy(eth->h_source, local_mac_addr.data(), ETHER_ADDR_LEN);
Taoyu Liaa6238b2019-09-06 17:38:52 +0900230 return frame_len;
231}
232
Taoyu Lie47df4a2019-11-08 12:48:57 +0900233void NDProxy::ReadAndProcessOneFrame(int fd) {
234 sockaddr_ll dst_addr;
235 struct iovec iov = {
236 .iov_base = in_frame_buffer_,
237 .iov_len = IP_MAXPACKET,
Taoyu Li43f66882019-10-25 16:59:34 +0900238 };
Taoyu Lie47df4a2019-11-08 12:48:57 +0900239 msghdr hdr = {
240 .msg_name = &dst_addr,
241 .msg_namelen = sizeof(dst_addr),
242 .msg_iov = &iov,
243 .msg_iovlen = 1,
244 .msg_control = nullptr,
245 .msg_controllen = 0,
246 .msg_flags = 0,
247 };
248
249 ssize_t len;
250 if ((len = recvmsg(fd, &hdr, 0)) < 0) {
251 PLOG(ERROR) << "recvmsg() failed";
252 return;
253 }
254 ip6_hdr* ip6 = reinterpret_cast<ip6_hdr*>(in_frame_buffer_ + ETH_HLEN);
255 icmp6_hdr* icmp6 = reinterpret_cast<icmp6_hdr*>(
256 in_frame_buffer_ + ETHER_HDR_LEN + sizeof(ip6_hdr));
257
258 if (ip6->ip6_nxt != IPPROTO_ICMPV6 || icmp6->icmp6_type < ND_ROUTER_SOLICIT ||
259 icmp6->icmp6_type > ND_NEIGHBOR_ADVERT)
260 return;
261
Taoyu Lic48871b2019-12-18 12:57:25 +0900262 // Notify DeviceManager on receiving NA from guest, so a /128 route to the
263 // guest can be added on the host.
264 if (icmp6->icmp6_type == ND_NEIGHBOR_ADVERT &&
Taoyu Lie47df4a2019-11-08 12:48:57 +0900265 IsGuestInterface(dst_addr.sll_ifindex) &&
266 !guest_discovery_handler_.is_null()) {
Taoyu Lic48871b2019-12-18 12:57:25 +0900267 nd_neighbor_advert* na = reinterpret_cast<nd_neighbor_advert*>(icmp6);
Taoyu Li76d86582020-03-27 14:19:50 +0900268 if (((na->nd_na_target.s6_addr[0] & 0xe0) == 0x20) // Global Unicast
269 || ((na->nd_na_target.s6_addr[0] & 0xfe) == 0xfc)) { // Unique Local
Taoyu Lic48871b2019-12-18 12:57:25 +0900270 char ifname[IFNAMSIZ];
271 if_indextoname(dst_addr.sll_ifindex, ifname);
272 char ipv6_addr_str[INET6_ADDRSTRLEN];
273 inet_ntop(AF_INET6, &(na->nd_na_target.s6_addr), ipv6_addr_str,
274 INET6_ADDRSTRLEN);
275 guest_discovery_handler_.Run(std::string(ifname),
276 std::string(ipv6_addr_str));
277 }
Taoyu Li43f66882019-10-25 16:59:34 +0900278 }
279
Taoyu Liacaf80a2021-05-19 20:41:56 +0900280 // TODO(b/187918638): with Fibocom cell modem we are observing RAs coming
281 // from a src IP that is not present in neighbor table. Forwarding this
282 // will cause guest OS to set up a default route that's not routable.
283 // Skip these RAs now to avoid blocking connectivity on those devices, and
284 // we can revisit this case later to proper address the issue, potentially
285 // by using host IP as router IP instead.
286 MacAddress router_mac;
287 if (icmp6->icmp6_type == ND_ROUTER_ADVERT &&
288 !GetNeighborMac(ip6->ip6_src, &router_mac)) {
289 LOG(WARNING) << "Detected RA from unreachable src on interface "
290 << dst_addr.sll_ifindex << ", skip proxying the RA.";
291 return;
292 }
293
Taoyu Lia0727dc2020-09-24 19:54:59 +0900294 // On receiving RA from router, generate an address for each guest-facing
295 // interface, and sent it to DeviceManager so it can be assigned. This address
296 // will be used when directly communicating with guest OS through IPv6.
297 if (icmp6->icmp6_type == ND_ROUTER_ADVERT &&
298 IsRouterInterface(dst_addr.sll_ifindex) &&
299 !router_discovery_handler_.is_null()) {
300 const nd_opt_prefix_info* prefix_info =
301 GetPrefixInfoOption(in_frame_buffer_, len);
302 if (prefix_info != nullptr && prefix_info->nd_opt_pi_prefix_len <= 64) {
303 // Generate an EUI-64 address from virtual interface MAC. A prefix
304 // larger that /64 is required.
305 for (int target_if : if_map_ra_[dst_addr.sll_ifindex]) {
306 MacAddress local_mac;
307 if (!GetLocalMac(target_if, &local_mac))
308 continue;
309 in6_addr eui64_ip;
310 GenerateEUI64Address(&eui64_ip, prefix_info->nd_opt_pi_prefix,
311 local_mac);
312 char eui64_addr_str[INET6_ADDRSTRLEN];
313 inet_ntop(AF_INET6, &eui64_ip, eui64_addr_str, INET6_ADDRSTRLEN);
314 char target_ifname[IFNAMSIZ];
315 if_indextoname(target_if, target_ifname);
316 router_discovery_handler_.Run(std::string(target_ifname),
317 std::string(eui64_addr_str));
318 }
319 }
320 }
321
322 // Translate the NDP frame and send it through proxy interface
Taoyu Lie47df4a2019-11-08 12:48:57 +0900323 auto map_entry = MapForType(icmp6->icmp6_type)->find(dst_addr.sll_ifindex);
324 if (map_entry == MapForType(icmp6->icmp6_type)->end())
325 return;
326 const auto& target_ifs = map_entry->second;
327 for (int target_if : target_ifs) {
328 MacAddress local_mac;
329 if (!GetLocalMac(target_if, &local_mac))
330 continue;
331 int result =
332 TranslateNDFrame(in_frame_buffer_, len, local_mac, out_frame_buffer_);
333 if (result < 0) {
334 switch (result) {
335 case kTranslateErrorNotICMPv6Frame:
336 LOG(DFATAL) << "Attempt to TranslateNDFrame on a non-ICMPv6 frame";
337 return;
338 case kTranslateErrorNotNDFrame:
339 LOG(DFATAL) << "Attempt to TranslateNDFrame on a non-NDP frame, "
340 "icmpv6 type = "
341 << static_cast<int>(reinterpret_cast<icmp6_hdr*>(
342 in_frame_buffer_ + ETHER_HDR_LEN +
343 sizeof(ip6_hdr))
344 ->icmp6_type);
345 return;
346 case kTranslateErrorInsufficientLength:
347 LOG(DFATAL) << "TranslateNDFrame failed: frame_len = " << len
348 << " is too small";
349 return;
350 default:
351 LOG(DFATAL) << "Unknown error in TranslateNDFrame";
352 return;
353 }
354 }
355
356 struct iovec iov_out = {
357 .iov_base = out_frame_buffer_,
358 .iov_len = static_cast<size_t>(len),
359 };
360 sockaddr_ll addr = {
361 .sll_family = AF_PACKET,
362 .sll_protocol = htons(ETH_P_IPV6),
363 .sll_ifindex = target_if,
364 .sll_halen = ETHER_ADDR_LEN,
365 };
366 memcpy(addr.sll_addr, reinterpret_cast<ethhdr*>(out_frame_buffer_)->h_dest,
367 ETHER_ADDR_LEN);
368 msghdr hdr = {
369 .msg_name = &addr,
370 .msg_namelen = sizeof(addr),
371 .msg_iov = &iov_out,
372 .msg_iovlen = 1,
373 .msg_control = nullptr,
374 .msg_controllen = 0,
375 };
376 if (sendmsg(fd, &hdr, 0) < 0) {
377 PLOG(ERROR) << "sendmsg() failed on interface " << target_if;
378 }
379 }
380}
381
Taoyu Lia0727dc2020-09-24 19:54:59 +0900382const nd_opt_prefix_info* NDProxy::GetPrefixInfoOption(const uint8_t* in_frame,
383 ssize_t frame_len) {
Taoyu Li2b9f0912020-10-13 18:16:59 +0900384 const uint8_t* ptr =
385 in_frame + ETH_HLEN + sizeof(ip6_hdr) + sizeof(nd_router_advert);
386 while (ptr + offsetof(nd_opt_hdr, nd_opt_len) < in_frame + frame_len) {
Taoyu Lia0727dc2020-09-24 19:54:59 +0900387 const nd_opt_hdr* opt = reinterpret_cast<const nd_opt_hdr*>(ptr);
Taoyu Li2b9f0912020-10-13 18:16:59 +0900388 if (opt->nd_opt_len == 0)
389 return nullptr;
390 ptr += opt->nd_opt_len << 3; // nd_opt_len is in 8 bytes
391 if (ptr > in_frame + frame_len)
392 return nullptr;
Taoyu Lia0727dc2020-09-24 19:54:59 +0900393 if (opt->nd_opt_type == ND_OPT_PREFIX_INFORMATION &&
394 opt->nd_opt_len << 3 == sizeof(nd_opt_prefix_info)) {
395 return reinterpret_cast<const nd_opt_prefix_info*>(opt);
396 }
397 }
398 return nullptr;
399}
400
Taoyu Lie47df4a2019-11-08 12:48:57 +0900401bool NDProxy::GetLocalMac(int if_id, MacAddress* mac_addr) {
402 ifreq ifr = {
403 .ifr_ifindex = if_id,
404 };
405 if (ioctl(dummy_fd_.get(), SIOCGIFNAME, &ifr) < 0) {
406 PLOG(ERROR) << "ioctl() failed to get interface name on interface "
407 << if_id;
408 return false;
409 }
410 if (ioctl(dummy_fd_.get(), SIOCGIFHWADDR, &ifr) < 0) {
411 PLOG(ERROR) << "ioctl() failed to get MAC address on interface " << if_id;
412 return false;
413 }
414 memcpy(mac_addr->data(), ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
415 return true;
416}
417
418bool NDProxy::GetNeighborMac(const in6_addr& ipv6_addr, MacAddress* mac_addr) {
Taoyu Li43f66882019-10-25 16:59:34 +0900419 sockaddr_nl kernel = {
420 .nl_family = AF_NETLINK,
421 .nl_groups = 0,
422 };
423 struct nl_req {
424 nlmsghdr hdr;
425 rtgenmsg gen;
426 } req = {
427 .hdr =
428 {
429 .nlmsg_len = NLMSG_LENGTH(sizeof(rtgenmsg)),
430 .nlmsg_type = RTM_GETNEIGH,
431 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
432 .nlmsg_seq = 1,
433 },
434 .gen =
435 {
436 .rtgen_family = AF_INET6,
437 },
438 };
439 iovec io_req = {
440 .iov_base = &req,
441 .iov_len = req.hdr.nlmsg_len,
442 };
443 msghdr rtnl_req = {
444 .msg_name = &kernel,
445 .msg_namelen = sizeof(kernel),
446 .msg_iov = &io_req,
447 .msg_iovlen = 1,
448 };
Taoyu Lie47df4a2019-11-08 12:48:57 +0900449 if (sendmsg(rtnl_fd_.get(), &rtnl_req, 0) < 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900450 PLOG(ERROR) << "sendmsg() failed on rtnetlink socket";
451 return false;
452 }
453
454 static constexpr size_t kRtnlReplyBufferSize = 32768;
455 char reply_buffer[kRtnlReplyBufferSize];
456 iovec io_reply = {
457 .iov_base = reply_buffer,
458 .iov_len = kRtnlReplyBufferSize,
459 };
460 msghdr rtnl_reply = {
461 .msg_name = &kernel,
462 .msg_namelen = sizeof(kernel),
463 .msg_iov = &io_reply,
464 .msg_iovlen = 1,
465 };
466
467 bool any_entry_matched = false;
468 bool done = false;
469 while (!done) {
470 ssize_t len;
Taoyu Lie47df4a2019-11-08 12:48:57 +0900471 if ((len = recvmsg(rtnl_fd_.get(), &rtnl_reply, 0)) < 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900472 PLOG(ERROR) << "recvmsg() failed on rtnetlink socket";
473 return false;
474 }
475 for (nlmsghdr* msg_ptr = reinterpret_cast<nlmsghdr*>(reply_buffer);
476 NLMSG_OK(msg_ptr, len); msg_ptr = NLMSG_NEXT(msg_ptr, len)) {
477 switch (msg_ptr->nlmsg_type) {
478 case NLMSG_DONE: {
479 done = true;
480 break;
481 }
482 case RTM_NEWNEIGH: {
483 // Bitmap - 0x1: Found IP match; 0x2: found MAC address;
484 uint8_t current_entry_status = 0x0;
485 uint8_t current_mac[ETHER_ADDR_LEN];
486 ndmsg* nd_msg = reinterpret_cast<ndmsg*>(NLMSG_DATA(msg_ptr));
487 rtattr* rt_attr = reinterpret_cast<rtattr*>(RTM_RTA(nd_msg));
488 size_t rt_attr_len = RTM_PAYLOAD(msg_ptr);
489 for (; RTA_OK(rt_attr, rt_attr_len);
490 rt_attr = RTA_NEXT(rt_attr, rt_attr_len)) {
491 if (rt_attr->rta_type == NDA_DST &&
Taoyu Lie47df4a2019-11-08 12:48:57 +0900492 memcmp(&ipv6_addr, RTA_DATA(rt_attr), sizeof(in6_addr)) == 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900493 current_entry_status |= 0x1;
494 } else if (rt_attr->rta_type == NDA_LLADDR) {
495 current_entry_status |= 0x2;
496 memcpy(current_mac, RTA_DATA(rt_attr), ETHER_ADDR_LEN);
497 }
498 }
499 if (current_entry_status == 0x3) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900500 memcpy(mac_addr->data(), current_mac, ETHER_ADDR_LEN);
Taoyu Li43f66882019-10-25 16:59:34 +0900501 any_entry_matched = true;
502 }
503 break;
504 }
505 default: {
506 LOG(WARNING) << "received unexpected rtnetlink message type "
507 << msg_ptr->nlmsg_type << ", length "
508 << msg_ptr->nlmsg_len;
509 break;
510 }
511 }
512 }
513 }
514 return any_entry_matched;
515}
516
Taoyu Lie47df4a2019-11-08 12:48:57 +0900517void NDProxy::RegisterOnGuestIpDiscoveryHandler(
518 const base::Callback<void(const std::string&, const std::string&)>&
519 handler) {
520 guest_discovery_handler_ = handler;
521}
522
Taoyu Lia0727dc2020-09-24 19:54:59 +0900523void NDProxy::RegisterOnRouterDiscoveryHandler(
524 const base::Callback<void(const std::string&, const std::string&)>&
525 handler) {
526 router_discovery_handler_ = handler;
527}
528
Taoyu Liaa6238b2019-09-06 17:38:52 +0900529NDProxy::interface_mapping* NDProxy::MapForType(uint8_t type) {
530 switch (type) {
531 case ND_ROUTER_SOLICIT:
532 return &if_map_rs_;
533 case ND_ROUTER_ADVERT:
534 return &if_map_ra_;
535 case ND_NEIGHBOR_SOLICIT:
536 return &if_map_ns_na_;
537 case ND_NEIGHBOR_ADVERT:
538 return &if_map_ns_na_;
539 default:
540 LOG(DFATAL) << "Attempt to get interface map on illegal icmpv6 type "
541 << static_cast<int>(type);
542 return nullptr;
543 }
544}
545
Taoyu Li7dca19a2020-03-16 16:27:07 +0900546bool NDProxy::AddInterfacePair(const std::string& ifname_physical,
547 const std::string& ifname_guest) {
548 LOG(INFO) << "Adding interface pair between physical: " << ifname_physical
549 << ", guest: " << ifname_guest;
550 int ifid_physical = if_nametoindex(ifname_physical.c_str());
551 if (ifid_physical == 0) {
552 PLOG(ERROR) << "Get interface index failed on " << ifname_physical;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900553 return false;
554 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900555 int ifid_guest = if_nametoindex(ifname_guest.c_str());
556 if (ifid_guest == 0) {
557 PLOG(ERROR) << "Get interface index failed on " << ifname_guest;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900558 return false;
559 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900560 if (ifid_physical == ifid_guest) {
Taoyu Liaa6238b2019-09-06 17:38:52 +0900561 LOG(ERROR) << "Rejected attempt to forward between same interface "
Taoyu Li7dca19a2020-03-16 16:27:07 +0900562 << ifname_physical << " and " << ifname_guest;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900563 return false;
564 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900565 if_map_rs_[ifid_guest].insert(ifid_physical);
566 if_map_ra_[ifid_physical].insert(ifid_guest);
567 if_map_ns_na_[ifid_physical].insert(ifid_guest);
568 if_map_ns_na_[ifid_guest].insert(ifid_physical);
569 for (int ifid_other_guest : if_map_ra_[ifid_physical]) {
570 if (ifid_other_guest != ifid_guest) {
571 if_map_ns_na_[ifid_other_guest].insert(ifid_guest);
572 if_map_ns_na_[ifid_guest].insert(ifid_other_guest);
573 }
Taoyu Liaa6238b2019-09-06 17:38:52 +0900574 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900575 return true;
576}
577
578bool NDProxy::RemoveInterfacePair(const std::string& ifname_physical,
579 const std::string& ifname_guest) {
580 LOG(INFO) << "Removing interface pair between physical: " << ifname_physical
581 << ", guest: " << ifname_guest;
582 int ifid_physical = if_nametoindex(ifname_physical.c_str());
583 if (ifid_physical == 0) {
584 PLOG(ERROR) << "Get interface index failed on " << ifname_physical;
585 return false;
586 }
587 int ifid_guest = if_nametoindex(ifname_guest.c_str());
588 if (ifid_guest == 0) {
589 PLOG(ERROR) << "Get interface index failed on " << ifname_guest;
590 return false;
591 }
592 if (ifid_physical == ifid_guest) {
593 LOG(ERROR) << "Rejected attempt to forward between same interface "
594 << ifname_physical << " and " << ifname_guest;
595 return false;
596 }
597 if_map_rs_.erase(ifid_guest);
598 if_map_ra_[ifid_physical].erase(ifid_guest);
599 if_map_ns_na_.erase(ifid_guest);
600 if_map_ns_na_[ifid_physical].erase(ifid_guest);
601 for (int ifid_other_guest : if_map_ra_[ifid_physical]) {
602 if_map_ns_na_[ifid_other_guest].erase(ifid_guest);
603 }
Taoyu Liaa6238b2019-09-06 17:38:52 +0900604 return true;
605}
606
607bool NDProxy::RemoveInterface(const std::string& ifname) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900608 LOG(INFO) << "Removing physical interface " << ifname;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900609 int ifindex = if_nametoindex(ifname.c_str());
610 if (ifindex == 0) {
611 PLOG(ERROR) << "Get interface index failed on " << ifname;
612 return false;
613 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900614 for (int ifid_guest : if_map_ra_[ifindex]) {
615 if_map_rs_.erase(ifid_guest);
616 if_map_ns_na_.erase(ifid_guest);
617 }
Taoyu Liaa6238b2019-09-06 17:38:52 +0900618 if_map_ra_.erase(ifindex);
Taoyu Liaa6238b2019-09-06 17:38:52 +0900619 if_map_ns_na_.erase(ifindex);
Taoyu Liaa6238b2019-09-06 17:38:52 +0900620 return true;
621}
622
Taoyu Liaf944c92019-10-01 12:22:31 +0900623bool NDProxy::IsGuestInterface(int ifindex) {
624 return if_map_rs_.find(ifindex) != if_map_rs_.end();
625}
626
Taoyu Lia0727dc2020-09-24 19:54:59 +0900627bool NDProxy::IsRouterInterface(int ifindex) {
628 return if_map_ra_.find(ifindex) != if_map_ra_.end();
629}
630
631std::vector<std::string> NDProxy::GetGuestInterfaces(
632 const std::string& ifname_physical) {
633 std::vector<std::string> result;
634 int ifid_physical = if_nametoindex(ifname_physical.c_str());
635 if (ifid_physical == 0)
636 return result;
637 for (int ifid_guest : if_map_ra_[ifid_physical]) {
638 char ifname[IFNAMSIZ];
639 if_indextoname(ifid_guest, ifname);
640 result.push_back(ifname);
641 }
642 return result;
643}
644
Taoyu Lie47df4a2019-11-08 12:48:57 +0900645NDProxyDaemon::NDProxyDaemon(base::ScopedFD control_fd)
646 : msg_dispatcher_(
647 std::make_unique<MessageDispatcher>(std::move(control_fd))) {}
648
649NDProxyDaemon::~NDProxyDaemon() {}
650
651int NDProxyDaemon::OnInit() {
652 // Prevent the main process from sending us any signals.
653 if (setsid() < 0) {
654 PLOG(ERROR) << "Failed to created a new session with setsid: exiting";
655 return EX_OSERR;
656 }
657
658 EnterChildProcessJail();
659
660 // Register control fd callbacks
661 if (msg_dispatcher_) {
662 msg_dispatcher_->RegisterFailureHandler(base::Bind(
663 &NDProxyDaemon::OnParentProcessExit, weak_factory_.GetWeakPtr()));
664 msg_dispatcher_->RegisterDeviceMessageHandler(base::Bind(
665 &NDProxyDaemon::OnDeviceMessage, weak_factory_.GetWeakPtr()));
666 }
667
668 // Initialize NDProxy and register guest IP discovery callback
669 if (!proxy_.Init()) {
670 PLOG(ERROR) << "Failed to initialize NDProxy internal state";
671 return EX_OSERR;
672 }
673 proxy_.RegisterOnGuestIpDiscoveryHandler(base::Bind(
674 &NDProxyDaemon::OnGuestIpDiscovery, weak_factory_.GetWeakPtr()));
Taoyu Lia0727dc2020-09-24 19:54:59 +0900675 proxy_.RegisterOnRouterDiscoveryHandler(base::Bind(
676 &NDProxyDaemon::OnRouterDiscovery, weak_factory_.GetWeakPtr()));
Taoyu Lie47df4a2019-11-08 12:48:57 +0900677
678 // Initialize data fd
Taoyu Liba04fe32020-01-14 13:19:35 +0900679 fd_ = NDProxy::PreparePacketSocket();
Taoyu Lie47df4a2019-11-08 12:48:57 +0900680 if (!fd_.is_valid()) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900681 return EX_OSERR;
682 }
683
684 // Start watching on data fd
685 watcher_ = base::FileDescriptorWatcher::WatchReadable(
686 fd_.get(), base::Bind(&NDProxyDaemon::OnDataSocketReadReady,
687 weak_factory_.GetWeakPtr()));
688 LOG(INFO) << "Started watching on packet fd...";
689
690 return Daemon::OnInit();
691}
692
693void NDProxyDaemon::OnDataSocketReadReady() {
694 proxy_.ReadAndProcessOneFrame(fd_.get());
695}
696
697void NDProxyDaemon::OnParentProcessExit() {
698 LOG(ERROR) << "Quitting because the parent process died";
699 Quit();
700}
701
702void NDProxyDaemon::OnDeviceMessage(const DeviceMessage& msg) {
703 const std::string& dev_ifname = msg.dev_ifname();
704 LOG_IF(DFATAL, dev_ifname.empty())
705 << "Received DeviceMessage w/ empty dev_ifname";
706 if (msg.has_teardown()) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900707 if (msg.has_br_ifname()) {
708 proxy_.RemoveInterfacePair(dev_ifname, msg.br_ifname());
Taoyu Lia0727dc2020-09-24 19:54:59 +0900709 if (guest_if_addrs_.find(msg.br_ifname()) != guest_if_addrs_.end()) {
710 SendMessage(NDProxyMessage::DEL_ADDR, msg.br_ifname(),
711 guest_if_addrs_[msg.br_ifname()]);
712 guest_if_addrs_.erase(msg.br_ifname());
713 }
714
Taoyu Li7dca19a2020-03-16 16:27:07 +0900715 } else {
Taoyu Lia0727dc2020-09-24 19:54:59 +0900716 auto guest_ifs = proxy_.GetGuestInterfaces(dev_ifname);
Taoyu Li7dca19a2020-03-16 16:27:07 +0900717 proxy_.RemoveInterface(dev_ifname);
Taoyu Lia0727dc2020-09-24 19:54:59 +0900718 for (const auto& guest_if : guest_ifs) {
719 if (guest_if_addrs_.find(guest_if) != guest_if_addrs_.end()) {
720 SendMessage(NDProxyMessage::DEL_ADDR, guest_if,
721 guest_if_addrs_[guest_if]);
722 guest_if_addrs_.erase(guest_if);
723 }
724 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900725 }
Taoyu Lie47df4a2019-11-08 12:48:57 +0900726 } else if (msg.has_br_ifname()) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900727 proxy_.AddInterfacePair(dev_ifname, msg.br_ifname());
Taoyu Lie47df4a2019-11-08 12:48:57 +0900728 }
729}
730
731void NDProxyDaemon::OnGuestIpDiscovery(const std::string& ifname,
732 const std::string& ip6addr) {
Taoyu Lia0727dc2020-09-24 19:54:59 +0900733 SendMessage(NDProxyMessage::ADD_ROUTE, ifname, ip6addr);
734}
735
736void NDProxyDaemon::OnRouterDiscovery(const std::string& ifname,
737 const std::string& ip6addr) {
738 std::string current_addr = guest_if_addrs_[ifname];
739 if (current_addr == ip6addr)
740 return;
741 if (!current_addr.empty()) {
742 SendMessage(NDProxyMessage::DEL_ADDR, ifname, current_addr);
743 }
744 SendMessage(NDProxyMessage::ADD_ADDR, ifname, ip6addr);
745 guest_if_addrs_[ifname] = ip6addr;
746}
747
748void NDProxyDaemon::SendMessage(NDProxyMessage::NDProxyEventType type,
749 const std::string& ifname,
750 const std::string& ip6addr) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900751 if (!msg_dispatcher_)
752 return;
Taoyu Lia0727dc2020-09-24 19:54:59 +0900753 NDProxyMessage msg;
754 msg.set_type(type);
755 msg.set_ifname(ifname);
756 msg.set_ip6addr(ip6addr);
Taoyu Lie47df4a2019-11-08 12:48:57 +0900757 IpHelperMessage ipm;
Taoyu Lia0727dc2020-09-24 19:54:59 +0900758 *ipm.mutable_ndproxy_message() = msg;
Taoyu Lie47df4a2019-11-08 12:48:57 +0900759 msg_dispatcher_->SendMessage(ipm);
760}
761
Garrick Evans3388a032020-03-24 11:25:55 +0900762} // namespace patchpanel