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 <sys/socket.h> 21 22 #include <functional> 23 24 #define LOG_TAG "InterfaceController" 25 #include <android-base/file.h> 26 #include <android-base/properties.h> 27 #include <android-base/stringprintf.h> 28 #include <cutils/log.h> 29 #include <logwrap/logwrap.h> 30 #include <netutils/ifc.h> 31 32 #include <android/net/INetd.h> 33 #include <netdutils/Misc.h> 34 #include <netdutils/Slice.h> 35 #include <netdutils/Syscalls.h> 36 37 #include "InterfaceController.h" 38 #include "RouteController.h" 39 40 using android::base::ReadFileToString; 41 using android::base::StringPrintf; 42 using android::base::WriteStringToFile; 43 using android::net::INetd; 44 using android::net::RouteController; 45 using android::netdutils::Status; 46 using android::netdutils::StatusOr; 47 using android::netdutils::makeSlice; 48 using android::netdutils::sSyscalls; 49 using android::netdutils::status::ok; 50 using android::netdutils::statusFromErrno; 51 using android::netdutils::toString; 52 53 namespace { 54 55 const char ipv6_proc_path[] = "/proc/sys/net/ipv6/conf"; 56 57 const char ipv4_neigh_conf_dir[] = "/proc/sys/net/ipv4/neigh"; 58 59 const char ipv6_neigh_conf_dir[] = "/proc/sys/net/ipv6/neigh"; 60 61 const char proc_net_path[] = "/proc/sys/net"; 62 const char sys_net_path[] = "/sys/class/net"; 63 64 const char wl_util_path[] = "/vendor/xbin/wlutil"; 65 66 constexpr int kRouteInfoMinPrefixLen = 48; 67 68 // RFC 7421 prefix length. 69 constexpr int kRouteInfoMaxPrefixLen = 64; 70 71 // Property used to persist RFC 7217 stable secret. Protected by SELinux policy. 72 const char kStableSecretProperty[] = "persist.netd.stable_secret"; 73 74 // RFC 7217 stable secret on linux is formatted as an IPv6 address. 75 // This function uses 128 bits of high quality entropy to generate an 76 // address for this purpose. This function should be not be called 77 // frequently. 78 StatusOr<std::string> randomIPv6Address() { 79 in6_addr addr = {}; 80 const auto& sys = sSyscalls.get(); 81 ASSIGN_OR_RETURN(auto fd, sys.open("/dev/random", O_RDONLY)); 82 RETURN_IF_NOT_OK(sys.read(fd, makeSlice(addr))); 83 return toString(addr); 84 } 85 86 inline bool isNormalPathComponent(const char *component) { 87 return (strcmp(component, ".") != 0) && 88 (strcmp(component, "..") != 0) && 89 (strchr(component, '/') == nullptr); 90 } 91 92 inline bool isAddressFamilyPathComponent(const char *component) { 93 return strcmp(component, "ipv4") == 0 || strcmp(component, "ipv6") == 0; 94 } 95 96 inline bool isInterfaceName(const char *name) { 97 return isNormalPathComponent(name) && 98 (strcmp(name, "default") != 0) && 99 (strcmp(name, "all") != 0); 100 } 101 102 int writeValueToPath( 103 const char* dirname, const char* subdirname, const char* basename, 104 const char* value) { 105 std::string path(StringPrintf("%s/%s/%s", dirname, subdirname, basename)); 106 return WriteStringToFile(value, path) ? 0 : -1; 107 } 108 109 // Run @fn on each interface as well as 'default' in the path @dirname. 110 void forEachInterface(const std::string& dirname, 111 std::function<void(const std::string& path, const std::string& iface)> fn) { 112 // Run on default, which controls the behavior of any interfaces that are created in the future. 113 fn(dirname, "default"); 114 DIR* dir = opendir(dirname.c_str()); 115 if (!dir) { 116 ALOGE("Can't list %s: %s", dirname.c_str(), strerror(errno)); 117 return; 118 } 119 while (true) { 120 const dirent *ent = readdir(dir); 121 if (!ent) { 122 break; 123 } 124 if ((ent->d_type != DT_DIR) || !isInterfaceName(ent->d_name)) { 125 continue; 126 } 127 fn(dirname, ent->d_name); 128 } 129 closedir(dir); 130 } 131 132 void setOnAllInterfaces(const char* dirname, const char* basename, const char* value) { 133 auto fn = [basename, value](const std::string& path, const std::string& iface) { 134 writeValueToPath(path.c_str(), iface.c_str(), basename, value); 135 }; 136 forEachInterface(dirname, fn); 137 } 138 139 void setIPv6UseOutgoingInterfaceAddrsOnly(const char *value) { 140 setOnAllInterfaces(ipv6_proc_path, "use_oif_addrs_only", value); 141 } 142 143 std::string getParameterPathname( 144 const char *family, const char *which, const char *interface, const char *parameter) { 145 if (!isAddressFamilyPathComponent(family)) { 146 errno = EAFNOSUPPORT; 147 return ""; 148 } else if (!isNormalPathComponent(which) || 149 !isInterfaceName(interface) || 150 !isNormalPathComponent(parameter)) { 151 errno = EINVAL; 152 return ""; 153 } 154 155 return StringPrintf("%s/%s/%s/%s/%s", proc_net_path, family, which, interface, parameter); 156 } 157 158 void setAcceptIPv6RIO(int min, int max) { 159 auto fn = [min, max](const std::string& prefix, const std::string& iface) { 160 int rv = writeValueToPath(prefix.c_str(), iface.c_str(), "accept_ra_rt_info_min_plen", 161 std::to_string(min).c_str()); 162 if (rv != 0) { 163 // Only update max_plen if the write to min_plen succeeded. This ordering will prevent 164 // RIOs from being accepted unless both min and max are written successfully. 165 return; 166 } 167 writeValueToPath(prefix.c_str(), iface.c_str(), "accept_ra_rt_info_max_plen", 168 std::to_string(max).c_str()); 169 }; 170 forEachInterface(ipv6_proc_path, fn); 171 } 172 173 // Ideally this function would return StatusOr<std::string>, however 174 // there is no safe value for dflt that will always differ from the 175 // stored property. Bugs code could conceivably end up persisting the 176 // reserved value resulting in surprising behavior. 177 std::string getProperty(const std::string& key, const std::string& dflt) { 178 return android::base::GetProperty(key, dflt); 179 }; 180 181 Status setProperty(const std::string& key, const std::string& val) { 182 // SetProperty does not dependably set errno to a meaningful value. Use our own error code so 183 // callers don't get confused. 184 return android::base::SetProperty(key, val) 185 ? ok 186 : statusFromErrno(EREMOTEIO, "SetProperty failed, see libc logs"); 187 }; 188 189 190 } // namespace 191 192 android::netdutils::Status InterfaceController::enableStablePrivacyAddresses( 193 const std::string& iface, GetPropertyFn getProperty, SetPropertyFn setProperty) { 194 const auto& sys = sSyscalls.get(); 195 const std::string procTarget = std::string(ipv6_proc_path) + "/" + iface + "/stable_secret"; 196 auto procFd = sys.open(procTarget, O_CLOEXEC | O_WRONLY); 197 198 // Devices with old kernels (typically < 4.4) don't support 199 // RFC 7217 stable privacy addresses. 200 if (equalToErrno(procFd, ENOENT)) { 201 return statusFromErrno(EOPNOTSUPP, 202 "Failed to open stable_secret. Assuming unsupported kernel version"); 203 } 204 205 // If stable_secret exists but we can't open it, something strange is going on. 206 RETURN_IF_NOT_OK(procFd); 207 208 const char kUninitialized[] = "uninitialized"; 209 const auto oldSecret = getProperty(kStableSecretProperty, kUninitialized); 210 std::string secret = oldSecret; 211 212 // Generate a new secret if no persistent property existed. 213 if (oldSecret == kUninitialized) { 214 ASSIGN_OR_RETURN(secret, randomIPv6Address()); 215 } 216 217 // Ask the OS to generate SLAAC addresses on iface using secret. 218 RETURN_IF_NOT_OK(sys.write(procFd.value(), makeSlice(secret))); 219 220 // Don't persist an existing secret. 221 if (oldSecret != kUninitialized) { 222 return ok; 223 } 224 225 return setProperty(kStableSecretProperty, secret); 226 } 227 228 void InterfaceController::initializeAll() { 229 // Initial IPv6 settings. 230 // By default, accept_ra is set to 1 (accept RAs unless forwarding is on) on all interfaces. 231 // This causes RAs to work or not work based on whether forwarding is on, and causes routes 232 // learned from RAs to go away when forwarding is turned on. Make this behaviour predictable 233 // by always setting accept_ra to 2. 234 setAcceptRA("2"); 235 236 // Accept RIOs with prefix length in the closed interval [48, 64]. 237 setAcceptIPv6RIO(kRouteInfoMinPrefixLen, kRouteInfoMaxPrefixLen); 238 239 setAcceptRARouteTable(-RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX); 240 241 // Enable optimistic DAD for IPv6 addresses on all interfaces. 242 setIPv6OptimisticMode("1"); 243 244 // Reduce the ARP/ND base reachable time from the default (30sec) to 15sec. 245 setBaseReachableTimeMs(15 * 1000); 246 247 // When sending traffic via a given interface use only addresses configured 248 // on that interface as possible source addresses. 249 setIPv6UseOutgoingInterfaceAddrsOnly("1"); 250 } 251 252 int InterfaceController::setEnableIPv6(const char *interface, const int on) { 253 if (!isIfaceName(interface)) { 254 errno = ENOENT; 255 return -1; 256 } 257 // When disable_ipv6 changes from 1 to 0, the kernel starts autoconf. 258 // When disable_ipv6 changes from 0 to 1, the kernel clears all autoconf 259 // addresses and routes and disables IPv6 on the interface. 260 const char *disable_ipv6 = on ? "0" : "1"; 261 return writeValueToPath(ipv6_proc_path, interface, "disable_ipv6", disable_ipv6); 262 } 263 264 // Changes to addrGenMode will not fully take effect until the next 265 // time disable_ipv6 transitions from 1 to 0. 266 Status InterfaceController::setIPv6AddrGenMode(const std::string& interface, int mode) { 267 if (!isIfaceName(interface)) { 268 return statusFromErrno(ENOENT, "invalid iface name: " + interface); 269 } 270 271 switch (mode) { 272 case INetd::IPV6_ADDR_GEN_MODE_EUI64: 273 // Ignore return value. If /proc/.../stable_secret is 274 // missing we're probably in EUI64 mode already. 275 writeValueToPath(ipv6_proc_path, interface.c_str(), "stable_secret", ""); 276 break; 277 case INetd::IPV6_ADDR_GEN_MODE_STABLE_PRIVACY: { 278 return enableStablePrivacyAddresses(interface, getProperty, setProperty); 279 } 280 case INetd::IPV6_ADDR_GEN_MODE_NONE: 281 case INetd::IPV6_ADDR_GEN_MODE_RANDOM: 282 default: 283 return statusFromErrno(EOPNOTSUPP, "unsupported addrGenMode"); 284 } 285 286 return ok; 287 } 288 289 int InterfaceController::setAcceptIPv6Ra(const char *interface, const int on) { 290 if (!isIfaceName(interface)) { 291 errno = ENOENT; 292 return -1; 293 } 294 // Because forwarding can be enabled even when tethering is off, we always 295 // use mode "2" (accept RAs, even if forwarding is enabled). 296 const char *accept_ra = on ? "2" : "0"; 297 return writeValueToPath(ipv6_proc_path, interface, "accept_ra", accept_ra); 298 } 299 300 int InterfaceController::setAcceptIPv6Dad(const char *interface, const int on) { 301 if (!isIfaceName(interface)) { 302 errno = ENOENT; 303 return -1; 304 } 305 const char *accept_dad = on ? "1" : "0"; 306 return writeValueToPath(ipv6_proc_path, interface, "accept_dad", accept_dad); 307 } 308 309 int InterfaceController::setIPv6DadTransmits(const char *interface, const char *value) { 310 if (!isIfaceName(interface)) { 311 errno = ENOENT; 312 return -1; 313 } 314 return writeValueToPath(ipv6_proc_path, interface, "dad_transmits", value); 315 } 316 317 int InterfaceController::setIPv6PrivacyExtensions(const char *interface, const int on) { 318 if (!isIfaceName(interface)) { 319 errno = ENOENT; 320 return -1; 321 } 322 // 0: disable IPv6 privacy addresses 323 // 2: enable IPv6 privacy addresses and prefer them over non-privacy ones. 324 return writeValueToPath(ipv6_proc_path, interface, "use_tempaddr", on ? "2" : "0"); 325 } 326 327 // Enables or disables IPv6 ND offload. This is useful for 464xlat on wifi, IPv6 tethering, and 328 // generally implementing IPv6 neighbour discovery and duplicate address detection properly. 329 // TODO: This should be implemented in wpa_supplicant via driver commands instead. 330 int InterfaceController::setIPv6NdOffload(char* interface, const int on) { 331 // Only supported on Broadcom chipsets via wlutil for now. 332 if (access(wl_util_path, X_OK) == 0) { 333 const char *argv[] = { 334 wl_util_path, 335 "-a", 336 interface, 337 "ndoe", 338 on ? "1" : "0" 339 }; 340 int ret = android_fork_execvp(ARRAY_SIZE(argv), const_cast<char**>(argv), NULL, 341 false, false); 342 ALOGD("%s ND offload on %s: %d (%s)", 343 (on ? "enabling" : "disabling"), interface, ret, strerror(errno)); 344 return ret; 345 } else { 346 return 0; 347 } 348 } 349 350 void InterfaceController::setAcceptRA(const char *value) { 351 setOnAllInterfaces(ipv6_proc_path, "accept_ra", value); 352 } 353 354 // |tableOrOffset| is interpreted as: 355 // If == 0: default. Routes go into RT6_TABLE_MAIN. 356 // If > 0: user set. Routes go into the specified table. 357 // If < 0: automatic. The absolute value is intepreted as an offset and added to the interface 358 // ID to get the table. If it's set to -1000, routes from interface ID 5 will go into 359 // table 1005, etc. 360 void InterfaceController::setAcceptRARouteTable(int tableOrOffset) { 361 std::string value(StringPrintf("%d", tableOrOffset)); 362 setOnAllInterfaces(ipv6_proc_path, "accept_ra_rt_table", value.c_str()); 363 } 364 365 int InterfaceController::setMtu(const char *interface, const char *mtu) 366 { 367 if (!isIfaceName(interface)) { 368 errno = ENOENT; 369 return -1; 370 } 371 return writeValueToPath(sys_net_path, interface, "mtu", mtu); 372 } 373 374 int InterfaceController::addAddress(const char *interface, 375 const char *addrString, int prefixLength) { 376 return ifc_add_address(interface, addrString, prefixLength); 377 } 378 379 int InterfaceController::delAddress(const char *interface, 380 const char *addrString, int prefixLength) { 381 return ifc_del_address(interface, addrString, prefixLength); 382 } 383 384 int InterfaceController::getParameter( 385 const char *family, const char *which, const char *interface, const char *parameter, 386 std::string *value) { 387 const std::string path(getParameterPathname(family, which, interface, parameter)); 388 if (path.empty()) { 389 return -errno; 390 } 391 return ReadFileToString(path, value) ? 0 : -errno; 392 } 393 394 int InterfaceController::setParameter( 395 const char *family, const char *which, const char *interface, const char *parameter, 396 const char *value) { 397 const std::string path(getParameterPathname(family, which, interface, parameter)); 398 if (path.empty()) { 399 return -errno; 400 } 401 return WriteStringToFile(value, path) ? 0 : -errno; 402 } 403 404 void InterfaceController::setBaseReachableTimeMs(unsigned int millis) { 405 std::string value(StringPrintf("%u", millis)); 406 setOnAllInterfaces(ipv4_neigh_conf_dir, "base_reachable_time_ms", value.c_str()); 407 setOnAllInterfaces(ipv6_neigh_conf_dir, "base_reachable_time_ms", value.c_str()); 408 } 409 410 void InterfaceController::setIPv6OptimisticMode(const char *value) { 411 setOnAllInterfaces(ipv6_proc_path, "optimistic_dad", value); 412 setOnAllInterfaces(ipv6_proc_path, "use_optimistic", value); 413 } 414