1 /*
2 * Copyright 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * tun_interface.cpp - creates tun or tap interfaces for testing purposes
17 */
18
19 #include <string>
20
21 #include <fcntl.h>
22 #include <linux/if.h>
23 #include <linux/if_tun.h>
24 #include <linux/netlink.h>
25 #include <linux/rtnetlink.h>
26 #include <net/if.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <stdlib.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <unistd.h>
35
36 #include <android-base/stringprintf.h>
37 #include <android-base/strings.h>
38 #include <android-base/unique_fd.h>
39 #include <netutils/ifc.h>
40
41 #include "tun_interface.h"
42
43 #define TUN_DEV "/dev/net/tun"
44
45 using android::base::StringPrintf;
46 using android::base::unique_fd;
47
48 namespace android {
49 namespace net {
50
init(const std::string & ifName,bool isTap)51 int TunInterface::init(const std::string& ifName, bool isTap) {
52 // Generate a random ULA address pair.
53 arc4random_buf(&mSrcAddr, sizeof(mSrcAddr));
54 mSrcAddr.s6_addr[0] = 0xfd;
55 memcpy(&mDstAddr, &mSrcAddr, sizeof(mDstAddr));
56 mDstAddr.s6_addr[15] ^= 1;
57
58 // Convert the addresses to strings because that's what ifc_add_address takes.
59 char srcStr[INET6_ADDRSTRLEN], dstStr[INET6_ADDRSTRLEN];
60 sockaddr_in6 src6 = { .sin6_family = AF_INET6, .sin6_addr = mSrcAddr, };
61 sockaddr_in6 dst6 = { .sin6_family = AF_INET6, .sin6_addr = mDstAddr, };
62 int flags = NI_NUMERICHOST;
63 if (getnameinfo((sockaddr *) &src6, sizeof(src6), srcStr, sizeof(srcStr), nullptr, 0, flags) ||
64 getnameinfo((sockaddr *) &dst6, sizeof(dst6), dstStr, sizeof(dstStr), nullptr, 0, flags)) {
65 return -EINVAL;
66 }
67
68 // Create a tun interface with a name based on a random number.
69 // In order to fit the size of interface alert name , resize ifname to 9
70 // Alert name format in netd: ("%sAlert", ifname)
71 // Limitation in kernel: char name[15] in struct xt_quota_mtinfo2
72
73 // Note that this form of alert doesn't actually appear to be used for interface alerts.
74 // It can only be created by BandwidthController::setInterfaceAlert, but that appears to have no
75 // actual callers in the framework, because mActiveAlerts is always empty.
76 // TODO: remove setInterfaceAlert and use a longer interface name.
77 mIfName = ifName;
78 if (mIfName.empty()) {
79 mIfName = StringPrintf("netd%x", arc4random());
80 }
81 mIfName.resize(9);
82
83 flags = IFF_NO_PI | (isTap ? IFF_TAP : IFF_TUN);
84 struct ifreq ifr = {
85 .ifr_ifru = {.ifru_flags = static_cast<short>(flags)},
86 };
87 strlcpy(ifr.ifr_name, mIfName.c_str(), sizeof(ifr.ifr_name));
88
89 mFd = open(TUN_DEV, O_RDWR | O_NONBLOCK | O_CLOEXEC);
90 if (mFd == -1) return -errno;
91
92 int ret = ioctl(mFd, TUNSETIFF, &ifr, sizeof(ifr));
93 if (ret == -1) {
94 ret = -errno;
95 close(mFd);
96 return ret;
97 }
98
99 mIfIndex = if_nametoindex(ifr.ifr_name);
100
101 if (addAddress(srcStr, 64) || addAddress(dstStr, 64)) {
102 ret = -errno;
103 close(mFd);
104 return ret;
105 }
106
107 if (int ret = ifc_enable(ifr.ifr_name)) {
108 return ret;
109 }
110
111 return 0;
112 }
113
destroy()114 void TunInterface::destroy() {
115 if (mFd != -1) {
116 ifc_disable(mIfName.c_str());
117 close(mFd);
118 mFd = -1;
119 }
120 }
121
addAddress(const std::string & addr,int prefixlen)122 int TunInterface::addAddress(const std::string& addr, int prefixlen) {
123 // Wait for an RTM_NEWADDR indicating that the address has been created.
124 // This is because IPv6 addresses, even addresses that are optimistic or created with
125 // IFA_F_NODAD, are not immediately usable when the netlink ACK returns.
126 // This is not generally necessary in device code because the framework hears about IP addresses
127 // asynchronously via netlink, but it is necessary to ensure tests aren't flaky.
128 unique_fd s(socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, 0));
129 if (s == -1) return -errno;
130
131 sockaddr_nl groups = {.nl_family = AF_NETLINK,
132 .nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR};
133 if (bind(s, reinterpret_cast<sockaddr*>(&groups), sizeof(groups)) == -1) return -errno;
134
135 sockaddr_nl kernel = {.nl_family = AF_NETLINK};
136 if (connect(s, reinterpret_cast<sockaddr*>(&kernel), sizeof(kernel)) == -1) return -errno;
137
138 // Wait up to 200ms for address to arrive.
139 timeval timeout = {.tv_usec = 200 * 1000};
140 if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) return -errno;
141
142 if (int ret = ifc_act_on_address(RTM_NEWADDR, mIfName.c_str(), addr.c_str(), prefixlen,
143 /*nodad*/ true))
144 return ret;
145
146 int family;
147 size_t addrlen;
148 union {
149 in_addr ip4;
150 in6_addr ip6;
151 } ip;
152 if (addr.find(':') != std::string::npos) {
153 family = AF_INET6;
154 inet_pton(AF_INET6, addr.c_str(), &ip.ip6);
155 addrlen = sizeof(ip.ip6);
156 } else {
157 family = AF_INET;
158 inet_pton(AF_INET, addr.c_str(), &ip.ip4);
159 addrlen = sizeof(ip.ip4);
160 }
161
162 while (1) {
163 char buf[4096];
164 ssize_t len = recv(s, buf, sizeof(buf), 0);
165
166 if (len == -1) break;
167 if (len < static_cast<ssize_t>(NLMSG_SPACE(sizeof(ifaddrmsg)))) continue;
168
169 nlmsghdr* nlmsg = reinterpret_cast<nlmsghdr*>(buf);
170 if (nlmsg->nlmsg_type != RTM_NEWADDR) continue;
171
172 ifaddrmsg* ifaddr = reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(nlmsg));
173 if (ifaddr->ifa_family != family) continue;
174 if (ifaddr->ifa_prefixlen != prefixlen) continue;
175 if (ifaddr->ifa_index != static_cast<uint32_t>(mIfIndex)) continue;
176
177 int ifalen = IFA_PAYLOAD(nlmsg);
178 for (rtattr* rta = IFA_RTA(ifaddr); RTA_OK(rta, ifalen); rta = RTA_NEXT(rta, ifalen)) {
179 if (rta->rta_type != IFA_LOCAL && rta->rta_type != IFA_ADDRESS) continue;
180 if (RTA_PAYLOAD(rta) != addrlen) continue;
181 if (!memcmp(RTA_DATA(rta), &ip, addrlen)) {
182 return 0;
183 }
184 }
185 }
186
187 return -errno;
188 }
189
190 } // namespace net
191 } // namespace android
192