blob: b3a160d95a9a4bdcbb16c7fc3a178e3ae5007d8b [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) {
295 if (android::base::StartsWith(line, prefix.c_str())
296 && android::base::EndsWith(line, suffix.c_str())) {
297 return true;
298 }
299 }
300 return false;
301}
302
303static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
304 const std::string& action) {
305 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
306 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
307 EXPECT_EQ(existsIp4, existsIp6);
308 return existsIp4;
309}
310
311TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100312 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100313
Jeff Sharkeyfe3cbd62016-12-13 13:26:47 -0700314 constexpr int baseUid = AID_USER_OFFSET * 5;
Robin Leeb8087362016-03-30 18:43:08 +0100315 std::vector<UidRange> uidRanges = {
316 {baseUid + 150, baseUid + 224},
317 {baseUid + 226, baseUid + 300}
318 };
319
320 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
321 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
322
323 // Create two valid rules.
324 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
325 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
326 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
327 for (auto const& range : uidRanges) {
328 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
329 }
330
331 // Remove the rules.
332 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
333 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
334 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
335 for (auto const& range : uidRanges) {
336 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
337 }
338
339 // Fail to remove the rules a second time after they are already deleted.
340 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
341 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
342 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
343
344 // All rules should be the same as before.
345 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
346 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
347}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900348
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900349// Create a socket pair that isLoopbackSocket won't think is local.
350void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900351 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900352 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900353 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
354
355 socklen_t addrlen = sizeof(server6);
356 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
357 ASSERT_EQ(0, listen(*serverSocket, 10));
358
359 *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900360 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900361 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900362 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
363 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
364
365 *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
366 ASSERT_NE(-1, *acceptedSocket);
367
368 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
369}
370
371void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
372 char buf[4096];
373 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
374 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
375 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
376}
377
378void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
379 // Check that the client socket was closed with ECONNABORTED.
380 int ret = write(clientSocket, "foo", sizeof("foo"));
381 int err = errno;
382 EXPECT_EQ(-1, ret);
383 EXPECT_EQ(ECONNABORTED, err);
384
385 // Check that it sent a RST to the server.
386 ret = write(acceptedSocket, "foo", sizeof("foo"));
387 err = errno;
388 EXPECT_EQ(-1, ret);
389 EXPECT_EQ(ECONNRESET, err);
390}
391
392TEST_F(BinderTest, TestSocketDestroy) {
393 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900394 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900395
396 // Pick a random UID in the system UID range.
397 constexpr int baseUid = AID_APP - 2000;
398 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
399 int uid = baseUid + 500 + arc4random_uniform(1000);
400 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
401
402 // UID ranges that don't contain uid.
403 std::vector<UidRange> uidRanges = {
404 {baseUid + 42, baseUid + 449},
405 {baseUid + 1536, AID_APP - 4},
406 {baseUid + 498, uid - 1},
407 {uid + 1, baseUid + 1520},
408 };
409 // A skip list that doesn't contain UID.
410 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
411
412 // Close sockets. Our test socket should be intact.
413 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
414 checkSocketpairOpen(clientSocket, acceptedSocket);
415
416 // UID ranges that do contain uid.
417 uidRanges = {
418 {baseUid + 42, baseUid + 449},
419 {baseUid + 1536, AID_APP - 4},
420 {baseUid + 498, baseUid + 1520},
421 };
422 // Add uid to the skip list.
423 skipUids.push_back(uid);
424
425 // Close sockets. Our test socket should still be intact because it's in the skip list.
426 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
427 checkSocketpairOpen(clientSocket, acceptedSocket);
428
429 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
430 skipUids.resize(skipUids.size() - 1);
431 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
432 checkSocketpairClosed(clientSocket, acceptedSocket);
433
434 close(clientSocket);
435 close(serverSocket);
436 close(acceptedSocket);
437}
Erik Klinecc4f2732016-08-03 11:24:27 +0900438
439namespace {
440
441int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
442 if (buf == nullptr) return -1;
443
444 int prefixLength = 0;
445 bool endOfContiguousBits = false;
446 for (unsigned int i = 0; i < buflen; i++) {
447 const uint8_t value = buf[i];
448
449 // Bad bit sequence: check for a contiguous set of bits from the high
450 // end by verifying that the inverted value + 1 is a power of 2
451 // (power of 2 iff. (v & (v - 1)) == 0).
452 const uint8_t inverse = ~value + 1;
453 if ((inverse & (inverse - 1)) != 0) return -1;
454
455 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
456
457 // Bogus netmask.
458 if (endOfContiguousBits && value != 0) return -1;
459
460 if (value != 0xff) endOfContiguousBits = true;
461 }
462
463 return prefixLength;
464}
465
466template<typename T>
467int netmaskToPrefixLength(const T *p) {
468 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
469}
470
471
472static bool interfaceHasAddress(
473 const std::string &ifname, const char *addrString, int prefixLength) {
474 struct addrinfo *addrinfoList = nullptr;
475 ScopedAddrinfo addrinfoCleanup(addrinfoList);
476
477 const struct addrinfo hints = {
478 .ai_flags = AI_NUMERICHOST,
479 .ai_family = AF_UNSPEC,
480 .ai_socktype = SOCK_DGRAM,
481 };
482 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
483 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
484 return false;
485 }
486
487 struct ifaddrs *ifaddrsList = nullptr;
488 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
489
490 if (getifaddrs(&ifaddrsList) != 0) {
491 return false;
492 }
493
494 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
495 if (std::string(addr->ifa_name) != ifname ||
496 addr->ifa_addr == nullptr ||
497 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
498 continue;
499 }
500
501 switch (addr->ifa_addr->sa_family) {
502 case AF_INET: {
503 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
504 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
505 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
506 continue;
507 }
508
509 if (prefixLength < 0) return true; // not checking prefix lengths
510
511 if (addr->ifa_netmask == nullptr) return false;
512 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
513 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
514 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
515 }
516 case AF_INET6: {
517 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
518 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
519 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
520 continue;
521 }
522
523 if (prefixLength < 0) return true; // not checking prefix lengths
524
525 if (addr->ifa_netmask == nullptr) return false;
526 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
527 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
528 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
529 }
530 default:
531 // Cannot happen because we have already screened for matching
532 // address families at the top of each iteration.
533 continue;
534 }
535 }
536
537 return false;
538}
539
540} // namespace
541
542TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
543 static const struct TestData {
544 const char *addrString;
545 const int prefixLength;
546 const bool expectSuccess;
547 } kTestData[] = {
548 { "192.0.2.1", 24, true },
549 { "192.0.2.2", 25, true },
550 { "192.0.2.3", 32, true },
551 { "192.0.2.4", 33, false },
552 { "192.not.an.ip", 24, false },
553 { "2001:db8::1", 64, true },
554 { "2001:db8::2", 65, true },
555 { "2001:db8::3", 128, true },
556 { "2001:db8::4", 129, false },
557 { "foo:bar::bad", 64, false },
558 };
559
560 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
561 const auto &td = kTestData[i];
562
563 // [1.a] Add the address.
564 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900565 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900566 if (td.expectSuccess) {
567 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
568 } else {
569 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
570 ASSERT_NE(0, status.serviceSpecificErrorCode());
571 }
572
573 // [1.b] Verify the addition meets the expectation.
574 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900575 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900576 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900577 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900578 }
579
580 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900581 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900582 if (td.expectSuccess) {
583 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
584 } else {
585 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
586 ASSERT_NE(0, status.serviceSpecificErrorCode());
587 }
588
589 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900590 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900591 }
592}
Erik Kline55b06f82016-07-04 09:57:18 +0900593
594TEST_F(BinderTest, TestSetProcSysNet) {
595 static const struct TestData {
596 const int family;
597 const int which;
598 const char *ifname;
599 const char *parameter;
600 const char *value;
601 const int expectedReturnCode;
602 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900603 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
604 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
605 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900606 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
607 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900608 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
609 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900610 };
611
612 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
613 const auto &td = kTestData[i];
614
615 const binder::Status status = mNetd->setProcSysNet(
616 td.family, td.which, td.ifname, td.parameter,
617 td.value);
618
619 if (td.expectedReturnCode == 0) {
620 SCOPED_TRACE(String8::format("test case %d should have passed", i));
621 EXPECT_EQ(0, status.exceptionCode());
622 EXPECT_EQ(0, status.serviceSpecificErrorCode());
623 } else {
624 SCOPED_TRACE(String8::format("test case %d should have failed", i));
625 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
626 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
627 }
628 }
629}
Ben Schwartze7601812017-04-28 16:38:29 -0400630
631static std::string base64Encode(const std::vector<uint8_t>& input) {
632 size_t out_len;
633 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
634 // out_len includes the trailing NULL.
635 uint8_t output_bytes[out_len];
636 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
637 return std::string(reinterpret_cast<char*>(output_bytes));
638}
639
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400640TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Ben Schwartze7601812017-04-28 16:38:29 -0400641 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400642 std::vector<uint8_t> short_fp(1);
643 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
644 std::vector<std::string> test_domains;
645 std::vector<int> test_params = { 300, 25, 8, 8 };
646 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400647 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400648 const std::vector<std::string> servers;
649 const std::string tlsName;
650 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400651 const int expectedReturnCode;
652 } kTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400653 { {"192.0.2.1"}, "", {}, 0 },
654 { {"2001:db8::2"}, "host.name", {}, 0 },
655 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
656 { {"2001:db8::4"}, "", { fp }, 0 },
657 { {"192.0.*.5"}, "", {}, EINVAL },
658 { {""}, "", {}, EINVAL },
659 { {"2001:dg8::6"}, "", {}, EINVAL },
660 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
661 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
662 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
663 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400664 };
665
666 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
667 const auto &td = kTestData[i];
668
669 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400670 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400671 fingerprints.push_back(base64Encode(fingerprint));
672 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400673 binder::Status status = mNetd->setResolverConfiguration(
674 test_netid, td.servers, test_domains, test_params,
675 true, td.tlsName, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400676
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400677 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400678 SCOPED_TRACE(String8::format("test case %d should have passed", i));
679 SCOPED_TRACE(status.toString8());
680 EXPECT_EQ(0, status.exceptionCode());
681 } else {
682 SCOPED_TRACE(String8::format("test case %d should have failed", i));
683 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400684 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400685 }
Ben Schwartze7601812017-04-28 16:38:29 -0400686 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400687 // Ensure TLS is disabled before the start of the next test.
688 mNetd->setResolverConfiguration(
689 test_netid, kTestData[0].servers, test_domains, test_params,
690 false, "", {});
Ben Schwartze7601812017-04-28 16:38:29 -0400691}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900692
693void expectNoTestCounterRules() {
694 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
695 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
696 std::string allRules = Join(runCommand(command), "\n");
697 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
698 }
699}
700
701void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
702 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
703 path, if1.c_str(), if2.c_str(), pkt, byte));
704}
705
706void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
707 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
708 path, if1.c_str(), if2.c_str()));
709 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
710 path, if2.c_str(), if1.c_str()));
711}
712
713TEST_F(BinderTest, TestTetherGetStats) {
714 expectNoTestCounterRules();
715
716 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
717 // disabling tethering. We don't check the return value because these commands will fail if
718 // tethering is already enabled.
719 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
720 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
721
722 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
723 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
724 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
725 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
726 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
727
728 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
729 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
730 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
731 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
732 // RX is from external to internal, and TX is from internal to external.
733 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
734 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
735
736 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
737 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
738
739 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
740 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
741
742 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
743 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
744 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
745
746 PersistableBundle stats;
747 binder::Status status = mNetd->tetherGetStats(&stats);
748 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
749
750 std::vector<int64_t> actual1;
751 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
752 EXPECT_EQ(expected1, actual1);
753
754 std::vector<int64_t> actual2;
755 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
756 EXPECT_EQ(expected2, actual2);
757
758 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
759 delTetherCounterValues(path, intIface1, extIface1);
760 delTetherCounterValues(path, intIface2, extIface2);
761 if (path == IP6TABLES_PATH) {
762 delTetherCounterValues(path, intIface3, extIface2);
763 }
764 }
765
766 expectNoTestCounterRules();
767}