blob: 732a19dd55fe8035e59baae85e90e7b8c40df399 [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;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090060using android::base::StartsWith;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090061using android::net::INetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090062using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010063using android::net::UidRange;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090064using android::os::PersistableBundle;
Robin Leeb8087362016-03-30 18:43:08 +010065
66static const char* IP_RULE_V4 = "-4";
67static const char* IP_RULE_V6 = "-6";
Lorenzo Colitti89faa342016-02-26 11:38:47 +090068
69class BinderTest : public ::testing::Test {
70
71public:
72 BinderTest() {
73 sp<IServiceManager> sm = defaultServiceManager();
74 sp<IBinder> binder = sm->getService(String16("netd"));
75 if (binder != nullptr) {
76 mNetd = interface_cast<INetd>(binder);
77 }
78 }
79
Lorenzo Colitti755faa92016-07-27 22:10:49 +090080 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +090081 ASSERT_NE(nullptr, mNetd.get());
82 }
83
Lorenzo Colitti755faa92016-07-27 22:10:49 +090084 // Static because setting up the tun interface takes about 40ms.
85 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090086 ASSERT_EQ(0, sTun.init());
87 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +090088 }
89
90 static void TearDownTestCase() {
91 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090092 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +090093 }
94
95 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +090096
Lorenzo Colitti89faa342016-02-26 11:38:47 +090097protected:
98 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090099 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900100};
101
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900102TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900103
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900104class TimedOperation : public Stopwatch {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900105public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700106 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900107 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900108 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900109 }
110
111private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900112 std::string mName;
113};
114
115TEST_F(BinderTest, TestIsAlive) {
116 TimedOperation t("isAlive RPC");
117 bool isAlive = false;
118 mNetd->isAlive(&isAlive);
119 ASSERT_TRUE(isAlive);
120}
121
122static int randomUid() {
123 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
124}
125
Robin Leeb8087362016-03-30 18:43:08 +0100126static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900127 std::vector<std::string> lines;
128 FILE *f;
129
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900130 if ((f = popen(command.c_str(), "r")) == nullptr) {
131 perror("popen");
132 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900133 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900134
135 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100136 size_t bufsize = 0;
137 ssize_t linelen = 0;
138 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900139 lines.push_back(std::string(line, linelen));
140 free(line);
141 line = nullptr;
142 }
143
144 pclose(f);
145 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900146}
147
Robin Leeb8087362016-03-30 18:43:08 +0100148static std::vector<std::string> listIpRules(const char *ipVersion) {
149 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
150 return runCommand(command);
151}
152
153static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900154 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100155 return runCommand(command);
156}
157
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900158static int iptablesRuleLineLength(const char *binary, const char *chainName) {
159 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900160}
161
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900162TEST_F(BinderTest, TestFirewallReplaceUidChain) {
163 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
164 const int kNumUids = 500;
165 std::vector<int32_t> noUids(0);
166 std::vector<int32_t> uids(kNumUids);
167 for (int i = 0; i < kNumUids; i++) {
168 uids[i] = randomUid();
169 }
170
171 bool ret;
172 {
173 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
174 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), true, uids, &ret);
175 }
176 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900177 EXPECT_EQ((int) uids.size() + 7, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
178 EXPECT_EQ((int) uids.size() + 13, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179 {
180 TimedOperation op("Clearing whitelist chain");
181 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
182 }
183 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900184 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
185 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900186
187 {
188 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
189 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, uids, &ret);
190 }
191 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900192 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
193 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900194
195 {
196 TimedOperation op("Clearing blacklist chain");
197 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
198 }
199 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900200 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
201 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900202
203 // Check that the call fails if iptables returns an error.
204 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
205 mNetd->firewallReplaceUidChain(String16(veryLongStringName.c_str()), true, noUids, &ret);
206 EXPECT_EQ(false, ret);
207}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900208
209static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900210 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900211
212 // Output looks like this:
213 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900214 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900215 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900216 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900217 //
218 // or:
219 //
220 // Chain bw_data_saver (1 references)
221 // target prot opt source destination
222 // ... possibly connectivity critical packet rules here ...
223 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900224
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900225 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900226
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900227 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
228 // Data saver disabled.
229 return 0;
230 }
231
232 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
233
234 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
235 // Data saver enabled.
236 return 1;
237 }
238
239 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900240}
241
242bool enableDataSaver(sp<INetd>& netd, bool enable) {
243 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
244 bool ret;
245 netd->bandwidthEnableDataSaver(enable, &ret);
246 return ret;
247}
248
249int getDataSaverState() {
250 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
251 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
252 EXPECT_EQ(enabled4, enabled6);
253 EXPECT_NE(-1, enabled4);
254 EXPECT_NE(-1, enabled6);
255 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
256 return -1;
257 }
258 return enabled6;
259}
260
261TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
262 const int wasEnabled = getDataSaverState();
263 ASSERT_NE(-1, wasEnabled);
264
265 if (wasEnabled) {
266 ASSERT_TRUE(enableDataSaver(mNetd, false));
267 EXPECT_EQ(0, getDataSaverState());
268 }
269
270 ASSERT_TRUE(enableDataSaver(mNetd, false));
271 EXPECT_EQ(0, getDataSaverState());
272
273 ASSERT_TRUE(enableDataSaver(mNetd, true));
274 EXPECT_EQ(1, getDataSaverState());
275
276 ASSERT_TRUE(enableDataSaver(mNetd, true));
277 EXPECT_EQ(1, getDataSaverState());
278
279 if (!wasEnabled) {
280 ASSERT_TRUE(enableDataSaver(mNetd, false));
281 EXPECT_EQ(0, getDataSaverState());
282 }
283}
Robin Leeb8087362016-03-30 18:43:08 +0100284
285static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
286 const std::string& action, const char* ipVersion) {
287 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100288 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100289 std::vector<std::string> rules = listIpRules(ipVersion);
290
291 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
292 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
293 range.getStart(), range.getStop(), action.c_str());
294 for (std::string line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800295 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100296 return true;
297 }
298 }
299 return false;
300}
301
302static 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
310TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100311 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100312
Jeff Sharkeyfe3cbd62016-12-13 13:26:47 -0700313 constexpr int baseUid = AID_USER_OFFSET * 5;
Robin Leeb8087362016-03-30 18:43:08 +0100314 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}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900347
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900348// Create a socket pair that isLoopbackSocket won't think is local.
349void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900350 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900351 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900352 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);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900359 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900360 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900361 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
370void 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
377void 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
391TEST_F(BinderTest, TestSocketDestroy) {
392 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900393 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900394
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}
Erik Klinecc4f2732016-08-03 11:24:27 +0900437
438namespace {
439
440int 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
465template<typename T>
466int netmaskToPrefixLength(const T *p) {
467 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
468}
469
470
471static 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
541TEST_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(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900564 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 // [1.b] Verify the addition meets the expectation.
573 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900574 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900575 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900576 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900577 }
578
579 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900580 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900581 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.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900589 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900590 }
591}
Erik Kline55b06f82016-07-04 09:57:18 +0900592
593TEST_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[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900602 { 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 },
Erik Kline55b06f82016-07-04 09:57:18 +0900605 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
606 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900607 { 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 },
Erik Kline55b06f82016-07-04 09:57:18 +0900609 };
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}
Ben Schwartze7601812017-04-28 16:38:29 -0400629
630static 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
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400639TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Ben Schwartze7601812017-04-28 16:38:29 -0400640 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400641 std::vector<uint8_t> short_fp(1);
642 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
643 std::vector<std::string> test_domains;
644 std::vector<int> test_params = { 300, 25, 8, 8 };
645 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400646 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400647 const std::vector<std::string> servers;
648 const std::string tlsName;
649 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400650 const int expectedReturnCode;
651 } kTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400652 { {"192.0.2.1"}, "", {}, 0 },
653 { {"2001:db8::2"}, "host.name", {}, 0 },
654 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
655 { {"2001:db8::4"}, "", { fp }, 0 },
656 { {"192.0.*.5"}, "", {}, EINVAL },
657 { {""}, "", {}, EINVAL },
658 { {"2001:dg8::6"}, "", {}, EINVAL },
659 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
660 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
661 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
662 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400663 };
664
665 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
666 const auto &td = kTestData[i];
667
668 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400669 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400670 fingerprints.push_back(base64Encode(fingerprint));
671 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400672 binder::Status status = mNetd->setResolverConfiguration(
673 test_netid, td.servers, test_domains, test_params,
674 true, td.tlsName, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400675
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400676 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400677 SCOPED_TRACE(String8::format("test case %d should have passed", i));
678 SCOPED_TRACE(status.toString8());
679 EXPECT_EQ(0, status.exceptionCode());
680 } else {
681 SCOPED_TRACE(String8::format("test case %d should have failed", i));
682 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400683 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400684 }
Ben Schwartze7601812017-04-28 16:38:29 -0400685 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400686 // Ensure TLS is disabled before the start of the next test.
687 mNetd->setResolverConfiguration(
688 test_netid, kTestData[0].servers, test_domains, test_params,
689 false, "", {});
Ben Schwartze7601812017-04-28 16:38:29 -0400690}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900691
692void expectNoTestCounterRules() {
693 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
694 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
695 std::string allRules = Join(runCommand(command), "\n");
696 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
697 }
698}
699
700void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
701 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
702 path, if1.c_str(), if2.c_str(), pkt, byte));
703}
704
705void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
706 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
707 path, if1.c_str(), if2.c_str()));
708 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
709 path, if2.c_str(), if1.c_str()));
710}
711
712TEST_F(BinderTest, TestTetherGetStats) {
713 expectNoTestCounterRules();
714
715 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
716 // disabling tethering. We don't check the return value because these commands will fail if
717 // tethering is already enabled.
718 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
719 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
720
721 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
722 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
723 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
724 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
725 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
726
727 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
728 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
729 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
730 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
731 // RX is from external to internal, and TX is from internal to external.
732 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
733 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
734
735 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
736 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
737
738 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
739 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
740
741 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
742 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
743 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
744
745 PersistableBundle stats;
746 binder::Status status = mNetd->tetherGetStats(&stats);
747 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
748
749 std::vector<int64_t> actual1;
750 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
751 EXPECT_EQ(expected1, actual1);
752
753 std::vector<int64_t> actual2;
754 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
755 EXPECT_EQ(expected2, actual2);
756
757 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
758 delTetherCounterValues(path, intIface1, extIface1);
759 delTetherCounterValues(path, intIface2, extIface2);
760 if (path == IP6TABLES_PATH) {
761 delTetherCounterValues(path, intIface3, extIface2);
762 }
763 }
764
765 expectNoTestCounterRules();
766}