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 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/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)51 int TunInterface::init(const std::string& ifName) {
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 struct ifreq ifr = {
84 .ifr_ifru = { .ifru_flags = IFF_TUN },
85 };
86 strlcpy(ifr.ifr_name, mIfName.c_str(), sizeof(ifr.ifr_name));
87
88 mFd = open(TUN_DEV, O_RDWR | O_NONBLOCK | O_CLOEXEC);
89 if (mFd == -1) return -errno;
90
91 int ret = ioctl(mFd, TUNSETIFF, &ifr, sizeof(ifr));
92 if (ret == -1) {
93 ret = -errno;
94 close(mFd);
95 return ret;
96 }
97
98 mIfIndex = if_nametoindex(ifr.ifr_name);
99
100 if (addAddress(srcStr, 64) || addAddress(dstStr, 64)) {
101 ret = -errno;
102 close(mFd);
103 return ret;
104 }
105
106 if (int ret = ifc_enable(ifr.ifr_name)) {
107 return ret;
108 }
109 return 0;
110 }
111
destroy()112 void TunInterface::destroy() {
113 if (mFd != -1) {
114 ifc_disable(mIfName.c_str());
115 close(mFd);
116 mFd = -1;
117 }
118 }
119
addAddress(const std::string & addr,int prefixlen)120 int TunInterface::addAddress(const std::string& addr, int prefixlen) {
121 // Wait for an RTM_NEWADDR indicating that the address has been created.
122 // This is because IPv6 addresses, even addresses that are optimistic or created with
123 // IFA_F_NODAD, are not immediately usable when the netlink ACK returns.
124 // This is not generally necessary in device code because the framework hears about IP addresses
125 // asynchronously via netlink, but it is necessary to ensure tests aren't flaky.
126 unique_fd s(socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, 0));
127 if (s == -1) return -errno;
128
129 sockaddr_nl groups = {.nl_family = AF_NETLINK,
130 .nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR};
131 if (bind(s, reinterpret_cast<sockaddr*>(&groups), sizeof(groups)) == -1) return -errno;
132
133 sockaddr_nl kernel = {.nl_family = AF_NETLINK};
134 if (connect(s, reinterpret_cast<sockaddr*>(&kernel), sizeof(kernel)) == -1) return -errno;
135
136 // Wait up to 200ms for address to arrive.
137 timeval timeout = {.tv_usec = 200 * 1000};
138 if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) return -errno;
139
140 if (ifc_add_address(mIfName.c_str(), addr.c_str(), prefixlen)) return -errno;
141
142 int family;
143 size_t addrlen;
144 union {
145 in_addr ip4;
146 in6_addr ip6;
147 } ip;
148 if (addr.find(':') != std::string::npos) {
149 family = AF_INET6;
150 inet_pton(AF_INET6, addr.c_str(), &ip.ip6);
151 addrlen = sizeof(ip.ip6);
152 } else {
153 family = AF_INET;
154 inet_pton(AF_INET, addr.c_str(), &ip.ip4);
155 addrlen = sizeof(ip.ip4);
156 }
157
158 while (1) {
159 char buf[4096];
160 ssize_t len = recv(s, buf, sizeof(buf), 0);
161
162 if (len == -1) break;
163 if (len < static_cast<ssize_t>(NLMSG_SPACE(sizeof(ifaddrmsg)))) continue;
164
165 nlmsghdr* nlmsg = reinterpret_cast<nlmsghdr*>(buf);
166 if (nlmsg->nlmsg_type != RTM_NEWADDR) continue;
167
168 ifaddrmsg* ifaddr = reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(nlmsg));
169 if (ifaddr->ifa_family != family) continue;
170 if (ifaddr->ifa_prefixlen != prefixlen) continue;
171 if (ifaddr->ifa_index != static_cast<uint32_t>(mIfIndex)) continue;
172
173 int ifalen = IFA_PAYLOAD(nlmsg);
174 for (rtattr* rta = IFA_RTA(ifaddr); RTA_OK(rta, ifalen); rta = RTA_NEXT(rta, ifalen)) {
175 if (rta->rta_type != IFA_LOCAL && rta->rta_type != IFA_ADDRESS) continue;
176 if (RTA_PAYLOAD(rta) != addrlen) continue;
177 if (!memcmp(RTA_DATA(rta), &ip, addrlen)) {
178 return 0;
179 }
180 }
181 }
182
183 return -errno;
184 }
185
186 } // namespace net
187 } // namespace android
188