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