blob: 8da522472f2ed963c45fa0096fa1200e4ad666c9 [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) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800324 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100325 return true;
326 }
327 }
328 return false;
329}
330
331static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
332 const std::string& action) {
333 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
334 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
335 EXPECT_EQ(existsIp4, existsIp6);
336 return existsIp4;
337}
338
339TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100340 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100341
Jeff Sharkeyfe3cbd62016-12-13 13:26:47 -0700342 constexpr int baseUid = AID_USER_OFFSET * 5;
Robin Leeb8087362016-03-30 18:43:08 +0100343 std::vector<UidRange> uidRanges = {
344 {baseUid + 150, baseUid + 224},
345 {baseUid + 226, baseUid + 300}
346 };
347
348 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
349 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
350
351 // Create two valid rules.
352 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
353 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
354 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
355 for (auto const& range : uidRanges) {
356 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
357 }
358
359 // Remove the rules.
360 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
361 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
362 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
363 for (auto const& range : uidRanges) {
364 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
365 }
366
367 // Fail to remove the rules a second time after they are already deleted.
368 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
369 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
370 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
371
372 // All rules should be the same as before.
373 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
374 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
375}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900376
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900377// Create a socket pair that isLoopbackSocket won't think is local.
378void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900379 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900380 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900381 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
382
383 socklen_t addrlen = sizeof(server6);
384 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
385 ASSERT_EQ(0, listen(*serverSocket, 10));
386
387 *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900388 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900389 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900390 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
391 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
392
393 *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
394 ASSERT_NE(-1, *acceptedSocket);
395
396 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
397}
398
399void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
400 char buf[4096];
401 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
402 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
403 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
404}
405
406void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
407 // Check that the client socket was closed with ECONNABORTED.
408 int ret = write(clientSocket, "foo", sizeof("foo"));
409 int err = errno;
410 EXPECT_EQ(-1, ret);
411 EXPECT_EQ(ECONNABORTED, err);
412
413 // Check that it sent a RST to the server.
414 ret = write(acceptedSocket, "foo", sizeof("foo"));
415 err = errno;
416 EXPECT_EQ(-1, ret);
417 EXPECT_EQ(ECONNRESET, err);
418}
419
420TEST_F(BinderTest, TestSocketDestroy) {
421 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900422 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900423
424 // Pick a random UID in the system UID range.
425 constexpr int baseUid = AID_APP - 2000;
426 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
427 int uid = baseUid + 500 + arc4random_uniform(1000);
428 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
429
430 // UID ranges that don't contain uid.
431 std::vector<UidRange> uidRanges = {
432 {baseUid + 42, baseUid + 449},
433 {baseUid + 1536, AID_APP - 4},
434 {baseUid + 498, uid - 1},
435 {uid + 1, baseUid + 1520},
436 };
437 // A skip list that doesn't contain UID.
438 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
439
440 // Close sockets. Our test socket should be intact.
441 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
442 checkSocketpairOpen(clientSocket, acceptedSocket);
443
444 // UID ranges that do contain uid.
445 uidRanges = {
446 {baseUid + 42, baseUid + 449},
447 {baseUid + 1536, AID_APP - 4},
448 {baseUid + 498, baseUid + 1520},
449 };
450 // Add uid to the skip list.
451 skipUids.push_back(uid);
452
453 // Close sockets. Our test socket should still be intact because it's in the skip list.
454 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
455 checkSocketpairOpen(clientSocket, acceptedSocket);
456
457 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
458 skipUids.resize(skipUids.size() - 1);
459 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
460 checkSocketpairClosed(clientSocket, acceptedSocket);
461
462 close(clientSocket);
463 close(serverSocket);
464 close(acceptedSocket);
465}
Erik Klinecc4f2732016-08-03 11:24:27 +0900466
467namespace {
468
469int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
470 if (buf == nullptr) return -1;
471
472 int prefixLength = 0;
473 bool endOfContiguousBits = false;
474 for (unsigned int i = 0; i < buflen; i++) {
475 const uint8_t value = buf[i];
476
477 // Bad bit sequence: check for a contiguous set of bits from the high
478 // end by verifying that the inverted value + 1 is a power of 2
479 // (power of 2 iff. (v & (v - 1)) == 0).
480 const uint8_t inverse = ~value + 1;
481 if ((inverse & (inverse - 1)) != 0) return -1;
482
483 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
484
485 // Bogus netmask.
486 if (endOfContiguousBits && value != 0) return -1;
487
488 if (value != 0xff) endOfContiguousBits = true;
489 }
490
491 return prefixLength;
492}
493
494template<typename T>
495int netmaskToPrefixLength(const T *p) {
496 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
497}
498
499
500static bool interfaceHasAddress(
501 const std::string &ifname, const char *addrString, int prefixLength) {
502 struct addrinfo *addrinfoList = nullptr;
503 ScopedAddrinfo addrinfoCleanup(addrinfoList);
504
505 const struct addrinfo hints = {
506 .ai_flags = AI_NUMERICHOST,
507 .ai_family = AF_UNSPEC,
508 .ai_socktype = SOCK_DGRAM,
509 };
510 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
511 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
512 return false;
513 }
514
515 struct ifaddrs *ifaddrsList = nullptr;
516 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
517
518 if (getifaddrs(&ifaddrsList) != 0) {
519 return false;
520 }
521
522 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
523 if (std::string(addr->ifa_name) != ifname ||
524 addr->ifa_addr == nullptr ||
525 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
526 continue;
527 }
528
529 switch (addr->ifa_addr->sa_family) {
530 case AF_INET: {
531 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
532 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
533 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
534 continue;
535 }
536
537 if (prefixLength < 0) return true; // not checking prefix lengths
538
539 if (addr->ifa_netmask == nullptr) return false;
540 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
541 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
542 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
543 }
544 case AF_INET6: {
545 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
546 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
547 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
548 continue;
549 }
550
551 if (prefixLength < 0) return true; // not checking prefix lengths
552
553 if (addr->ifa_netmask == nullptr) return false;
554 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
555 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
556 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
557 }
558 default:
559 // Cannot happen because we have already screened for matching
560 // address families at the top of each iteration.
561 continue;
562 }
563 }
564
565 return false;
566}
567
568} // namespace
569
570TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
571 static const struct TestData {
572 const char *addrString;
573 const int prefixLength;
574 const bool expectSuccess;
575 } kTestData[] = {
576 { "192.0.2.1", 24, true },
577 { "192.0.2.2", 25, true },
578 { "192.0.2.3", 32, true },
579 { "192.0.2.4", 33, false },
580 { "192.not.an.ip", 24, false },
581 { "2001:db8::1", 64, true },
582 { "2001:db8::2", 65, true },
583 { "2001:db8::3", 128, true },
584 { "2001:db8::4", 129, false },
585 { "foo:bar::bad", 64, false },
586 };
587
588 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
589 const auto &td = kTestData[i];
590
591 // [1.a] Add the address.
592 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900593 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900594 if (td.expectSuccess) {
595 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
596 } else {
597 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
598 ASSERT_NE(0, status.serviceSpecificErrorCode());
599 }
600
601 // [1.b] Verify the addition meets the expectation.
602 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900603 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900604 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900605 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900606 }
607
608 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900609 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900610 if (td.expectSuccess) {
611 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
612 } else {
613 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
614 ASSERT_NE(0, status.serviceSpecificErrorCode());
615 }
616
617 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900618 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900619 }
620}
Erik Kline55b06f82016-07-04 09:57:18 +0900621
622TEST_F(BinderTest, TestSetProcSysNet) {
623 static const struct TestData {
624 const int family;
625 const int which;
626 const char *ifname;
627 const char *parameter;
628 const char *value;
629 const int expectedReturnCode;
630 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900631 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
632 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
633 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900634 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
635 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900636 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
637 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900638 };
639
640 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
641 const auto &td = kTestData[i];
642
643 const binder::Status status = mNetd->setProcSysNet(
644 td.family, td.which, td.ifname, td.parameter,
645 td.value);
646
647 if (td.expectedReturnCode == 0) {
648 SCOPED_TRACE(String8::format("test case %d should have passed", i));
649 EXPECT_EQ(0, status.exceptionCode());
650 EXPECT_EQ(0, status.serviceSpecificErrorCode());
651 } else {
652 SCOPED_TRACE(String8::format("test case %d should have failed", i));
653 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
654 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
655 }
656 }
657}
Ben Schwartze7601812017-04-28 16:38:29 -0400658
659static std::string base64Encode(const std::vector<uint8_t>& input) {
660 size_t out_len;
661 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
662 // out_len includes the trailing NULL.
663 uint8_t output_bytes[out_len];
664 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
665 return std::string(reinterpret_cast<char*>(output_bytes));
666}
667
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400668TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Ben Schwartze7601812017-04-28 16:38:29 -0400669 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400670 std::vector<uint8_t> short_fp(1);
671 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
672 std::vector<std::string> test_domains;
673 std::vector<int> test_params = { 300, 25, 8, 8 };
674 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400675 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400676 const std::vector<std::string> servers;
677 const std::string tlsName;
678 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400679 const int expectedReturnCode;
680 } kTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400681 { {"192.0.2.1"}, "", {}, 0 },
682 { {"2001:db8::2"}, "host.name", {}, 0 },
683 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
684 { {"2001:db8::4"}, "", { fp }, 0 },
685 { {"192.0.*.5"}, "", {}, EINVAL },
686 { {""}, "", {}, EINVAL },
687 { {"2001:dg8::6"}, "", {}, EINVAL },
688 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
689 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
690 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
691 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400692 };
693
694 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
695 const auto &td = kTestData[i];
696
697 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400698 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400699 fingerprints.push_back(base64Encode(fingerprint));
700 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400701 binder::Status status = mNetd->setResolverConfiguration(
702 test_netid, td.servers, test_domains, test_params,
703 true, td.tlsName, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400704
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400705 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400706 SCOPED_TRACE(String8::format("test case %d should have passed", i));
707 SCOPED_TRACE(status.toString8());
708 EXPECT_EQ(0, status.exceptionCode());
709 } else {
710 SCOPED_TRACE(String8::format("test case %d should have failed", i));
711 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400712 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400713 }
Ben Schwartze7601812017-04-28 16:38:29 -0400714 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400715 // Ensure TLS is disabled before the start of the next test.
716 mNetd->setResolverConfiguration(
717 test_netid, kTestData[0].servers, test_domains, test_params,
718 false, "", {});
Ben Schwartze7601812017-04-28 16:38:29 -0400719}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900720
721void expectNoTestCounterRules() {
722 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
723 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
724 std::string allRules = Join(runCommand(command), "\n");
725 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
726 }
727}
728
729void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
730 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
731 path, if1.c_str(), if2.c_str(), pkt, byte));
732}
733
734void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
735 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
736 path, if1.c_str(), if2.c_str()));
737 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
738 path, if2.c_str(), if1.c_str()));
739}
740
741TEST_F(BinderTest, TestTetherGetStats) {
742 expectNoTestCounterRules();
743
744 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
745 // disabling tethering. We don't check the return value because these commands will fail if
746 // tethering is already enabled.
747 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
748 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
749
750 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
751 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
752 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
753 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
754 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
755
756 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
757 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
758 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
759 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
760 // RX is from external to internal, and TX is from internal to external.
761 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
762 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
763
764 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
765 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
766
767 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
768 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
769
770 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
771 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
772 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
773
774 PersistableBundle stats;
775 binder::Status status = mNetd->tetherGetStats(&stats);
776 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
777
778 std::vector<int64_t> actual1;
779 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
780 EXPECT_EQ(expected1, actual1);
781
782 std::vector<int64_t> actual2;
783 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
784 EXPECT_EQ(expected2, actual2);
785
786 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
787 delTetherCounterValues(path, intIface1, extIface1);
788 delTetherCounterValues(path, intIface2, extIface2);
789 if (path == IP6TABLES_PATH) {
790 delTetherCounterValues(path, intIface3, extIface2);
791 }
792 }
793
794 expectNoTestCounterRules();
795}