blob: 96b55d2db2eb3c7ec96b6bbe8b535b0863b5e9c1 [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
273 // Notify DeviceManager on receiving guest NA with unicast IPv6 address so
274 // a /128 route to the guest can be added on the host
275 if ((ip6->ip6_src.s6_addr[0] & 0xe0) == 0x20 // Global Unicast
276 && icmp6->icmp6_type == ND_NEIGHBOR_ADVERT &&
277 IsGuestInterface(dst_addr.sll_ifindex) &&
278 !guest_discovery_handler_.is_null()) {
279 char ifname[IFNAMSIZ];
280 if_indextoname(dst_addr.sll_ifindex, ifname);
281 char ipv6_addr_str[INET6_ADDRSTRLEN];
282 inet_ntop(AF_INET6, &(ip6->ip6_src.s6_addr), ipv6_addr_str,
283 INET6_ADDRSTRLEN);
284 guest_discovery_handler_.Run(std::string(ifname),
285 std::string(ipv6_addr_str));
Taoyu Li43f66882019-10-25 16:59:34 +0900286 }
287
Taoyu Lie47df4a2019-11-08 12:48:57 +0900288 auto map_entry = MapForType(icmp6->icmp6_type)->find(dst_addr.sll_ifindex);
289 if (map_entry == MapForType(icmp6->icmp6_type)->end())
290 return;
291 const auto& target_ifs = map_entry->second;
292 for (int target_if : target_ifs) {
293 MacAddress local_mac;
294 if (!GetLocalMac(target_if, &local_mac))
295 continue;
296 int result =
297 TranslateNDFrame(in_frame_buffer_, len, local_mac, out_frame_buffer_);
298 if (result < 0) {
299 switch (result) {
300 case kTranslateErrorNotICMPv6Frame:
301 LOG(DFATAL) << "Attempt to TranslateNDFrame on a non-ICMPv6 frame";
302 return;
303 case kTranslateErrorNotNDFrame:
304 LOG(DFATAL) << "Attempt to TranslateNDFrame on a non-NDP frame, "
305 "icmpv6 type = "
306 << static_cast<int>(reinterpret_cast<icmp6_hdr*>(
307 in_frame_buffer_ + ETHER_HDR_LEN +
308 sizeof(ip6_hdr))
309 ->icmp6_type);
310 return;
311 case kTranslateErrorInsufficientLength:
312 LOG(DFATAL) << "TranslateNDFrame failed: frame_len = " << len
313 << " is too small";
314 return;
315 default:
316 LOG(DFATAL) << "Unknown error in TranslateNDFrame";
317 return;
318 }
319 }
320
321 struct iovec iov_out = {
322 .iov_base = out_frame_buffer_,
323 .iov_len = static_cast<size_t>(len),
324 };
325 sockaddr_ll addr = {
326 .sll_family = AF_PACKET,
327 .sll_protocol = htons(ETH_P_IPV6),
328 .sll_ifindex = target_if,
329 .sll_halen = ETHER_ADDR_LEN,
330 };
331 memcpy(addr.sll_addr, reinterpret_cast<ethhdr*>(out_frame_buffer_)->h_dest,
332 ETHER_ADDR_LEN);
333 msghdr hdr = {
334 .msg_name = &addr,
335 .msg_namelen = sizeof(addr),
336 .msg_iov = &iov_out,
337 .msg_iovlen = 1,
338 .msg_control = nullptr,
339 .msg_controllen = 0,
340 };
341 if (sendmsg(fd, &hdr, 0) < 0) {
342 PLOG(ERROR) << "sendmsg() failed on interface " << target_if;
343 }
344 }
345}
346
347bool NDProxy::GetLocalMac(int if_id, MacAddress* mac_addr) {
348 ifreq ifr = {
349 .ifr_ifindex = if_id,
350 };
351 if (ioctl(dummy_fd_.get(), SIOCGIFNAME, &ifr) < 0) {
352 PLOG(ERROR) << "ioctl() failed to get interface name on interface "
353 << if_id;
354 return false;
355 }
356 if (ioctl(dummy_fd_.get(), SIOCGIFHWADDR, &ifr) < 0) {
357 PLOG(ERROR) << "ioctl() failed to get MAC address on interface " << if_id;
358 return false;
359 }
360 memcpy(mac_addr->data(), ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
361 return true;
362}
363
364bool NDProxy::GetNeighborMac(const in6_addr& ipv6_addr, MacAddress* mac_addr) {
Taoyu Li43f66882019-10-25 16:59:34 +0900365 sockaddr_nl kernel = {
366 .nl_family = AF_NETLINK,
367 .nl_groups = 0,
368 };
369 struct nl_req {
370 nlmsghdr hdr;
371 rtgenmsg gen;
372 } req = {
373 .hdr =
374 {
375 .nlmsg_len = NLMSG_LENGTH(sizeof(rtgenmsg)),
376 .nlmsg_type = RTM_GETNEIGH,
377 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
378 .nlmsg_seq = 1,
379 },
380 .gen =
381 {
382 .rtgen_family = AF_INET6,
383 },
384 };
385 iovec io_req = {
386 .iov_base = &req,
387 .iov_len = req.hdr.nlmsg_len,
388 };
389 msghdr rtnl_req = {
390 .msg_name = &kernel,
391 .msg_namelen = sizeof(kernel),
392 .msg_iov = &io_req,
393 .msg_iovlen = 1,
394 };
Taoyu Lie47df4a2019-11-08 12:48:57 +0900395 if (sendmsg(rtnl_fd_.get(), &rtnl_req, 0) < 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900396 PLOG(ERROR) << "sendmsg() failed on rtnetlink socket";
397 return false;
398 }
399
400 static constexpr size_t kRtnlReplyBufferSize = 32768;
401 char reply_buffer[kRtnlReplyBufferSize];
402 iovec io_reply = {
403 .iov_base = reply_buffer,
404 .iov_len = kRtnlReplyBufferSize,
405 };
406 msghdr rtnl_reply = {
407 .msg_name = &kernel,
408 .msg_namelen = sizeof(kernel),
409 .msg_iov = &io_reply,
410 .msg_iovlen = 1,
411 };
412
413 bool any_entry_matched = false;
414 bool done = false;
415 while (!done) {
416 ssize_t len;
Taoyu Lie47df4a2019-11-08 12:48:57 +0900417 if ((len = recvmsg(rtnl_fd_.get(), &rtnl_reply, 0)) < 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900418 PLOG(ERROR) << "recvmsg() failed on rtnetlink socket";
419 return false;
420 }
421 for (nlmsghdr* msg_ptr = reinterpret_cast<nlmsghdr*>(reply_buffer);
422 NLMSG_OK(msg_ptr, len); msg_ptr = NLMSG_NEXT(msg_ptr, len)) {
423 switch (msg_ptr->nlmsg_type) {
424 case NLMSG_DONE: {
425 done = true;
426 break;
427 }
428 case RTM_NEWNEIGH: {
429 // Bitmap - 0x1: Found IP match; 0x2: found MAC address;
430 uint8_t current_entry_status = 0x0;
431 uint8_t current_mac[ETHER_ADDR_LEN];
432 ndmsg* nd_msg = reinterpret_cast<ndmsg*>(NLMSG_DATA(msg_ptr));
433 rtattr* rt_attr = reinterpret_cast<rtattr*>(RTM_RTA(nd_msg));
434 size_t rt_attr_len = RTM_PAYLOAD(msg_ptr);
435 for (; RTA_OK(rt_attr, rt_attr_len);
436 rt_attr = RTA_NEXT(rt_attr, rt_attr_len)) {
437 if (rt_attr->rta_type == NDA_DST &&
Taoyu Lie47df4a2019-11-08 12:48:57 +0900438 memcmp(&ipv6_addr, RTA_DATA(rt_attr), sizeof(in6_addr)) == 0) {
Taoyu Li43f66882019-10-25 16:59:34 +0900439 current_entry_status |= 0x1;
440 } else if (rt_attr->rta_type == NDA_LLADDR) {
441 current_entry_status |= 0x2;
442 memcpy(current_mac, RTA_DATA(rt_attr), ETHER_ADDR_LEN);
443 }
444 }
445 if (current_entry_status == 0x3) {
Taoyu Lie47df4a2019-11-08 12:48:57 +0900446 memcpy(mac_addr->data(), current_mac, ETHER_ADDR_LEN);
Taoyu Li43f66882019-10-25 16:59:34 +0900447 any_entry_matched = true;
448 }
449 break;
450 }
451 default: {
452 LOG(WARNING) << "received unexpected rtnetlink message type "
453 << msg_ptr->nlmsg_type << ", length "
454 << msg_ptr->nlmsg_len;
455 break;
456 }
457 }
458 }
459 }
460 return any_entry_matched;
461}
462
Taoyu Lie47df4a2019-11-08 12:48:57 +0900463void NDProxy::RegisterOnGuestIpDiscoveryHandler(
464 const base::Callback<void(const std::string&, const std::string&)>&
465 handler) {
466 guest_discovery_handler_ = handler;
467}
468
469bool NDProxy::AddRouterInterfacePair(const std::string& ifname_physical,
470 const std::string& ifname_guest) {
471 LOG(INFO) << "Adding interface pair between physical: " << ifname_physical
472 << ", guest: " << ifname_guest;
473 return AddInterfacePairInternal(ifname_physical, ifname_guest, true);
474}
475
476bool NDProxy::AddPeeringInterfacePair(const std::string& ifname1,
477 const std::string& ifname2) {
478 LOG(INFO) << "Adding peering interface pair between " << ifname1 << " and "
479 << ifname2;
480 return AddInterfacePairInternal(ifname1, ifname2, false);
481}
482
Taoyu Liaa6238b2019-09-06 17:38:52 +0900483NDProxy::interface_mapping* NDProxy::MapForType(uint8_t type) {
484 switch (type) {
485 case ND_ROUTER_SOLICIT:
486 return &if_map_rs_;
487 case ND_ROUTER_ADVERT:
488 return &if_map_ra_;
489 case ND_NEIGHBOR_SOLICIT:
490 return &if_map_ns_na_;
491 case ND_NEIGHBOR_ADVERT:
492 return &if_map_ns_na_;
493 default:
494 LOG(DFATAL) << "Attempt to get interface map on illegal icmpv6 type "
495 << static_cast<int>(type);
496 return nullptr;
497 }
498}
499
Taoyu Liaa6238b2019-09-06 17:38:52 +0900500bool NDProxy::AddInterfacePairInternal(const std::string& ifname1,
501 const std::string& ifname2,
502 bool proxy_rs_ra) {
503 int ifindex1 = if_nametoindex(ifname1.c_str());
504 if (ifindex1 == 0) {
505 PLOG(ERROR) << "Get interface index failed on " << ifname1;
506 return false;
507 }
508 int ifindex2 = if_nametoindex(ifname2.c_str());
509 if (ifindex2 == 0) {
510 PLOG(ERROR) << "Get interface index failed on " << ifname2;
511 return false;
512 }
513 if (ifindex1 == ifindex2) {
514 LOG(ERROR) << "Rejected attempt to forward between same interface "
515 << ifname1 << " and " << ifname2;
516 return false;
517 }
518 if (proxy_rs_ra) {
519 if_map_rs_[ifindex2].insert(ifindex1);
520 if_map_ra_[ifindex1].insert(ifindex2);
521 }
522 if_map_ns_na_[ifindex1].insert(ifindex2);
523 if_map_ns_na_[ifindex2].insert(ifindex1);
524 return true;
525}
526
527bool NDProxy::RemoveInterface(const std::string& ifname) {
Taoyu Lif0370c92019-09-18 15:04:37 +0900528 LOG(INFO) << "Removing interface " << ifname;
Taoyu Liaa6238b2019-09-06 17:38:52 +0900529 int ifindex = if_nametoindex(ifname.c_str());
530 if (ifindex == 0) {
531 PLOG(ERROR) << "Get interface index failed on " << ifname;
532 return false;
533 }
534 if_map_rs_.erase(ifindex);
535 for (auto& kv : if_map_rs_)
536 kv.second.erase(ifindex);
537 if_map_ra_.erase(ifindex);
538 for (auto& kv : if_map_ra_)
539 kv.second.erase(ifindex);
540 if_map_ns_na_.erase(ifindex);
541 for (auto& kv : if_map_ns_na_)
542 kv.second.erase(ifindex);
543 return true;
544}
545
Taoyu Liaf944c92019-10-01 12:22:31 +0900546bool NDProxy::IsGuestInterface(int ifindex) {
547 return if_map_rs_.find(ifindex) != if_map_rs_.end();
548}
549
Taoyu Lie47df4a2019-11-08 12:48:57 +0900550NDProxyDaemon::NDProxyDaemon(base::ScopedFD control_fd)
551 : msg_dispatcher_(
552 std::make_unique<MessageDispatcher>(std::move(control_fd))) {}
553
554NDProxyDaemon::~NDProxyDaemon() {}
555
556int NDProxyDaemon::OnInit() {
557 // Prevent the main process from sending us any signals.
558 if (setsid() < 0) {
559 PLOG(ERROR) << "Failed to created a new session with setsid: exiting";
560 return EX_OSERR;
561 }
562
563 EnterChildProcessJail();
564
565 // Register control fd callbacks
566 if (msg_dispatcher_) {
567 msg_dispatcher_->RegisterFailureHandler(base::Bind(
568 &NDProxyDaemon::OnParentProcessExit, weak_factory_.GetWeakPtr()));
569 msg_dispatcher_->RegisterDeviceMessageHandler(base::Bind(
570 &NDProxyDaemon::OnDeviceMessage, weak_factory_.GetWeakPtr()));
571 }
572
573 // Initialize NDProxy and register guest IP discovery callback
574 if (!proxy_.Init()) {
575 PLOG(ERROR) << "Failed to initialize NDProxy internal state";
576 return EX_OSERR;
577 }
578 proxy_.RegisterOnGuestIpDiscoveryHandler(base::Bind(
579 &NDProxyDaemon::OnGuestIpDiscovery, weak_factory_.GetWeakPtr()));
580
581 // Initialize data fd
582 fd_ = base::ScopedFD(
583 socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC, htons(ETH_P_IPV6)));
584 if (!fd_.is_valid()) {
585 PLOG(ERROR) << "socket() failed";
586 return EX_OSERR;
587 }
588 if (setsockopt(fd_.get(), SOL_SOCKET, SO_ATTACH_FILTER, &kNDFrameBpfProgram,
589 sizeof(kNDFrameBpfProgram))) {
590 PLOG(ERROR) << "setsockopt(SO_ATTACH_FILTER) failed";
591 return EX_OSERR;
592 }
593
594 // Start watching on data fd
595 watcher_ = base::FileDescriptorWatcher::WatchReadable(
596 fd_.get(), base::Bind(&NDProxyDaemon::OnDataSocketReadReady,
597 weak_factory_.GetWeakPtr()));
598 LOG(INFO) << "Started watching on packet fd...";
599
600 return Daemon::OnInit();
601}
602
603void NDProxyDaemon::OnDataSocketReadReady() {
604 proxy_.ReadAndProcessOneFrame(fd_.get());
605}
606
607void NDProxyDaemon::OnParentProcessExit() {
608 LOG(ERROR) << "Quitting because the parent process died";
609 Quit();
610}
611
612void NDProxyDaemon::OnDeviceMessage(const DeviceMessage& msg) {
613 const std::string& dev_ifname = msg.dev_ifname();
614 LOG_IF(DFATAL, dev_ifname.empty())
615 << "Received DeviceMessage w/ empty dev_ifname";
616 if (msg.has_teardown()) {
617 proxy_.RemoveInterface(dev_ifname);
618 } else if (msg.has_br_ifname()) {
619 proxy_.AddRouterInterfacePair(dev_ifname, msg.br_ifname());
620 }
621}
622
623void NDProxyDaemon::OnGuestIpDiscovery(const std::string& ifname,
624 const std::string& ip6addr) {
625 // Send information back to DeviceManager
626 if (!msg_dispatcher_)
627 return;
628 DeviceMessage msg;
629 msg.set_dev_ifname(ifname);
630 msg.set_guest_ip6addr(ip6addr);
631 IpHelperMessage ipm;
632 *ipm.mutable_device_message() = msg;
633 msg_dispatcher_->SendMessage(ipm);
634}
635
Taoyu Liaa6238b2019-09-06 17:38:52 +0900636} // namespace arc_networkd