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 <cutils/multiuser.h>
     41 #include <gtest/gtest.h>
     42 #include <logwrap/logwrap.h>
     43 #include <netutils/ifc.h>
     44 
     45 #include "NetdConstants.h"
     46 #include "Stopwatch.h"
     47 #include "tun_interface.h"
     48 #include "android/net/INetd.h"
     49 #include "android/net/UidRange.h"
     50 #include "binder/IServiceManager.h"
     51 
     52 #define IP_PATH "/system/bin/ip"
     53 #define IP6TABLES_PATH "/system/bin/ip6tables"
     54 #define IPTABLES_PATH "/system/bin/iptables"
     55 #define TUN_DEV "/dev/tun"
     56 
     57 using namespace android;
     58 using namespace android::base;
     59 using namespace android::binder;
     60 using android::base::StartsWith;
     61 using android::net::INetd;
     62 using android::net::TunInterface;
     63 using android::net::UidRange;
     64 
     65 static const char* IP_RULE_V4 = "-4";
     66 static const char* IP_RULE_V6 = "-6";
     67 
     68 class BinderTest : public ::testing::Test {
     69 
     70 public:
     71     BinderTest() {
     72         sp<IServiceManager> sm = defaultServiceManager();
     73         sp<IBinder> binder = sm->getService(String16("netd"));
     74         if (binder != nullptr) {
     75             mNetd = interface_cast<INetd>(binder);
     76         }
     77     }
     78 
     79     void SetUp() override {
     80         ASSERT_NE(nullptr, mNetd.get());
     81     }
     82 
     83     // Static because setting up the tun interface takes about 40ms.
     84     static void SetUpTestCase() {
     85         ASSERT_EQ(0, sTun.init());
     86         ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
     87     }
     88 
     89     static void TearDownTestCase() {
     90         // Closing the socket removes the interface and IP addresses.
     91         sTun.destroy();
     92     }
     93 
     94     static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
     95 
     96 protected:
     97     sp<INetd> mNetd;
     98     static TunInterface sTun;
     99 };
    100 
    101 TunInterface BinderTest::sTun;
    102 
    103 class TimedOperation : public Stopwatch {
    104 public:
    105     explicit TimedOperation(const std::string &name): mName(name) {}
    106     virtual ~TimedOperation() {
    107         fprintf(stderr, "    %s: %6.1f ms\n", mName.c_str(), timeTaken());
    108     }
    109 
    110 private:
    111     std::string mName;
    112 };
    113 
    114 TEST_F(BinderTest, TestIsAlive) {
    115     TimedOperation t("isAlive RPC");
    116     bool isAlive = false;
    117     mNetd->isAlive(&isAlive);
    118     ASSERT_TRUE(isAlive);
    119 }
    120 
    121 static int randomUid() {
    122     return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
    123 }
    124 
    125 static std::vector<std::string> runCommand(const std::string& command) {
    126     std::vector<std::string> lines;
    127     FILE *f;
    128 
    129     if ((f = popen(command.c_str(), "r")) == nullptr) {
    130         perror("popen");
    131         return lines;
    132     }
    133 
    134     char *line = nullptr;
    135     size_t bufsize = 0;
    136     ssize_t linelen = 0;
    137     while ((linelen = getline(&line, &bufsize, f)) >= 0) {
    138         lines.push_back(std::string(line, linelen));
    139         free(line);
    140         line = nullptr;
    141     }
    142 
    143     pclose(f);
    144     return lines;
    145 }
    146 
    147 static std::vector<std::string> listIpRules(const char *ipVersion) {
    148     std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
    149     return runCommand(command);
    150 }
    151 
    152 static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
    153     std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
    154     return runCommand(command);
    155 }
    156 
    157 static int iptablesRuleLineLength(const char *binary, const char *chainName) {
    158     return listIptablesRule(binary, chainName).size();
    159 }
    160 
    161 TEST_F(BinderTest, TestFirewallReplaceUidChain) {
    162     std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
    163     const int kNumUids = 500;
    164     std::vector<int32_t> noUids(0);
    165     std::vector<int32_t> uids(kNumUids);
    166     for (int i = 0; i < kNumUids; i++) {
    167         uids[i] = randomUid();
    168     }
    169 
    170     bool ret;
    171     {
    172         TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
    173         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), true, uids, &ret);
    174     }
    175     EXPECT_EQ(true, ret);
    176     EXPECT_EQ((int) uids.size() + 7, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    177     EXPECT_EQ((int) uids.size() + 13, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    178     {
    179         TimedOperation op("Clearing whitelist chain");
    180         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
    181     }
    182     EXPECT_EQ(true, ret);
    183     EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    184     EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    185 
    186     {
    187         TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
    188         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, uids, &ret);
    189     }
    190     EXPECT_EQ(true, ret);
    191     EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    192     EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    193 
    194     {
    195         TimedOperation op("Clearing blacklist chain");
    196         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
    197     }
    198     EXPECT_EQ(true, ret);
    199     EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    200     EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    201 
    202     // Check that the call fails if iptables returns an error.
    203     std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
    204     mNetd->firewallReplaceUidChain(String16(veryLongStringName.c_str()), true, noUids, &ret);
    205     EXPECT_EQ(false, ret);
    206 }
    207 
    208 static int bandwidthDataSaverEnabled(const char *binary) {
    209     std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
    210 
    211     // Output looks like this:
    212     //
    213     // Chain bw_data_saver (1 references)
    214     // target     prot opt source               destination
    215     // RETURN     all  --  0.0.0.0/0            0.0.0.0/0
    216     //
    217     // or:
    218     //
    219     // Chain bw_data_saver (1 references)
    220     // target     prot opt source               destination
    221     // ... possibly connectivity critical packet rules here ...
    222     // REJECT     all  --  ::/0            ::/0
    223 
    224     EXPECT_GE(lines.size(), 3U);
    225 
    226     if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
    227         // Data saver disabled.
    228         return 0;
    229     }
    230 
    231     size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
    232 
    233     if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
    234         // Data saver enabled.
    235         return 1;
    236     }
    237 
    238     return -1;
    239 }
    240 
    241 bool enableDataSaver(sp<INetd>& netd, bool enable) {
    242     TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
    243     bool ret;
    244     netd->bandwidthEnableDataSaver(enable, &ret);
    245     return ret;
    246 }
    247 
    248 int getDataSaverState() {
    249     const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
    250     const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
    251     EXPECT_EQ(enabled4, enabled6);
    252     EXPECT_NE(-1, enabled4);
    253     EXPECT_NE(-1, enabled6);
    254     if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
    255         return -1;
    256     }
    257     return enabled6;
    258 }
    259 
    260 TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
    261     const int wasEnabled = getDataSaverState();
    262     ASSERT_NE(-1, wasEnabled);
    263 
    264     if (wasEnabled) {
    265         ASSERT_TRUE(enableDataSaver(mNetd, false));
    266         EXPECT_EQ(0, getDataSaverState());
    267     }
    268 
    269     ASSERT_TRUE(enableDataSaver(mNetd, false));
    270     EXPECT_EQ(0, getDataSaverState());
    271 
    272     ASSERT_TRUE(enableDataSaver(mNetd, true));
    273     EXPECT_EQ(1, getDataSaverState());
    274 
    275     ASSERT_TRUE(enableDataSaver(mNetd, true));
    276     EXPECT_EQ(1, getDataSaverState());
    277 
    278     if (!wasEnabled) {
    279         ASSERT_TRUE(enableDataSaver(mNetd, false));
    280         EXPECT_EQ(0, getDataSaverState());
    281     }
    282 }
    283 
    284 static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
    285         const std::string& action, const char* ipVersion) {
    286     // Output looks like this:
    287     //   "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
    288     std::vector<std::string> rules = listIpRules(ipVersion);
    289 
    290     std::string prefix = StringPrintf("%" PRIu32 ":", priority);
    291     std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
    292             range.getStart(), range.getStop(), action.c_str());
    293     for (std::string line : rules) {
    294         if (android::base::StartsWith(line, prefix.c_str())
    295                 && android::base::EndsWith(line, suffix.c_str())) {
    296             return true;
    297         }
    298     }
    299     return false;
    300 }
    301 
    302 static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
    303         const std::string& action) {
    304     bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
    305     bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
    306     EXPECT_EQ(existsIp4, existsIp6);
    307     return existsIp4;
    308 }
    309 
    310 TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
    311     constexpr uint32_t RULE_PRIORITY = 12500;
    312 
    313     constexpr int baseUid = AID_USER_OFFSET * 5;
    314     std::vector<UidRange> uidRanges = {
    315         {baseUid + 150, baseUid + 224},
    316         {baseUid + 226, baseUid + 300}
    317     };
    318 
    319     const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
    320     const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
    321 
    322     // Create two valid rules.
    323     ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
    324     EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
    325     EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
    326     for (auto const& range : uidRanges) {
    327         EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
    328     }
    329 
    330     // Remove the rules.
    331     ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
    332     EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
    333     EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
    334     for (auto const& range : uidRanges) {
    335         EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
    336     }
    337 
    338     // Fail to remove the rules a second time after they are already deleted.
    339     binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
    340     ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    341     EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
    342 
    343     // All rules should be the same as before.
    344     EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
    345     EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
    346 }
    347 
    348 // Create a socket pair that isLoopbackSocket won't think is local.
    349 void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
    350     *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
    351     struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
    352     ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
    353 
    354     socklen_t addrlen = sizeof(server6);
    355     ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
    356     ASSERT_EQ(0, listen(*serverSocket, 10));
    357 
    358     *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
    359     struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
    360     ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
    361     ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
    362     ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
    363 
    364     *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
    365     ASSERT_NE(-1, *acceptedSocket);
    366 
    367     ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
    368 }
    369 
    370 void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
    371     char buf[4096];
    372     EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
    373     EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
    374     EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
    375 }
    376 
    377 void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
    378     // Check that the client socket was closed with ECONNABORTED.
    379     int ret = write(clientSocket, "foo", sizeof("foo"));
    380     int err = errno;
    381     EXPECT_EQ(-1, ret);
    382     EXPECT_EQ(ECONNABORTED, err);
    383 
    384     // Check that it sent a RST to the server.
    385     ret = write(acceptedSocket, "foo", sizeof("foo"));
    386     err = errno;
    387     EXPECT_EQ(-1, ret);
    388     EXPECT_EQ(ECONNRESET, err);
    389 }
    390 
    391 TEST_F(BinderTest, TestSocketDestroy) {
    392     int clientSocket, serverSocket, acceptedSocket;
    393     ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
    394 
    395     // Pick a random UID in the system UID range.
    396     constexpr int baseUid = AID_APP - 2000;
    397     static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
    398     int uid = baseUid + 500 + arc4random_uniform(1000);
    399     EXPECT_EQ(0, fchown(clientSocket, uid, -1));
    400 
    401     // UID ranges that don't contain uid.
    402     std::vector<UidRange> uidRanges = {
    403         {baseUid + 42, baseUid + 449},
    404         {baseUid + 1536, AID_APP - 4},
    405         {baseUid + 498, uid - 1},
    406         {uid + 1, baseUid + 1520},
    407     };
    408     // A skip list that doesn't contain UID.
    409     std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
    410 
    411     // Close sockets. Our test socket should be intact.
    412     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    413     checkSocketpairOpen(clientSocket, acceptedSocket);
    414 
    415     // UID ranges that do contain uid.
    416     uidRanges = {
    417         {baseUid + 42, baseUid + 449},
    418         {baseUid + 1536, AID_APP - 4},
    419         {baseUid + 498, baseUid + 1520},
    420     };
    421     // Add uid to the skip list.
    422     skipUids.push_back(uid);
    423 
    424     // Close sockets. Our test socket should still be intact because it's in the skip list.
    425     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    426     checkSocketpairOpen(clientSocket, acceptedSocket);
    427 
    428     // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
    429     skipUids.resize(skipUids.size() - 1);
    430     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    431     checkSocketpairClosed(clientSocket, acceptedSocket);
    432 
    433     close(clientSocket);
    434     close(serverSocket);
    435     close(acceptedSocket);
    436 }
    437 
    438 namespace {
    439 
    440 int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
    441     if (buf == nullptr) return -1;
    442 
    443     int prefixLength = 0;
    444     bool endOfContiguousBits = false;
    445     for (unsigned int i = 0; i < buflen; i++) {
    446         const uint8_t value = buf[i];
    447 
    448         // Bad bit sequence: check for a contiguous set of bits from the high
    449         // end by verifying that the inverted value + 1 is a power of 2
    450         // (power of 2 iff. (v & (v - 1)) == 0).
    451         const uint8_t inverse = ~value + 1;
    452         if ((inverse & (inverse - 1)) != 0) return -1;
    453 
    454         prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
    455 
    456         // Bogus netmask.
    457         if (endOfContiguousBits && value != 0) return -1;
    458 
    459         if (value != 0xff) endOfContiguousBits = true;
    460     }
    461 
    462     return prefixLength;
    463 }
    464 
    465 template<typename T>
    466 int netmaskToPrefixLength(const T *p) {
    467     return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
    468 }
    469 
    470 
    471 static bool interfaceHasAddress(
    472         const std::string &ifname, const char *addrString, int prefixLength) {
    473     struct addrinfo *addrinfoList = nullptr;
    474     ScopedAddrinfo addrinfoCleanup(addrinfoList);
    475 
    476     const struct addrinfo hints = {
    477         .ai_flags    = AI_NUMERICHOST,
    478         .ai_family   = AF_UNSPEC,
    479         .ai_socktype = SOCK_DGRAM,
    480     };
    481     if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
    482         addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
    483         return false;
    484     }
    485 
    486     struct ifaddrs *ifaddrsList = nullptr;
    487     ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
    488 
    489     if (getifaddrs(&ifaddrsList) != 0) {
    490         return false;
    491     }
    492 
    493     for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
    494         if (std::string(addr->ifa_name) != ifname ||
    495             addr->ifa_addr == nullptr ||
    496             addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
    497             continue;
    498         }
    499 
    500         switch (addr->ifa_addr->sa_family) {
    501         case AF_INET: {
    502             auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
    503             auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
    504             if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
    505                 continue;
    506             }
    507 
    508             if (prefixLength < 0) return true;  // not checking prefix lengths
    509 
    510             if (addr->ifa_netmask == nullptr) return false;
    511             auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
    512             EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
    513             return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
    514         }
    515         case AF_INET6: {
    516             auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
    517             auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
    518             if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
    519                 continue;
    520             }
    521 
    522             if (prefixLength < 0) return true;  // not checking prefix lengths
    523 
    524             if (addr->ifa_netmask == nullptr) return false;
    525             auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
    526             EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
    527             return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
    528         }
    529         default:
    530             // Cannot happen because we have already screened for matching
    531             // address families at the top of each iteration.
    532             continue;
    533         }
    534     }
    535 
    536     return false;
    537 }
    538 
    539 }  // namespace
    540 
    541 TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
    542     static const struct TestData {
    543         const char *addrString;
    544         const int   prefixLength;
    545         const bool  expectSuccess;
    546     } kTestData[] = {
    547         { "192.0.2.1", 24, true },
    548         { "192.0.2.2", 25, true },
    549         { "192.0.2.3", 32, true },
    550         { "192.0.2.4", 33, false },
    551         { "192.not.an.ip", 24, false },
    552         { "2001:db8::1", 64, true },
    553         { "2001:db8::2", 65, true },
    554         { "2001:db8::3", 128, true },
    555         { "2001:db8::4", 129, false },
    556         { "foo:bar::bad", 64, false },
    557     };
    558 
    559     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    560         const auto &td = kTestData[i];
    561 
    562         // [1.a] Add the address.
    563         binder::Status status = mNetd->interfaceAddAddress(
    564                 sTun.name(), td.addrString, td.prefixLength);
    565         if (td.expectSuccess) {
    566             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
    567         } else {
    568             ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    569             ASSERT_NE(0, status.serviceSpecificErrorCode());
    570         }
    571 
    572         // [1.b] Verify the addition meets the expectation.
    573         if (td.expectSuccess) {
    574             EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
    575         } else {
    576             EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
    577         }
    578 
    579         // [2.a] Try to remove the address.  If it was not previously added, removing it fails.
    580         status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
    581         if (td.expectSuccess) {
    582             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
    583         } else {
    584             ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    585             ASSERT_NE(0, status.serviceSpecificErrorCode());
    586         }
    587 
    588         // [2.b] No matter what, the address should not be present.
    589         EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
    590     }
    591 }
    592 
    593 TEST_F(BinderTest, TestSetProcSysNet) {
    594     static const struct TestData {
    595         const int family;
    596         const int which;
    597         const char *ifname;
    598         const char *parameter;
    599         const char *value;
    600         const int expectedReturnCode;
    601     } kTestData[] = {
    602         { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
    603         { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
    604         { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
    605         { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
    606         { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
    607         { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
    608         { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
    609     };
    610 
    611     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    612         const auto &td = kTestData[i];
    613 
    614         const binder::Status status = mNetd->setProcSysNet(
    615                     td.family, td.which, td.ifname, td.parameter,
    616                     td.value);
    617 
    618         if (td.expectedReturnCode == 0) {
    619             SCOPED_TRACE(String8::format("test case %d should have passed", i));
    620             EXPECT_EQ(0, status.exceptionCode());
    621             EXPECT_EQ(0, status.serviceSpecificErrorCode());
    622         } else {
    623             SCOPED_TRACE(String8::format("test case %d should have failed", i));
    624             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    625             EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
    626         }
    627     }
    628 }
    629 
    630 static std::string base64Encode(const std::vector<uint8_t>& input) {
    631     size_t out_len;
    632     EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
    633     // out_len includes the trailing NULL.
    634     uint8_t output_bytes[out_len];
    635     EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
    636     return std::string(reinterpret_cast<char*>(output_bytes));
    637 }
    638 
    639 TEST_F(BinderTest, TestAddPrivateDnsServer) {
    640     std::vector<uint8_t> fp(SHA256_SIZE);
    641     static const struct TestData {
    642         const std::string address;
    643         const int port;
    644         const std::string fingerprintAlgorithm;
    645         const std::set<std::vector<uint8_t>> fingerprints;
    646         const int expectedReturnCode;
    647     } kTestData[] = {
    648         { "192.0.2.1", 853, "", {}, INetd::PRIVATE_DNS_SUCCESS },
    649         { "2001:db8::2", 65535, "", {}, INetd::PRIVATE_DNS_SUCCESS },
    650         { "192.0.2.3", 443, "SHA-256", { fp }, INetd::PRIVATE_DNS_SUCCESS },
    651         { "2001:db8::4", 1, "SHA-256", { fp }, INetd::PRIVATE_DNS_SUCCESS },
    652         { "192.0.*.5", 853, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
    653         { "", 853, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
    654         { "2001:dg8::6", 65535, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
    655         { "192.0.2.7", 0, "SHA-256", { fp }, INetd::PRIVATE_DNS_BAD_PORT },
    656         { "2001:db8::8", 65536, "", {}, INetd::PRIVATE_DNS_BAD_PORT },
    657         { "192.0.2.9", 50053, "SHA-512", { fp }, INetd::PRIVATE_DNS_UNKNOWN_ALGORITHM },
    658         { "2001:db8::a", 853, "", { fp }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
    659         { "192.0.2.11", 853, "SHA-256", {}, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
    660         { "2001:db8::c", 853, "SHA-256", { { 1 } }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
    661         { "192.0.2.12", 853, "SHA-256", { std::vector<uint8_t>(SHA256_SIZE + 1) },
    662                 INetd::PRIVATE_DNS_BAD_FINGERPRINT },
    663         { "2001:db8::e", 1, "SHA-256", { fp, fp, fp }, INetd::PRIVATE_DNS_SUCCESS },
    664         { "192.0.2.14", 853, "SHA-256", { fp, { 1 } }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
    665     };
    666 
    667     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    668         const auto &td = kTestData[i];
    669 
    670         std::vector<std::string> fingerprints;
    671         for (const std::vector<uint8_t>& fingerprint : td.fingerprints) {
    672             fingerprints.push_back(base64Encode(fingerprint));
    673         }
    674         const binder::Status status = mNetd->addPrivateDnsServer(
    675                 td.address, td.port, td.fingerprintAlgorithm, fingerprints);
    676 
    677         if (td.expectedReturnCode == INetd::PRIVATE_DNS_SUCCESS) {
    678             SCOPED_TRACE(String8::format("test case %d should have passed", i));
    679             SCOPED_TRACE(status.toString8());
    680             EXPECT_EQ(0, status.exceptionCode());
    681         } else {
    682             SCOPED_TRACE(String8::format("test case %d should have failed", i));
    683             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    684         }
    685         EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
    686     }
    687 }
    688 
    689 TEST_F(BinderTest, TestRemovePrivateDnsServer) {
    690     static const struct TestData {
    691         const std::string address;
    692         const int expectedReturnCode;
    693     } kTestData[] = {
    694         { "192.0.2.1", INetd::PRIVATE_DNS_SUCCESS },
    695         { "2001:db8::2", INetd::PRIVATE_DNS_SUCCESS },
    696         { "192.0.*.3", INetd::PRIVATE_DNS_BAD_ADDRESS },
    697         { "2001:dg8::4", INetd::PRIVATE_DNS_BAD_ADDRESS },
    698         { "", INetd::PRIVATE_DNS_BAD_ADDRESS },
    699     };
    700 
    701     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    702         const auto &td = kTestData[i];
    703 
    704         const binder::Status status = mNetd->removePrivateDnsServer(td.address);
    705 
    706         if (td.expectedReturnCode == INetd::PRIVATE_DNS_SUCCESS) {
    707             SCOPED_TRACE(String8::format("test case %d should have passed", i));
    708             EXPECT_EQ(0, status.exceptionCode());
    709         } else {
    710             SCOPED_TRACE(String8::format("test case %d should have failed", i));
    711             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    712         }
    713         EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
    714     }
    715 }
    716