| /* |
| * Copyright 2016 The Android Open Source Project |
| * |
| * Licensed under the Apache License, Version 2.0 (the "License"); |
| * you may not use this file except in compliance with the License. |
| * You may obtain a copy of the License at |
| * |
| * http://www.apache.org/licenses/LICENSE-2.0 |
| * |
| * Unless required by applicable law or agreed to in writing, software |
| * distributed under the License is distributed on an "AS IS" BASIS, |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| * See the License for the specific language governing permissions and |
| * limitations under the License. |
| * |
| * binder_test.cpp - unit tests for netd binder RPCs. |
| */ |
| |
| #include <cerrno> |
| #include <chrono> |
| #include <cinttypes> |
| #include <condition_variable> |
| #include <cstdint> |
| #include <cstdlib> |
| #include <iostream> |
| #include <mutex> |
| #include <numeric> |
| #include <regex> |
| #include <set> |
| #include <string> |
| #include <vector> |
| |
| #include <dirent.h> |
| #include <fcntl.h> |
| #include <ifaddrs.h> |
| #include <linux/if.h> |
| #include <linux/if_tun.h> |
| #include <net/ethernet.h> |
| #include <net/if.h> |
| #include <netdb.h> |
| #include <netinet/in.h> |
| #include <netinet/tcp.h> |
| #include <openssl/base64.h> |
| #include <sys/socket.h> |
| #include <sys/types.h> |
| |
| #include <android-base/file.h> |
| #include <android-base/format.h> |
| #include <android-base/macros.h> |
| #include <android-base/scopeguard.h> |
| #include <android-base/stringprintf.h> |
| #include <android-base/strings.h> |
| #include <android/multinetwork.h> |
| #include <binder/IPCThreadState.h> |
| #include <bpf/BpfMap.h> |
| #include <bpf/BpfUtils.h> |
| #include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h> |
| #include <com/android/internal/net/IOemNetd.h> |
| #include <cutils/multiuser.h> |
| #include <gtest/gtest.h> |
| #include <netdutils/NetNativeTestBase.h> |
| #include <netutils/ifc.h> |
| #include <utils/Errors.h> |
| #include "Fwmark.h" |
| #include "InterfaceController.h" |
| #include "NetdClient.h" |
| #include "NetdConstants.h" |
| #include "NetworkController.h" |
| #include "RouteController.h" |
| #include "SockDiag.h" |
| #include "TestUnsolService.h" |
| #include "XfrmController.h" |
| #include "android/net/INetd.h" |
| #include "android/net/mdns/aidl/BnMDnsEventListener.h" |
| #include "android/net/mdns/aidl/DiscoveryInfo.h" |
| #include "android/net/mdns/aidl/GetAddressInfo.h" |
| #include "android/net/mdns/aidl/IMDns.h" |
| #include "android/net/mdns/aidl/RegistrationInfo.h" |
| #include "android/net/mdns/aidl/ResolutionInfo.h" |
| #include "binder/IServiceManager.h" |
| #include "netdutils/InternetAddresses.h" |
| #include "netdutils/Stopwatch.h" |
| #include "netdutils/Syscalls.h" |
| #include "netdutils/Utils.h" |
| #include "netid_client.h" // NETID_UNSET |
| #include "nettestutils/DumpService.h" |
| #include "test_utils.h" |
| #include "tun_interface.h" |
| |
| #define IP6TABLES_PATH "/system/bin/ip6tables" |
| #define IPTABLES_PATH "/system/bin/iptables" |
| #define RAW_TABLE "raw" |
| #define MANGLE_TABLE "mangle" |
| #define FILTER_TABLE "filter" |
| #define NAT_TABLE "nat" |
| |
| namespace binder = android::binder; |
| |
| using android::IBinder; |
| using android::IServiceManager; |
| using android::sp; |
| using android::String16; |
| using android::String8; |
| using android::base::Join; |
| using android::base::make_scope_guard; |
| using android::base::ReadFileToString; |
| using android::base::StartsWith; |
| using android::base::StringPrintf; |
| using android::base::Trim; |
| using android::base::unique_fd; |
| using android::binder::Status; |
| using android::net::INetd; |
| using android::net::InterfaceConfigurationParcel; |
| using android::net::InterfaceController; |
| using android::net::MarkMaskParcel; |
| using android::net::NativeNetworkConfig; |
| using android::net::NativeNetworkType; |
| using android::net::NativeVpnType; |
| using android::net::RULE_PRIORITY_BYPASSABLE_VPN_LOCAL_EXCLUSION; |
| using android::net::RULE_PRIORITY_BYPASSABLE_VPN_NO_LOCAL_EXCLUSION; |
| using android::net::RULE_PRIORITY_DEFAULT_NETWORK; |
| using android::net::RULE_PRIORITY_EXPLICIT_NETWORK; |
| using android::net::RULE_PRIORITY_LOCAL_ROUTES; |
| using android::net::RULE_PRIORITY_OUTPUT_INTERFACE; |
| using android::net::RULE_PRIORITY_PROHIBIT_NON_VPN; |
| using android::net::RULE_PRIORITY_SECURE_VPN; |
| using android::net::RULE_PRIORITY_TETHERING; |
| using android::net::RULE_PRIORITY_UID_DEFAULT_NETWORK; |
| using android::net::RULE_PRIORITY_UID_DEFAULT_UNREACHABLE; |
| using android::net::RULE_PRIORITY_UID_EXPLICIT_NETWORK; |
| using android::net::RULE_PRIORITY_UID_IMPLICIT_NETWORK; |
| using android::net::RULE_PRIORITY_UID_LOCAL_ROUTES; |
| using android::net::RULE_PRIORITY_VPN_FALLTHROUGH; |
| using android::net::SockDiag; |
| using android::net::TetherOffloadRuleParcel; |
| using android::net::TetherStatsParcel; |
| using android::net::TunInterface; |
| using android::net::UidRangeParcel; |
| using android::net::UidRanges; |
| using android::net::V4_FIXED_LOCAL_PREFIXES; |
| using android::net::mdns::aidl::DiscoveryInfo; |
| using android::net::mdns::aidl::GetAddressInfo; |
| using android::net::mdns::aidl::IMDns; |
| using android::net::mdns::aidl::RegistrationInfo; |
| using android::net::mdns::aidl::ResolutionInfo; |
| using android::net::netd::aidl::NativeUidRangeConfig; |
| using android::netdutils::getIfaceNames; |
| using android::netdutils::IPAddress; |
| using android::netdutils::IPSockAddr; |
| using android::netdutils::ScopedAddrinfo; |
| using android::netdutils::sSyscalls; |
| using android::netdutils::Stopwatch; |
| |
| static const char* IP_RULE_V4 = "-4"; |
| static const char* IP_RULE_V6 = "-6"; |
| static const int TEST_NETID1 = 65501; |
| static const int TEST_NETID2 = 65502; |
| static const int TEST_NETID3 = 65503; |
| static const int TEST_NETID4 = 65504; |
| static const int TEST_DUMP_NETID = 65123; |
| static const char* DNSMASQ = "dnsmasq"; |
| |
| // Use maximum reserved appId for applications to avoid conflict with existing |
| // uids. |
| static const int TEST_UID1 = 99999; |
| static const int TEST_UID2 = 99998; |
| static const int TEST_UID3 = 99997; |
| static const int TEST_UID4 = 99996; |
| static const int TEST_UID5 = 99995; |
| static const int TEST_UID6 = 99994; |
| |
| constexpr int BASE_UID = AID_USER_OFFSET * 5; |
| |
| static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294"); |
| static const std::string ESP_ALLOW_RULE("esp"); |
| |
| static const in6_addr V6_ADDR = { |
| {// 2001:db8:cafe::8888 |
| .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}}; |
| |
| class NetdBinderTest : public NetNativeTestBase { |
| public: |
| NetdBinderTest() { |
| sp<IServiceManager> sm = android::defaultServiceManager(); |
| sp<IBinder> binder = sm->getService(String16("netd")); |
| if (binder != nullptr) { |
| mNetd = android::interface_cast<INetd>(binder); |
| } |
| } |
| |
| void SetUp() override { |
| ASSERT_NE(nullptr, mNetd.get()); |
| } |
| |
| void TearDown() override { |
| mNetd->networkDestroy(TEST_NETID1); |
| mNetd->networkDestroy(TEST_NETID2); |
| mNetd->networkDestroy(TEST_NETID3); |
| mNetd->networkDestroy(TEST_NETID4); |
| setNetworkForProcess(NETID_UNSET); |
| // Restore default network |
| if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork); |
| } |
| |
| bool allocateIpSecResources(bool expectOk, int32_t* spi); |
| |
| // Static because setting up the tun interface takes about 40ms. |
| static void SetUpTestCase() { |
| ASSERT_EQ(0, sTun.init()); |
| ASSERT_EQ(0, sTun2.init()); |
| ASSERT_EQ(0, sTun3.init()); |
| ASSERT_EQ(0, sTun4.init()); |
| ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ)); |
| ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ)); |
| ASSERT_LE(sTun3.name().size(), static_cast<size_t>(IFNAMSIZ)); |
| ASSERT_LE(sTun4.name().size(), static_cast<size_t>(IFNAMSIZ)); |
| } |
| |
| static void TearDownTestCase() { |
| // Closing the socket removes the interface and IP addresses. |
| sTun.destroy(); |
| sTun2.destroy(); |
| sTun3.destroy(); |
| sTun4.destroy(); |
| } |
| |
| static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket, |
| unique_fd* acceptedSocket); |
| |
| void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2, |
| int fallthroughNetId = TEST_NETID1, |
| int nonDefaultNetId = TEST_NETID3); |
| |
| void createAndSetDefaultNetwork(int netId, const std::string& interface, |
| int permission = INetd::PERMISSION_NONE); |
| |
| void createPhysicalNetwork(int netId, const std::string& interface, |
| int permission = INetd::PERMISSION_NONE); |
| |
| void createDefaultAndOtherPhysicalNetwork(int defaultNetId, int otherNetId); |
| |
| void createVpnAndOtherPhysicalNetwork(int systemDefaultNetId, int otherNetId, int vpnNetId, |
| bool secure); |
| |
| void createVpnAndAppDefaultNetworkWithUid(int systemDefaultNetId, int appDefaultNetId, |
| int vpnNetId, bool secure, |
| std::vector<UidRangeParcel>&& appDefaultUidRanges, |
| std::vector<UidRangeParcel>&& vpnUidRanges); |
| |
| void setupNetworkRoutesForVpnAndDefaultNetworks( |
| int systemDefaultNetId, int appDefaultNetId, int vpnNetId, int otherNetId, bool secure, |
| bool excludeLocalRoutes, bool testV6, bool differentLocalAddr, |
| std::vector<UidRangeParcel>&& appDefaultUidRanges, |
| std::vector<UidRangeParcel>&& vpnUidRanges); |
| |
| protected: |
| // Use -1 to represent that default network was not modified because |
| // real netId must be an unsigned value. |
| int mStoredDefaultNetwork = -1; |
| sp<INetd> mNetd; |
| static TunInterface sTun; |
| static TunInterface sTun2; |
| static TunInterface sTun3; |
| static TunInterface sTun4; |
| }; |
| |
| TunInterface NetdBinderTest::sTun; |
| TunInterface NetdBinderTest::sTun2; |
| TunInterface NetdBinderTest::sTun3; |
| TunInterface NetdBinderTest::sTun4; |
| |
| class TimedOperation : public Stopwatch { |
| public: |
| explicit TimedOperation(const std::string &name): mName(name) {} |
| virtual ~TimedOperation() { |
| std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl; |
| } |
| |
| private: |
| std::string mName; |
| }; |
| |
| TEST_F(NetdBinderTest, IsAlive) { |
| TimedOperation t("isAlive RPC"); |
| bool isAlive = false; |
| mNetd->isAlive(&isAlive); |
| ASSERT_TRUE(isAlive); |
| } |
| |
| namespace { |
| |
| NativeNetworkConfig makeNativeNetworkConfig(int netId, NativeNetworkType networkType, |
| int permission, bool secure, bool excludeLocalRoutes) { |
| NativeNetworkConfig config = {}; |
| config.netId = netId; |
| config.networkType = networkType; |
| config.permission = permission; |
| config.secure = secure; |
| // The vpnType doesn't matter in AOSP. Just pick a well defined one from INetd. |
| config.vpnType = NativeVpnType::PLATFORM; |
| config.excludeLocalRoutes = excludeLocalRoutes; |
| return config; |
| } |
| |
| } // namespace |
| |
| bool testNetworkExistsButCannotConnect(const sp<INetd>& netd, TunInterface& ifc, const int netId) { |
| // If this network exists, we should definitely not be able to create it. |
| // Note that this networkCreate is never allowed to create reserved network IDs, so |
| // this call may fail for other reasons than the network already existing. |
| const auto& config = makeNativeNetworkConfig(netId, NativeNetworkType::PHYSICAL, |
| INetd::PERMISSION_NONE, false, false); |
| EXPECT_FALSE(netd->networkCreate(config).isOk()); |
| // Test if the network exist by adding interface. INetd has no dedicated method to query. When |
| // the network exists and the interface can be added, the function succeeds. When the network |
| // exists but the interface cannot be added, it fails with EINVAL, otherwise it is ENONET. |
| binder::Status status = netd->networkAddInterface(netId, ifc.name()); |
| if (status.isOk()) { // clean up |
| EXPECT_TRUE(netd->networkRemoveInterface(netId, ifc.name()).isOk()); |
| } else if (status.serviceSpecificErrorCode() == ENONET) { |
| return false; |
| } |
| |
| const sockaddr_in6 sin6 = {.sin6_family = AF_INET6, |
| .sin6_addr = {{.u6_addr32 = {htonl(0x20010db8), 0, 0, 0}}}, |
| .sin6_port = 53}; |
| const int s = socket(AF_INET6, SOCK_DGRAM, 0); |
| EXPECT_NE(-1, s); |
| if (s == -1) return true; |
| Fwmark fwmark; |
| fwmark.explicitlySelected = true; |
| fwmark.netId = netId; |
| EXPECT_EQ(0, setsockopt(s, SOL_SOCKET, SO_MARK, &fwmark.intValue, sizeof(fwmark.intValue))); |
| const int ret = connect(s, (struct sockaddr*)&sin6, sizeof(sin6)); |
| const int err = errno; |
| EXPECT_EQ(-1, ret); |
| EXPECT_EQ(ENETUNREACH, err); |
| close(s); |
| return true; |
| } |
| |
| TEST_F(NetdBinderTest, InitialNetworksExist) { |
| EXPECT_TRUE(testNetworkExistsButCannotConnect(mNetd, sTun, INetd::DUMMY_NET_ID)); |
| EXPECT_TRUE(testNetworkExistsButCannotConnect(mNetd, sTun, INetd::LOCAL_NET_ID)); |
| EXPECT_TRUE(testNetworkExistsButCannotConnect(mNetd, sTun, INetd::UNREACHABLE_NET_ID)); |
| EXPECT_FALSE(testNetworkExistsButCannotConnect(mNetd, sTun, 77 /* not exist */)); |
| } |
| |
| TEST_F(NetdBinderTest, IpSecTunnelInterface) { |
| const struct TestData { |
| const std::string family; |
| const std::string deviceName; |
| const std::string localAddress; |
| const std::string remoteAddress; |
| int32_t iKey; |
| int32_t oKey; |
| int32_t ifId; |
| } kTestData[] = { |
| {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE}, |
| {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50, |
| 0xFFFE}, |
| }; |
| |
| for (size_t i = 0; i < std::size(kTestData); i++) { |
| const auto& td = kTestData[i]; |
| |
| binder::Status status; |
| |
| // Create Tunnel Interface. |
| status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress, |
| td.iKey, td.oKey, td.ifId); |
| EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage(); |
| |
| // Check that the interface exists |
| EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str())); |
| |
| // Update Tunnel Interface. |
| status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress, |
| td.iKey, td.oKey, td.ifId); |
| EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage(); |
| |
| // Remove Tunnel Interface. |
| status = mNetd->ipSecRemoveTunnelInterface(td.deviceName); |
| EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage(); |
| |
| // Check that the interface no longer exists |
| EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str())); |
| } |
| } |
| |
| TEST_F(NetdBinderTest, IpSecSetEncapSocketOwner) { |
| unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)); |
| android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd)); |
| |
| int sockOptVal = UDP_ENCAP_ESPINUDP; |
| setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal)); |
| |
| binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001); |
| EXPECT_TRUE(res.isOk()); |
| |
| struct stat info; |
| EXPECT_EQ(0, fstat(sockFd.get(), &info)); |
| EXPECT_EQ(1001, (int) info.st_uid); |
| } |
| |
| // IPsec tests are not run in 32 bit mode; both 32-bit kernels and |
| // mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported. |
| #if INTPTR_MAX != INT32_MAX |
| |
| using android::net::XfrmController; |
| |
| static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN), |
| static_cast<int>(android::net::XfrmDirection::OUT)}; |
| static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6}; |
| |
| #define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \ |
| do { if ((_expect_) != (_ret_)) return false; } while(false) |
| bool NetdBinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) { |
| android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi); |
| SCOPED_TRACE(status); |
| RETURN_FALSE_IF_NEQ(status.ok(), expectOk); |
| |
| // Add a policy |
| status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0); |
| SCOPED_TRACE(status); |
| RETURN_FALSE_IF_NEQ(status.ok(), expectOk); |
| |
| // Add an ipsec interface |
| return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D, |
| 0xD00D, 0xE00D, false) |
| .ok(); |
| } |
| |
| TEST_F(NetdBinderTest, XfrmDualSelectorTunnelModePoliciesV4) { |
| android::binder::Status status; |
| |
| // Repeat to ensure cleanup and recreation works correctly |
| for (int i = 0; i < 2; i++) { |
| for (int direction : XFRM_DIRECTIONS) { |
| for (int addrFamily : ADDRESS_FAMILIES) { |
| status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5", |
| "127.0.0.6", 123, 0, 0, 0); |
| EXPECT_TRUE(status.isOk()) |
| << " family: " << addrFamily << " direction: " << direction; |
| } |
| } |
| |
| // Cleanup |
| for (int direction : XFRM_DIRECTIONS) { |
| for (int addrFamily : ADDRESS_FAMILIES) { |
| status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0); |
| EXPECT_TRUE(status.isOk()); |
| } |
| } |
| } |
| } |
| |
| TEST_F(NetdBinderTest, XfrmDualSelectorTunnelModePoliciesV6) { |
| binder::Status status; |
| |
| // Repeat to ensure cleanup and recreation works correctly |
| for (int i = 0; i < 2; i++) { |
| for (int direction : XFRM_DIRECTIONS) { |
| for (int addrFamily : ADDRESS_FAMILIES) { |
| status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d", |
| "2001:db8::d00d", 123, 0, 0, 0); |
| EXPECT_TRUE(status.isOk()) |
| << " family: " << addrFamily << " direction: " << direction; |
| } |
| } |
| |
| // Cleanup |
| for (int direction : XFRM_DIRECTIONS) { |
| for (int addrFamily : ADDRESS_FAMILIES) { |
| status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0); |
| EXPECT_TRUE(status.isOk()); |
| } |
| } |
| } |
| } |
| |
| TEST_F(NetdBinderTest, XfrmControllerInit) { |
| android::netdutils::Status status; |
| status = XfrmController::Init(); |
| SCOPED_TRACE(status); |
| |
| // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec |
| // feature. |
| if (status.code() == EOPNOTSUPP) return; |
| |
| ASSERT_TRUE(status.ok()); |
| |
| int32_t spi = 0; |
| |
| ASSERT_TRUE(allocateIpSecResources(true, &spi)); |
| ASSERT_TRUE(allocateIpSecResources(false, &spi)); |
| |
| status = XfrmController::Init(); |
| ASSERT_TRUE(status.ok()); |
| ASSERT_TRUE(allocateIpSecResources(true, &spi)); |
| |
| // Clean up |
| status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0); |
| SCOPED_TRACE(status); |
| ASSERT_TRUE(status.ok()); |
| |
| status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0); |
| SCOPED_TRACE(status); |
| ASSERT_TRUE(status.ok()); |
| |
| // Remove Virtual Tunnel Interface. |
| ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok()); |
| } |
| |
| #endif // INTPTR_MAX != INT32_MAX |
| |
| static int bandwidthDataSaverEnabled(const char *binary) { |
| std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver"); |
| |
| // Output looks like this: |
| // |
| // Chain bw_data_saver (1 references) |
| // target prot opt source destination |
| // RETURN all -- 0.0.0.0/0 0.0.0.0/0 |
| // |
| // or: |
| // |
| // Chain bw_data_saver (1 references) |
| // target prot opt source destination |
| // ... possibly connectivity critical packet rules here ... |
| // REJECT all -- ::/0 ::/0 |
| |
| EXPECT_GE(lines.size(), 3U); |
| |
| if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) { |
| // Data saver disabled. |
| return 0; |
| } |
| |
| size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9; |
| |
| if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) { |
| // Data saver enabled. |
| return 1; |
| } |
| |
| return -1; |
| } |
| |
| bool enableDataSaver(sp<INetd>& netd, bool enable) { |
| TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver"); |
| bool ret; |
| netd->bandwidthEnableDataSaver(enable, &ret); |
| return ret; |
| } |
| |
| int getDataSaverState() { |
| const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH); |
| const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH); |
| EXPECT_EQ(enabled4, enabled6); |
| EXPECT_NE(-1, enabled4); |
| EXPECT_NE(-1, enabled6); |
| if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) { |
| return -1; |
| } |
| return enabled6; |
| } |
| |
| TEST_F(NetdBinderTest, BandwidthEnableDataSaver) { |
| const int wasEnabled = getDataSaverState(); |
| ASSERT_NE(-1, wasEnabled); |
| |
| if (wasEnabled) { |
| ASSERT_TRUE(enableDataSaver(mNetd, false)); |
| EXPECT_EQ(0, getDataSaverState()); |
| } |
| |
| ASSERT_TRUE(enableDataSaver(mNetd, false)); |
| EXPECT_EQ(0, getDataSaverState()); |
| |
| ASSERT_TRUE(enableDataSaver(mNetd, true)); |
| EXPECT_EQ(1, getDataSaverState()); |
| |
| ASSERT_TRUE(enableDataSaver(mNetd, true)); |
| EXPECT_EQ(1, getDataSaverState()); |
| |
| if (!wasEnabled) { |
| ASSERT_TRUE(enableDataSaver(mNetd, false)); |
| EXPECT_EQ(0, getDataSaverState()); |
| } |
| } |
| |
| static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range, |
| const std::string& action, const char* ipVersion, |
| const char* oif) { |
| // Output looks like this: |
| // "<priority>:\tfrom all iif lo oif netdc0ca6 uidrange 500000-500000 lookup netdc0ca6" |
| // "<priority>:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit" |
| std::vector<std::string> rules = listIpRules(ipVersion); |
| |
| std::string prefix = StringPrintf("%" PRIu32 ":", priority); |
| std::string suffix; |
| if (oif) { |
| suffix = StringPrintf(" iif lo oif %s uidrange %d-%d %s\n", oif, range.start, range.stop, |
| action.c_str()); |
| } else { |
| suffix = StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, |
| action.c_str()); |
| } |
| for (const auto& line : rules) { |
| if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) { |
| return true; |
| } |
| } |
| return false; |
| } |
| |
| // Overloads function with oif parameter for VPN rules compare. |
| static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range, |
| const std::string& action, const char* oif) { |
| bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4, oif); |
| bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6, oif); |
| EXPECT_EQ(existsIp4, existsIp6); |
| return existsIp4; |
| } |
| |
| static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range, |
| const std::string& action) { |
| return ipRuleExistsForRange(priority, range, action, nullptr); |
| } |
| |
| namespace { |
| |
| UidRangeParcel makeUidRangeParcel(int start, int stop) { |
| UidRangeParcel res; |
| res.start = start; |
| res.stop = stop; |
| |
| return res; |
| } |
| |
| UidRangeParcel makeUidRangeParcel(int uid) { |
| return makeUidRangeParcel(uid, uid); |
| } |
| |
| NativeUidRangeConfig makeNativeUidRangeConfig(unsigned netId, std::vector<UidRangeParcel> uidRanges, |
| int32_t subPriority) { |
| NativeUidRangeConfig res; |
| res.netId = netId; |
| res.uidRanges = std::move(uidRanges); |
| res.subPriority = subPriority; |
| |
| return res; |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, NetworkInterfaces) { |
| auto config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL, |
| INetd::PERMISSION_NONE, false, false); |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_EQ(EEXIST, mNetd->networkCreate(config).serviceSpecificErrorCode()); |
| |
| config.networkType = NativeNetworkType::VIRTUAL; |
| config.secure = true; |
| EXPECT_EQ(EEXIST, mNetd->networkCreate(config).serviceSpecificErrorCode()); |
| |
| config.netId = TEST_NETID2; |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk()); |
| EXPECT_EQ(EBUSY, |
| mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode()); |
| |
| EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk()); |
| EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk()); |
| EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode()); |
| } |
| |
| TEST_F(NetdBinderTest, NetworkUidRules) { |
| auto config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::VIRTUAL, |
| INetd::PERMISSION_NONE, true, false); |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_EQ(EEXIST, mNetd->networkCreate(config).serviceSpecificErrorCode()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk()); |
| |
| std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012), |
| makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)}; |
| UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299); |
| std::string action = StringPrintf("lookup %s ", sTun.name().c_str()); |
| |
| EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk()); |
| |
| EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], action)); |
| EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, action)); |
| EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk()); |
| EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], action)); |
| |
| EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk()); |
| EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], action)); |
| EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk()); |
| EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], action)); |
| |
| EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode()); |
| } |
| |
| TEST_F(NetdBinderTest, NetworkRejectNonSecureVpn) { |
| std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224), |
| makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)}; |
| // Make sure no rules existed before calling commands. |
| for (auto const& range : uidRanges) { |
| EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_PROHIBIT_NON_VPN, range, "prohibit")); |
| } |
| // Create two valid rules. |
| ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk()); |
| for (auto const& range : uidRanges) { |
| EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_PROHIBIT_NON_VPN, range, "prohibit")); |
| } |
| |
| // Remove the rules. |
| ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk()); |
| for (auto const& range : uidRanges) { |
| EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_PROHIBIT_NON_VPN, range, "prohibit")); |
| } |
| |
| // Fail to remove the rules a second time after they are already deleted. |
| binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges); |
| ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode()); |
| } |
| |
| // Create a socket pair that isLoopbackSocket won't think is local. |
| void NetdBinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket, |
| unique_fd* acceptedSocket) { |
| serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0)); |
| struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() }; |
| ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6))); |
| |
| socklen_t addrlen = sizeof(server6); |
| ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen)); |
| ASSERT_EQ(0, listen(*serverSocket, 10)); |
| |
| clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0)); |
| struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() }; |
| ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6))); |
| ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6))); |
| ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen)); |
| |
| acceptedSocket->reset( |
| accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC)); |
| ASSERT_NE(-1, *acceptedSocket); |
| |
| ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6))); |
| } |
| |
| void checkSocketpairOpen(int clientSocket, int acceptedSocket) { |
| char buf[4096]; |
| EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo"))); |
| EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf))); |
| EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo"))); |
| } |
| |
| void checkSocketpairClosed(int clientSocket, int acceptedSocket) { |
| // Check that the client socket was closed with ECONNABORTED. |
| int ret = write(clientSocket, "foo", sizeof("foo")); |
| int err = errno; |
| EXPECT_EQ(-1, ret); |
| EXPECT_EQ(ECONNABORTED, err); |
| |
| // Check that it sent a RST to the server. |
| ret = write(acceptedSocket, "foo", sizeof("foo")); |
| err = errno; |
| EXPECT_EQ(-1, ret); |
| EXPECT_EQ(ECONNRESET, err); |
| } |
| |
| TEST_F(NetdBinderTest, SocketDestroy) { |
| unique_fd clientSocket, serverSocket, acceptedSocket; |
| ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket)); |
| |
| // Pick a random UID in the system UID range. |
| constexpr int baseUid = AID_APP - 2000; |
| static_assert(baseUid > 0, "Not enough UIDs? Please fix this test."); |
| int uid = baseUid + 500 + arc4random_uniform(1000); |
| EXPECT_EQ(0, fchown(clientSocket, uid, -1)); |
| |
| // UID ranges that don't contain uid. |
| std::vector<UidRangeParcel> uidRanges = { |
| makeUidRangeParcel(baseUid + 42, baseUid + 449), |
| makeUidRangeParcel(baseUid + 1536, AID_APP - 4), |
| makeUidRangeParcel(baseUid + 498, uid - 1), |
| makeUidRangeParcel(uid + 1, baseUid + 1520), |
| }; |
| // A skip list that doesn't contain UID. |
| std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 }; |
| |
| // Close sockets. Our test socket should be intact. |
| EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk()); |
| checkSocketpairOpen(clientSocket, acceptedSocket); |
| |
| // UID ranges that do contain uid. |
| uidRanges = { |
| makeUidRangeParcel(baseUid + 42, baseUid + 449), |
| makeUidRangeParcel(baseUid + 1536, AID_APP - 4), |
| makeUidRangeParcel(baseUid + 498, baseUid + 1520), |
| }; |
| // Add uid to the skip list. |
| skipUids.push_back(uid); |
| |
| // Close sockets. Our test socket should still be intact because it's in the skip list. |
| EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk()); |
| checkSocketpairOpen(clientSocket, acceptedSocket); |
| |
| // Now remove uid from skipUids, and close sockets. Our test socket should have been closed. |
| skipUids.resize(skipUids.size() - 1); |
| EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk()); |
| checkSocketpairClosed(clientSocket, acceptedSocket); |
| } |
| |
| TEST_F(NetdBinderTest, SocketDestroyLinkLocal) { |
| // Add the same link-local address to two interfaces. |
| const char* kLinkLocalAddress = "fe80::ace:d00d"; |
| |
| const struct addrinfo hints = { |
| .ai_family = AF_INET6, |
| .ai_socktype = SOCK_STREAM, |
| .ai_flags = AI_NUMERICHOST, |
| }; |
| |
| binder::Status status = mNetd->interfaceAddAddress(sTun.name(), kLinkLocalAddress, 64); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| status = mNetd->interfaceAddAddress(sTun2.name(), kLinkLocalAddress, 64); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| // Bind a listening socket to the address on each of two interfaces. |
| // The sockets must be open at the same time, because this test checks that SOCK_DESTROY only |
| // destroys the sockets on the interface where the address is deleted. |
| struct addrinfo* addrinfoList = nullptr; |
| int ret = getaddrinfo(kLinkLocalAddress, nullptr, &hints, &addrinfoList); |
| ScopedAddrinfo addrinfoCleanup(addrinfoList); |
| ASSERT_EQ(0, ret); |
| |
| socklen_t len = addrinfoList[0].ai_addrlen; |
| sockaddr_in6 sin6_1 = *reinterpret_cast<sockaddr_in6*>(addrinfoList[0].ai_addr); |
| sockaddr_in6 sin6_2 = sin6_1; |
| sin6_1.sin6_scope_id = if_nametoindex(sTun.name().c_str()); |
| sin6_2.sin6_scope_id = if_nametoindex(sTun2.name().c_str()); |
| |
| int s1 = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, 0); |
| ASSERT_EQ(0, bind(s1, reinterpret_cast<sockaddr*>(&sin6_1), len)); |
| ASSERT_EQ(0, getsockname(s1, reinterpret_cast<sockaddr*>(&sin6_1), &len)); |
| // getsockname technically writes to len, but sizeof(sockaddr_in6) doesn't change. |
| |
| int s2 = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, 0); |
| ASSERT_EQ(0, bind(s2, reinterpret_cast<sockaddr*>(&sin6_2), len)); |
| ASSERT_EQ(0, getsockname(s2, reinterpret_cast<sockaddr*>(&sin6_2), &len)); |
| |
| ASSERT_EQ(0, listen(s1, 10)); |
| ASSERT_EQ(0, listen(s2, 10)); |
| |
| // Connect one client socket to each and accept the connections. |
| int c1 = socket(AF_INET6, SOCK_STREAM, 0); |
| int c2 = socket(AF_INET6, SOCK_STREAM, 0); |
| ASSERT_EQ(0, connect(c1, reinterpret_cast<sockaddr*>(&sin6_1), len)); |
| ASSERT_EQ(0, connect(c2, reinterpret_cast<sockaddr*>(&sin6_2), len)); |
| int a1 = accept(s1, nullptr, 0); |
| ASSERT_NE(-1, a1); |
| int a2 = accept(s2, nullptr, 0); |
| ASSERT_NE(-1, a2); |
| |
| // Delete the address on sTun2. |
| status = mNetd->interfaceDelAddress(sTun2.name(), kLinkLocalAddress, 64); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| // The client sockets on sTun2 are closed, but the ones on sTun1 remain open. |
| char buf[1024]; |
| EXPECT_EQ(-1, read(c2, buf, sizeof(buf))); |
| EXPECT_EQ(ECONNABORTED, errno); |
| // The blocking read above ensures that SOCK_DESTROY has completed. |
| |
| EXPECT_EQ(3, write(a1, "foo", 3)); |
| EXPECT_EQ(3, read(c1, buf, sizeof(buf))); |
| EXPECT_EQ(-1, write(a2, "foo", 3)); |
| EXPECT_TRUE(errno == ECONNABORTED || errno == ECONNRESET); |
| |
| // Check the server sockets too. |
| EXPECT_EQ(-1, accept(s1, nullptr, 0)); |
| EXPECT_EQ(EAGAIN, errno); |
| EXPECT_EQ(-1, accept(s2, nullptr, 0)); |
| EXPECT_EQ(EINVAL, errno); |
| } |
| |
| namespace { |
| |
| int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) { |
| if (buf == nullptr) return -1; |
| |
| int prefixLength = 0; |
| bool endOfContiguousBits = false; |
| for (unsigned int i = 0; i < buflen; i++) { |
| const uint8_t value = buf[i]; |
| |
| // Bad bit sequence: check for a contiguous set of bits from the high |
| // end by verifying that the inverted value + 1 is a power of 2 |
| // (power of 2 iff. (v & (v - 1)) == 0). |
| const uint8_t inverse = ~value + 1; |
| if ((inverse & (inverse - 1)) != 0) return -1; |
| |
| prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1; |
| |
| // Bogus netmask. |
| if (endOfContiguousBits && value != 0) return -1; |
| |
| if (value != 0xff) endOfContiguousBits = true; |
| } |
| |
| return prefixLength; |
| } |
| |
| template<typename T> |
| int netmaskToPrefixLength(const T *p) { |
| return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T)); |
| } |
| |
| |
| static bool interfaceHasAddress( |
| const std::string &ifname, const char *addrString, int prefixLength) { |
| struct addrinfo *addrinfoList = nullptr; |
| |
| const struct addrinfo hints = { |
| .ai_flags = AI_NUMERICHOST, |
| .ai_family = AF_UNSPEC, |
| .ai_socktype = SOCK_DGRAM, |
| }; |
| if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 || |
| addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) { |
| return false; |
| } |
| ScopedAddrinfo addrinfoCleanup(addrinfoList); |
| |
| struct ifaddrs *ifaddrsList = nullptr; |
| ScopedIfaddrs ifaddrsCleanup(ifaddrsList); |
| |
| if (getifaddrs(&ifaddrsList) != 0) { |
| return false; |
| } |
| |
| for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) { |
| if (std::string(addr->ifa_name) != ifname || |
| addr->ifa_addr == nullptr || |
| addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) { |
| continue; |
| } |
| |
| switch (addr->ifa_addr->sa_family) { |
| case AF_INET: { |
| auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr); |
| auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr); |
| if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) { |
| continue; |
| } |
| |
| if (prefixLength < 0) return true; // not checking prefix lengths |
| |
| if (addr->ifa_netmask == nullptr) return false; |
| auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask); |
| EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr)); |
| return (prefixLength == netmaskToPrefixLength(&nm->sin_addr)); |
| } |
| case AF_INET6: { |
| auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr); |
| auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr); |
| if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) { |
| continue; |
| } |
| |
| if (prefixLength < 0) return true; // not checking prefix lengths |
| |
| if (addr->ifa_netmask == nullptr) return false; |
| auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask); |
| EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr)); |
| return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr)); |
| } |
| default: |
| // Cannot happen because we have already screened for matching |
| // address families at the top of each iteration. |
| continue; |
| } |
| } |
| |
| return false; |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, InterfaceAddRemoveAddress) { |
| static const struct TestData { |
| const char *addrString; |
| const int prefixLength; |
| const int expectAddResult; |
| const int expectRemoveResult; |
| } kTestData[] = { |
| {"192.0.2.1", 24, 0, 0}, |
| {"192.0.2.2", 25, 0, 0}, |
| {"192.0.2.3", 32, 0, 0}, |
| {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL}, |
| {"192.not.an.ip", 24, EINVAL, EINVAL}, |
| {"2001:db8::1", 64, 0, 0}, |
| {"2001:db8::2", 65, 0, 0}, |
| {"2001:db8::3", 128, 0, 0}, |
| {"fe80::1234", 64, 0, 0}, |
| {"2001:db8::4", 129, EINVAL, EINVAL}, |
| {"foo:bar::bad", 64, EINVAL, EINVAL}, |
| {"2001:db8::1/64", 64, EINVAL, EINVAL}, |
| }; |
| |
| for (size_t i = 0; i < std::size(kTestData); i++) { |
| const auto &td = kTestData[i]; |
| |
| SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength)); |
| |
| // [1.a] Add the address. |
| binder::Status status = mNetd->interfaceAddAddress( |
| sTun.name(), td.addrString, td.prefixLength); |
| if (td.expectAddResult == 0) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| } else { |
| ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode()); |
| } |
| |
| // [1.b] Verify the addition meets the expectation. |
| if (td.expectAddResult == 0) { |
| EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength)); |
| } else { |
| EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1)); |
| } |
| |
| // [2.a] Try to remove the address. If it was not previously added, removing it fails. |
| status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength); |
| if (td.expectRemoveResult == 0) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| } else { |
| ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode()); |
| } |
| |
| // [2.b] No matter what, the address should not be present. |
| EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1)); |
| } |
| |
| // Check that netlink errors are returned correctly. |
| // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled, |
| // which returns EACCES. |
| TunInterface tun; |
| ASSERT_EQ(0, tun.init()); |
| binder::Status status = |
| mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1"); |
| ASSERT_TRUE(status.isOk()) << status.exceptionMessage(); |
| status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64); |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_EQ(EACCES, status.serviceSpecificErrorCode()); |
| tun.destroy(); |
| } |
| |
| TEST_F(NetdBinderTest, GetProcSysNet) { |
| const char* LOOPBACK = "lo"; |
| static const struct { |
| const int ipversion; |
| const int which; |
| const char* ifname; |
| const char* parameter; |
| const char* expectedValue; |
| const int expectedReturnCode; |
| } kTestData[] = { |
| {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0}, |
| {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT}, |
| {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL}, |
| {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL}, |
| {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL}, |
| {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL}, |
| {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0}, |
| }; |
| |
| for (size_t i = 0; i < std::size(kTestData); i++) { |
| const auto& td = kTestData[i]; |
| |
| std::string value; |
| const binder::Status status = |
| mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value); |
| |
| if (td.expectedReturnCode == 0) { |
| SCOPED_TRACE(String8::format("test case %zu should have passed", i)); |
| EXPECT_EQ(0, status.exceptionCode()); |
| EXPECT_EQ(0, status.serviceSpecificErrorCode()); |
| EXPECT_EQ(td.expectedValue, value); |
| } else { |
| SCOPED_TRACE(String8::format("test case %zu should have failed", i)); |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode()); |
| } |
| } |
| } |
| |
| TEST_F(NetdBinderTest, SetProcSysNet) { |
| static const struct { |
| const int ipversion; |
| const int which; |
| const char* ifname; |
| const char* parameter; |
| const char* value; |
| const int expectedReturnCode; |
| } kTestData[] = { |
| {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0}, |
| {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT}, |
| {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL}, |
| {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL}, |
| {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL}, |
| {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL}, |
| {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0}, |
| }; |
| |
| for (size_t i = 0; i < std::size(kTestData); i++) { |
| const auto& td = kTestData[i]; |
| const binder::Status status = |
| mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value); |
| |
| if (td.expectedReturnCode == 0) { |
| SCOPED_TRACE(String8::format("test case %zu should have passed", i)); |
| EXPECT_EQ(0, status.exceptionCode()); |
| EXPECT_EQ(0, status.serviceSpecificErrorCode()); |
| } else { |
| SCOPED_TRACE(String8::format("test case %zu should have failed", i)); |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode()); |
| } |
| } |
| } |
| |
| TEST_F(NetdBinderTest, GetSetProcSysNet) { |
| const int ipversion = INetd::IPV6; |
| const int category = INetd::NEIGH; |
| const std::string& tun = sTun.name(); |
| const std::string parameter("ucast_solicit"); |
| |
| std::string value{}; |
| EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk()); |
| ASSERT_FALSE(value.empty()); |
| const int ival = std::stoi(value); |
| EXPECT_GT(ival, 0); |
| // Try doubling the parameter value (always best!). |
| EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival)) |
| .isOk()); |
| EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk()); |
| EXPECT_EQ(2 * ival, std::stoi(value)); |
| // Try resetting the parameter. |
| EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival)) |
| .isOk()); |
| EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk()); |
| EXPECT_EQ(ival, std::stoi(value)); |
| } |
| |
| namespace { |
| |
| void expectNoTestCounterRules() { |
| for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) { |
| std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary); |
| std::string allRules = Join(runCommand(command), "\n"); |
| EXPECT_EQ(std::string::npos, allRules.find("netdtest_")); |
| } |
| } |
| |
| void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2, |
| int byte, int pkt) { |
| runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d", |
| path, if1.c_str(), if2.c_str(), pkt, byte)); |
| } |
| |
| void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) { |
| runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN", |
| path, if1.c_str(), if2.c_str())); |
| runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN", |
| path, if2.c_str(), if1.c_str())); |
| } |
| |
| std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec, |
| const std::string& iface) { |
| for (auto& stats : statsVec) { |
| if (stats.iface == iface) { |
| return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets}; |
| } |
| } |
| return {}; |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, TetherGetStats) { |
| expectNoTestCounterRules(); |
| |
| // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and |
| // disabling tethering. We don't check the return value because these commands will fail if |
| // tethering is already enabled. |
| runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH)); |
| runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH)); |
| |
| std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000)); |
| std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000)); |
| std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000)); |
| |
| // Ensure we won't use the same interface name, otherwise the test will fail. |
| u_int32_t rNumber = arc4random_uniform(10000); |
| std::string extIface1 = StringPrintf("netdtest_%u", rNumber); |
| std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1); |
| |
| addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111); |
| addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10); |
| addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222); |
| addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20); |
| // RX is from external to internal, and TX is from internal to external. |
| // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc. |
| std::vector<int64_t> expected1 = { 975, 242, 579, 121 }; |
| |
| addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333); |
| addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30); |
| |
| addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444); |
| addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40); |
| |
| addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25); |
| addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35); |
| std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 }; |
| |
| std::vector<TetherStatsParcel> statsVec; |
| binder::Status status = mNetd->tetherGetStats(&statsVec); |
| EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status; |
| |
| EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1)); |
| |
| EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2)); |
| |
| for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) { |
| delTetherCounterValues(path, intIface1, extIface1); |
| delTetherCounterValues(path, intIface2, extIface2); |
| if (strcmp(path, IP6TABLES_PATH) == 0) { |
| delTetherCounterValues(path, intIface3, extIface2); |
| } |
| } |
| |
| expectNoTestCounterRules(); |
| } |
| |
| namespace { |
| |
| constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING"; |
| constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING"; |
| |
| static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table, |
| const char* chainName) { |
| std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName); |
| return runCommand(command); |
| } |
| |
| // TODO: It is a duplicate function, need to remove it |
| bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName, |
| const std::string& expectedInterface, |
| const std::string& expectedRule, const char* table) { |
| std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName); |
| for (const auto& rule : rules) { |
| if (rule.find(expectedInterface) != std::string::npos) { |
| if (rule.find(expectedRule) != std::string::npos) { |
| return true; |
| } |
| } |
| } |
| return false; |
| } |
| |
| void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout, |
| const std::string& classLabel) { |
| std::string IdletimerRule = |
| StringPrintf("timeout:%u label:%s send_nl_msg", timeout, classLabel.c_str()); |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname, |
| IdletimerRule, RAW_TABLE)); |
| EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING, |
| ifname, IdletimerRule, MANGLE_TABLE)); |
| } |
| } |
| |
| void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout, |
| const std::string& classLabel) { |
| std::string IdletimerRule = |
| StringPrintf("timeout:%u label:%s send_nl_msg", timeout, classLabel.c_str()); |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname, |
| IdletimerRule, RAW_TABLE)); |
| EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING, |
| ifname, IdletimerRule, MANGLE_TABLE)); |
| } |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, IdletimerAddRemoveInterface) { |
| // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same |
| // rule in the table. Because we only check the result after calling remove function. We might |
| // check the actual rule which is removed by our function (maybe compare the results between |
| // calling function before and after) |
| binder::Status status; |
| const struct TestData { |
| const std::string ifname; |
| int32_t timeout; |
| const std::string classLabel; |
| } idleTestData[] = { |
| {"wlan0", 1234, "happyday"}, |
| {"rmnet_data0", 4567, "friday"}, |
| }; |
| for (const auto& td : idleTestData) { |
| status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel); |
| |
| status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel); |
| } |
| } |
| |
| namespace { |
| |
| constexpr char STRICT_OUTPUT[] = "st_OUTPUT"; |
| constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught"; |
| |
| // Output looks like this: |
| // |
| // IPv4: |
| // |
| // throw dst proto static scope link |
| // unreachable dst proto static scope link |
| // dst via nextHop dev ifName proto static |
| // dst dev ifName proto static scope link |
| // |
| // IPv6: |
| // |
| // throw dst dev lo proto static metric 1024 |
| // unreachable dst dev lo proto static metric 1024 |
| // dst via nextHop dev ifName proto static metric 1024 |
| // dst dev ifName proto static metric 1024 |
| std::string ipRoutePrefix(const std::string& ifName, const std::string& dst, |
| const std::string& nextHop) { |
| std::string prefixString; |
| |
| bool isThrow = nextHop == "throw"; |
| bool isUnreachable = nextHop == "unreachable"; |
| bool isDefault = (dst == "0.0.0.0/0" || dst == "::/0"); |
| bool isIPv6 = dst.find(':') != std::string::npos; |
| bool isThrowOrUnreachable = isThrow || isUnreachable; |
| |
| if (isThrowOrUnreachable) { |
| prefixString += nextHop + " "; |
| } |
| |
| prefixString += isDefault ? "default" : dst; |
| |
| if (!nextHop.empty() && !isThrowOrUnreachable) { |
| prefixString += " via " + nextHop; |
| } |
| |
| if (isThrowOrUnreachable) { |
| if (isIPv6) { |
| prefixString += " dev lo"; |
| } |
| } else { |
| prefixString += " dev " + ifName; |
| } |
| |
| prefixString += " proto static"; |
| |
| // IPv6 routes report the metric, IPv4 routes report the scope. |
| if (isIPv6) { |
| prefixString += " metric 1024"; |
| } else { |
| if (nextHop.empty() || isThrowOrUnreachable) { |
| prefixString += " scope link"; |
| } |
| } |
| |
| return prefixString; |
| } |
| |
| void expectStrictSetUidAccept(const int uid) { |
| std::string uidRule = StringPrintf("owner UID match %u", uid); |
| std::string perUidChain = StringPrintf("st_clear_caught_%u", uid); |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule)); |
| EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule)); |
| EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str())); |
| } |
| } |
| |
| void expectStrictSetUidLog(const int uid) { |
| static const char logRule[] = "st_penalty_log all"; |
| std::string uidRule = StringPrintf("owner UID match %u", uid); |
| std::string perUidChain = StringPrintf("st_clear_caught_%u", uid); |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule)); |
| EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule)); |
| EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule)); |
| } |
| } |
| |
| void expectStrictSetUidReject(const int uid) { |
| static const char rejectRule[] = "st_penalty_reject all"; |
| std::string uidRule = StringPrintf("owner UID match %u", uid); |
| std::string perUidChain = StringPrintf("st_clear_caught_%u", uid); |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule)); |
| EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule)); |
| EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule)); |
| } |
| } |
| |
| bool ipRuleExists(const char* ipVersion, const std::string& ipRule) { |
| std::vector<std::string> rules = listIpRules(ipVersion); |
| for (const auto& rule : rules) { |
| if (rule.find(ipRule) != std::string::npos) { |
| return true; |
| } |
| } |
| return false; |
| } |
| |
| std::vector<std::string> ipRouteSubstrings(const std::string& ifName, const std::string& dst, |
| const std::string& nextHop, const std::string& mtu) { |
| std::vector<std::string> routeSubstrings; |
| |
| routeSubstrings.push_back(ipRoutePrefix(ifName, dst, nextHop)); |
| |
| if (!mtu.empty()) { |
| // Add separate substring to match mtu value. |
| // This is needed because on some devices "error -11"/"error -113" appears between ip prefix |
| // and mtu for throw/unreachable routes. |
| routeSubstrings.push_back("mtu " + mtu); |
| } |
| |
| return routeSubstrings; |
| } |
| |
| void expectNetworkRouteDoesNotExistWithMtu(const char* ipVersion, const std::string& ifName, |
| const std::string& dst, const std::string& nextHop, |
| const std::string& mtu, const char* table) { |
| std::vector<std::string> routeSubstrings = ipRouteSubstrings(ifName, dst, nextHop, mtu); |
| EXPECT_FALSE(ipRouteExists(ipVersion, table, routeSubstrings)) |
| << "Found unexpected route [" << Join(routeSubstrings, ", ") << "] in table " << table; |
| } |
| |
| void expectNetworkRouteExistsWithMtu(const char* ipVersion, const std::string& ifName, |
| const std::string& dst, const std::string& nextHop, |
| const std::string& mtu, const char* table) { |
| std::vector<std::string> routeSubstrings = ipRouteSubstrings(ifName, dst, nextHop, mtu); |
| EXPECT_TRUE(ipRouteExists(ipVersion, table, routeSubstrings)) |
| << "Couldn't find route to " << dst << ": [" << Join(routeSubstrings, ", ") |
| << "] in table " << table; |
| } |
| |
| void expectVpnLocalExclusionRuleExists(const std::string& ifName, bool expectExists) { |
| std::string tableName = std::string(ifName + "_local"); |
| // Check if rule exists |
| std::string vpnLocalExclusionRule = |
| StringPrintf("%d:\tfrom all fwmark 0x0/0x10000 iif lo lookup %s", |
| RULE_PRIORITY_LOCAL_ROUTES, tableName.c_str()); |
| for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) { |
| EXPECT_EQ(expectExists, ipRuleExists(ipVersion, vpnLocalExclusionRule)); |
| } |
| } |
| |
| void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName, |
| const std::string& dst, const std::string& nextHop, |
| const char* table) { |
| expectNetworkRouteExistsWithMtu(ipVersion, ifName, dst, nextHop, "", table); |
| } |
| |
| void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName, |
| const std::string& dst, const std::string& nextHop, |
| const char* table) { |
| expectNetworkRouteDoesNotExistWithMtu(ipVersion, ifName, dst, nextHop, "", table); |
| } |
| |
| void expectNetworkDefaultIpRuleExists(const char* ifName) { |
| std::string networkDefaultRule = |
| StringPrintf("%u:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", |
| RULE_PRIORITY_DEFAULT_NETWORK, ifName); |
| |
| for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) { |
| EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule)); |
| } |
| } |
| |
| void expectNetworkDefaultIpRuleDoesNotExist() { |
| std::string networkDefaultRule = |
| StringPrintf("%u:\tfrom all fwmark 0x0/0xffff iif lo", RULE_PRIORITY_DEFAULT_NETWORK); |
| |
| for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) { |
| EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule)); |
| } |
| } |
| |
| void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) { |
| std::string networkPermissionRule = ""; |
| switch (permission) { |
| case INetd::PERMISSION_NONE: |
| networkPermissionRule = |
| StringPrintf("%u:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", |
| RULE_PRIORITY_EXPLICIT_NETWORK, ifName); |
| break; |
| case INetd::PERMISSION_NETWORK: |
| networkPermissionRule = |
| StringPrintf("%u:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", |
| RULE_PRIORITY_EXPLICIT_NETWORK, ifName); |
| break; |
| case INetd::PERMISSION_SYSTEM: |
| networkPermissionRule = |
| StringPrintf("%u:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", |
| RULE_PRIORITY_EXPLICIT_NETWORK, ifName); |
| break; |
| } |
| |
| for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) { |
| EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule)); |
| } |
| } |
| |
| // TODO: It is a duplicate function, need to remove it |
| bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName, |
| const std::string& expectedInterface, |
| const std::string& expectedRule, |
| const char* table) { |
| std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName); |
| for (const auto& rule : rules) { |
| if (rule.find(expectedInterface) != std::string::npos) { |
| if (rule.find(expectedRule) != std::string::npos) { |
| return true; |
| } |
| } |
| } |
| return false; |
| } |
| |
| void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) { |
| static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT"; |
| std::string networkIncomingPacketMarkRule = ""; |
| switch (permission) { |
| case INetd::PERMISSION_NONE: |
| networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff"; |
| break; |
| case INetd::PERMISSION_NETWORK: |
| networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff"; |
| break; |
| case INetd::PERMISSION_SYSTEM: |
| networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff"; |
| break; |
| } |
| |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists( |
| binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE)); |
| } |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, StrictSetUidCleartextPenalty) { |
| binder::Status status; |
| int32_t uid = randomUid(); |
| |
| // setUidCleartextPenalty Policy:Log with randomUid |
| status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectStrictSetUidLog(uid); |
| |
| // setUidCleartextPenalty Policy:Accept with randomUid |
| status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT); |
| expectStrictSetUidAccept(uid); |
| |
| // setUidCleartextPenalty Policy:Reject with randomUid |
| status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectStrictSetUidReject(uid); |
| |
| // setUidCleartextPenalty Policy:Accept with randomUid |
| status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT); |
| expectStrictSetUidAccept(uid); |
| |
| // test wrong policy |
| int32_t wrongPolicy = -123; |
| status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy); |
| EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode()); |
| } |
| |
| namespace { |
| |
| std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1, |
| uint32_t intervalMs = 50) { |
| // Output looks like:(clatd) |
| // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ... |
| // ... |
| // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0' |
| |
| // (dnsmasq) |
| // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ... |
| |
| if (maxTries == 0) return {}; |
| |
| std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str()); |
| std::vector<std::string> result; |
| for (uint32_t run = 1;;) { |
| result = runCommand(cmd); |
| if (result.size() || ++run > maxTries) { |
| break; |
| } |
| |
| usleep(intervalMs * 1000); |
| } |
| return result; |
| } |
| |
| void expectProcessExists(const std::string& processName) { |
| EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size()); |
| } |
| |
| void expectProcessDoesNotExist(const std::string& processName) { |
| EXPECT_FALSE(tryToFindProcesses(processName).size()); |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, NetworkAddRemoveRouteToLocalExcludeTable) { |
| static const struct { |
| const char* ipVersion; |
| const char* testDest; |
| const char* testNextHop; |
| const bool expectInLocalTable; |
| } kTestData[] = {{IP_RULE_V6, "::/0", "fe80::", false}, |
| {IP_RULE_V6, "::/0", "", false}, |
| {IP_RULE_V6, "2001:db8:cafe::/64", "fe80::", false}, |
| {IP_RULE_V6, "fe80::/64", "", true}, |
| {IP_RULE_V6, "2001:db8:cafe::/48", "", true}, |
| {IP_RULE_V6, "2001:db8:cafe::/64", "unreachable", false}, |
| {IP_RULE_V6, "2001:db8:ca00::/40", "", true}, |
| {IP_RULE_V4, "0.0.0.0/0", "10.251.10.1", false}, |
| {IP_RULE_V4, "192.1.0.0/16", "", false}, |
| {IP_RULE_V4, "192.168.0.0/15", "", false}, |
| {IP_RULE_V4, "192.168.0.0/16", "", true}, |
| {IP_RULE_V4, "192.168.0.0/24", "", true}, |
| {IP_RULE_V4, "100.1.0.0/16", "", false}, |
| {IP_RULE_V4, "100.0.0.0/8", "", false}, |
| {IP_RULE_V4, "100.64.0.0/10", "", true}, |
| {IP_RULE_V4, "100.64.0.0/16", "", true}, |
| {IP_RULE_V4, "100.64.0.0/10", "throw", false}, |
| {IP_RULE_V4, "172.0.0.0/8", "", false}, |
| {IP_RULE_V4, "172.16.0.0/12", "", true}, |
| {IP_RULE_V4, "172.16.0.0/16", "", true}, |
| {IP_RULE_V4, "172.16.0.0/12", "unreachable", false}, |
| {IP_RULE_V4, "172.32.0.0/12", "", false}, |
| {IP_RULE_V4, "169.0.0.0/8", "", false}, |
| {IP_RULE_V4, "169.254.0.0/16", "", true}, |
| {IP_RULE_V4, "169.254.0.0/20", "", true}, |
| {IP_RULE_V4, "169.254.3.0/24", "", true}, |
| {IP_RULE_V4, "170.254.0.0/16", "", false}, |
| {IP_RULE_V4, "10.0.0.0/8", "", true}, |
| {IP_RULE_V4, "10.0.0.0/7", "", false}, |
| {IP_RULE_V4, "10.0.0.0/16", "", true}, |
| {IP_RULE_V4, "10.251.0.0/16", "", true}, |
| {IP_RULE_V4, "10.251.250.0/24", "", true}, |
| {IP_RULE_V4, "10.251.10.2/31", "throw", false}, |
| {IP_RULE_V4, "10.251.10.2/31", "unreachable", false}}; |
| |
| // To ensure that the nexthops for the above are reachable. |
| // Otherwise, the routes can't be created. |
| static const struct { |
| const char* ipVersion; |
| const char* testDest; |
| const char* testNextHop; |
| } kDirectlyConnectedRoutes[] = { |
| {IP_RULE_V4, "10.251.10.0/30", ""}, |
| {IP_RULE_V6, "2001:db8::/32", ""}, |
| }; |
| |
| // Add test physical network |
| const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL, |
| INetd::PERMISSION_NONE, false, false); |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk()); |
| |
| // Get current default network NetId |
| binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork); |
| ASSERT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| // Set default network |
| EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk()); |
| |
| std::string localTableName = std::string(sTun.name() + "_local"); |
| |
| // Verify the fixed routes exist in the local table. |
| for (size_t i = 0; i < std::size(V4_FIXED_LOCAL_PREFIXES); i++) { |
| expectNetworkRouteExists(IP_RULE_V4, sTun.name(), V4_FIXED_LOCAL_PREFIXES[i], "", |
| localTableName.c_str()); |
| } |
| |
| // Set up link-local routes for connectivity to the "gateway" |
| for (size_t i = 0; i < std::size(kDirectlyConnectedRoutes); i++) { |
| const auto& td = kDirectlyConnectedRoutes[i]; |
| |
| binder::Status status = |
| mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| sTun.name().c_str()); |
| // Verify routes in local table |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| localTableName.c_str()); |
| } |
| |
| for (size_t i = 0; i < std::size(kTestData); i++) { |
| const auto& td = kTestData[i]; |
| SCOPED_TRACE(StringPrintf("case ip:%s, dest:%s, nexHop:%s, expect:%d", td.ipVersion, |
| td.testDest, td.testNextHop, td.expectInLocalTable)); |
| binder::Status status = |
| mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| // Verify routes in local table |
| if (td.expectInLocalTable) { |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| localTableName.c_str()); |
| } else { |
| expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| localTableName.c_str()); |
| } |
| |
| status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| localTableName.c_str()); |
| } |
| |
| for (size_t i = 0; i < std::size(kDirectlyConnectedRoutes); i++) { |
| const auto& td = kDirectlyConnectedRoutes[i]; |
| status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| } |
| |
| // Set default network back |
| status = mNetd->networkSetDefault(mStoredDefaultNetwork); |
| |
| // Remove test physical network |
| EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk()); |
| } |
| |
| namespace { |
| |
| bool getIpfwdV4Enable() { |
| static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward"; |
| std::vector<std::string> result = runCommand(ipv4IpfwdCmd); |
| EXPECT_TRUE(!result.empty()); |
| int v4Enable = std::stoi(result[0]); |
| return v4Enable; |
| } |
| |
| bool getIpfwdV6Enable() { |
| static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding"; |
| std::vector<std::string> result = runCommand(ipv6IpfwdCmd); |
| EXPECT_TRUE(!result.empty()); |
| int v6Enable = std::stoi(result[0]); |
| return v6Enable; |
| } |
| |
| void expectIpfwdEnable(bool enable) { |
| int enableIPv4 = getIpfwdV4Enable(); |
| int enableIPv6 = getIpfwdV6Enable(); |
| EXPECT_EQ(enable, enableIPv4); |
| EXPECT_EQ(enable, enableIPv6); |
| } |
| |
| bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) { |
| std::vector<std::string> rules = listIpRules(ipVersion); |
| for (const auto& rule : rules) { |
| if (rule.find(ipfwdRule) != std::string::npos) { |
| return true; |
| } |
| } |
| return false; |
| } |
| |
| void expectIpfwdRuleExists(const char* fromIf, const char* toIf) { |
| std::string ipfwdRule = |
| StringPrintf("%u:\tfrom all iif %s lookup %s ", RULE_PRIORITY_TETHERING, fromIf, toIf); |
| |
| for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) { |
| EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule)); |
| } |
| } |
| |
| void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) { |
| std::string ipfwdRule = |
| StringPrintf("%u:\tfrom all iif %s lookup %s ", RULE_PRIORITY_TETHERING, fromIf, toIf); |
| |
| for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) { |
| EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule)); |
| } |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, TestIpfwdEnableDisableStatusForwarding) { |
| // Get ipfwd requester list from Netd |
| std::vector<std::string> requesterList; |
| binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| bool ipfwdEnabled; |
| if (requesterList.size() == 0) { |
| // No requester in Netd, ipfwd should be disabled |
| // So add one test requester and verify |
| status = mNetd->ipfwdEnableForwarding("TestRequester"); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| expectIpfwdEnable(true); |
| status = mNetd->ipfwdEnabled(&ipfwdEnabled); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| EXPECT_TRUE(ipfwdEnabled); |
| |
| // Remove test one, verify again |
| status = mNetd->ipfwdDisableForwarding("TestRequester"); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| expectIpfwdEnable(false); |
| status = mNetd->ipfwdEnabled(&ipfwdEnabled); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| EXPECT_FALSE(ipfwdEnabled); |
| } else { |
| // Disable all requesters |
| for (const auto& requester : requesterList) { |
| status = mNetd->ipfwdDisableForwarding(requester); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| } |
| |
| // After disable all requester, ipfwd should be disabled |
| expectIpfwdEnable(false); |
| status = mNetd->ipfwdEnabled(&ipfwdEnabled); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| EXPECT_FALSE(ipfwdEnabled); |
| |
| // Enable them back |
| for (const auto& requester : requesterList) { |
| status = mNetd->ipfwdEnableForwarding(requester); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| } |
| |
| // ipfwd should be enabled |
| expectIpfwdEnable(true); |
| status = mNetd->ipfwdEnabled(&ipfwdEnabled); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| EXPECT_TRUE(ipfwdEnabled); |
| } |
| } |
| |
| TEST_F(NetdBinderTest, TestIpfwdAddRemoveInterfaceForward) { |
| // Add test physical network |
| auto config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL, |
| INetd::PERMISSION_NONE, false, false); |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk()); |
| |
| config.netId = TEST_NETID2; |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk()); |
| |
| binder::Status status = mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name()); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str()); |
| |
| status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name()); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str()); |
| } |
| |
| namespace { |
| |
| constexpr char BANDWIDTH_INPUT[] = "bw_INPUT"; |
| constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT"; |
| constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD"; |
| constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box"; |
| constexpr char BANDWIDTH_ALERT[] = "bw_global_alert"; |
| |
| // TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top. |
| // Use either a std::vector<std::string> of things to match, or a variadic function. |
| bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table, |
| const char* chainName, const std::string& expectedTargetA, |
| const std::string& expectedTargetB) { |
| std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName); |
| int matchCount = 0; |
| |
| for (const auto& rule : rules) { |
| if (rule.find(expectedTargetA) != std::string::npos) { |
| if (rule.find(expectedTargetB) != std::string::npos) { |
| matchCount++; |
| } |
| } |
| } |
| return matchCount == expectedCount; |
| } |
| |
| void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) { |
| std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname); |
| std::string result = ""; |
| |
| EXPECT_TRUE(ReadFileToString(path, &result)); |
| // Quota value might be decreased while matching packets |
| EXPECT_GE(quotaBytes, std::stol(Trim(result))); |
| } |
| |
| void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) { |
| std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname); |
| std::string quotaRule = StringPrintf("quota %s", ifname); |
| |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname, |
| BANDWIDTH_COSTLY_IF)); |
| EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname, |
| BANDWIDTH_COSTLY_IF)); |
| EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname, |
| BANDWIDTH_COSTLY_IF)); |
| EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY)); |
| EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule)); |
| } |
| expectXtQuotaValueEqual(ifname, quotaBytes); |
| } |
| |
| void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) { |
| std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname); |
| std::string quotaRule = StringPrintf("quota %s", ifname); |
| |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname, |
| BANDWIDTH_COSTLY_IF)); |
| EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname, |
| BANDWIDTH_COSTLY_IF)); |
| EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname, |
| BANDWIDTH_COSTLY_IF)); |
| EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY)); |
| EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule)); |
| } |
| } |
| |
| void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) { |
| std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname); |
| std::string alertRule = StringPrintf("quota %sAlert", ifname); |
| std::string alertName = StringPrintf("%sAlert", ifname); |
| |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule)); |
| } |
| expectXtQuotaValueEqual(alertName.c_str(), alertBytes); |
| } |
| |
| void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) { |
| std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname); |
| std::string alertRule = StringPrintf("quota %sAlert", ifname); |
| |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule)); |
| } |
| } |
| |
| void expectBandwidthGlobalAlertRuleExists(long alertBytes) { |
| static const char globalAlertRule[] = "quota globalAlert"; |
| static const char globalAlertName[] = "globalAlert"; |
| |
| for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) { |
| EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule)); |
| } |
| expectXtQuotaValueEqual(globalAlertName, alertBytes); |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, BandwidthSetRemoveInterfaceQuota) { |
| long testQuotaBytes = 5550; |
| |
| // Add test physical network |
| const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL, |
| INetd::PERMISSION_NONE, false, false); |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk()); |
| |
| binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes); |
| |
| status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name()); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str()); |
| |
| // Remove test physical network |
| EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk()); |
| } |
| |
| TEST_F(NetdBinderTest, BandwidthSetRemoveInterfaceAlert) { |
| long testAlertBytes = 373; |
| // Add test physical network |
| const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL, |
| INetd::PERMISSION_NONE, false, false); |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk()); |
| // Need to have a prior interface quota set to set an alert |
| binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes); |
| status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes); |
| |
| status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name()); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str()); |
| |
| // Remove interface quota |
| status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name()); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str()); |
| |
| // Remove test physical network |
| EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk()); |
| } |
| |
| TEST_F(NetdBinderTest, BandwidthSetGlobalAlert) { |
| int64_t testAlertBytes = 2097200; |
| |
| binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectBandwidthGlobalAlertRuleExists(testAlertBytes); |
| |
| testAlertBytes = 2098230; |
| status = mNetd->bandwidthSetGlobalAlert(testAlertBytes); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectBandwidthGlobalAlertRuleExists(testAlertBytes); |
| } |
| |
| TEST_F(NetdBinderTest, NetworkAddRemoveRouteUserPermission) { |
| static const struct { |
| const char* ipVersion; |
| const char* testDest; |
| const char* testNextHop; |
| const bool expectSuccess; |
| } kTestData[] = { |
| {IP_RULE_V4, "0.0.0.0/0", "", true}, |
| {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true}, |
| {IP_RULE_V4, "10.251.0.0/16", "", true}, |
| {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true}, |
| {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false}, |
| {IP_RULE_V6, "::/0", "", true}, |
| {IP_RULE_V6, "::/0", "2001:db8::", true}, |
| {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true}, |
| {IP_RULE_V4, "fe80::/64", "0.0.0.0", false}, |
| {IP_RULE_V4, "10.251.10.2/31", "throw", true}, |
| {IP_RULE_V4, "10.251.10.2/31", "unreachable", true}, |
| {IP_RULE_V4, "0.0.0.0/0", "throw", true}, |
| {IP_RULE_V4, "0.0.0.0/0", "unreachable", true}, |
| {IP_RULE_V6, "::/0", "throw", true}, |
| {IP_RULE_V6, "::/0", "unreachable", true}, |
| {IP_RULE_V6, "2001:db8:cafe::/64", "throw", true}, |
| {IP_RULE_V6, "2001:db8:cafe::/64", "unreachable", true}, |
| }; |
| |
| static const struct { |
| const char* ipVersion; |
| const char* testDest; |
| const char* testNextHop; |
| } kTestDataWithNextHop[] = { |
| {IP_RULE_V4, "10.251.10.0/30", ""}, |
| {IP_RULE_V6, "2001:db8::/32", ""}, |
| }; |
| |
| static const char testTableLegacySystem[] = "legacy_system"; |
| static const char testTableLegacyNetwork[] = "legacy_network"; |
| const int testUid = randomUid(); |
| const std::vector<int32_t> testUids = {testUid}; |
| |
| // Add test physical network |
| const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL, |
| INetd::PERMISSION_NONE, false, false); |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk()); |
| |
| // Setup route for testing nextHop |
| for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) { |
| const auto& td = kTestDataWithNextHop[i]; |
| |
| // All route for test tun will disappear once the tun interface is deleted. |
| binder::Status status = |
| mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| sTun.name().c_str()); |
| |
| // Add system permission for test uid, setup route in legacy system table. |
| EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk()); |
| |
| status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop, |
| testUid); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| testTableLegacySystem); |
| |
| // Remove system permission for test uid, setup route in legacy network table. |
| EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk()); |
| |
| status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop, |
| testUid); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| testTableLegacyNetwork); |
| } |
| |
| for (size_t i = 0; i < std::size(kTestData); i++) { |
| const auto& td = kTestData[i]; |
| |
| binder::Status status = |
| mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| sTun.name().c_str()); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| |
| status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| sTun.name().c_str()); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| |
| // Add system permission for test uid, route will be added into legacy system table. |
| EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk()); |
| |
| status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop, |
| testUid); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| testTableLegacySystem); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| |
| status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, |
| td.testNextHop, testUid); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| testTableLegacySystem); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| |
| // Remove system permission for test uid, route will be added into legacy network table. |
| EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk()); |
| |
| status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop, |
| testUid); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| testTableLegacyNetwork); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| |
| status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, |
| td.testNextHop, testUid); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| testTableLegacyNetwork); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| } |
| |
| /* |
| * Test networkUpdateRouteParcel behavior in case of route MTU change. |
| * |
| * Change of route MTU should be treated as an update of the route: |
| * - networkUpdateRouteParcel should succeed and update route MTU. |
| */ |
| for (size_t i = 0; i < std::size(kTestData); i++) { |
| const auto& td = kTestData[i]; |
| int mtu = (i % 2) ? 1480 : 1280; |
| |
| android::net::RouteInfoParcel parcel; |
| parcel.ifName = sTun.name(); |
| parcel.destination = td.testDest; |
| parcel.nextHop = td.testNextHop; |
| parcel.mtu = mtu; |
| binder::Status status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| std::to_string(parcel.mtu), sTun.name().c_str()); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| |
| parcel.mtu = 1337; |
| status = mNetd->networkUpdateRouteParcel(TEST_NETID1, parcel); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| std::to_string(parcel.mtu), sTun.name().c_str()); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| |
| status = mNetd->networkRemoveRouteParcel(TEST_NETID1, parcel); |
| if (td.expectSuccess) { |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| sTun.name().c_str()); |
| } else { |
| EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode()); |
| EXPECT_NE(0, status.serviceSpecificErrorCode()); |
| } |
| } |
| |
| /* |
| * Test network[Update|Add]RouteParcel behavior in case of route type change. |
| * |
| * Change of route type should be treated as an update of the route: |
| * - networkUpdateRouteParcel should succeed and update route type. |
| * - networkAddRouteParcel should silently fail, because the route already exists. Route type |
| * should not be changed in this case. |
| */ |
| for (size_t i = 0; i < std::size(kTestData); i++) { |
| const auto& td = kTestData[i]; |
| |
| if (!td.expectSuccess) { |
| continue; |
| } |
| |
| android::net::RouteInfoParcel parcel; |
| parcel.ifName = sTun.name(); |
| parcel.destination = td.testDest; |
| parcel.nextHop = td.testNextHop; |
| parcel.mtu = 1280; |
| binder::Status status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop, |
| std::to_string(parcel.mtu), sTun.name().c_str()); |
| |
| parcel.nextHop = parcel.nextHop == "throw" ? "unreachable" : "throw"; |
| const char* oldNextHop = td.testNextHop; |
| const char* newNextHop = parcel.nextHop.c_str(); |
| |
| // Trying to add same route with changed type, this should silently fail. |
| status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel); |
| // No error reported. |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| // Old route still exists. |
| expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, oldNextHop, |
| std::to_string(parcel.mtu), sTun.name().c_str()); |
| // New route was not actually added. |
| expectNetworkRouteDoesNotExistWithMtu(td.ipVersion, sTun.name(), td.testDest, newNextHop, |
| std::to_string(parcel.mtu), sTun.name().c_str()); |
| |
| // Update should succeed. |
| status = mNetd->networkUpdateRouteParcel(TEST_NETID1, parcel); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, newNextHop, |
| std::to_string(parcel.mtu), sTun.name().c_str()); |
| expectNetworkRouteDoesNotExistWithMtu(td.ipVersion, sTun.name(), td.testDest, oldNextHop, |
| std::to_string(parcel.mtu), sTun.name().c_str()); |
| |
| status = mNetd->networkRemoveRouteParcel(TEST_NETID1, parcel); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkRouteDoesNotExistWithMtu(td.ipVersion, sTun.name(), td.testDest, newNextHop, |
| std::to_string(parcel.mtu), sTun.name().c_str()); |
| } |
| |
| // Remove test physical network |
| EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk()); |
| } |
| |
| TEST_F(NetdBinderTest, NetworkPermissionDefault) { |
| // Add test physical network |
| const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL, |
| INetd::PERMISSION_NONE, false, false); |
| EXPECT_TRUE(mNetd->networkCreate(config).isOk()); |
| EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk()); |
| |
| // Get current default network NetId |
| binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork); |
| ASSERT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| // Test SetDefault |
| status = mNetd->networkSetDefault(TEST_NETID1); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkDefaultIpRuleExists(sTun.name().c_str()); |
| |
| status = mNetd->networkClearDefault(); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkDefaultIpRuleDoesNotExist(); |
| |
| // Set default network back |
| status = mNetd->networkSetDefault(mStoredDefaultNetwork); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| // Test SetPermission |
| status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM); |
| expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM); |
| |
| status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE); |
| expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE); |
| |
| // Remove test physical network |
| EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk()); |
| } |
| |
| TEST_F(NetdBinderTest, NetworkSetProtectAllowDeny) { |
| binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| bool ret = false; |
| status = mNetd->networkCanProtect(TEST_UID1, &ret); |
| EXPECT_TRUE(ret); |
| |
| status = mNetd->networkSetProtectDeny(TEST_UID1); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| // Clear uid permission before calling networkCanProtect to ensure |
| // the call won't be affected by uid permission. |
| EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk()); |
| |
| status = mNetd->networkCanProtect(TEST_UID1, &ret); |
| EXPECT_FALSE(ret); |
| } |
| |
| namespace { |
| |
| int readIntFromPath(const std::string& path) { |
| std::string result = ""; |
| EXPECT_TRUE(ReadFileToString(path, &result)); |
| return std::stoi(result); |
| } |
| |
| int getTetherAcceptIPv6Ra(const std::string& ifName) { |
| std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str()); |
| return readIntFromPath(path); |
| } |
| |
| bool getTetherAcceptIPv6Dad(const std::string& ifName) { |
| std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str()); |
| return readIntFromPath(path); |
| } |
| |
| int getTetherIPv6DadTransmits(const std::string& ifName) { |
| std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str()); |
| return readIntFromPath(path); |
| } |
| |
| bool getTetherEnableIPv6(const std::string& ifName) { |
| std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str()); |
| int disableIPv6 = readIntFromPath(path); |
| return !disableIPv6; |
| } |
| |
| bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) { |
| for (const auto& iface : ifList) { |
| if (iface == ifName) { |
| return true; |
| } |
| } |
| return false; |
| } |
| |
| void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) { |
| EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0); |
| EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName)); |
| EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0); |
| EXPECT_TRUE(getTetherEnableIPv6(ifName)); |
| } |
| |
| void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) { |
| EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2); |
| EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName)); |
| EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1); |
| EXPECT_FALSE(getTetherEnableIPv6(ifName)); |
| } |
| |
| void expectTetherInterfaceExists(const std::vector<std::string>& ifList, |
| const std::string& ifName) { |
| EXPECT_TRUE(interfaceListContains(ifList, ifName)); |
| } |
| |
| void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList, |
| const std::string& ifName) { |
| EXPECT_FALSE(interfaceListContains(ifList, ifName)); |
| } |
| |
| void expectTetherDnsListEquals(const std::vector<std::string>& dnsList, |
| const std::vector<std::string>& testDnsAddrs) { |
| EXPECT_TRUE(dnsList == testDnsAddrs); |
| } |
| |
| } // namespace |
| |
| TEST_F(NetdBinderTest, TetherStartStopStatus) { |
| std::vector<std::string> noDhcpRange = {}; |
| for (bool usingLegacyDnsProxy : {true, false}) { |
| android::net::TetherConfigParcel config; |
| config.usingLegacyDnsProxy = usingLegacyDnsProxy; |
| config.dhcpRanges = noDhcpRange; |
| binder::Status status = mNetd->tetherStartWithConfiguration(config); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy)); |
| if (usingLegacyDnsProxy == true) { |
| expectProcessExists(DNSMASQ); |
| } else { |
| expectProcessDoesNotExist(DNSMASQ); |
| } |
| |
| bool tetherEnabled; |
| status = mNetd->tetherIsEnabled(&tetherEnabled); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| EXPECT_TRUE(tetherEnabled); |
| |
| status = mNetd->tetherStop(); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectProcessDoesNotExist(DNSMASQ); |
| |
| status = mNetd->tetherIsEnabled(&tetherEnabled); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| EXPECT_FALSE(tetherEnabled); |
| } |
| } |
| |
| TEST_F(NetdBinderTest, TetherInterfaceAddRemoveList) { |
| // TODO: verify if dnsmasq update interface successfully |
| |
| binder::Status status = mNetd->tetherInterfaceAdd(sTun.name()); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectTetherInterfaceConfigureForIPv6Router(sTun.name()); |
| |
| std::vector<std::string> ifList; |
| status = mNetd->tetherInterfaceList(&ifList); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectTetherInterfaceExists(ifList, sTun.name()); |
| |
| status = mNetd->tetherInterfaceRemove(sTun.name()); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectTetherInterfaceConfigureForIPv6Client(sTun.name()); |
| |
| status = mNetd->tetherInterfaceList(&ifList); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectTetherInterfaceNotExists(ifList, sTun.name()); |
| |
| // Disable IPv6 tethering will disable IPv6 abilities by changing IPv6 settings(accept_ra, |
| // dad_transmits, accept_dad, disable_ipv6). See tetherInterfaceRemove in details. |
| // Re-init sTun to reset the interface to prevent affecting other test that requires IPv6 with |
| // the same interface. |
| sTun.destroy(); |
| sTun.init(); |
| } |
| |
| TEST_F(NetdBinderTest, TetherDnsSetList) { |
| // TODO: verify if dnsmasq update dns successfully |
| std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3", |
| "fe80::1%" + sTun.name()}; |
| |
| binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| |
| std::vector<std::string> dnsList; |
| status = mNetd->tetherDnsList(&dnsList); |
| EXPECT_TRUE(status.isOk()) << status.exceptionMessage(); |
| expectTetherDnsListEquals(dnsList, testDnsAddrs); |
| } |
| |
| namespace { |
| |
| std::vector<IPAddress> findDnsSockets(SockDiag* sd, unsigned numExpected) { |
| std::vector<IPAddress> listenAddrs; |
| |
| // Callback lambda that finds all IPv4 sockets with source port 53. |
| auto findDnsSockets = [&](uint8_t /* proto */, const inet_diag_msg* msg) { |
| // Always return false, which means do not destroy this socket. |
| if (msg->id.idiag_sport != htons(53)) return false; |
| IPAddress addr(*(in_addr*)msg->id.idiag_src); |
| listenAddrs.push_back(addr); |
| return false; |
| }; |
| |
| // There is no way to know if dnsmasq has finished processing the update_interfaces command and |
| // opened listening sockets. So, just spin a few times and return the first list of sockets |
| // that is at least numExpected long. |
| // Pick a relatively large timeout to avoid flaky tests, particularly when running on shared |
| // devices. |
| constexpr int kMaxAttempts = 50; |
| constexpr int kSleepMs = 100; |
| for (int i = 0; i < kMaxAttempts; i++) { |
| listenAddrs.clear(); |
| EXPECT_EQ(0, sd->sendDumpRequest(IPPROTO_TCP, AF_INET, 1 << TCP_LISTEN)) |
| << "Failed to dump sockets, attempt " << i << " of " << kMaxAttempts; |
| sd->readDiagMsg(IPPROTO_TCP, findDnsSockets); |
| if (listenAddrs.size() >= numExpected) { |
| break; |
| } |
| usleep(kSleepMs * 1000); |
| } |
| |
| return listenAddrs; |
| } |
| |
| } // namespace |
| |
| // Checks that when starting dnsmasq on an interface that no longer exists, it doesn't attempt to |
| // start on other interfaces instead. |
| TEST_F(NetdBinderTest, TetherDeletedInterface) { |
| // Do this first so we don't need to clean up anything else if it fails. |
| SockDiag sd; |
| ASSERT_TRUE(sd.open()) << "Failed to open SOCK_DIAG socket"; |
| |
| // Create our own TunInterfaces (so we can delete them without affecting other tests), and add |
| // IP addresses to them. They must be IPv4 because t
|