blob: f5a8d43b616f913094e7817eda43a9709518ddad [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
Benedict Wongb2daefb2017-12-06 22:05:46 -080069static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
70static const std::string ESP_ALLOW_RULE("esp");
71
Lorenzo Colitti89faa342016-02-26 11:38:47 +090072class BinderTest : public ::testing::Test {
73
74public:
75 BinderTest() {
76 sp<IServiceManager> sm = defaultServiceManager();
77 sp<IBinder> binder = sm->getService(String16("netd"));
78 if (binder != nullptr) {
79 mNetd = interface_cast<INetd>(binder);
80 }
81 }
82
Lorenzo Colitti755faa92016-07-27 22:10:49 +090083 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +090084 ASSERT_NE(nullptr, mNetd.get());
85 }
86
Lorenzo Colitti755faa92016-07-27 22:10:49 +090087 // Static because setting up the tun interface takes about 40ms.
88 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090089 ASSERT_EQ(0, sTun.init());
90 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +090091 }
92
93 static void TearDownTestCase() {
94 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090095 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +090096 }
97
98 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +090099
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900100protected:
101 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900102 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900103};
104
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900105TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900106
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900107class TimedOperation : public Stopwatch {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900108public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700109 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900111 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900112 }
113
114private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115 std::string mName;
116};
117
118TEST_F(BinderTest, TestIsAlive) {
119 TimedOperation t("isAlive RPC");
120 bool isAlive = false;
121 mNetd->isAlive(&isAlive);
122 ASSERT_TRUE(isAlive);
123}
124
125static int randomUid() {
126 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
127}
128
Robin Leeb8087362016-03-30 18:43:08 +0100129static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900130 std::vector<std::string> lines;
131 FILE *f;
132
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900133 if ((f = popen(command.c_str(), "r")) == nullptr) {
134 perror("popen");
135 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900136 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900137
138 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100139 size_t bufsize = 0;
140 ssize_t linelen = 0;
141 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900142 lines.push_back(std::string(line, linelen));
143 free(line);
144 line = nullptr;
145 }
146
147 pclose(f);
148 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900149}
150
Robin Leeb8087362016-03-30 18:43:08 +0100151static std::vector<std::string> listIpRules(const char *ipVersion) {
152 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
153 return runCommand(command);
154}
155
156static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900157 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100158 return runCommand(command);
159}
160
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900161static int iptablesRuleLineLength(const char *binary, const char *chainName) {
162 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900163}
164
Benedict Wongb2daefb2017-12-06 22:05:46 -0800165static bool iptablesRuleExists(const char *binary,
166 const char *chainName,
167 const std::string expectedRule) {
168 std::vector<std::string> rules = listIptablesRule(binary, chainName);
169 for(std::string &rule: rules) {
170 if(rule.find(expectedRule) != std::string::npos) {
171 return true;
172 }
173 }
174 return false;
175}
176
177static bool iptablesNoSocketAllowRuleExists(const char *chainName){
178 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
179 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
180}
181
182static bool iptablesEspAllowRuleExists(const char *chainName){
183 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
184 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
185}
186
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900187TEST_F(BinderTest, TestFirewallReplaceUidChain) {
188 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
189 const int kNumUids = 500;
190 std::vector<int32_t> noUids(0);
191 std::vector<int32_t> uids(kNumUids);
192 for (int i = 0; i < kNumUids; i++) {
193 uids[i] = randomUid();
194 }
195
196 bool ret;
197 {
198 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
199 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), true, uids, &ret);
200 }
201 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800202 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
203 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
204 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
205 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900206 {
207 TimedOperation op("Clearing whitelist chain");
208 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
209 }
210 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900211 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
212 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900213
214 {
215 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
216 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, uids, &ret);
217 }
218 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900219 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
220 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800221 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
222 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900223
224 {
225 TimedOperation op("Clearing blacklist chain");
226 mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
227 }
228 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900229 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
230 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900231
232 // Check that the call fails if iptables returns an error.
233 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
234 mNetd->firewallReplaceUidChain(String16(veryLongStringName.c_str()), true, noUids, &ret);
235 EXPECT_EQ(false, ret);
236}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900237
238static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900239 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900240
241 // Output looks like this:
242 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900243 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900244 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900245 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900246 //
247 // or:
248 //
249 // Chain bw_data_saver (1 references)
250 // target prot opt source destination
251 // ... possibly connectivity critical packet rules here ...
252 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900253
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900254 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900255
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900256 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
257 // Data saver disabled.
258 return 0;
259 }
260
261 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
262
263 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
264 // Data saver enabled.
265 return 1;
266 }
267
268 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900269}
270
271bool enableDataSaver(sp<INetd>& netd, bool enable) {
272 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
273 bool ret;
274 netd->bandwidthEnableDataSaver(enable, &ret);
275 return ret;
276}
277
278int getDataSaverState() {
279 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
280 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
281 EXPECT_EQ(enabled4, enabled6);
282 EXPECT_NE(-1, enabled4);
283 EXPECT_NE(-1, enabled6);
284 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
285 return -1;
286 }
287 return enabled6;
288}
289
290TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
291 const int wasEnabled = getDataSaverState();
292 ASSERT_NE(-1, wasEnabled);
293
294 if (wasEnabled) {
295 ASSERT_TRUE(enableDataSaver(mNetd, false));
296 EXPECT_EQ(0, getDataSaverState());
297 }
298
299 ASSERT_TRUE(enableDataSaver(mNetd, false));
300 EXPECT_EQ(0, getDataSaverState());
301
302 ASSERT_TRUE(enableDataSaver(mNetd, true));
303 EXPECT_EQ(1, getDataSaverState());
304
305 ASSERT_TRUE(enableDataSaver(mNetd, true));
306 EXPECT_EQ(1, getDataSaverState());
307
308 if (!wasEnabled) {
309 ASSERT_TRUE(enableDataSaver(mNetd, false));
310 EXPECT_EQ(0, getDataSaverState());
311 }
312}
Robin Leeb8087362016-03-30 18:43:08 +0100313
314static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
315 const std::string& action, const char* ipVersion) {
316 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100317 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100318 std::vector<std::string> rules = listIpRules(ipVersion);
319
320 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
321 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
322 range.getStart(), range.getStop(), action.c_str());
323 for (std::string line : rules) {
324 if (android::base::StartsWith(line, prefix.c_str())
325 && android::base::EndsWith(line, suffix.c_str())) {
326 return true;
327 }
328 }
329 return false;
330}
331
332static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
333 const std::string& action) {
334 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
335 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
336 EXPECT_EQ(existsIp4, existsIp6);
337 return existsIp4;
338}
339
340TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100341 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100342
Jeff Sharkeyfe3cbd62016-12-13 13:26:47 -0700343 constexpr int baseUid = AID_USER_OFFSET * 5;
Robin Leeb8087362016-03-30 18:43:08 +0100344 std::vector<UidRange> uidRanges = {
345 {baseUid + 150, baseUid + 224},
346 {baseUid + 226, baseUid + 300}
347 };
348
349 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
350 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
351
352 // Create two valid rules.
353 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
354 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
355 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
356 for (auto const& range : uidRanges) {
357 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
358 }
359
360 // Remove the rules.
361 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
362 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
363 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
364 for (auto const& range : uidRanges) {
365 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
366 }
367
368 // Fail to remove the rules a second time after they are already deleted.
369 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
370 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
371 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
372
373 // All rules should be the same as before.
374 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
375 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
376}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900377
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900378// Create a socket pair that isLoopbackSocket won't think is local.
379void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900380 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900381 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900382 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
383
384 socklen_t addrlen = sizeof(server6);
385 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
386 ASSERT_EQ(0, listen(*serverSocket, 10));
387
388 *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900389 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900390 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900391 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
392 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
393
394 *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
395 ASSERT_NE(-1, *acceptedSocket);
396
397 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
398}
399
400void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
401 char buf[4096];
402 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
403 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
404 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
405}
406
407void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
408 // Check that the client socket was closed with ECONNABORTED.
409 int ret = write(clientSocket, "foo", sizeof("foo"));
410 int err = errno;
411 EXPECT_EQ(-1, ret);
412 EXPECT_EQ(ECONNABORTED, err);
413
414 // Check that it sent a RST to the server.
415 ret = write(acceptedSocket, "foo", sizeof("foo"));
416 err = errno;
417 EXPECT_EQ(-1, ret);
418 EXPECT_EQ(ECONNRESET, err);
419}
420
421TEST_F(BinderTest, TestSocketDestroy) {
422 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900423 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900424
425 // Pick a random UID in the system UID range.
426 constexpr int baseUid = AID_APP - 2000;
427 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
428 int uid = baseUid + 500 + arc4random_uniform(1000);
429 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
430
431 // UID ranges that don't contain uid.
432 std::vector<UidRange> uidRanges = {
433 {baseUid + 42, baseUid + 449},
434 {baseUid + 1536, AID_APP - 4},
435 {baseUid + 498, uid - 1},
436 {uid + 1, baseUid + 1520},
437 };
438 // A skip list that doesn't contain UID.
439 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
440
441 // Close sockets. Our test socket should be intact.
442 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
443 checkSocketpairOpen(clientSocket, acceptedSocket);
444
445 // UID ranges that do contain uid.
446 uidRanges = {
447 {baseUid + 42, baseUid + 449},
448 {baseUid + 1536, AID_APP - 4},
449 {baseUid + 498, baseUid + 1520},
450 };
451 // Add uid to the skip list.
452 skipUids.push_back(uid);
453
454 // Close sockets. Our test socket should still be intact because it's in the skip list.
455 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
456 checkSocketpairOpen(clientSocket, acceptedSocket);
457
458 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
459 skipUids.resize(skipUids.size() - 1);
460 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
461 checkSocketpairClosed(clientSocket, acceptedSocket);
462
463 close(clientSocket);
464 close(serverSocket);
465 close(acceptedSocket);
466}
Erik Klinecc4f2732016-08-03 11:24:27 +0900467
468namespace {
469
470int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
471 if (buf == nullptr) return -1;
472
473 int prefixLength = 0;
474 bool endOfContiguousBits = false;
475 for (unsigned int i = 0; i < buflen; i++) {
476 const uint8_t value = buf[i];
477
478 // Bad bit sequence: check for a contiguous set of bits from the high
479 // end by verifying that the inverted value + 1 is a power of 2
480 // (power of 2 iff. (v & (v - 1)) == 0).
481 const uint8_t inverse = ~value + 1;
482 if ((inverse & (inverse - 1)) != 0) return -1;
483
484 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
485
486 // Bogus netmask.
487 if (endOfContiguousBits && value != 0) return -1;
488
489 if (value != 0xff) endOfContiguousBits = true;
490 }
491
492 return prefixLength;
493}
494
495template<typename T>
496int netmaskToPrefixLength(const T *p) {
497 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
498}
499
500
501static bool interfaceHasAddress(
502 const std::string &ifname, const char *addrString, int prefixLength) {
503 struct addrinfo *addrinfoList = nullptr;
504 ScopedAddrinfo addrinfoCleanup(addrinfoList);
505
506 const struct addrinfo hints = {
507 .ai_flags = AI_NUMERICHOST,
508 .ai_family = AF_UNSPEC,
509 .ai_socktype = SOCK_DGRAM,
510 };
511 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
512 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
513 return false;
514 }
515
516 struct ifaddrs *ifaddrsList = nullptr;
517 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
518
519 if (getifaddrs(&ifaddrsList) != 0) {
520 return false;
521 }
522
523 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
524 if (std::string(addr->ifa_name) != ifname ||
525 addr->ifa_addr == nullptr ||
526 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
527 continue;
528 }
529
530 switch (addr->ifa_addr->sa_family) {
531 case AF_INET: {
532 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
533 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
534 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
535 continue;
536 }
537
538 if (prefixLength < 0) return true; // not checking prefix lengths
539
540 if (addr->ifa_netmask == nullptr) return false;
541 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
542 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
543 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
544 }
545 case AF_INET6: {
546 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
547 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
548 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
549 continue;
550 }
551
552 if (prefixLength < 0) return true; // not checking prefix lengths
553
554 if (addr->ifa_netmask == nullptr) return false;
555 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
556 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
557 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
558 }
559 default:
560 // Cannot happen because we have already screened for matching
561 // address families at the top of each iteration.
562 continue;
563 }
564 }
565
566 return false;
567}
568
569} // namespace
570
571TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
572 static const struct TestData {
573 const char *addrString;
574 const int prefixLength;
575 const bool expectSuccess;
576 } kTestData[] = {
577 { "192.0.2.1", 24, true },
578 { "192.0.2.2", 25, true },
579 { "192.0.2.3", 32, true },
580 { "192.0.2.4", 33, false },
581 { "192.not.an.ip", 24, false },
582 { "2001:db8::1", 64, true },
583 { "2001:db8::2", 65, true },
584 { "2001:db8::3", 128, true },
585 { "2001:db8::4", 129, false },
586 { "foo:bar::bad", 64, false },
587 };
588
589 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
590 const auto &td = kTestData[i];
591
592 // [1.a] Add the address.
593 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900594 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900595 if (td.expectSuccess) {
596 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
597 } else {
598 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
599 ASSERT_NE(0, status.serviceSpecificErrorCode());
600 }
601
602 // [1.b] Verify the addition meets the expectation.
603 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900604 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900605 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900606 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900607 }
608
609 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900610 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900611 if (td.expectSuccess) {
612 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
613 } else {
614 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
615 ASSERT_NE(0, status.serviceSpecificErrorCode());
616 }
617
618 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900619 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900620 }
621}
Erik Kline55b06f82016-07-04 09:57:18 +0900622
623TEST_F(BinderTest, TestSetProcSysNet) {
624 static const struct TestData {
625 const int family;
626 const int which;
627 const char *ifname;
628 const char *parameter;
629 const char *value;
630 const int expectedReturnCode;
631 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900632 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
633 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
634 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900635 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
636 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900637 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
638 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900639 };
640
641 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
642 const auto &td = kTestData[i];
643
644 const binder::Status status = mNetd->setProcSysNet(
645 td.family, td.which, td.ifname, td.parameter,
646 td.value);
647
648 if (td.expectedReturnCode == 0) {
649 SCOPED_TRACE(String8::format("test case %d should have passed", i));
650 EXPECT_EQ(0, status.exceptionCode());
651 EXPECT_EQ(0, status.serviceSpecificErrorCode());
652 } else {
653 SCOPED_TRACE(String8::format("test case %d should have failed", i));
654 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
655 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
656 }
657 }
658}
Ben Schwartze7601812017-04-28 16:38:29 -0400659
660static std::string base64Encode(const std::vector<uint8_t>& input) {
661 size_t out_len;
662 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
663 // out_len includes the trailing NULL.
664 uint8_t output_bytes[out_len];
665 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
666 return std::string(reinterpret_cast<char*>(output_bytes));
667}
668
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400669TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Ben Schwartze7601812017-04-28 16:38:29 -0400670 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400671 std::vector<uint8_t> short_fp(1);
672 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
673 std::vector<std::string> test_domains;
674 std::vector<int> test_params = { 300, 25, 8, 8 };
675 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400676 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400677 const std::vector<std::string> servers;
678 const std::string tlsName;
679 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400680 const int expectedReturnCode;
681 } kTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400682 { {"192.0.2.1"}, "", {}, 0 },
683 { {"2001:db8::2"}, "host.name", {}, 0 },
684 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
685 { {"2001:db8::4"}, "", { fp }, 0 },
686 { {"192.0.*.5"}, "", {}, EINVAL },
687 { {""}, "", {}, EINVAL },
688 { {"2001:dg8::6"}, "", {}, EINVAL },
689 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
690 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
691 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
692 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400693 };
694
695 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
696 const auto &td = kTestData[i];
697
698 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400699 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400700 fingerprints.push_back(base64Encode(fingerprint));
701 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400702 binder::Status status = mNetd->setResolverConfiguration(
703 test_netid, td.servers, test_domains, test_params,
704 true, td.tlsName, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400705
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400706 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400707 SCOPED_TRACE(String8::format("test case %d should have passed", i));
708 SCOPED_TRACE(status.toString8());
709 EXPECT_EQ(0, status.exceptionCode());
710 } else {
711 SCOPED_TRACE(String8::format("test case %d should have failed", i));
712 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400713 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400714 }
Ben Schwartze7601812017-04-28 16:38:29 -0400715 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400716 // Ensure TLS is disabled before the start of the next test.
717 mNetd->setResolverConfiguration(
718 test_netid, kTestData[0].servers, test_domains, test_params,
719 false, "", {});
Ben Schwartze7601812017-04-28 16:38:29 -0400720}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900721
722void expectNoTestCounterRules() {
723 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
724 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
725 std::string allRules = Join(runCommand(command), "\n");
726 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
727 }
728}
729
730void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
731 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
732 path, if1.c_str(), if2.c_str(), pkt, byte));
733}
734
735void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
736 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
737 path, if1.c_str(), if2.c_str()));
738 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
739 path, if2.c_str(), if1.c_str()));
740}
741
742TEST_F(BinderTest, TestTetherGetStats) {
743 expectNoTestCounterRules();
744
745 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
746 // disabling tethering. We don't check the return value because these commands will fail if
747 // tethering is already enabled.
748 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
749 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
750
751 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
752 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
753 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
754 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
755 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
756
757 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
758 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
759 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
760 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
761 // RX is from external to internal, and TX is from internal to external.
762 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
763 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
764
765 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
766 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
767
768 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
769 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
770
771 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
772 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
773 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
774
775 PersistableBundle stats;
776 binder::Status status = mNetd->tetherGetStats(&stats);
777 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
778
779 std::vector<int64_t> actual1;
780 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
781 EXPECT_EQ(expected1, actual1);
782
783 std::vector<int64_t> actual2;
784 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
785 EXPECT_EQ(expected2, actual2);
786
787 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
788 delTetherCounterValues(path, intIface1, extIface1);
789 delTetherCounterValues(path, intIface2, extIface2);
790 if (path == IP6TABLES_PATH) {
791 delTetherCounterValues(path, intIface3, extIface2);
792 }
793 }
794
795 expectNoTestCounterRules();
796}