blob: e5ef53fcc85ee2a7c8ac9fc8878e4e3342945091 [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>
Ben Schwartze7601812017-04-28 16:38:29 -040035#include <openssl/base64.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090036
Erik Klinecc4f2732016-08-03 11:24:27 +090037#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090038#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090039#include <android-base/strings.h>
Robin Leeb8087362016-03-30 18:43:08 +010040#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090041#include <gtest/gtest.h>
42#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090043#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044
45#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090046#include "Stopwatch.h"
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090047#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048#include "android/net/INetd.h"
Robin Leeb8087362016-03-30 18:43:08 +010049#include "android/net/UidRange.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090050#include "binder/IServiceManager.h"
51
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090052#define IP_PATH "/system/bin/ip"
53#define IP6TABLES_PATH "/system/bin/ip6tables"
54#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090055#define TUN_DEV "/dev/tun"
56
Lorenzo Colitti89faa342016-02-26 11:38:47 +090057using namespace android;
58using namespace android::base;
59using namespace android::binder;
60using android::net::INetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090061using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010062using android::net::UidRange;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090063using android::os::PersistableBundle;
Robin Leeb8087362016-03-30 18:43:08 +010064
65static const char* IP_RULE_V4 = "-4";
66static const char* IP_RULE_V6 = "-6";
Lorenzo Colitti89faa342016-02-26 11:38:47 +090067
68class BinderTest : public ::testing::Test {
69
70public:
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
Lorenzo Colitti755faa92016-07-27 22:10:49 +090079 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +090080 ASSERT_NE(nullptr, mNetd.get());
81 }
82
Lorenzo Colitti755faa92016-07-27 22:10:49 +090083 // Static because setting up the tun interface takes about 40ms.
84 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090085 ASSERT_EQ(0, sTun.init());
86 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +090087 }
88
89 static void TearDownTestCase() {
90 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090091 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +090092 }
93
94 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +090095
Lorenzo Colitti89faa342016-02-26 11:38:47 +090096protected:
97 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090098 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090099};
100
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900101TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900102
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900103class TimedOperation : public Stopwatch {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900104public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700105 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900106 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900107 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900108 }
109
110private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900111 std::string mName;
112};
113
114TEST_F(BinderTest, TestIsAlive) {
115 TimedOperation t("isAlive RPC");
116 bool isAlive = false;
117 mNetd->isAlive(&isAlive);
118 ASSERT_TRUE(isAlive);
119}
120
121static int randomUid() {
122 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
123}
124
Robin Leeb8087362016-03-30 18:43:08 +0100125static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900126 std::vector<std::string> lines;
127 FILE *f;
128
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900129 if ((f = popen(command.c_str(), "r")) == nullptr) {
130 perror("popen");
131 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900132 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900133
134 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100135 size_t bufsize = 0;
136 ssize_t linelen = 0;
137 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900138 lines.push_back(std::string(line, linelen));
139 free(line);
140 line = nullptr;
141 }
142
143 pclose(f);
144 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900145}
146
Robin Leeb8087362016-03-30 18:43:08 +0100147static 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
152static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900153 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100154 return runCommand(command);
155}
156
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900157static int iptablesRuleLineLength(const char *binary, const char *chainName) {
158 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900159}
160
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900161TEST_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);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900176 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()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900178 {
179 TimedOperation op("Clearing whitelist chain");
180 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
181 }
182 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900183 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
184 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900185
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);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900191 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()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900193
194 {
195 TimedOperation op("Clearing blacklist chain");
196 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
197 }
198 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900199 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
200 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900201
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}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900207
208static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900209 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900210
211 // Output looks like this:
212 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900213 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900214 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900215 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900216 EXPECT_EQ(3U, lines.size());
217 if (lines.size() != 3) return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900218
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900219 EXPECT_TRUE(android::base::StartsWith(lines[2], "RETURN ") ||
220 android::base::StartsWith(lines[2], "REJECT "));
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900221
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900222 return android::base::StartsWith(lines[2], "REJECT");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900223}
224
225bool enableDataSaver(sp<INetd>& netd, bool enable) {
226 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
227 bool ret;
228 netd->bandwidthEnableDataSaver(enable, &ret);
229 return ret;
230}
231
232int getDataSaverState() {
233 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
234 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
235 EXPECT_EQ(enabled4, enabled6);
236 EXPECT_NE(-1, enabled4);
237 EXPECT_NE(-1, enabled6);
238 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
239 return -1;
240 }
241 return enabled6;
242}
243
244TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
245 const int wasEnabled = getDataSaverState();
246 ASSERT_NE(-1, wasEnabled);
247
248 if (wasEnabled) {
249 ASSERT_TRUE(enableDataSaver(mNetd, false));
250 EXPECT_EQ(0, getDataSaverState());
251 }
252
253 ASSERT_TRUE(enableDataSaver(mNetd, false));
254 EXPECT_EQ(0, getDataSaverState());
255
256 ASSERT_TRUE(enableDataSaver(mNetd, true));
257 EXPECT_EQ(1, getDataSaverState());
258
259 ASSERT_TRUE(enableDataSaver(mNetd, true));
260 EXPECT_EQ(1, getDataSaverState());
261
262 if (!wasEnabled) {
263 ASSERT_TRUE(enableDataSaver(mNetd, false));
264 EXPECT_EQ(0, getDataSaverState());
265 }
266}
Robin Leeb8087362016-03-30 18:43:08 +0100267
268static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
269 const std::string& action, const char* ipVersion) {
270 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100271 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100272 std::vector<std::string> rules = listIpRules(ipVersion);
273
274 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
275 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
276 range.getStart(), range.getStop(), action.c_str());
277 for (std::string line : rules) {
278 if (android::base::StartsWith(line, prefix.c_str())
279 && android::base::EndsWith(line, suffix.c_str())) {
280 return true;
281 }
282 }
283 return false;
284}
285
286static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
287 const std::string& action) {
288 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
289 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
290 EXPECT_EQ(existsIp4, existsIp6);
291 return existsIp4;
292}
293
294TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100295 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100296
Jeff Sharkeyfe3cbd62016-12-13 13:26:47 -0700297 constexpr int baseUid = AID_USER_OFFSET * 5;
Robin Leeb8087362016-03-30 18:43:08 +0100298 std::vector<UidRange> uidRanges = {
299 {baseUid + 150, baseUid + 224},
300 {baseUid + 226, baseUid + 300}
301 };
302
303 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
304 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
305
306 // Create two valid rules.
307 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
308 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
309 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
310 for (auto const& range : uidRanges) {
311 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
312 }
313
314 // Remove the rules.
315 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
316 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
317 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
318 for (auto const& range : uidRanges) {
319 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
320 }
321
322 // Fail to remove the rules a second time after they are already deleted.
323 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
324 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
325 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
326
327 // All rules should be the same as before.
328 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
329 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
330}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900331
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900332// Create a socket pair that isLoopbackSocket won't think is local.
333void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900334 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900335 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900336 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
337
338 socklen_t addrlen = sizeof(server6);
339 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
340 ASSERT_EQ(0, listen(*serverSocket, 10));
341
342 *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900343 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900344 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900345 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
346 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
347
348 *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
349 ASSERT_NE(-1, *acceptedSocket);
350
351 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
352}
353
354void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
355 char buf[4096];
356 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
357 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
358 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
359}
360
361void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
362 // Check that the client socket was closed with ECONNABORTED.
363 int ret = write(clientSocket, "foo", sizeof("foo"));
364 int err = errno;
365 EXPECT_EQ(-1, ret);
366 EXPECT_EQ(ECONNABORTED, err);
367
368 // Check that it sent a RST to the server.
369 ret = write(acceptedSocket, "foo", sizeof("foo"));
370 err = errno;
371 EXPECT_EQ(-1, ret);
372 EXPECT_EQ(ECONNRESET, err);
373}
374
375TEST_F(BinderTest, TestSocketDestroy) {
376 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900377 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900378
379 // Pick a random UID in the system UID range.
380 constexpr int baseUid = AID_APP - 2000;
381 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
382 int uid = baseUid + 500 + arc4random_uniform(1000);
383 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
384
385 // UID ranges that don't contain uid.
386 std::vector<UidRange> uidRanges = {
387 {baseUid + 42, baseUid + 449},
388 {baseUid + 1536, AID_APP - 4},
389 {baseUid + 498, uid - 1},
390 {uid + 1, baseUid + 1520},
391 };
392 // A skip list that doesn't contain UID.
393 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
394
395 // Close sockets. Our test socket should be intact.
396 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
397 checkSocketpairOpen(clientSocket, acceptedSocket);
398
399 // UID ranges that do contain uid.
400 uidRanges = {
401 {baseUid + 42, baseUid + 449},
402 {baseUid + 1536, AID_APP - 4},
403 {baseUid + 498, baseUid + 1520},
404 };
405 // Add uid to the skip list.
406 skipUids.push_back(uid);
407
408 // Close sockets. Our test socket should still be intact because it's in the skip list.
409 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
410 checkSocketpairOpen(clientSocket, acceptedSocket);
411
412 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
413 skipUids.resize(skipUids.size() - 1);
414 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
415 checkSocketpairClosed(clientSocket, acceptedSocket);
416
417 close(clientSocket);
418 close(serverSocket);
419 close(acceptedSocket);
420}
Erik Klinecc4f2732016-08-03 11:24:27 +0900421
422namespace {
423
424int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
425 if (buf == nullptr) return -1;
426
427 int prefixLength = 0;
428 bool endOfContiguousBits = false;
429 for (unsigned int i = 0; i < buflen; i++) {
430 const uint8_t value = buf[i];
431
432 // Bad bit sequence: check for a contiguous set of bits from the high
433 // end by verifying that the inverted value + 1 is a power of 2
434 // (power of 2 iff. (v & (v - 1)) == 0).
435 const uint8_t inverse = ~value + 1;
436 if ((inverse & (inverse - 1)) != 0) return -1;
437
438 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
439
440 // Bogus netmask.
441 if (endOfContiguousBits && value != 0) return -1;
442
443 if (value != 0xff) endOfContiguousBits = true;
444 }
445
446 return prefixLength;
447}
448
449template<typename T>
450int netmaskToPrefixLength(const T *p) {
451 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
452}
453
454
455static bool interfaceHasAddress(
456 const std::string &ifname, const char *addrString, int prefixLength) {
457 struct addrinfo *addrinfoList = nullptr;
458 ScopedAddrinfo addrinfoCleanup(addrinfoList);
459
460 const struct addrinfo hints = {
461 .ai_flags = AI_NUMERICHOST,
462 .ai_family = AF_UNSPEC,
463 .ai_socktype = SOCK_DGRAM,
464 };
465 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
466 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
467 return false;
468 }
469
470 struct ifaddrs *ifaddrsList = nullptr;
471 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
472
473 if (getifaddrs(&ifaddrsList) != 0) {
474 return false;
475 }
476
477 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
478 if (std::string(addr->ifa_name) != ifname ||
479 addr->ifa_addr == nullptr ||
480 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
481 continue;
482 }
483
484 switch (addr->ifa_addr->sa_family) {
485 case AF_INET: {
486 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
487 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
488 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
489 continue;
490 }
491
492 if (prefixLength < 0) return true; // not checking prefix lengths
493
494 if (addr->ifa_netmask == nullptr) return false;
495 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
496 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
497 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
498 }
499 case AF_INET6: {
500 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
501 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
502 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
503 continue;
504 }
505
506 if (prefixLength < 0) return true; // not checking prefix lengths
507
508 if (addr->ifa_netmask == nullptr) return false;
509 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
510 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
511 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
512 }
513 default:
514 // Cannot happen because we have already screened for matching
515 // address families at the top of each iteration.
516 continue;
517 }
518 }
519
520 return false;
521}
522
523} // namespace
524
525TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
526 static const struct TestData {
527 const char *addrString;
528 const int prefixLength;
529 const bool expectSuccess;
530 } kTestData[] = {
531 { "192.0.2.1", 24, true },
532 { "192.0.2.2", 25, true },
533 { "192.0.2.3", 32, true },
534 { "192.0.2.4", 33, false },
535 { "192.not.an.ip", 24, false },
536 { "2001:db8::1", 64, true },
537 { "2001:db8::2", 65, true },
538 { "2001:db8::3", 128, true },
539 { "2001:db8::4", 129, false },
540 { "foo:bar::bad", 64, false },
541 };
542
543 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
544 const auto &td = kTestData[i];
545
546 // [1.a] Add the address.
547 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900548 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900549 if (td.expectSuccess) {
550 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
551 } else {
552 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
553 ASSERT_NE(0, status.serviceSpecificErrorCode());
554 }
555
556 // [1.b] Verify the addition meets the expectation.
557 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900558 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900559 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900560 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900561 }
562
563 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900564 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900565 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 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900573 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900574 }
575}
Erik Kline55b06f82016-07-04 09:57:18 +0900576
577TEST_F(BinderTest, TestSetProcSysNet) {
578 static const struct TestData {
579 const int family;
580 const int which;
581 const char *ifname;
582 const char *parameter;
583 const char *value;
584 const int expectedReturnCode;
585 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900586 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
587 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
588 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900589 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
590 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900591 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
592 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900593 };
594
595 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
596 const auto &td = kTestData[i];
597
598 const binder::Status status = mNetd->setProcSysNet(
599 td.family, td.which, td.ifname, td.parameter,
600 td.value);
601
602 if (td.expectedReturnCode == 0) {
603 SCOPED_TRACE(String8::format("test case %d should have passed", i));
604 EXPECT_EQ(0, status.exceptionCode());
605 EXPECT_EQ(0, status.serviceSpecificErrorCode());
606 } else {
607 SCOPED_TRACE(String8::format("test case %d should have failed", i));
608 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
609 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
610 }
611 }
612}
Ben Schwartze7601812017-04-28 16:38:29 -0400613
614static std::string base64Encode(const std::vector<uint8_t>& input) {
615 size_t out_len;
616 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
617 // out_len includes the trailing NULL.
618 uint8_t output_bytes[out_len];
619 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
620 return std::string(reinterpret_cast<char*>(output_bytes));
621}
622
623TEST_F(BinderTest, TestAddPrivateDnsServer) {
624 std::vector<uint8_t> fp(SHA256_SIZE);
625 static const struct TestData {
626 const std::string address;
627 const int port;
628 const std::string fingerprintAlgorithm;
629 const std::set<std::vector<uint8_t>> fingerprints;
630 const int expectedReturnCode;
631 } kTestData[] = {
632 { "192.0.2.1", 853, "", {}, INetd::PRIVATE_DNS_SUCCESS },
633 { "2001:db8::2", 65535, "", {}, INetd::PRIVATE_DNS_SUCCESS },
634 { "192.0.2.3", 443, "SHA-256", { fp }, INetd::PRIVATE_DNS_SUCCESS },
635 { "2001:db8::4", 1, "SHA-256", { fp }, INetd::PRIVATE_DNS_SUCCESS },
636 { "192.0.*.5", 853, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
637 { "", 853, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
638 { "2001:dg8::6", 65535, "", {}, INetd::PRIVATE_DNS_BAD_ADDRESS },
639 { "192.0.2.7", 0, "SHA-256", { fp }, INetd::PRIVATE_DNS_BAD_PORT },
640 { "2001:db8::8", 65536, "", {}, INetd::PRIVATE_DNS_BAD_PORT },
641 { "192.0.2.9", 50053, "SHA-512", { fp }, INetd::PRIVATE_DNS_UNKNOWN_ALGORITHM },
642 { "2001:db8::a", 853, "", { fp }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
643 { "192.0.2.11", 853, "SHA-256", {}, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
644 { "2001:db8::c", 853, "SHA-256", { { 1 } }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
645 { "192.0.2.12", 853, "SHA-256", { std::vector<uint8_t>(SHA256_SIZE + 1) },
646 INetd::PRIVATE_DNS_BAD_FINGERPRINT },
647 { "2001:db8::e", 1, "SHA-256", { fp, fp, fp }, INetd::PRIVATE_DNS_SUCCESS },
648 { "192.0.2.14", 853, "SHA-256", { fp, { 1 } }, INetd::PRIVATE_DNS_BAD_FINGERPRINT },
649 };
650
651 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
652 const auto &td = kTestData[i];
653
654 std::vector<std::string> fingerprints;
655 for (const std::vector<uint8_t>& fingerprint : td.fingerprints) {
656 fingerprints.push_back(base64Encode(fingerprint));
657 }
658 const binder::Status status = mNetd->addPrivateDnsServer(
659 td.address, td.port, td.fingerprintAlgorithm, fingerprints);
660
661 if (td.expectedReturnCode == INetd::PRIVATE_DNS_SUCCESS) {
662 SCOPED_TRACE(String8::format("test case %d should have passed", i));
663 SCOPED_TRACE(status.toString8());
664 EXPECT_EQ(0, status.exceptionCode());
665 } else {
666 SCOPED_TRACE(String8::format("test case %d should have failed", i));
667 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
668 }
669 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
670 }
671}
672
673TEST_F(BinderTest, TestRemovePrivateDnsServer) {
674 static const struct TestData {
675 const std::string address;
676 const int expectedReturnCode;
677 } kTestData[] = {
678 { "192.0.2.1", INetd::PRIVATE_DNS_SUCCESS },
679 { "2001:db8::2", INetd::PRIVATE_DNS_SUCCESS },
680 { "192.0.*.3", INetd::PRIVATE_DNS_BAD_ADDRESS },
681 { "2001:dg8::4", INetd::PRIVATE_DNS_BAD_ADDRESS },
682 { "", INetd::PRIVATE_DNS_BAD_ADDRESS },
683 };
684
685 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
686 const auto &td = kTestData[i];
687
688 const binder::Status status = mNetd->removePrivateDnsServer(td.address);
689
690 if (td.expectedReturnCode == INetd::PRIVATE_DNS_SUCCESS) {
691 SCOPED_TRACE(String8::format("test case %d should have passed", i));
692 EXPECT_EQ(0, status.exceptionCode());
693 } else {
694 SCOPED_TRACE(String8::format("test case %d should have failed", i));
695 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
696 }
697 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
698 }
699}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900700
701void expectNoTestCounterRules() {
702 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
703 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
704 std::string allRules = Join(runCommand(command), "\n");
705 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
706 }
707}
708
709void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
710 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
711 path, if1.c_str(), if2.c_str(), pkt, byte));
712}
713
714void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
715 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
716 path, if1.c_str(), if2.c_str()));
717 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
718 path, if2.c_str(), if1.c_str()));
719}
720
721TEST_F(BinderTest, TestTetherGetStats) {
722 expectNoTestCounterRules();
723
724 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
725 // disabling tethering. We don't check the return value because these commands will fail if
726 // tethering is already enabled.
727 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
728 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
729
730 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
731 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
732 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
733 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
734 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
735
736 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
737 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
738 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
739 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
740 // RX is from external to internal, and TX is from internal to external.
741 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
742 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
743
744 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
745 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
746
747 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
748 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
749
750 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
751 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
752 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
753
754 PersistableBundle stats;
755 binder::Status status = mNetd->tetherGetStats(&stats);
756 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
757
758 std::vector<int64_t> actual1;
759 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
760 EXPECT_EQ(expected1, actual1);
761
762 std::vector<int64_t> actual2;
763 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
764 EXPECT_EQ(expected2, actual2);
765
766 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
767 delTetherCounterValues(path, intIface1, extIface1);
768 delTetherCounterValues(path, intIface2, extIface2);
769 if (path == IP6TABLES_PATH) {
770 delTetherCounterValues(path, intIface3, extIface2);
771 }
772 }
773
774 expectNoTestCounterRules();
775}