blob: f4964a76677a972c072c34f9da40c556eb4993d5 [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 Lia0727dc2020-09-24 19:54:59 +0900280 // On receiving RA from router, generate an address for each guest-facing
281 // interface, and sent it to DeviceManager so it can be assigned. This address
282 // will be used when directly communicating with guest OS through IPv6.
283 if (icmp6->icmp6_type == ND_ROUTER_ADVERT &&
284 IsRouterInterface(dst_addr.sll_ifindex) &&
285 !router_discovery_handler_.is_null()) {
286 const nd_opt_prefix_info* prefix_info =
287 GetPrefixInfoOption(in_frame_buffer_, len);
288 if (prefix_info != nullptr && prefix_info->nd_opt_pi_prefix_len <= 64) {
289 // Generate an EUI-64 address from virtual interface MAC. A prefix
290 // larger that /64 is required.
291 for (int target_if : if_map_ra_[dst_addr.sll_ifindex]) {
292 MacAddress local_mac;
293 if (!GetLocalMac(target_if, &local_mac))
294 continue;
295 in6_addr eui64_ip;
296 GenerateEUI64Address(&eui64_ip, prefix_info->nd_opt_pi_prefix,
297 local_mac);
298 char eui64_addr_str[INET6_ADDRSTRLEN];
299 inet_ntop(AF_INET6, &eui64_ip, eui64_addr_str, INET6_ADDRSTRLEN);
300 char target_ifname[IFNAMSIZ];
301 if_indextoname(target_if, target_ifname);
302 router_discovery_handler_.Run(std::string(target_ifname),
303 std::string(eui64_addr_str));
304 }
305 }
306 }
307
308 // Translate the NDP frame and send it through proxy interface
Taoyu Lie47df4a2019-11-08 12:48:57 +0900309 auto map_entry = MapForType(icmp6->icmp6_type)->find(dst_addr.sll_ifindex);
310 if (map_entry == MapForType(icmp6->icmp6_type)->end())
311 return;
312 const auto& target_ifs = map_entry->second;
313 for (int target_if : target_ifs) {
314 MacAddress local_mac;
315 if (!GetLocalMac(target_if, &local_mac))
316 continue;
317 int result =
318 TranslateNDFrame(in_frame_buffer_, len, local_mac, out_frame_buffer_);
319 if (result < 0) {
320 switch (result) {
321 case kTranslateErrorNotICMPv6Frame:
322 LOG(DFATAL) << "Attempt to TranslateNDFrame on a non-ICMPv6 frame";
323 return;
324 case kTranslateErrorNotNDFrame:
325 LOG(DFATAL) << "Attempt to TranslateNDFrame on a non-NDP frame, "
326 "icmpv6 type = "
327 << static_cast<int>(reinterpret_cast<icmp6_hdr*>(
328 in_frame_buffer_ + ETHER_HDR_LEN +
329 sizeof(ip6_hdr))
330 ->icmp6_type);
331 return;
332 case kTranslateErrorInsufficientLength:
333 LOG(DFATAL) << "TranslateNDFrame failed: frame_len = " << len
334 << " is too small";
335 return;
336 default:
337 LOG(DFATAL) << "Unknown error in TranslateNDFrame";
338 return;
339 }
340 }
341
342 struct iovec iov_out = {
343 .iov_base = out_frame_buffer_,
344 .iov_len = static_cast<size_t>(len),
345 };
346 sockaddr_ll addr = {
347 .sll_family = AF_PACKET,
348 .sll_protocol = htons(ETH_P_IPV6),
349 .sll_ifindex = target_if,
350 .sll_halen = ETHER_ADDR_LEN,
351 };
352 memcpy(addr.sll_addr, reinterpret_cast<ethhdr*>(out_frame_buffer_)->h_dest,
353 ETHER_ADDR_LEN);
354 msghdr hdr = {
355 .msg_name = &addr,
356 .msg_namelen = sizeof(addr),
357 .msg_iov = &iov_out,
358 .msg_iovlen = 1,
359 .msg_control = nullptr,
360 .msg_controllen = 0,
361 };
362 if (sendmsg(fd, &hdr, 0) < 0) {
363 PLOG(ERROR) << "sendmsg() failed on interface " << target_if;
364 }
365 }
366}
367
Taoyu Lia0727dc2020-09-24 19:54:59 +0900368const nd_opt_prefix_info* NDProxy::GetPrefixInfoOption(const uint8_t* in_frame,
369 ssize_t frame_len) {
Taoyu Li2b9f0912020-10-13 18:16:59 +0900370 const uint8_t* ptr =
371 in_frame + ETH_HLEN + sizeof(ip6_hdr) + sizeof(nd_router_advert);
372 while (ptr + offsetof(nd_opt_hdr, nd_opt_len) < in_frame + frame_len) {
Taoyu Lia0727dc2020-09-24 19:54:59 +0900373 const nd_opt_hdr* opt = reinterpret_cast<const nd_opt_hdr*>(ptr);
Taoyu Li2b9f0912020-10-13 18:16:59 +0900374 if (opt->nd_opt_len == 0)
375 return nullptr;
376 ptr += opt->nd_opt_len << 3; // nd_opt_len is in 8 bytes
377 if (ptr > in_frame + frame_len)
378 return nullptr;
Taoyu Lia0727dc2020-09-24 19:54:59 +0900379 if (opt->nd_opt_type == ND_OPT_PREFIX_INFORMATION &&
380 opt->nd_opt_len << 3 == sizeof(nd_opt_prefix_info)) {
381 return reinterpret_cast<const nd_opt_prefix_info*>(opt);
382 }
383 }
384 return nullptr;
385}
386
Taoyu Lie47df4a2019-11-08 12:48:57 +0900387bool NDProxy::GetLocalMac(int if_id, MacAddress* mac_addr) {
388 ifreq ifr = {
389 .ifr_ifindex = if_id,
390 };
391 if (ioctl(dummy_fd_.get(), SIOCGIFNAME, &ifr) < 0) {
392 PLOG(ERROR) << "ioctl() failed to get interface name on interface "
393 << if_id;
394 return false;
395 }
396 if (ioctl(dummy_fd_.get(), SIOCGIFHWADDR, &ifr) < 0) {
397 PLOG(ERROR) << "ioctl() failed to get MAC address on interface " << if_id;
398 return false;
399 }
400 memcpy(mac_addr->data(), ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
401 return true;
402}
403
404bool NDProxy::GetNeighborMac(const in6_addr& ipv6_addr, MacAddress* mac_addr) {
Taoyu Li43f66882019-10-25 16:59:34 +0900405 sockaddr_nl kernel = {
406 .nl_family = AF_NETLINK,
407 .nl_groups = 0,
408 };
409 struct nl_req {
410 nlmsghdr hdr;
411 rtgenmsg gen;
412 } req = {
413 .hdr =
414 {
415 .nlmsg_len = NLMSG_LENGTH(sizeof(rtgenmsg)),
416 .nlmsg_type = RTM_GETNEIGH,
417 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
418 .nlmsg_seq = 1,
419 },
420 .gen =
421 {
422 .rtgen_family = AF_INET6,
423 },
424 };
425 iovec io_req = {
426 .iov_base = &req,
427 .iov_len = req.hdr.nlmsg_len,
428 };
429 msghdr rtnl_req = {
430 .msg_name = &kernel,
431 .msg_namelen = sizeof(kernel),
432 .msg_iov = &io_req,
433 .msg_iovlen = 1,
434 };
Taoyu Lie47df4a2019-11-08 12:48:57 +0900435 if (sendmsg(rtnl_fd_.get(), &rtnl_req, 0) < 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900436 PLOG(ERROR) << "sendmsg() failed on rtnetlink socket";
437 return false;
438 }
439
440 static constexpr size_t kRtnlReplyBufferSize = 32768;
441 char reply_buffer[kRtnlReplyBufferSize];
442 iovec io_reply = {
443 .iov_base = reply_buffer,
444 .iov_len = kRtnlReplyBufferSize,
445 };
446 msghdr rtnl_reply = {
447 .msg_name = &kernel,
448 .msg_namelen = sizeof(kernel),
449 .msg_iov = &io_reply,
450 .msg_iovlen = 1,
451 };
452
453 bool any_entry_matched = false;
454 bool done = false;
455 while (!done) {
456 ssize_t len;
Taoyu Lie47df4a2019-11-08 12:48:57 +0900457 if ((len = recvmsg(rtnl_fd_.get(), &rtnl_reply, 0)) < 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900458 PLOG(ERROR) << "recvmsg() failed on rtnetlink socket";
459 return false;
460 }
461 for (nlmsghdr* msg_ptr = reinterpret_cast<nlmsghdr*>(reply_buffer);
462 NLMSG_OK(msg_ptr, len); msg_ptr = NLMSG_NEXT(msg_ptr, len)) {
463 switch (msg_ptr->nlmsg_type) {
464 case NLMSG_DONE: {
465 done = true;
466 break;
467 }
468 case RTM_NEWNEIGH: {
469 // Bitmap - 0x1: Found IP match; 0x2: found MAC address;
470 uint8_t current_entry_status = 0x0;
471 uint8_t current_mac[ETHER_ADDR_LEN];
472 ndmsg* nd_msg = reinterpret_cast<ndmsg*>(NLMSG_DATA(msg_ptr));
473 rtattr* rt_attr = reinterpret_cast<rtattr*>(RTM_RTA(nd_msg));
474 size_t rt_attr_len = RTM_PAYLOAD(msg_ptr);
475 for (; RTA_OK(rt_attr, rt_attr_len);
476 rt_attr = RTA_NEXT(rt_attr, rt_attr_len)) {
477 if (rt_attr->rta_type == NDA_DST &&
Taoyu Lie47df4a2019-11-08 12:48:57 +0900478 memcmp(&ipv6_addr, RTA_DATA(rt_attr), sizeof(in6_addr)) == 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900479 current_entry_status |= 0x1;
480 } else if (rt_attr->rta_type == NDA_LLADDR) {
481 current_entry_status |= 0x2;
482 memcpy(current_mac, RTA_DATA(rt_attr), ETHER_ADDR_LEN);
483 }
484 }
485 if (current_entry_status == 0x3) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900486 memcpy(mac_addr->data(), current_mac, ETHER_ADDR_LEN);
Taoyu Li43f66882019-10-25 16:59:34 +0900487 any_entry_matched = true;
488 }
489 break;
490 }
491 default: {
492 LOG(WARNING) << "received unexpected rtnetlink message type "
493 << msg_ptr->nlmsg_type << ", length "
494 << msg_ptr->nlmsg_len;
495 break;
496 }
497 }
498 }
499 }
500 return any_entry_matched;
501}
502
Taoyu Lie47df4a2019-11-08 12:48:57 +0900503void NDProxy::RegisterOnGuestIpDiscoveryHandler(
504 const base::Callback<void(const std::string&, const std::string&)>&
505 handler) {
506 guest_discovery_handler_ = handler;
507}
508
Taoyu Lia0727dc2020-09-24 19:54:59 +0900509void NDProxy::RegisterOnRouterDiscoveryHandler(
510 const base::Callback<void(const std::string&, const std::string&)>&
511 handler) {
512 router_discovery_handler_ = handler;
513}
514
Taoyu Liaa6238b2019-09-06 17:38:52 +0900515NDProxy::interface_mapping* NDProxy::MapForType(uint8_t type) {
516 switch (type) {
517 case ND_ROUTER_SOLICIT:
518 return &if_map_rs_;
519 case ND_ROUTER_ADVERT:
520 return &if_map_ra_;
521 case ND_NEIGHBOR_SOLICIT:
522 return &if_map_ns_na_;
523 case ND_NEIGHBOR_ADVERT:
524 return &if_map_ns_na_;
525 default:
526 LOG(DFATAL) << "Attempt to get interface map on illegal icmpv6 type "
527 << static_cast<int>(type);
528 return nullptr;
529 }
530}
531
Taoyu Li7dca19a2020-03-16 16:27:07 +0900532bool NDProxy::AddInterfacePair(const std::string& ifname_physical,
533 const std::string& ifname_guest) {
534 LOG(INFO) << "Adding interface pair between physical: " << ifname_physical
535 << ", guest: " << ifname_guest;
536 int ifid_physical = if_nametoindex(ifname_physical.c_str());
537 if (ifid_physical == 0) {
538 PLOG(ERROR) << "Get interface index failed on " << ifname_physical;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900539 return false;
540 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900541 int ifid_guest = if_nametoindex(ifname_guest.c_str());
542 if (ifid_guest == 0) {
543 PLOG(ERROR) << "Get interface index failed on " << ifname_guest;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900544 return false;
545 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900546 if (ifid_physical == ifid_guest) {
Taoyu Liaa6238b2019-09-06 17:38:52 +0900547 LOG(ERROR) << "Rejected attempt to forward between same interface "
Taoyu Li7dca19a2020-03-16 16:27:07 +0900548 << ifname_physical << " and " << ifname_guest;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900549 return false;
550 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900551 if_map_rs_[ifid_guest].insert(ifid_physical);
552 if_map_ra_[ifid_physical].insert(ifid_guest);
553 if_map_ns_na_[ifid_physical].insert(ifid_guest);
554 if_map_ns_na_[ifid_guest].insert(ifid_physical);
555 for (int ifid_other_guest : if_map_ra_[ifid_physical]) {
556 if (ifid_other_guest != ifid_guest) {
557 if_map_ns_na_[ifid_other_guest].insert(ifid_guest);
558 if_map_ns_na_[ifid_guest].insert(ifid_other_guest);
559 }
Taoyu Liaa6238b2019-09-06 17:38:52 +0900560 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900561 return true;
562}
563
564bool NDProxy::RemoveInterfacePair(const std::string& ifname_physical,
565 const std::string& ifname_guest) {
566 LOG(INFO) << "Removing interface pair between physical: " << ifname_physical
567 << ", guest: " << ifname_guest;
568 int ifid_physical = if_nametoindex(ifname_physical.c_str());
569 if (ifid_physical == 0) {
570 PLOG(ERROR) << "Get interface index failed on " << ifname_physical;
571 return false;
572 }
573 int ifid_guest = if_nametoindex(ifname_guest.c_str());
574 if (ifid_guest == 0) {
575 PLOG(ERROR) << "Get interface index failed on " << ifname_guest;
576 return false;
577 }
578 if (ifid_physical == ifid_guest) {
579 LOG(ERROR) << "Rejected attempt to forward between same interface "
580 << ifname_physical << " and " << ifname_guest;
581 return false;
582 }
583 if_map_rs_.erase(ifid_guest);
584 if_map_ra_[ifid_physical].erase(ifid_guest);
585 if_map_ns_na_.erase(ifid_guest);
586 if_map_ns_na_[ifid_physical].erase(ifid_guest);
587 for (int ifid_other_guest : if_map_ra_[ifid_physical]) {
588 if_map_ns_na_[ifid_other_guest].erase(ifid_guest);
589 }
Taoyu Liaa6238b2019-09-06 17:38:52 +0900590 return true;
591}
592
593bool NDProxy::RemoveInterface(const std::string& ifname) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900594 LOG(INFO) << "Removing physical interface " << ifname;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900595 int ifindex = if_nametoindex(ifname.c_str());
596 if (ifindex == 0) {
597 PLOG(ERROR) << "Get interface index failed on " << ifname;
598 return false;
599 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900600 for (int ifid_guest : if_map_ra_[ifindex]) {
601 if_map_rs_.erase(ifid_guest);
602 if_map_ns_na_.erase(ifid_guest);
603 }
Taoyu Liaa6238b2019-09-06 17:38:52 +0900604 if_map_ra_.erase(ifindex);
Taoyu Liaa6238b2019-09-06 17:38:52 +0900605 if_map_ns_na_.erase(ifindex);
Taoyu Liaa6238b2019-09-06 17:38:52 +0900606 return true;
607}
608
Taoyu Liaf944c92019-10-01 12:22:31 +0900609bool NDProxy::IsGuestInterface(int ifindex) {
610 return if_map_rs_.find(ifindex) != if_map_rs_.end();
611}
612
Taoyu Lia0727dc2020-09-24 19:54:59 +0900613bool NDProxy::IsRouterInterface(int ifindex) {
614 return if_map_ra_.find(ifindex) != if_map_ra_.end();
615}
616
617std::vector<std::string> NDProxy::GetGuestInterfaces(
618 const std::string& ifname_physical) {
619 std::vector<std::string> result;
620 int ifid_physical = if_nametoindex(ifname_physical.c_str());
621 if (ifid_physical == 0)
622 return result;
623 for (int ifid_guest : if_map_ra_[ifid_physical]) {
624 char ifname[IFNAMSIZ];
625 if_indextoname(ifid_guest, ifname);
626 result.push_back(ifname);
627 }
628 return result;
629}
630
Taoyu Lie47df4a2019-11-08 12:48:57 +0900631NDProxyDaemon::NDProxyDaemon(base::ScopedFD control_fd)
632 : msg_dispatcher_(
633 std::make_unique<MessageDispatcher>(std::move(control_fd))) {}
634
635NDProxyDaemon::~NDProxyDaemon() {}
636
637int NDProxyDaemon::OnInit() {
638 // Prevent the main process from sending us any signals.
639 if (setsid() < 0) {
640 PLOG(ERROR) << "Failed to created a new session with setsid: exiting";
641 return EX_OSERR;
642 }
643
644 EnterChildProcessJail();
645
646 // Register control fd callbacks
647 if (msg_dispatcher_) {
648 msg_dispatcher_->RegisterFailureHandler(base::Bind(
649 &NDProxyDaemon::OnParentProcessExit, weak_factory_.GetWeakPtr()));
650 msg_dispatcher_->RegisterDeviceMessageHandler(base::Bind(
651 &NDProxyDaemon::OnDeviceMessage, weak_factory_.GetWeakPtr()));
652 }
653
654 // Initialize NDProxy and register guest IP discovery callback
655 if (!proxy_.Init()) {
656 PLOG(ERROR) << "Failed to initialize NDProxy internal state";
657 return EX_OSERR;
658 }
659 proxy_.RegisterOnGuestIpDiscoveryHandler(base::Bind(
660 &NDProxyDaemon::OnGuestIpDiscovery, weak_factory_.GetWeakPtr()));
Taoyu Lia0727dc2020-09-24 19:54:59 +0900661 proxy_.RegisterOnRouterDiscoveryHandler(base::Bind(
662 &NDProxyDaemon::OnRouterDiscovery, weak_factory_.GetWeakPtr()));
Taoyu Lie47df4a2019-11-08 12:48:57 +0900663
664 // Initialize data fd
Taoyu Liba04fe32020-01-14 13:19:35 +0900665 fd_ = NDProxy::PreparePacketSocket();
Taoyu Lie47df4a2019-11-08 12:48:57 +0900666 if (!fd_.is_valid()) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900667 return EX_OSERR;
668 }
669
670 // Start watching on data fd
671 watcher_ = base::FileDescriptorWatcher::WatchReadable(
672 fd_.get(), base::Bind(&NDProxyDaemon::OnDataSocketReadReady,
673 weak_factory_.GetWeakPtr()));
674 LOG(INFO) << "Started watching on packet fd...";
675
676 return Daemon::OnInit();
677}
678
679void NDProxyDaemon::OnDataSocketReadReady() {
680 proxy_.ReadAndProcessOneFrame(fd_.get());
681}
682
683void NDProxyDaemon::OnParentProcessExit() {
684 LOG(ERROR) << "Quitting because the parent process died";
685 Quit();
686}
687
688void NDProxyDaemon::OnDeviceMessage(const DeviceMessage& msg) {
689 const std::string& dev_ifname = msg.dev_ifname();
690 LOG_IF(DFATAL, dev_ifname.empty())
691 << "Received DeviceMessage w/ empty dev_ifname";
692 if (msg.has_teardown()) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900693 if (msg.has_br_ifname()) {
694 proxy_.RemoveInterfacePair(dev_ifname, msg.br_ifname());
Taoyu Lia0727dc2020-09-24 19:54:59 +0900695 if (guest_if_addrs_.find(msg.br_ifname()) != guest_if_addrs_.end()) {
696 SendMessage(NDProxyMessage::DEL_ADDR, msg.br_ifname(),
697 guest_if_addrs_[msg.br_ifname()]);
698 guest_if_addrs_.erase(msg.br_ifname());
699 }
700
Taoyu Li7dca19a2020-03-16 16:27:07 +0900701 } else {
Taoyu Lia0727dc2020-09-24 19:54:59 +0900702 auto guest_ifs = proxy_.GetGuestInterfaces(dev_ifname);
Taoyu Li7dca19a2020-03-16 16:27:07 +0900703 proxy_.RemoveInterface(dev_ifname);
Taoyu Lia0727dc2020-09-24 19:54:59 +0900704 for (const auto& guest_if : guest_ifs) {
705 if (guest_if_addrs_.find(guest_if) != guest_if_addrs_.end()) {
706 SendMessage(NDProxyMessage::DEL_ADDR, guest_if,
707 guest_if_addrs_[guest_if]);
708 guest_if_addrs_.erase(guest_if);
709 }
710 }
Taoyu Li7dca19a2020-03-16 16:27:07 +0900711 }
Taoyu Lie47df4a2019-11-08 12:48:57 +0900712 } else if (msg.has_br_ifname()) {
Taoyu Li7dca19a2020-03-16 16:27:07 +0900713 proxy_.AddInterfacePair(dev_ifname, msg.br_ifname());
Taoyu Lie47df4a2019-11-08 12:48:57 +0900714 }
715}
716
717void NDProxyDaemon::OnGuestIpDiscovery(const std::string& ifname,
718 const std::string& ip6addr) {
Taoyu Lia0727dc2020-09-24 19:54:59 +0900719 SendMessage(NDProxyMessage::ADD_ROUTE, ifname, ip6addr);
720}
721
722void NDProxyDaemon::OnRouterDiscovery(const std::string& ifname,
723 const std::string& ip6addr) {
724 std::string current_addr = guest_if_addrs_[ifname];
725 if (current_addr == ip6addr)
726 return;
727 if (!current_addr.empty()) {
728 SendMessage(NDProxyMessage::DEL_ADDR, ifname, current_addr);
729 }
730 SendMessage(NDProxyMessage::ADD_ADDR, ifname, ip6addr);
731 guest_if_addrs_[ifname] = ip6addr;
732}
733
734void NDProxyDaemon::SendMessage(NDProxyMessage::NDProxyEventType type,
735 const std::string& ifname,
736 const std::string& ip6addr) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900737 if (!msg_dispatcher_)
738 return;
Taoyu Lia0727dc2020-09-24 19:54:59 +0900739 NDProxyMessage msg;
740 msg.set_type(type);
741 msg.set_ifname(ifname);
742 msg.set_ip6addr(ip6addr);
Taoyu Lie47df4a2019-11-08 12:48:57 +0900743 IpHelperMessage ipm;
Taoyu Lia0727dc2020-09-24 19:54:59 +0900744 *ipm.mutable_ndproxy_message() = msg;
Taoyu Lie47df4a2019-11-08 12:48:57 +0900745 msg_dispatcher_->SendMessage(ipm);
746}
747
Garrick Evans3388a032020-03-24 11:25:55 +0900748} // namespace patchpanel