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