1 /*
2 * Copyright (C) 2012 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
17 #include <dirent.h>
18 #include <errno.h>
19 #include <malloc.h>
20 #include <net/if.h>
21 #include <net/if_arp.h>
22 #include <sys/socket.h>
23
24 #include <functional>
25
26 #define LOG_TAG "InterfaceController"
27 #include <android-base/file.h>
28 #include <android-base/properties.h>
29 #include <android-base/stringprintf.h>
30 #include <android-base/strings.h>
31 #include <linux/if_ether.h>
32 #include <log/log.h>
33 #include <netutils/ifc.h>
34
35 #include <android/net/INetd.h>
36 #include <netdutils/Misc.h>
37 #include <netdutils/Slice.h>
38 #include <netdutils/Syscalls.h>
39
40 #include "InterfaceController.h"
41 #include "RouteController.h"
42
43 using android::base::ReadFileToString;
44 using android::base::StringPrintf;
45 using android::base::Trim;
46 using android::base::WriteStringToFile;
47 using android::netdutils::isOk;
48 using android::netdutils::makeSlice;
49 using android::netdutils::sSyscalls;
50 using android::netdutils::Status;
51 using android::netdutils::statusFromErrno;
52 using android::netdutils::StatusOr;
53 using android::netdutils::toString;
54 using android::netdutils::status::ok;
55
56 namespace {
57
58 const char ipv4_proc_path[] = "/proc/sys/net/ipv4/conf";
59 const char ipv6_proc_path[] = "/proc/sys/net/ipv6/conf";
60
61 const char ipv4_neigh_conf_dir[] = "/proc/sys/net/ipv4/neigh";
62 const char ipv6_neigh_conf_dir[] = "/proc/sys/net/ipv6/neigh";
63
64 const char proc_net_path[] = "/proc/sys/net";
65 const char sys_net_path[] = "/sys/class/net";
66
67 constexpr int kRouteInfoMinPrefixLen = 48;
68
69 // RFC 7421 prefix length.
70 constexpr int kRouteInfoMaxPrefixLen = 64;
71
72 // Property used to persist RFC 7217 stable secret. Protected by SELinux policy.
73 const char kStableSecretProperty[] = "persist.netd.stable_secret";
74
75 // RFC 7217 stable secret on linux is formatted as an IPv6 address.
76 // This function uses 128 bits of high quality entropy to generate an
77 // address for this purpose. This function should be not be called
78 // frequently.
randomIPv6Address()79 StatusOr<std::string> randomIPv6Address() {
80 in6_addr addr = {};
81 const auto& sys = sSyscalls.get();
82 ASSIGN_OR_RETURN(auto fd, sys.open("/dev/random", O_RDONLY));
83 RETURN_IF_NOT_OK(sys.read(fd, makeSlice(addr)));
84 return toString(addr);
85 }
86
isNormalPathComponent(const char * component)87 inline bool isNormalPathComponent(const char *component) {
88 return (strcmp(component, ".") != 0) &&
89 (strcmp(component, "..") != 0) &&
90 (strchr(component, '/') == nullptr);
91 }
92
isAddressFamilyPathComponent(const char * component)93 inline bool isAddressFamilyPathComponent(const char *component) {
94 return strcmp(component, "ipv4") == 0 || strcmp(component, "ipv6") == 0;
95 }
96
isInterfaceName(const char * name)97 inline bool isInterfaceName(const char *name) {
98 return isNormalPathComponent(name) &&
99 (strcmp(name, "default") != 0) &&
100 (strcmp(name, "all") != 0);
101 }
102
writeValueToPath(const char * dirname,const char * subdirname,const char * basename,const char * value)103 int writeValueToPath(
104 const char* dirname, const char* subdirname, const char* basename,
105 const char* value) {
106 std::string path(StringPrintf("%s/%s/%s", dirname, subdirname, basename));
107 return WriteStringToFile(value, path) ? 0 : -EREMOTEIO;
108 }
109
110 // Run @fn on each interface as well as 'default' in the path @dirname.
forEachInterface(const std::string & dirname,const std::function<void (const std::string & path,const std::string & iface)> & fn)111 void forEachInterface(
112 const std::string& dirname,
113 const std::function<void(const std::string& path, const std::string& iface)>& fn) {
114 // Run on default, which controls the behavior of any interfaces that are created in the future.
115 fn(dirname, "default");
116 DIR* dir = opendir(dirname.c_str());
117 if (!dir) {
118 ALOGE("Can't list %s: %s", dirname.c_str(), strerror(errno));
119 return;
120 }
121 while (true) {
122 const dirent *ent = readdir(dir);
123 if (!ent) {
124 break;
125 }
126 if ((ent->d_type != DT_DIR) || !isInterfaceName(ent->d_name)) {
127 continue;
128 }
129 fn(dirname, ent->d_name);
130 }
131 closedir(dir);
132 }
133
setOnAllInterfaces(const char * dirname,const char * basename,const char * value)134 void setOnAllInterfaces(const char* dirname, const char* basename, const char* value) {
135 auto fn = [basename, value](const std::string& path, const std::string& iface) {
136 writeValueToPath(path.c_str(), iface.c_str(), basename, value);
137 };
138 forEachInterface(dirname, fn);
139 }
140
setIPv6UseOutgoingInterfaceAddrsOnly(const char * value)141 void setIPv6UseOutgoingInterfaceAddrsOnly(const char *value) {
142 setOnAllInterfaces(ipv6_proc_path, "use_oif_addrs_only", value);
143 }
144
getParameterPathname(const char * family,const char * which,const char * interface,const char * parameter)145 std::string getParameterPathname(
146 const char *family, const char *which, const char *interface, const char *parameter) {
147 if (!isAddressFamilyPathComponent(family)) {
148 errno = EAFNOSUPPORT;
149 return "";
150 } else if (!isNormalPathComponent(which) ||
151 !isInterfaceName(interface) ||
152 !isNormalPathComponent(parameter)) {
153 errno = EINVAL;
154 return "";
155 }
156
157 return StringPrintf("%s/%s/%s/%s/%s", proc_net_path, family, which, interface, parameter);
158 }
159
setAcceptIPv6RIO(int min,int max)160 void setAcceptIPv6RIO(int min, int max) {
161 auto fn = [min, max](const std::string& prefix, const std::string& iface) {
162 int rv = writeValueToPath(prefix.c_str(), iface.c_str(), "accept_ra_rt_info_min_plen",
163 std::to_string(min).c_str());
164 if (rv != 0) {
165 // Only update max_plen if the write to min_plen succeeded. This ordering will prevent
166 // RIOs from being accepted unless both min and max are written successfully.
167 return;
168 }
169 writeValueToPath(prefix.c_str(), iface.c_str(), "accept_ra_rt_info_max_plen",
170 std::to_string(max).c_str());
171 };
172 forEachInterface(ipv6_proc_path, fn);
173 }
174
175 // Ideally this function would return StatusOr<std::string>, however
176 // there is no safe value for dflt that will always differ from the
177 // stored property. Bugs code could conceivably end up persisting the
178 // reserved value resulting in surprising behavior.
getProperty(const std::string & key,const std::string & dflt)179 std::string getProperty(const std::string& key, const std::string& dflt) {
180 return android::base::GetProperty(key, dflt);
181 };
182
setProperty(const std::string & key,const std::string & val)183 Status setProperty(const std::string& key, const std::string& val) {
184 // SetProperty does not dependably set errno to a meaningful value. Use our own error code so
185 // callers don't get confused.
186 return android::base::SetProperty(key, val)
187 ? ok
188 : statusFromErrno(EREMOTEIO, "SetProperty failed, see libc logs");
189 };
190
191
192 } // namespace
193
194 namespace android {
195 namespace net {
196 std::mutex InterfaceController::mutex;
197
enableStablePrivacyAddresses(const std::string & iface,const GetPropertyFn & getProperty,const SetPropertyFn & setProperty)198 android::netdutils::Status InterfaceController::enableStablePrivacyAddresses(
199 const std::string& iface,
200 const GetPropertyFn& getProperty,
201 const SetPropertyFn& setProperty) {
202 const auto& sys = sSyscalls.get();
203 const std::string procTarget = std::string(ipv6_proc_path) + "/" + iface + "/stable_secret";
204 auto procFd = sys.open(procTarget, O_CLOEXEC | O_WRONLY);
205
206 // Devices with old kernels (typically < 4.4) don't support
207 // RFC 7217 stable privacy addresses.
208 if (equalToErrno(procFd, ENOENT)) {
209 return statusFromErrno(EOPNOTSUPP,
210 "Failed to open stable_secret. Assuming unsupported kernel version");
211 }
212
213 // If stable_secret exists but we can't open it, something strange is going on.
214 RETURN_IF_NOT_OK(procFd);
215
216 const char kUninitialized[] = "uninitialized";
217 const auto oldSecret = getProperty(kStableSecretProperty, kUninitialized);
218 std::string secret = oldSecret;
219
220 // Generate a new secret if no persistent property existed.
221 if (oldSecret == kUninitialized) {
222 ASSIGN_OR_RETURN(secret, randomIPv6Address());
223 }
224
225 // Ask the OS to generate SLAAC addresses on iface using secret.
226 RETURN_IF_NOT_OK(sys.write(procFd.value(), makeSlice(secret)));
227
228 // Don't persist an existing secret.
229 if (oldSecret != kUninitialized) {
230 return ok;
231 }
232
233 return setProperty(kStableSecretProperty, secret);
234 }
235
initializeAll()236 void InterfaceController::initializeAll() {
237 // Initial IPv6 settings.
238 // By default, accept_ra is set to 1 (accept RAs unless forwarding is on) on all interfaces.
239 // This causes RAs to work or not work based on whether forwarding is on, and causes routes
240 // learned from RAs to go away when forwarding is turned on. Make this behaviour predictable
241 // by always setting accept_ra to 2.
242 setAcceptRA("2");
243
244 // Accept RIOs with prefix length in the closed interval [48, 64].
245 setAcceptIPv6RIO(kRouteInfoMinPrefixLen, kRouteInfoMaxPrefixLen);
246
247 setAcceptRARouteTable(-RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX);
248
249 // Enable optimistic DAD for IPv6 addresses on all interfaces.
250 setIPv6OptimisticMode("1");
251
252 // Reduce the ARP/ND base reachable time from the default (30sec) to 15sec.
253 setBaseReachableTimeMs(15 * 1000);
254
255 // When sending traffic via a given interface use only addresses configured
256 // on that interface as possible source addresses.
257 setIPv6UseOutgoingInterfaceAddrsOnly("1");
258
259 // Ensure that ICMP redirects are rejected globally on all interfaces.
260 disableIcmpRedirects();
261 }
262
setEnableIPv6(const char * interface,const int on)263 int InterfaceController::setEnableIPv6(const char *interface, const int on) {
264 if (!isIfaceName(interface)) {
265 return -ENOENT;
266 }
267 // When disable_ipv6 changes from 1 to 0, the kernel starts autoconf.
268 // When disable_ipv6 changes from 0 to 1, the kernel clears all autoconf
269 // addresses and routes and disables IPv6 on the interface.
270 const char *disable_ipv6 = on ? "0" : "1";
271 return writeValueToPath(ipv6_proc_path, interface, "disable_ipv6", disable_ipv6);
272 }
273
274 // Changes to addrGenMode will not fully take effect until the next
275 // time disable_ipv6 transitions from 1 to 0.
setIPv6AddrGenMode(const std::string & interface,int mode)276 Status InterfaceController::setIPv6AddrGenMode(const std::string& interface, int mode) {
277 if (!isIfaceName(interface)) {
278 return statusFromErrno(ENOENT, "invalid iface name: " + interface);
279 }
280
281 switch (mode) {
282 case INetd::IPV6_ADDR_GEN_MODE_EUI64:
283 // Ignore return value. If /proc/.../addr_gen_mode is
284 // missing we're probably in EUI64 mode already.
285 writeValueToPath(ipv6_proc_path, interface.c_str(), "addr_gen_mode", "0");
286 break;
287 case INetd::IPV6_ADDR_GEN_MODE_STABLE_PRIVACY: {
288 return enableStablePrivacyAddresses(interface, getProperty, setProperty);
289 }
290 case INetd::IPV6_ADDR_GEN_MODE_NONE:
291 case INetd::IPV6_ADDR_GEN_MODE_RANDOM:
292 default:
293 return statusFromErrno(EOPNOTSUPP, "unsupported addrGenMode");
294 }
295
296 return ok;
297 }
298
setAcceptIPv6Ra(const char * interface,const int on)299 int InterfaceController::setAcceptIPv6Ra(const char *interface, const int on) {
300 if (!isIfaceName(interface)) {
301 errno = ENOENT;
302 return -1;
303 }
304 // Because forwarding can be enabled even when tethering is off, we always
305 // use mode "2" (accept RAs, even if forwarding is enabled).
306 const char *accept_ra = on ? "2" : "0";
307 return writeValueToPath(ipv6_proc_path, interface, "accept_ra", accept_ra);
308 }
309
setAcceptIPv6Dad(const char * interface,const int on)310 int InterfaceController::setAcceptIPv6Dad(const char *interface, const int on) {
311 if (!isIfaceName(interface)) {
312 errno = ENOENT;
313 return -1;
314 }
315 const char *accept_dad = on ? "1" : "0";
316 return writeValueToPath(ipv6_proc_path, interface, "accept_dad", accept_dad);
317 }
318
setIPv6DadTransmits(const char * interface,const char * value)319 int InterfaceController::setIPv6DadTransmits(const char *interface, const char *value) {
320 if (!isIfaceName(interface)) {
321 errno = ENOENT;
322 return -1;
323 }
324 return writeValueToPath(ipv6_proc_path, interface, "dad_transmits", value);
325 }
326
setIPv6PrivacyExtensions(const char * interface,const int on)327 int InterfaceController::setIPv6PrivacyExtensions(const char *interface, const int on) {
328 if (!isIfaceName(interface)) {
329 errno = ENOENT;
330 return -errno;
331 }
332 // 0: disable IPv6 privacy addresses
333 // 2: enable IPv6 privacy addresses and prefer them over non-privacy ones.
334 return writeValueToPath(ipv6_proc_path, interface, "use_tempaddr", on ? "2" : "0");
335 }
336
setAcceptRA(const char * value)337 void InterfaceController::setAcceptRA(const char *value) {
338 setOnAllInterfaces(ipv6_proc_path, "accept_ra", value);
339 }
340
341 // |tableOrOffset| is interpreted as:
342 // If == 0: default. Routes go into RT6_TABLE_MAIN.
343 // If > 0: user set. Routes go into the specified table.
344 // If < 0: automatic. The absolute value is intepreted as an offset and added to the interface
345 // ID to get the table. If it's set to -1000, routes from interface ID 5 will go into
346 // table 1005, etc.
setAcceptRARouteTable(int tableOrOffset)347 void InterfaceController::setAcceptRARouteTable(int tableOrOffset) {
348 std::string value(StringPrintf("%d", tableOrOffset));
349 setOnAllInterfaces(ipv6_proc_path, "accept_ra_rt_table", value.c_str());
350 }
351
setMtu(const char * interface,const char * mtu)352 int InterfaceController::setMtu(const char *interface, const char *mtu)
353 {
354 if (!isIfaceName(interface)) {
355 errno = ENOENT;
356 return -errno;
357 }
358 return writeValueToPath(sys_net_path, interface, "mtu", mtu);
359 }
360
361 // Returns zero on success and negative errno on failure.
addAddress(const char * interface,const char * addrString,int prefixLength)362 int InterfaceController::addAddress(const char *interface,
363 const char *addrString, int prefixLength) {
364 return ifc_add_address(interface, addrString, prefixLength);
365 }
366
367 // Returns zero on success and negative errno on failure.
delAddress(const char * interface,const char * addrString,int prefixLength)368 int InterfaceController::delAddress(const char *interface,
369 const char *addrString, int prefixLength) {
370 return ifc_del_address(interface, addrString, prefixLength);
371 }
372
disableIcmpRedirects()373 int InterfaceController::disableIcmpRedirects() {
374 int rv = 0;
375 rv |= writeValueToPath(ipv4_proc_path, "all", "accept_redirects", "0");
376 rv |= writeValueToPath(ipv6_proc_path, "all", "accept_redirects", "0");
377 setOnAllInterfaces(ipv4_proc_path, "accept_redirects", "0");
378 setOnAllInterfaces(ipv6_proc_path, "accept_redirects", "0");
379 return rv;
380 }
381
getParameter(const char * family,const char * which,const char * interface,const char * parameter,std::string * value)382 int InterfaceController::getParameter(
383 const char *family, const char *which, const char *interface, const char *parameter,
384 std::string *value) {
385 const std::string path(getParameterPathname(family, which, interface, parameter));
386 if (path.empty()) {
387 return -errno;
388 }
389 if (ReadFileToString(path, value)) {
390 *value = Trim(*value);
391 return 0;
392 }
393 return -errno;
394 }
395
setParameter(const char * family,const char * which,const char * interface,const char * parameter,const char * value)396 int InterfaceController::setParameter(
397 const char *family, const char *which, const char *interface, const char *parameter,
398 const char *value) {
399 const std::string path(getParameterPathname(family, which, interface, parameter));
400 if (path.empty()) {
401 return -errno;
402 }
403 return WriteStringToFile(value, path) ? 0 : -errno;
404 }
405
setBaseReachableTimeMs(unsigned int millis)406 void InterfaceController::setBaseReachableTimeMs(unsigned int millis) {
407 std::string value(StringPrintf("%u", millis));
408 setOnAllInterfaces(ipv4_neigh_conf_dir, "base_reachable_time_ms", value.c_str());
409 setOnAllInterfaces(ipv6_neigh_conf_dir, "base_reachable_time_ms", value.c_str());
410 }
411
setIPv6OptimisticMode(const char * value)412 void InterfaceController::setIPv6OptimisticMode(const char *value) {
413 setOnAllInterfaces(ipv6_proc_path, "optimistic_dad", value);
414 setOnAllInterfaces(ipv6_proc_path, "use_optimistic", value);
415 }
416
417 namespace {
418
hwAddrToStr(unsigned char * hwaddr)419 std::string hwAddrToStr(unsigned char* hwaddr) {
420 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
421 hwaddr[4], hwaddr[5]);
422 }
423
ipv4NetmaskToPrefixLength(in_addr_t mask)424 int ipv4NetmaskToPrefixLength(in_addr_t mask) {
425 int prefixLength = 0;
426 uint32_t m = ntohl(mask);
427 while (m & (1 << 31)) {
428 prefixLength++;
429 m = m << 1;
430 }
431 return prefixLength;
432 }
433
toStdString(const String16 & s)434 std::string toStdString(const String16& s) {
435 return std::string(String8(s.string()));
436 }
437
438 } // namespace
439
setCfg(const InterfaceConfigurationParcel & cfg)440 Status InterfaceController::setCfg(const InterfaceConfigurationParcel& cfg) {
441 const auto& sys = sSyscalls.get();
442 ASSIGN_OR_RETURN(auto fd, sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
443 struct ifreq ifr = {
444 .ifr_addr = {.sa_family = AF_INET}, // Clear the IPv4 address.
445 };
446 strlcpy(ifr.ifr_name, cfg.ifName.c_str(), IFNAMSIZ);
447
448 // Make sure that clear IPv4 address before set flag
449 // SIOCGIFFLAGS might override ifr and caused clear IPv4 addr ioctl error
450 RETURN_IF_NOT_OK(sys.ioctl(fd, SIOCSIFADDR, &ifr));
451
452 if (!cfg.flags.empty()) {
453 RETURN_IF_NOT_OK(sys.ioctl(fd, SIOCGIFFLAGS, &ifr));
454 uint16_t flags = ifr.ifr_flags;
455
456 for (const auto& flag : cfg.flags) {
457 if (flag == toStdString(INetd::IF_STATE_UP())) {
458 ifr.ifr_flags = ifr.ifr_flags | IFF_UP;
459 } else if (flag == toStdString(INetd::IF_STATE_DOWN())) {
460 ifr.ifr_flags = (ifr.ifr_flags & (~IFF_UP));
461 }
462 }
463
464 if (ifr.ifr_flags != flags) {
465 RETURN_IF_NOT_OK(sys.ioctl(fd, SIOCSIFFLAGS, &ifr));
466 }
467 }
468
469 if (int ret = ifc_add_address(cfg.ifName.c_str(), cfg.ipv4Addr.c_str(), cfg.prefixLength)) {
470 return statusFromErrno(-ret, "Failed to add addr");
471 }
472
473 return ok;
474 }
475
getCfg(const std::string & ifName)476 StatusOr<InterfaceConfigurationParcel> InterfaceController::getCfg(const std::string& ifName) {
477 struct in_addr addr = {};
478 int prefixLength = 0;
479 unsigned char hwaddr[ETH_ALEN] = {};
480 unsigned flags = 0;
481 InterfaceConfigurationParcel cfgResult;
482
483 const auto& sys = sSyscalls.get();
484 ASSIGN_OR_RETURN(auto fd, sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
485
486 struct ifreq ifr = {};
487 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
488
489 if (isOk(sys.ioctl(fd, SIOCGIFADDR, &ifr))) {
490 addr.s_addr = ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr;
491 }
492
493 if (isOk(sys.ioctl(fd, SIOCGIFNETMASK, &ifr))) {
494 prefixLength =
495 ipv4NetmaskToPrefixLength(((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr);
496 }
497
498 if (isOk(sys.ioctl(fd, SIOCGIFFLAGS, &ifr))) {
499 flags = ifr.ifr_flags;
500 }
501
502 // ETH_ALEN is for ARPHRD_ETHER, it is better to check the sa_family.
503 // However, we keep old design for the consistency.
504 if (isOk(sys.ioctl(fd, SIOCGIFHWADDR, &ifr))) {
505 memcpy((void*) hwaddr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
506 } else {
507 ALOGW("Failed to retrieve HW addr for %s (%s)", ifName.c_str(), strerror(errno));
508 }
509
510 cfgResult.ifName = ifName;
511 cfgResult.hwAddr = hwAddrToStr(hwaddr);
512 cfgResult.ipv4Addr = std::string(inet_ntoa(addr));
513 cfgResult.prefixLength = prefixLength;
514 cfgResult.flags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
515 : toStdString(INetd::IF_STATE_DOWN()));
516
517 if (flags & IFF_BROADCAST) cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
518 if (flags & IFF_LOOPBACK) cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
519 if (flags & IFF_POINTOPOINT)
520 cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
521 if (flags & IFF_RUNNING) cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
522 if (flags & IFF_MULTICAST) cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
523
524 return cfgResult;
525 }
526
clearAddrs(const std::string & ifName)527 int InterfaceController::clearAddrs(const std::string& ifName) {
528 return ifc_clear_addresses(ifName.c_str());
529 }
530
531 } // namespace net
532 } // namespace android
533