Home | History | Annotate | Download | only in tests
      1 /*
      2  * Copyright 2016 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  *
     16  * binder_test.cpp - unit tests for netd binder RPCs.
     17  */
     18 
     19 #include <cerrno>
     20 #include <cinttypes>
     21 #include <cstdint>
     22 #include <cstdio>
     23 #include <cstdlib>
     24 #include <set>
     25 #include <vector>
     26 
     27 #include <fcntl.h>
     28 #include <ifaddrs.h>
     29 #include <netdb.h>
     30 #include <sys/socket.h>
     31 #include <sys/types.h>
     32 #include <netinet/in.h>
     33 #include <linux/if.h>
     34 #include <linux/if_tun.h>
     35 #include <openssl/base64.h>
     36 
     37 #include <android-base/macros.h>
     38 #include <android-base/stringprintf.h>
     39 #include <android-base/strings.h>
     40 #include <bpf/BpfUtils.h>
     41 #include <cutils/multiuser.h>
     42 #include <gtest/gtest.h>
     43 #include <logwrap/logwrap.h>
     44 #include <netutils/ifc.h>
     45 
     46 #include "InterfaceController.h"
     47 #include "NetdConstants.h"
     48 #include "Stopwatch.h"
     49 #include "XfrmController.h"
     50 #include "tun_interface.h"
     51 #include "android/net/INetd.h"
     52 #include "android/net/UidRange.h"
     53 #include "binder/IServiceManager.h"
     54 #include "netdutils/Syscalls.h"
     55 
     56 #define IP_PATH "/system/bin/ip"
     57 #define IP6TABLES_PATH "/system/bin/ip6tables"
     58 #define IPTABLES_PATH "/system/bin/iptables"
     59 #define TUN_DEV "/dev/tun"
     60 
     61 using namespace android;
     62 using namespace android::base;
     63 using namespace android::binder;
     64 using android::base::StartsWith;
     65 using android::bpf::hasBpfSupport;
     66 using android::net::INetd;
     67 using android::net::TunInterface;
     68 using android::net::UidRange;
     69 using android::net::XfrmController;
     70 using android::netdutils::sSyscalls;
     71 using android::os::PersistableBundle;
     72 
     73 #define SKIP_IF_BPF_SUPPORTED         \
     74     do {                              \
     75         if (hasBpfSupport()) return;  \
     76     } while (0);
     77 
     78 static const char* IP_RULE_V4 = "-4";
     79 static const char* IP_RULE_V6 = "-6";
     80 static const int TEST_NETID1 = 65501;
     81 static const int TEST_NETID2 = 65502;
     82 constexpr int BASE_UID = AID_USER_OFFSET * 5;
     83 
     84 static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
     85 static const std::string ESP_ALLOW_RULE("esp");
     86 
     87 class BinderTest : public ::testing::Test {
     88 
     89 public:
     90     BinderTest() {
     91         sp<IServiceManager> sm = defaultServiceManager();
     92         sp<IBinder> binder = sm->getService(String16("netd"));
     93         if (binder != nullptr) {
     94             mNetd = interface_cast<INetd>(binder);
     95         }
     96     }
     97 
     98     void SetUp() override {
     99         ASSERT_NE(nullptr, mNetd.get());
    100     }
    101 
    102     void TearDown() override {
    103         mNetd->networkDestroy(TEST_NETID1);
    104         mNetd->networkDestroy(TEST_NETID2);
    105     }
    106 
    107     bool allocateIpSecResources(bool expectOk, int32_t *spi);
    108 
    109     // Static because setting up the tun interface takes about 40ms.
    110     static void SetUpTestCase() {
    111         ASSERT_EQ(0, sTun.init());
    112         ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
    113     }
    114 
    115     static void TearDownTestCase() {
    116         // Closing the socket removes the interface and IP addresses.
    117         sTun.destroy();
    118     }
    119 
    120     static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
    121 
    122 protected:
    123     sp<INetd> mNetd;
    124     static TunInterface sTun;
    125 };
    126 
    127 TunInterface BinderTest::sTun;
    128 
    129 class TimedOperation : public Stopwatch {
    130 public:
    131     explicit TimedOperation(const std::string &name): mName(name) {}
    132     virtual ~TimedOperation() {
    133         fprintf(stderr, "    %s: %6.1f ms\n", mName.c_str(), timeTaken());
    134     }
    135 
    136 private:
    137     std::string mName;
    138 };
    139 
    140 TEST_F(BinderTest, TestIsAlive) {
    141     TimedOperation t("isAlive RPC");
    142     bool isAlive = false;
    143     mNetd->isAlive(&isAlive);
    144     ASSERT_TRUE(isAlive);
    145 }
    146 
    147 static int randomUid() {
    148     return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
    149 }
    150 
    151 static std::vector<std::string> runCommand(const std::string& command) {
    152     std::vector<std::string> lines;
    153     FILE *f;
    154 
    155     if ((f = popen(command.c_str(), "r")) == nullptr) {
    156         perror("popen");
    157         return lines;
    158     }
    159 
    160     char *line = nullptr;
    161     size_t bufsize = 0;
    162     ssize_t linelen = 0;
    163     while ((linelen = getline(&line, &bufsize, f)) >= 0) {
    164         lines.push_back(std::string(line, linelen));
    165         free(line);
    166         line = nullptr;
    167     }
    168 
    169     pclose(f);
    170     return lines;
    171 }
    172 
    173 static std::vector<std::string> listIpRules(const char *ipVersion) {
    174     std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
    175     return runCommand(command);
    176 }
    177 
    178 static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
    179     std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
    180     return runCommand(command);
    181 }
    182 
    183 static int iptablesRuleLineLength(const char *binary, const char *chainName) {
    184     return listIptablesRule(binary, chainName).size();
    185 }
    186 
    187 static bool iptablesRuleExists(const char *binary,
    188                                const char *chainName,
    189                                const std::string expectedRule) {
    190     std::vector<std::string> rules = listIptablesRule(binary, chainName);
    191     for(std::string &rule: rules) {
    192         if(rule.find(expectedRule) != std::string::npos) {
    193             return true;
    194         }
    195     }
    196     return false;
    197 }
    198 
    199 static bool iptablesNoSocketAllowRuleExists(const char *chainName){
    200     return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
    201            iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
    202 }
    203 
    204 static bool iptablesEspAllowRuleExists(const char *chainName){
    205     return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
    206            iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
    207 }
    208 
    209 TEST_F(BinderTest, TestFirewallReplaceUidChain) {
    210     SKIP_IF_BPF_SUPPORTED;
    211 
    212     std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
    213     const int kNumUids = 500;
    214     std::vector<int32_t> noUids(0);
    215     std::vector<int32_t> uids(kNumUids);
    216     for (int i = 0; i < kNumUids; i++) {
    217         uids[i] = randomUid();
    218     }
    219 
    220     bool ret;
    221     {
    222         TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
    223         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), true, uids, &ret);
    224     }
    225     EXPECT_EQ(true, ret);
    226     EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    227     EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    228     EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
    229     EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
    230     {
    231         TimedOperation op("Clearing whitelist chain");
    232         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
    233     }
    234     EXPECT_EQ(true, ret);
    235     EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    236     EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    237 
    238     {
    239         TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
    240         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, uids, &ret);
    241     }
    242     EXPECT_EQ(true, ret);
    243     EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    244     EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    245     EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
    246     EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
    247 
    248     {
    249         TimedOperation op("Clearing blacklist chain");
    250         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
    251     }
    252     EXPECT_EQ(true, ret);
    253     EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    254     EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    255 
    256     // Check that the call fails if iptables returns an error.
    257     std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
    258     mNetd->firewallReplaceUidChain(String16(veryLongStringName.c_str()), true, noUids, &ret);
    259     EXPECT_EQ(false, ret);
    260 }
    261 
    262 TEST_F(BinderTest, TestVirtualTunnelInterface) {
    263     static const struct TestData {
    264         const std::string& family;
    265         const std::string& deviceName;
    266         const std::string& localAddress;
    267         const std::string& remoteAddress;
    268         int32_t iKey;
    269         int32_t oKey;
    270     } kTestData[] = {
    271         {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
    272         {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
    273     };
    274 
    275     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    276         const auto& td = kTestData[i];
    277 
    278         binder::Status status;
    279 
    280         // Create Virtual Tunnel Interface.
    281         status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
    282                                                   td.iKey, td.oKey);
    283         EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
    284 
    285         // Update Virtual Tunnel Interface.
    286         status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
    287                                                      td.remoteAddress, td.iKey, td.oKey);
    288         EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
    289 
    290         // Remove Virtual Tunnel Interface.
    291         status = mNetd->removeVirtualTunnelInterface(td.deviceName);
    292         EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
    293     }
    294 }
    295 
    296 // IPsec tests are not run in 32 bit mode; both 32-bit kernels and
    297 // mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
    298 #if INTPTR_MAX != INT32_MAX
    299 #define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
    300         do { if ((_expect_) != (_ret_)) return false; } while(false)
    301 bool BinderTest::allocateIpSecResources(bool expectOk, int32_t *spi) {
    302     netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
    303     SCOPED_TRACE(status);
    304     RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
    305 
    306     // Add a policy
    307     status = XfrmController::ipSecAddSecurityPolicy(0, 0, "::", "::1", 123, 0, 0);
    308     SCOPED_TRACE(status);
    309     RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
    310 
    311     // Add an ipsec interface
    312     status = netdutils::statusFromErrno(
    313             XfrmController::addVirtualTunnelInterface(
    314                     "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
    315             "addVirtualTunnelInterface");
    316     return (status.ok() == expectOk);
    317 }
    318 
    319 TEST_F(BinderTest, TestXfrmControllerInit) {
    320     netdutils::Status status;
    321     status = XfrmController::Init();
    322     SCOPED_TRACE(status);
    323 
    324     // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
    325     // feature.
    326     if (status.code() == EOPNOTSUPP) return;
    327 
    328     ASSERT_TRUE(status.ok());
    329 
    330     int32_t spi = 0;
    331 
    332     ASSERT_TRUE(allocateIpSecResources(true, &spi));
    333     ASSERT_TRUE(allocateIpSecResources(false, &spi));
    334 
    335     status = XfrmController::Init();
    336     ASSERT_TRUE(status.ok());
    337     ASSERT_TRUE(allocateIpSecResources(true, &spi));
    338 
    339     // Clean up
    340     status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
    341     SCOPED_TRACE(status);
    342     ASSERT_TRUE(status.ok());
    343 
    344     status = XfrmController::ipSecDeleteSecurityPolicy(0, 0, "::", "::1", 0, 0);
    345     SCOPED_TRACE(status);
    346     ASSERT_TRUE(status.ok());
    347 
    348     // Remove Virtual Tunnel Interface.
    349     status = netdutils::statusFromErrno(
    350             XfrmController::removeVirtualTunnelInterface("ipsec_test"),
    351             "removeVirtualTunnelInterface");
    352 
    353     ASSERT_TRUE(status.ok());
    354 }
    355 #endif
    356 
    357 static int bandwidthDataSaverEnabled(const char *binary) {
    358     std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
    359 
    360     // Output looks like this:
    361     //
    362     // Chain bw_data_saver (1 references)
    363     // target     prot opt source               destination
    364     // RETURN     all  --  0.0.0.0/0            0.0.0.0/0
    365     //
    366     // or:
    367     //
    368     // Chain bw_data_saver (1 references)
    369     // target     prot opt source               destination
    370     // ... possibly connectivity critical packet rules here ...
    371     // REJECT     all  --  ::/0            ::/0
    372 
    373     EXPECT_GE(lines.size(), 3U);
    374 
    375     if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
    376         // Data saver disabled.
    377         return 0;
    378     }
    379 
    380     size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
    381 
    382     if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
    383         // Data saver enabled.
    384         return 1;
    385     }
    386 
    387     return -1;
    388 }
    389 
    390 bool enableDataSaver(sp<INetd>& netd, bool enable) {
    391     TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
    392     bool ret;
    393     netd->bandwidthEnableDataSaver(enable, &ret);
    394     return ret;
    395 }
    396 
    397 int getDataSaverState() {
    398     const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
    399     const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
    400     EXPECT_EQ(enabled4, enabled6);
    401     EXPECT_NE(-1, enabled4);
    402     EXPECT_NE(-1, enabled6);
    403     if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
    404         return -1;
    405     }
    406     return enabled6;
    407 }
    408 
    409 TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
    410     const int wasEnabled = getDataSaverState();
    411     ASSERT_NE(-1, wasEnabled);
    412 
    413     if (wasEnabled) {
    414         ASSERT_TRUE(enableDataSaver(mNetd, false));
    415         EXPECT_EQ(0, getDataSaverState());
    416     }
    417 
    418     ASSERT_TRUE(enableDataSaver(mNetd, false));
    419     EXPECT_EQ(0, getDataSaverState());
    420 
    421     ASSERT_TRUE(enableDataSaver(mNetd, true));
    422     EXPECT_EQ(1, getDataSaverState());
    423 
    424     ASSERT_TRUE(enableDataSaver(mNetd, true));
    425     EXPECT_EQ(1, getDataSaverState());
    426 
    427     if (!wasEnabled) {
    428         ASSERT_TRUE(enableDataSaver(mNetd, false));
    429         EXPECT_EQ(0, getDataSaverState());
    430     }
    431 }
    432 
    433 static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
    434         const std::string& action, const char* ipVersion) {
    435     // Output looks like this:
    436     //   "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
    437     std::vector<std::string> rules = listIpRules(ipVersion);
    438 
    439     std::string prefix = StringPrintf("%" PRIu32 ":", priority);
    440     std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
    441             range.getStart(), range.getStop(), action.c_str());
    442     for (std::string line : rules) {
    443         if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
    444             return true;
    445         }
    446     }
    447     return false;
    448 }
    449 
    450 static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
    451         const std::string& action) {
    452     bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
    453     bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
    454     EXPECT_EQ(existsIp4, existsIp6);
    455     return existsIp4;
    456 }
    457 
    458 TEST_F(BinderTest, TestNetworkInterfaces) {
    459     EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
    460     EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, "").serviceSpecificErrorCode());
    461     EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
    462     EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
    463 
    464     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
    465     EXPECT_EQ(EBUSY,
    466               mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
    467 
    468     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
    469     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
    470     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
    471 }
    472 
    473 TEST_F(BinderTest, TestNetworkUidRules) {
    474     const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
    475 
    476     EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
    477     EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
    478     EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
    479 
    480     std::vector<UidRange> uidRanges = {
    481         {BASE_UID + 8005, BASE_UID + 8012},
    482         {BASE_UID + 8090, BASE_UID + 8099}
    483     };
    484     UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
    485     std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
    486 
    487     EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
    488 
    489     EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
    490     EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
    491     EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
    492     EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
    493 
    494     EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
    495     EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
    496     EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
    497     EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
    498 
    499     EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
    500 }
    501 
    502 TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
    503     constexpr uint32_t RULE_PRIORITY = 12500;
    504 
    505     std::vector<UidRange> uidRanges = {
    506         {BASE_UID + 150, BASE_UID + 224},
    507         {BASE_UID + 226, BASE_UID + 300}
    508     };
    509 
    510     const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
    511     const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
    512 
    513     // Create two valid rules.
    514     ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
    515     EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
    516     EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
    517     for (auto const& range : uidRanges) {
    518         EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
    519     }
    520 
    521     // Remove the rules.
    522     ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
    523     EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
    524     EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
    525     for (auto const& range : uidRanges) {
    526         EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
    527     }
    528 
    529     // Fail to remove the rules a second time after they are already deleted.
    530     binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
    531     ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    532     EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
    533 
    534     // All rules should be the same as before.
    535     EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
    536     EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
    537 }
    538 
    539 // Create a socket pair that isLoopbackSocket won't think is local.
    540 void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
    541     *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
    542     struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
    543     ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
    544 
    545     socklen_t addrlen = sizeof(server6);
    546     ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
    547     ASSERT_EQ(0, listen(*serverSocket, 10));
    548 
    549     *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
    550     struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
    551     ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
    552     ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
    553     ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
    554 
    555     *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
    556     ASSERT_NE(-1, *acceptedSocket);
    557 
    558     ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
    559 }
    560 
    561 void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
    562     char buf[4096];
    563     EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
    564     EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
    565     EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
    566 }
    567 
    568 void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
    569     // Check that the client socket was closed with ECONNABORTED.
    570     int ret = write(clientSocket, "foo", sizeof("foo"));
    571     int err = errno;
    572     EXPECT_EQ(-1, ret);
    573     EXPECT_EQ(ECONNABORTED, err);
    574 
    575     // Check that it sent a RST to the server.
    576     ret = write(acceptedSocket, "foo", sizeof("foo"));
    577     err = errno;
    578     EXPECT_EQ(-1, ret);
    579     EXPECT_EQ(ECONNRESET, err);
    580 }
    581 
    582 TEST_F(BinderTest, TestSocketDestroy) {
    583     int clientSocket, serverSocket, acceptedSocket;
    584     ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
    585 
    586     // Pick a random UID in the system UID range.
    587     constexpr int baseUid = AID_APP - 2000;
    588     static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
    589     int uid = baseUid + 500 + arc4random_uniform(1000);
    590     EXPECT_EQ(0, fchown(clientSocket, uid, -1));
    591 
    592     // UID ranges that don't contain uid.
    593     std::vector<UidRange> uidRanges = {
    594         {baseUid + 42, baseUid + 449},
    595         {baseUid + 1536, AID_APP - 4},
    596         {baseUid + 498, uid - 1},
    597         {uid + 1, baseUid + 1520},
    598     };
    599     // A skip list that doesn't contain UID.
    600     std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
    601 
    602     // Close sockets. Our test socket should be intact.
    603     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    604     checkSocketpairOpen(clientSocket, acceptedSocket);
    605 
    606     // UID ranges that do contain uid.
    607     uidRanges = {
    608         {baseUid + 42, baseUid + 449},
    609         {baseUid + 1536, AID_APP - 4},
    610         {baseUid + 498, baseUid + 1520},
    611     };
    612     // Add uid to the skip list.
    613     skipUids.push_back(uid);
    614 
    615     // Close sockets. Our test socket should still be intact because it's in the skip list.
    616     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    617     checkSocketpairOpen(clientSocket, acceptedSocket);
    618 
    619     // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
    620     skipUids.resize(skipUids.size() - 1);
    621     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    622     checkSocketpairClosed(clientSocket, acceptedSocket);
    623 
    624     close(clientSocket);
    625     close(serverSocket);
    626     close(acceptedSocket);
    627 }
    628 
    629 namespace {
    630 
    631 int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
    632     if (buf == nullptr) return -1;
    633 
    634     int prefixLength = 0;
    635     bool endOfContiguousBits = false;
    636     for (unsigned int i = 0; i < buflen; i++) {
    637         const uint8_t value = buf[i];
    638 
    639         // Bad bit sequence: check for a contiguous set of bits from the high
    640         // end by verifying that the inverted value + 1 is a power of 2
    641         // (power of 2 iff. (v & (v - 1)) == 0).
    642         const uint8_t inverse = ~value + 1;
    643         if ((inverse & (inverse - 1)) != 0) return -1;
    644 
    645         prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
    646 
    647         // Bogus netmask.
    648         if (endOfContiguousBits && value != 0) return -1;
    649 
    650         if (value != 0xff) endOfContiguousBits = true;
    651     }
    652 
    653     return prefixLength;
    654 }
    655 
    656 template<typename T>
    657 int netmaskToPrefixLength(const T *p) {
    658     return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
    659 }
    660 
    661 
    662 static bool interfaceHasAddress(
    663         const std::string &ifname, const char *addrString, int prefixLength) {
    664     struct addrinfo *addrinfoList = nullptr;
    665     ScopedAddrinfo addrinfoCleanup(addrinfoList);
    666 
    667     const struct addrinfo hints = {
    668         .ai_flags    = AI_NUMERICHOST,
    669         .ai_family   = AF_UNSPEC,
    670         .ai_socktype = SOCK_DGRAM,
    671     };
    672     if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
    673         addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
    674         return false;
    675     }
    676 
    677     struct ifaddrs *ifaddrsList = nullptr;
    678     ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
    679 
    680     if (getifaddrs(&ifaddrsList) != 0) {
    681         return false;
    682     }
    683 
    684     for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
    685         if (std::string(addr->ifa_name) != ifname ||
    686             addr->ifa_addr == nullptr ||
    687             addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
    688             continue;
    689         }
    690 
    691         switch (addr->ifa_addr->sa_family) {
    692         case AF_INET: {
    693             auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
    694             auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
    695             if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
    696                 continue;
    697             }
    698 
    699             if (prefixLength < 0) return true;  // not checking prefix lengths
    700 
    701             if (addr->ifa_netmask == nullptr) return false;
    702             auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
    703             EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
    704             return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
    705         }
    706         case AF_INET6: {
    707             auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
    708             auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
    709             if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
    710                 continue;
    711             }
    712 
    713             if (prefixLength < 0) return true;  // not checking prefix lengths
    714 
    715             if (addr->ifa_netmask == nullptr) return false;
    716             auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
    717             EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
    718             return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
    719         }
    720         default:
    721             // Cannot happen because we have already screened for matching
    722             // address families at the top of each iteration.
    723             continue;
    724         }
    725     }
    726 
    727     return false;
    728 }
    729 
    730 }  // namespace
    731 
    732 TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
    733     static const struct TestData {
    734         const char *addrString;
    735         const int   prefixLength;
    736         const bool  expectSuccess;
    737     } kTestData[] = {
    738         { "192.0.2.1", 24, true },
    739         { "192.0.2.2", 25, true },
    740         { "192.0.2.3", 32, true },
    741         { "192.0.2.4", 33, false },
    742         { "192.not.an.ip", 24, false },
    743         { "2001:db8::1", 64, true },
    744         { "2001:db8::2", 65, true },
    745         { "2001:db8::3", 128, true },
    746         { "2001:db8::4", 129, false },
    747         { "foo:bar::bad", 64, false },
    748     };
    749 
    750     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    751         const auto &td = kTestData[i];
    752 
    753         // [1.a] Add the address.
    754         binder::Status status = mNetd->interfaceAddAddress(
    755                 sTun.name(), td.addrString, td.prefixLength);
    756         if (td.expectSuccess) {
    757             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
    758         } else {
    759             ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    760             ASSERT_NE(0, status.serviceSpecificErrorCode());
    761         }
    762 
    763         // [1.b] Verify the addition meets the expectation.
    764         if (td.expectSuccess) {
    765             EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
    766         } else {
    767             EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
    768         }
    769 
    770         // [2.a] Try to remove the address.  If it was not previously added, removing it fails.
    771         status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
    772         if (td.expectSuccess) {
    773             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
    774         } else {
    775             ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    776             ASSERT_NE(0, status.serviceSpecificErrorCode());
    777         }
    778 
    779         // [2.b] No matter what, the address should not be present.
    780         EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
    781     }
    782 }
    783 
    784 TEST_F(BinderTest, TestSetProcSysNet) {
    785     static const struct TestData {
    786         const int family;
    787         const int which;
    788         const char *ifname;
    789         const char *parameter;
    790         const char *value;
    791         const int expectedReturnCode;
    792     } kTestData[] = {
    793         { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
    794         { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
    795         { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
    796         { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
    797         { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
    798         { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
    799         { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
    800     };
    801 
    802     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    803         const auto &td = kTestData[i];
    804 
    805         const binder::Status status = mNetd->setProcSysNet(
    806                     td.family, td.which, td.ifname, td.parameter,
    807                     td.value);
    808 
    809         if (td.expectedReturnCode == 0) {
    810             SCOPED_TRACE(String8::format("test case %d should have passed", i));
    811             EXPECT_EQ(0, status.exceptionCode());
    812             EXPECT_EQ(0, status.serviceSpecificErrorCode());
    813         } else {
    814             SCOPED_TRACE(String8::format("test case %d should have failed", i));
    815             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    816             EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
    817         }
    818     }
    819 }
    820 
    821 static std::string base64Encode(const std::vector<uint8_t>& input) {
    822     size_t out_len;
    823     EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
    824     // out_len includes the trailing NULL.
    825     uint8_t output_bytes[out_len];
    826     EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
    827     return std::string(reinterpret_cast<char*>(output_bytes));
    828 }
    829 
    830 TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
    831     const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
    832     std::vector<uint8_t> fp(SHA256_SIZE);
    833     std::vector<uint8_t> short_fp(1);
    834     std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
    835     std::vector<std::string> test_domains;
    836     std::vector<int> test_params = { 300, 25, 8, 8 };
    837     unsigned test_netid = 0;
    838     static const struct TestData {
    839         const std::vector<std::string> servers;
    840         const std::string tlsName;
    841         const std::vector<std::vector<uint8_t>> tlsFingerprints;
    842         const int expectedReturnCode;
    843     } kTlsTestData[] = {
    844         { {"192.0.2.1"}, "", {}, 0 },
    845         { {"2001:db8::2"}, "host.name", {}, 0 },
    846         { {"192.0.2.3"}, "@@@@", { fp }, 0 },
    847         { {"2001:db8::4"}, "", { fp }, 0 },
    848         { {}, "", {}, 0 },
    849         { {""}, "", {}, EINVAL },
    850         { {"192.0.*.5"}, "", {}, EINVAL },
    851         { {"2001:dg8::6"}, "", {}, EINVAL },
    852         { {"2001:db8::c"}, "", { short_fp }, EINVAL },
    853         { {"192.0.2.12"}, "", { long_fp }, EINVAL },
    854         { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
    855         { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
    856     };
    857 
    858     for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
    859         const auto &td = kTlsTestData[i];
    860 
    861         std::vector<std::string> fingerprints;
    862         for (const auto& fingerprint : td.tlsFingerprints) {
    863             fingerprints.push_back(base64Encode(fingerprint));
    864         }
    865         binder::Status status = mNetd->setResolverConfiguration(
    866                 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
    867                 td.tlsName, td.servers, fingerprints);
    868 
    869         if (td.expectedReturnCode == 0) {
    870             SCOPED_TRACE(String8::format("test case %d should have passed", i));
    871             SCOPED_TRACE(status.toString8());
    872             EXPECT_EQ(0, status.exceptionCode());
    873         } else {
    874             SCOPED_TRACE(String8::format("test case %d should have failed", i));
    875             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    876             EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
    877         }
    878     }
    879     // Ensure TLS is disabled before the start of the next test.
    880     mNetd->setResolverConfiguration(
    881         test_netid, kTlsTestData[0].servers, test_domains, test_params,
    882         "", {}, {});
    883 }
    884 
    885 void expectNoTestCounterRules() {
    886     for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
    887         std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
    888         std::string allRules = Join(runCommand(command), "\n");
    889         EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
    890     }
    891 }
    892 
    893 void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
    894     runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
    895                             path, if1.c_str(), if2.c_str(), pkt, byte));
    896 }
    897 
    898 void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
    899     runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
    900                             path, if1.c_str(), if2.c_str()));
    901     runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
    902                             path, if2.c_str(), if1.c_str()));
    903 }
    904 
    905 TEST_F(BinderTest, TestTetherGetStats) {
    906     expectNoTestCounterRules();
    907 
    908     // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
    909     // disabling tethering. We don't check the return value because these commands will fail if
    910     // tethering is already enabled.
    911     runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
    912     runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
    913 
    914     std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
    915     std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
    916     std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
    917     std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
    918     std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
    919 
    920     addTetherCounterValues(IPTABLES_PATH,  intIface1, extIface1, 123, 111);
    921     addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456,  10);
    922     addTetherCounterValues(IPTABLES_PATH,  extIface1, intIface1, 321, 222);
    923     addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654,  20);
    924     // RX is from external to internal, and TX is from internal to external.
    925     // So rxBytes is 321 + 654  = 975, txBytes is 123 + 456 = 579, etc.
    926     std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
    927 
    928     addTetherCounterValues(IPTABLES_PATH,  intIface2, extIface2, 1000, 333);
    929     addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000,  30);
    930 
    931     addTetherCounterValues(IPTABLES_PATH,  extIface2, intIface2, 2000, 444);
    932     addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000,  40);
    933 
    934     addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000,  25);
    935     addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000,  35);
    936     std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
    937 
    938     PersistableBundle stats;
    939     binder::Status status = mNetd->tetherGetStats(&stats);
    940     EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
    941 
    942     std::vector<int64_t> actual1;
    943     EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
    944     EXPECT_EQ(expected1, actual1);
    945 
    946     std::vector<int64_t> actual2;
    947     EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
    948     EXPECT_EQ(expected2, actual2);
    949 
    950     for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
    951         delTetherCounterValues(path, intIface1, extIface1);
    952         delTetherCounterValues(path, intIface2, extIface2);
    953         if (path == IP6TABLES_PATH) {
    954             delTetherCounterValues(path, intIface3, extIface2);
    955         }
    956     }
    957 
    958     expectNoTestCounterRules();
    959 }
    960