blob: fccc8adc3d855119ca841e4c840a2268f75a4893 [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
5#include "arc/network/ndproxy.h"
6
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
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090030#include "arc/network/minijailed_process_runner.h"
31
Taoyu Liaa6238b2019-09-06 17:38:52 +090032namespace arc_networkd {
33namespace {
Taoyu Lifbcda452019-09-11 16:57:25 +090034const unsigned char kBroadcastMacAddress[] = {0xff, 0xff, 0xff,
Taoyu Liaa6238b2019-09-06 17:38:52 +090035 0xff, 0xff, 0xff};
Taoyu Lifbcda452019-09-11 16:57:25 +090036
37sock_filter kNDFrameBpfInstructions[] = {
38 // Load ethernet type.
39 BPF_STMT(BPF_LD | BPF_H | BPF_ABS, offsetof(ether_header, ether_type)),
40 // Check if it equals IPv6, if not, then goto return 0.
41 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ETHERTYPE_IPV6, 0, 9),
42 // Move index to start of IPv6 header.
43 BPF_STMT(BPF_LDX | BPF_IMM, sizeof(ether_header)),
44 // Load IPv6 next header.
45 BPF_STMT(BPF_LD | BPF_B | BPF_IND, offsetof(ip6_hdr, ip6_nxt)),
46 // Check if equals ICMPv6, if not, then goto return 0.
47 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_ICMPV6, 0, 6),
48 // Move index to start of ICMPv6 header.
49 BPF_STMT(BPF_LDX | BPF_IMM, sizeof(ether_header) + sizeof(ip6_hdr)),
50 // Load ICMPv6 type.
51 BPF_STMT(BPF_LD | BPF_B | BPF_IND, offsetof(icmp6_hdr, icmp6_type)),
52 // Check if is ND ICMPv6 message.
53 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_ROUTER_SOLICIT, 4, 0),
54 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_ROUTER_ADVERT, 3, 0),
55 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_NEIGHBOR_SOLICIT, 2, 0),
56 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_NEIGHBOR_ADVERT, 1, 0),
57 // Return 0.
58 BPF_STMT(BPF_RET | BPF_K, 0),
59 // Return MAX.
60 BPF_STMT(BPF_RET | BPF_K, IP_MAXPACKET),
61};
62const sock_fprog kNDFrameBpfProgram = {
63 .len = sizeof(kNDFrameBpfInstructions) / sizeof(sock_filter),
64 .filter = kNDFrameBpfInstructions};
65
Taoyu Liaa6238b2019-09-06 17:38:52 +090066} // namespace
67
Taoyu Lie47df4a2019-11-08 12:48:57 +090068constexpr ssize_t NDProxy::kTranslateErrorNotICMPv6Frame;
69constexpr ssize_t NDProxy::kTranslateErrorNotNDFrame;
70constexpr ssize_t NDProxy::kTranslateErrorInsufficientLength;
71constexpr ssize_t NDProxy::kTranslateErrorBufferMisaligned;
72
73NDProxy::NDProxy()
74 : in_frame_buffer_(AlignFrameBuffer(in_frame_buffer_extended_)),
75 out_frame_buffer_(AlignFrameBuffer(out_frame_buffer_extended_)) {}
76
77bool NDProxy::Init() {
78 rtnl_fd_ = base::ScopedFD(
79 socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE));
80 if (!rtnl_fd_.is_valid()) {
81 PLOG(ERROR) << "socket() failed for rtnetlink socket";
82 return false;
83 }
84 sockaddr_nl local = {
85 .nl_family = AF_NETLINK,
86 .nl_groups = 0,
87 };
88 if (bind(rtnl_fd_.get(), reinterpret_cast<sockaddr*>(&local), sizeof(local)) <
89 0) {
90 PLOG(ERROR) << "bind() failed on rtnetlink socket";
91 return false;
92 }
93
94 dummy_fd_ = base::ScopedFD(socket(AF_INET6, SOCK_DGRAM, 0));
95 if (!dummy_fd_.is_valid()) {
96 PLOG(ERROR) << "socket() failed for dummy socket";
97 return false;
98 }
99 return true;
100}
Taoyu Liaa6238b2019-09-06 17:38:52 +0900101
102// RFC 1071 and RFC 8200 Section 8.1
103// We are doing calculation directly in network order. Note this algorithm works
104// regardless of the endianess of the host.
105uint16_t NDProxy::Icmpv6Checksum(const ip6_hdr* ip6, const icmp6_hdr* icmp6) {
106 uint32_t sum = 0;
107 // Src and Dst IP
108 for (size_t i = 0; i < (sizeof(struct in6_addr) >> 1); ++i)
109 sum += ip6->ip6_src.s6_addr16[i];
110 for (size_t i = 0; i < (sizeof(struct in6_addr) >> 1); ++i)
111 sum += ip6->ip6_dst.s6_addr16[i];
112
113 // Upper-Layer Packet Length
114 sum += ip6->ip6_plen;
115 // Next Header
116 sum += IPPROTO_ICMPV6 << 8;
117
118 // ICMP
119 const uint16_t* word = reinterpret_cast<const uint16_t*>(icmp6);
120 uint16_t len;
121 for (len = ntohs(ip6->ip6_plen); len > 1; len -= 2)
122 sum += *word++;
123 if (len)
124 sum += *word & htons(0x0000ffff);
125
126 // Fold 32-bit into 16 bits
127 while (sum >> 16)
128 sum = (sum & 0xffff) + (sum >> 16);
129 return ~sum;
130}
131
132// In an ICMPv6 Ethernet Frame *frame with length frame_len, replace the mac
133// address in option opt_type into *target_mac. nd_hdr_len indicates the length
134// of ICMPv6 ND message headers (so the first option starts after nd_hdr_len.)
135void NDProxy::ReplaceMacInIcmpOption(uint8_t* frame,
136 ssize_t frame_len,
137 size_t nd_hdr_len,
138 uint8_t opt_type,
Taoyu Lie47df4a2019-11-08 12:48:57 +0900139 const MacAddress& target_mac) {
Taoyu Liaa6238b2019-09-06 17:38:52 +0900140 nd_opt_hdr* opt;
141 nd_opt_hdr* end = reinterpret_cast<nd_opt_hdr*>(&frame[frame_len]);
142 for (opt = reinterpret_cast<nd_opt_hdr*>(frame + ETHER_HDR_LEN +
143 sizeof(ip6_hdr) + nd_hdr_len);
144 opt < end && opt->nd_opt_len > 0;
145 opt = reinterpret_cast<nd_opt_hdr*>(reinterpret_cast<uint64_t*>(opt) +
146 opt->nd_opt_len)) {
147 if (opt->nd_opt_type == opt_type) {
148 uint8_t* mac_in_opt =
149 reinterpret_cast<uint8_t*>(opt) + sizeof(nd_opt_hdr);
Taoyu Lie47df4a2019-11-08 12:48:57 +0900150 memcpy(mac_in_opt, target_mac.data(), ETHER_ADDR_LEN);
Taoyu Liaa6238b2019-09-06 17:38:52 +0900151 }
152 }
153}
154
155// RFC 4389
156// Read the input ICMPv6 frame and determine whether it should be proxied. If
157// so, fill out_frame buffer with proxied frame and return the length of proxied
158// frame (usually same with input frame length). Return a negative value if
159// proxy is not needed or error occured.
Taoyu Li18041fe2019-11-13 15:49:31 +0900160// in_frame: buffer containing input ethernet frame; needs special alignment
161// so that IP header is 4-bytes aligned;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900162// frame_len: the length of input frame;
163// local_mac_addr: MAC address of interface that will be used to send frame;
Taoyu Li18041fe2019-11-13 15:49:31 +0900164// out_frame: buffer for output frame; should have at least space of frame_len;
165// needs special alignment so that IP header is 4-bytes aligned.
Taoyu Liaa6238b2019-09-06 17:38:52 +0900166ssize_t NDProxy::TranslateNDFrame(const uint8_t* in_frame,
167 ssize_t frame_len,
Taoyu Lie47df4a2019-11-08 12:48:57 +0900168 const MacAddress& local_mac_addr,
Taoyu Liaa6238b2019-09-06 17:38:52 +0900169 uint8_t* out_frame) {
Taoyu Li18041fe2019-11-13 15:49:31 +0900170 if ((reinterpret_cast<uintptr_t>(in_frame + ETHER_HDR_LEN) & 0x3) != 0 ||
171 (reinterpret_cast<uintptr_t>(out_frame + ETHER_HDR_LEN) & 0x3) != 0) {
172 return kTranslateErrorBufferMisaligned;
173 }
Taoyu Licc621b22019-10-21 15:03:12 +0900174 if (frame_len < ETHER_HDR_LEN + sizeof(ip6_hdr) + sizeof(icmp6_hdr)) {
Taoyu Liaa6238b2019-09-06 17:38:52 +0900175 return kTranslateErrorInsufficientLength;
176 }
177 if (reinterpret_cast<const ethhdr*>(in_frame)->h_proto != htons(ETH_P_IPV6) ||
178 reinterpret_cast<const ip6_hdr*>(in_frame + ETHER_HDR_LEN)->ip6_nxt !=
179 IPPROTO_ICMPV6) {
180 return kTranslateErrorNotICMPv6Frame;
181 }
182
183 memcpy(out_frame, in_frame, frame_len);
184 ethhdr* eth = reinterpret_cast<ethhdr*>(out_frame);
185 ip6_hdr* ip6 = reinterpret_cast<ip6_hdr*>(out_frame + ETHER_HDR_LEN);
186 icmp6_hdr* icmp6 =
187 reinterpret_cast<icmp6_hdr*>(out_frame + ETHER_HDR_LEN + sizeof(ip6_hdr));
188
189 // If destination MAC is unicast (Individual/Group bit in MAC address == 0),
Taoyu Li43f66882019-10-25 16:59:34 +0900190 // it needs to be modified so guest OS L3 stack can see it.
Taoyu Liaa6238b2019-09-06 17:38:52 +0900191 if (!(eth->h_dest[0] & 0x1)) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900192 MacAddress neighbor_mac;
193 if (GetNeighborMac(ip6->ip6_dst, &neighbor_mac)) {
194 memcpy(eth->h_dest, neighbor_mac.data(), ETHER_ADDR_LEN);
195 } else {
Taoyu Li43f66882019-10-25 16:59:34 +0900196 // If we can't resolve the destination IP into MAC from kernel neighbor
197 // table, fill destination MAC with broadcast MAC instead.
198 memcpy(eth->h_dest, kBroadcastMacAddress, ETHER_ADDR_LEN);
199 }
Taoyu Liaa6238b2019-09-06 17:38:52 +0900200 }
201
202 switch (icmp6->icmp6_type) {
203 case ND_ROUTER_SOLICIT:
204 ReplaceMacInIcmpOption(out_frame, frame_len, sizeof(nd_router_solicit),
205 ND_OPT_SOURCE_LINKADDR, local_mac_addr);
206 break;
207 case ND_ROUTER_ADVERT: {
208 // RFC 4389 Section 4.1.3.3 - Set Proxy bit
209 nd_router_advert* ra = reinterpret_cast<nd_router_advert*>(icmp6);
210 if (ra->nd_ra_flags_reserved & 0x04) {
211 // According to RFC 4389, an RA packet with 'Proxy' bit set already
212 // should not be proxied again, in order to avoid loop. However, we'll
213 // need this form of proxy cascading in Crostini (Host->VM->Container)
214 // so we are ignoring the check here. Note that we know we are doing RA
215 // proxy in only one direction so there should be no loop.
216 }
217 ra->nd_ra_flags_reserved |= 0x04;
218
219 ReplaceMacInIcmpOption(out_frame, frame_len, sizeof(nd_router_advert),
220 ND_OPT_SOURCE_LINKADDR, local_mac_addr);
221 break;
222 }
223 case ND_NEIGHBOR_SOLICIT:
224 ReplaceMacInIcmpOption(out_frame, frame_len, sizeof(nd_neighbor_solicit),
225 ND_OPT_SOURCE_LINKADDR, local_mac_addr);
226 break;
227 case ND_NEIGHBOR_ADVERT:
228 ReplaceMacInIcmpOption(out_frame, frame_len, sizeof(nd_neighbor_advert),
229 ND_OPT_TARGET_LINKADDR, local_mac_addr);
230 break;
231 default:
232 return kTranslateErrorNotNDFrame;
233 }
234
235 // We need to clear the old checksum first so checksum calculation does not
236 // wrongly take old checksum into account.
237 icmp6->icmp6_cksum = 0;
238 icmp6->icmp6_cksum = Icmpv6Checksum(ip6, icmp6);
239
Taoyu Lie47df4a2019-11-08 12:48:57 +0900240 memcpy(eth->h_source, local_mac_addr.data(), ETHER_ADDR_LEN);
Taoyu Liaa6238b2019-09-06 17:38:52 +0900241 return frame_len;
242}
243
Taoyu Lie47df4a2019-11-08 12:48:57 +0900244void NDProxy::ReadAndProcessOneFrame(int fd) {
245 sockaddr_ll dst_addr;
246 struct iovec iov = {
247 .iov_base = in_frame_buffer_,
248 .iov_len = IP_MAXPACKET,
Taoyu Li43f66882019-10-25 16:59:34 +0900249 };
Taoyu Lie47df4a2019-11-08 12:48:57 +0900250 msghdr hdr = {
251 .msg_name = &dst_addr,
252 .msg_namelen = sizeof(dst_addr),
253 .msg_iov = &iov,
254 .msg_iovlen = 1,
255 .msg_control = nullptr,
256 .msg_controllen = 0,
257 .msg_flags = 0,
258 };
259
260 ssize_t len;
261 if ((len = recvmsg(fd, &hdr, 0)) < 0) {
262 PLOG(ERROR) << "recvmsg() failed";
263 return;
264 }
265 ip6_hdr* ip6 = reinterpret_cast<ip6_hdr*>(in_frame_buffer_ + ETH_HLEN);
266 icmp6_hdr* icmp6 = reinterpret_cast<icmp6_hdr*>(
267 in_frame_buffer_ + ETHER_HDR_LEN + sizeof(ip6_hdr));
268
269 if (ip6->ip6_nxt != IPPROTO_ICMPV6 || icmp6->icmp6_type < ND_ROUTER_SOLICIT ||
270 icmp6->icmp6_type > ND_NEIGHBOR_ADVERT)
271 return;
272
Taoyu Lic48871b2019-12-18 12:57:25 +0900273 // Notify DeviceManager on receiving NA from guest, so a /128 route to the
274 // guest can be added on the host.
275 if (icmp6->icmp6_type == ND_NEIGHBOR_ADVERT &&
Taoyu Lie47df4a2019-11-08 12:48:57 +0900276 IsGuestInterface(dst_addr.sll_ifindex) &&
277 !guest_discovery_handler_.is_null()) {
Taoyu Lic48871b2019-12-18 12:57:25 +0900278 nd_neighbor_advert* na = reinterpret_cast<nd_neighbor_advert*>(icmp6);
279 if ((na->nd_na_target.s6_addr[0] & 0xe0) == 0x20) { // Global Unicast
280 char ifname[IFNAMSIZ];
281 if_indextoname(dst_addr.sll_ifindex, ifname);
282 char ipv6_addr_str[INET6_ADDRSTRLEN];
283 inet_ntop(AF_INET6, &(na->nd_na_target.s6_addr), ipv6_addr_str,
284 INET6_ADDRSTRLEN);
285 guest_discovery_handler_.Run(std::string(ifname),
286 std::string(ipv6_addr_str));
287 }
Taoyu Li43f66882019-10-25 16:59:34 +0900288 }
289
Taoyu Lie47df4a2019-11-08 12:48:57 +0900290 auto map_entry = MapForType(icmp6->icmp6_type)->find(dst_addr.sll_ifindex);
291 if (map_entry == MapForType(icmp6->icmp6_type)->end())
292 return;
293 const auto& target_ifs = map_entry->second;
294 for (int target_if : target_ifs) {
295 MacAddress local_mac;
296 if (!GetLocalMac(target_if, &local_mac))
297 continue;
298 int result =
299 TranslateNDFrame(in_frame_buffer_, len, local_mac, out_frame_buffer_);
300 if (result < 0) {
301 switch (result) {
302 case kTranslateErrorNotICMPv6Frame:
303 LOG(DFATAL) << "Attempt to TranslateNDFrame on a non-ICMPv6 frame";
304 return;
305 case kTranslateErrorNotNDFrame:
306 LOG(DFATAL) << "Attempt to TranslateNDFrame on a non-NDP frame, "
307 "icmpv6 type = "
308 << static_cast<int>(reinterpret_cast<icmp6_hdr*>(
309 in_frame_buffer_ + ETHER_HDR_LEN +
310 sizeof(ip6_hdr))
311 ->icmp6_type);
312 return;
313 case kTranslateErrorInsufficientLength:
314 LOG(DFATAL) << "TranslateNDFrame failed: frame_len = " << len
315 << " is too small";
316 return;
317 default:
318 LOG(DFATAL) << "Unknown error in TranslateNDFrame";
319 return;
320 }
321 }
322
323 struct iovec iov_out = {
324 .iov_base = out_frame_buffer_,
325 .iov_len = static_cast<size_t>(len),
326 };
327 sockaddr_ll addr = {
328 .sll_family = AF_PACKET,
329 .sll_protocol = htons(ETH_P_IPV6),
330 .sll_ifindex = target_if,
331 .sll_halen = ETHER_ADDR_LEN,
332 };
333 memcpy(addr.sll_addr, reinterpret_cast<ethhdr*>(out_frame_buffer_)->h_dest,
334 ETHER_ADDR_LEN);
335 msghdr hdr = {
336 .msg_name = &addr,
337 .msg_namelen = sizeof(addr),
338 .msg_iov = &iov_out,
339 .msg_iovlen = 1,
340 .msg_control = nullptr,
341 .msg_controllen = 0,
342 };
343 if (sendmsg(fd, &hdr, 0) < 0) {
344 PLOG(ERROR) << "sendmsg() failed on interface " << target_if;
345 }
346 }
347}
348
349bool NDProxy::GetLocalMac(int if_id, MacAddress* mac_addr) {
350 ifreq ifr = {
351 .ifr_ifindex = if_id,
352 };
353 if (ioctl(dummy_fd_.get(), SIOCGIFNAME, &ifr) < 0) {
354 PLOG(ERROR) << "ioctl() failed to get interface name on interface "
355 << if_id;
356 return false;
357 }
358 if (ioctl(dummy_fd_.get(), SIOCGIFHWADDR, &ifr) < 0) {
359 PLOG(ERROR) << "ioctl() failed to get MAC address on interface " << if_id;
360 return false;
361 }
362 memcpy(mac_addr->data(), ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
363 return true;
364}
365
366bool NDProxy::GetNeighborMac(const in6_addr& ipv6_addr, MacAddress* mac_addr) {
Taoyu Li43f66882019-10-25 16:59:34 +0900367 sockaddr_nl kernel = {
368 .nl_family = AF_NETLINK,
369 .nl_groups = 0,
370 };
371 struct nl_req {
372 nlmsghdr hdr;
373 rtgenmsg gen;
374 } req = {
375 .hdr =
376 {
377 .nlmsg_len = NLMSG_LENGTH(sizeof(rtgenmsg)),
378 .nlmsg_type = RTM_GETNEIGH,
379 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
380 .nlmsg_seq = 1,
381 },
382 .gen =
383 {
384 .rtgen_family = AF_INET6,
385 },
386 };
387 iovec io_req = {
388 .iov_base = &req,
389 .iov_len = req.hdr.nlmsg_len,
390 };
391 msghdr rtnl_req = {
392 .msg_name = &kernel,
393 .msg_namelen = sizeof(kernel),
394 .msg_iov = &io_req,
395 .msg_iovlen = 1,
396 };
Taoyu Lie47df4a2019-11-08 12:48:57 +0900397 if (sendmsg(rtnl_fd_.get(), &rtnl_req, 0) < 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900398 PLOG(ERROR) << "sendmsg() failed on rtnetlink socket";
399 return false;
400 }
401
402 static constexpr size_t kRtnlReplyBufferSize = 32768;
403 char reply_buffer[kRtnlReplyBufferSize];
404 iovec io_reply = {
405 .iov_base = reply_buffer,
406 .iov_len = kRtnlReplyBufferSize,
407 };
408 msghdr rtnl_reply = {
409 .msg_name = &kernel,
410 .msg_namelen = sizeof(kernel),
411 .msg_iov = &io_reply,
412 .msg_iovlen = 1,
413 };
414
415 bool any_entry_matched = false;
416 bool done = false;
417 while (!done) {
418 ssize_t len;
Taoyu Lie47df4a2019-11-08 12:48:57 +0900419 if ((len = recvmsg(rtnl_fd_.get(), &rtnl_reply, 0)) < 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900420 PLOG(ERROR) << "recvmsg() failed on rtnetlink socket";
421 return false;
422 }
423 for (nlmsghdr* msg_ptr = reinterpret_cast<nlmsghdr*>(reply_buffer);
424 NLMSG_OK(msg_ptr, len); msg_ptr = NLMSG_NEXT(msg_ptr, len)) {
425 switch (msg_ptr->nlmsg_type) {
426 case NLMSG_DONE: {
427 done = true;
428 break;
429 }
430 case RTM_NEWNEIGH: {
431 // Bitmap - 0x1: Found IP match; 0x2: found MAC address;
432 uint8_t current_entry_status = 0x0;
433 uint8_t current_mac[ETHER_ADDR_LEN];
434 ndmsg* nd_msg = reinterpret_cast<ndmsg*>(NLMSG_DATA(msg_ptr));
435 rtattr* rt_attr = reinterpret_cast<rtattr*>(RTM_RTA(nd_msg));
436 size_t rt_attr_len = RTM_PAYLOAD(msg_ptr);
437 for (; RTA_OK(rt_attr, rt_attr_len);
438 rt_attr = RTA_NEXT(rt_attr, rt_attr_len)) {
439 if (rt_attr->rta_type == NDA_DST &&
Taoyu Lie47df4a2019-11-08 12:48:57 +0900440 memcmp(&ipv6_addr, RTA_DATA(rt_attr), sizeof(in6_addr)) == 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900441 current_entry_status |= 0x1;
442 } else if (rt_attr->rta_type == NDA_LLADDR) {
443 current_entry_status |= 0x2;
444 memcpy(current_mac, RTA_DATA(rt_attr), ETHER_ADDR_LEN);
445 }
446 }
447 if (current_entry_status == 0x3) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900448 memcpy(mac_addr->data(), current_mac, ETHER_ADDR_LEN);
Taoyu Li43f66882019-10-25 16:59:34 +0900449 any_entry_matched = true;
450 }
451 break;
452 }
453 default: {
454 LOG(WARNING) << "received unexpected rtnetlink message type "
455 << msg_ptr->nlmsg_type << ", length "
456 << msg_ptr->nlmsg_len;
457 break;
458 }
459 }
460 }
461 }
462 return any_entry_matched;
463}
464
Taoyu Lie47df4a2019-11-08 12:48:57 +0900465void NDProxy::RegisterOnGuestIpDiscoveryHandler(
466 const base::Callback<void(const std::string&, const std::string&)>&
467 handler) {
468 guest_discovery_handler_ = handler;
469}
470
471bool NDProxy::AddRouterInterfacePair(const std::string& ifname_physical,
472 const std::string& ifname_guest) {
473 LOG(INFO) << "Adding interface pair between physical: " << ifname_physical
474 << ", guest: " << ifname_guest;
475 return AddInterfacePairInternal(ifname_physical, ifname_guest, true);
476}
477
478bool NDProxy::AddPeeringInterfacePair(const std::string& ifname1,
479 const std::string& ifname2) {
480 LOG(INFO) << "Adding peering interface pair between " << ifname1 << " and "
481 << ifname2;
482 return AddInterfacePairInternal(ifname1, ifname2, false);
483}
484
Taoyu Liaa6238b2019-09-06 17:38:52 +0900485NDProxy::interface_mapping* NDProxy::MapForType(uint8_t type) {
486 switch (type) {
487 case ND_ROUTER_SOLICIT:
488 return &if_map_rs_;
489 case ND_ROUTER_ADVERT:
490 return &if_map_ra_;
491 case ND_NEIGHBOR_SOLICIT:
492 return &if_map_ns_na_;
493 case ND_NEIGHBOR_ADVERT:
494 return &if_map_ns_na_;
495 default:
496 LOG(DFATAL) << "Attempt to get interface map on illegal icmpv6 type "
497 << static_cast<int>(type);
498 return nullptr;
499 }
500}
501
Taoyu Liaa6238b2019-09-06 17:38:52 +0900502bool NDProxy::AddInterfacePairInternal(const std::string& ifname1,
503 const std::string& ifname2,
504 bool proxy_rs_ra) {
505 int ifindex1 = if_nametoindex(ifname1.c_str());
506 if (ifindex1 == 0) {
507 PLOG(ERROR) << "Get interface index failed on " << ifname1;
508 return false;
509 }
510 int ifindex2 = if_nametoindex(ifname2.c_str());
511 if (ifindex2 == 0) {
512 PLOG(ERROR) << "Get interface index failed on " << ifname2;
513 return false;
514 }
515 if (ifindex1 == ifindex2) {
516 LOG(ERROR) << "Rejected attempt to forward between same interface "
517 << ifname1 << " and " << ifname2;
518 return false;
519 }
520 if (proxy_rs_ra) {
521 if_map_rs_[ifindex2].insert(ifindex1);
522 if_map_ra_[ifindex1].insert(ifindex2);
523 }
524 if_map_ns_na_[ifindex1].insert(ifindex2);
525 if_map_ns_na_[ifindex2].insert(ifindex1);
526 return true;
527}
528
529bool NDProxy::RemoveInterface(const std::string& ifname) {
Taoyu Lif0370c92019-09-18 15:04:37 +0900530 LOG(INFO) << "Removing interface " << ifname;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900531 int ifindex = if_nametoindex(ifname.c_str());
532 if (ifindex == 0) {
533 PLOG(ERROR) << "Get interface index failed on " << ifname;
534 return false;
535 }
536 if_map_rs_.erase(ifindex);
537 for (auto& kv : if_map_rs_)
538 kv.second.erase(ifindex);
539 if_map_ra_.erase(ifindex);
540 for (auto& kv : if_map_ra_)
541 kv.second.erase(ifindex);
542 if_map_ns_na_.erase(ifindex);
543 for (auto& kv : if_map_ns_na_)
544 kv.second.erase(ifindex);
545 return true;
546}
547
Taoyu Liaf944c92019-10-01 12:22:31 +0900548bool NDProxy::IsGuestInterface(int ifindex) {
549 return if_map_rs_.find(ifindex) != if_map_rs_.end();
550}
551
Taoyu Lie47df4a2019-11-08 12:48:57 +0900552NDProxyDaemon::NDProxyDaemon(base::ScopedFD control_fd)
553 : msg_dispatcher_(
554 std::make_unique<MessageDispatcher>(std::move(control_fd))) {}
555
556NDProxyDaemon::~NDProxyDaemon() {}
557
558int NDProxyDaemon::OnInit() {
559 // Prevent the main process from sending us any signals.
560 if (setsid() < 0) {
561 PLOG(ERROR) << "Failed to created a new session with setsid: exiting";
562 return EX_OSERR;
563 }
564
565 EnterChildProcessJail();
566
567 // Register control fd callbacks
568 if (msg_dispatcher_) {
569 msg_dispatcher_->RegisterFailureHandler(base::Bind(
570 &NDProxyDaemon::OnParentProcessExit, weak_factory_.GetWeakPtr()));
571 msg_dispatcher_->RegisterDeviceMessageHandler(base::Bind(
572 &NDProxyDaemon::OnDeviceMessage, weak_factory_.GetWeakPtr()));
573 }
574
575 // Initialize NDProxy and register guest IP discovery callback
576 if (!proxy_.Init()) {
577 PLOG(ERROR) << "Failed to initialize NDProxy internal state";
578 return EX_OSERR;
579 }
580 proxy_.RegisterOnGuestIpDiscoveryHandler(base::Bind(
581 &NDProxyDaemon::OnGuestIpDiscovery, weak_factory_.GetWeakPtr()));
582
583 // Initialize data fd
584 fd_ = base::ScopedFD(
585 socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC, htons(ETH_P_IPV6)));
586 if (!fd_.is_valid()) {
587 PLOG(ERROR) << "socket() failed";
588 return EX_OSERR;
589 }
590 if (setsockopt(fd_.get(), SOL_SOCKET, SO_ATTACH_FILTER, &kNDFrameBpfProgram,
591 sizeof(kNDFrameBpfProgram))) {
592 PLOG(ERROR) << "setsockopt(SO_ATTACH_FILTER) failed";
593 return EX_OSERR;
594 }
595
596 // Start watching on data fd
597 watcher_ = base::FileDescriptorWatcher::WatchReadable(
598 fd_.get(), base::Bind(&NDProxyDaemon::OnDataSocketReadReady,
599 weak_factory_.GetWeakPtr()));
600 LOG(INFO) << "Started watching on packet fd...";
601
602 return Daemon::OnInit();
603}
604
605void NDProxyDaemon::OnDataSocketReadReady() {
606 proxy_.ReadAndProcessOneFrame(fd_.get());
607}
608
609void NDProxyDaemon::OnParentProcessExit() {
610 LOG(ERROR) << "Quitting because the parent process died";
611 Quit();
612}
613
614void NDProxyDaemon::OnDeviceMessage(const DeviceMessage& msg) {
615 const std::string& dev_ifname = msg.dev_ifname();
616 LOG_IF(DFATAL, dev_ifname.empty())
617 << "Received DeviceMessage w/ empty dev_ifname";
618 if (msg.has_teardown()) {
619 proxy_.RemoveInterface(dev_ifname);
620 } else if (msg.has_br_ifname()) {
621 proxy_.AddRouterInterfacePair(dev_ifname, msg.br_ifname());
622 }
623}
624
625void NDProxyDaemon::OnGuestIpDiscovery(const std::string& ifname,
626 const std::string& ip6addr) {
627 // Send information back to DeviceManager
628 if (!msg_dispatcher_)
629 return;
630 DeviceMessage msg;
631 msg.set_dev_ifname(ifname);
632 msg.set_guest_ip6addr(ip6addr);
633 IpHelperMessage ipm;
634 *ipm.mutable_device_message() = msg;
635 msg_dispatcher_->SendMessage(ipm);
636}
637
Taoyu Liaa6238b2019-09-06 17:38:52 +0900638} // namespace arc_networkd