blob: 341a7b94f1979a0c3a667f762380b4eed0c3ac6c [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
Nathan Harold21299f72018-03-16 20:13:03 -070045#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090046#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090047#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070048#include "XfrmController.h"
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090049#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090050#include "android/net/INetd.h"
Robin Leeb8087362016-03-30 18:43:08 +010051#include "android/net/UidRange.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090052#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070053#include "netdutils/Syscalls.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090054
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090055#define IP_PATH "/system/bin/ip"
56#define IP6TABLES_PATH "/system/bin/ip6tables"
57#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090058#define TUN_DEV "/dev/tun"
59
Lorenzo Colitti89faa342016-02-26 11:38:47 +090060using namespace android;
61using namespace android::base;
62using namespace android::binder;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090063using android::base::StartsWith;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090064using android::net::INetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090065using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010066using android::net::UidRange;
Nathan Harold21299f72018-03-16 20:13:03 -070067using android::net::XfrmController;
68using android::netdutils::sSyscalls;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090069using android::os::PersistableBundle;
Robin Leeb8087362016-03-30 18:43:08 +010070
71static const char* IP_RULE_V4 = "-4";
72static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090073static const int TEST_NETID1 = 65501;
74static const int TEST_NETID2 = 65502;
75constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090076
Benedict Wongb2daefb2017-12-06 22:05:46 -080077static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
78static const std::string ESP_ALLOW_RULE("esp");
79
Lorenzo Colitti89faa342016-02-26 11:38:47 +090080class BinderTest : public ::testing::Test {
81
82public:
83 BinderTest() {
84 sp<IServiceManager> sm = defaultServiceManager();
85 sp<IBinder> binder = sm->getService(String16("netd"));
86 if (binder != nullptr) {
87 mNetd = interface_cast<INetd>(binder);
88 }
89 }
90
Lorenzo Colitti755faa92016-07-27 22:10:49 +090091 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +090092 ASSERT_NE(nullptr, mNetd.get());
93 }
94
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090095 void TearDown() override {
96 mNetd->networkDestroy(TEST_NETID1);
97 mNetd->networkDestroy(TEST_NETID2);
98 }
99
Nathan Harold21299f72018-03-16 20:13:03 -0700100 bool allocateIpSecResources(bool expectOk, int32_t *spi);
101
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900102 // Static because setting up the tun interface takes about 40ms.
103 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900104 ASSERT_EQ(0, sTun.init());
105 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900106 }
107
108 static void TearDownTestCase() {
109 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900110 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900111 }
112
113 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900114
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115protected:
116 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900117 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900118};
119
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900120TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900122class TimedOperation : public Stopwatch {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900123public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700124 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900125 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900126 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900127 }
128
129private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130 std::string mName;
131};
132
133TEST_F(BinderTest, TestIsAlive) {
134 TimedOperation t("isAlive RPC");
135 bool isAlive = false;
136 mNetd->isAlive(&isAlive);
137 ASSERT_TRUE(isAlive);
138}
139
140static int randomUid() {
141 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
142}
143
Robin Leeb8087362016-03-30 18:43:08 +0100144static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900145 std::vector<std::string> lines;
146 FILE *f;
147
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900148 if ((f = popen(command.c_str(), "r")) == nullptr) {
149 perror("popen");
150 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900151 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900152
153 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100154 size_t bufsize = 0;
155 ssize_t linelen = 0;
156 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900157 lines.push_back(std::string(line, linelen));
158 free(line);
159 line = nullptr;
160 }
161
162 pclose(f);
163 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900164}
165
Robin Leeb8087362016-03-30 18:43:08 +0100166static std::vector<std::string> listIpRules(const char *ipVersion) {
167 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
168 return runCommand(command);
169}
170
171static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900172 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100173 return runCommand(command);
174}
175
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900176static int iptablesRuleLineLength(const char *binary, const char *chainName) {
177 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900178}
179
Benedict Wongb2daefb2017-12-06 22:05:46 -0800180static bool iptablesRuleExists(const char *binary,
181 const char *chainName,
182 const std::string expectedRule) {
183 std::vector<std::string> rules = listIptablesRule(binary, chainName);
184 for(std::string &rule: rules) {
185 if(rule.find(expectedRule) != std::string::npos) {
186 return true;
187 }
188 }
189 return false;
190}
191
192static bool iptablesNoSocketAllowRuleExists(const char *chainName){
193 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
194 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
195}
196
197static bool iptablesEspAllowRuleExists(const char *chainName){
198 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
199 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
200}
201
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900202TEST_F(BinderTest, TestFirewallReplaceUidChain) {
203 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
204 const int kNumUids = 500;
205 std::vector<int32_t> noUids(0);
206 std::vector<int32_t> uids(kNumUids);
207 for (int i = 0; i < kNumUids; i++) {
208 uids[i] = randomUid();
209 }
210
211 bool ret;
212 {
213 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900214 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900215 }
216 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800217 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
218 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
219 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
220 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900221 {
222 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900223 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900224 }
225 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900226 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
227 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900228
229 {
230 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900231 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900232 }
233 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900234 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
235 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800236 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
237 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900238
239 {
240 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900241 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900242 }
243 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900244 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
245 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900246
247 // Check that the call fails if iptables returns an error.
248 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900249 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900250 EXPECT_EQ(false, ret);
251}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900252
manojboopathi8707f232018-01-02 14:45:47 -0800253TEST_F(BinderTest, TestVirtualTunnelInterface) {
254 static const struct TestData {
255 const std::string& family;
256 const std::string& deviceName;
257 const std::string& localAddress;
258 const std::string& remoteAddress;
259 int32_t iKey;
260 int32_t oKey;
261 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700262 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
263 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800264 };
265
266 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700267 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800268
269 binder::Status status;
270
271 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700272 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
273 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800274 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
275
276 // Update Virtual Tunnel Interface.
277 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
278 td.remoteAddress, td.iKey, td.oKey);
279 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
280
281 // Remove Virtual Tunnel Interface.
282 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
283 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
284 }
285}
286
Nathan Harold21299f72018-03-16 20:13:03 -0700287#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
288 do { if ((_expect_) != (_ret_)) return false; } while(false)
289bool BinderTest::allocateIpSecResources(bool expectOk, int32_t *spi) {
290 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
291 SCOPED_TRACE(status);
292 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
293
294 // Add a policy
295 status = XfrmController::ipSecAddSecurityPolicy(0, 0, "::", "::1", 123, 0, 0);
296 SCOPED_TRACE(status);
297 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
298
299 // Add an ipsec interface
300 status = netdutils::statusFromErrno(
301 XfrmController::addVirtualTunnelInterface(
302 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
303 "addVirtualTunnelInterface");
304 return (status.ok() == expectOk);
305}
306
307
308TEST_F(BinderTest, TestXfrmControllerInit) {
309 netdutils::Status status;
310 status = XfrmController::Init();
311 SCOPED_TRACE(status);
312 ASSERT_TRUE(status.ok());
313
314 int32_t spi = 0;
315
316 ASSERT_TRUE(allocateIpSecResources(true, &spi));
317 ASSERT_TRUE(allocateIpSecResources(false, &spi));
318
319 status = XfrmController::Init();
320 ASSERT_TRUE(allocateIpSecResources(true, &spi));
321
322 // Clean up
323 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
324 SCOPED_TRACE(status);
325 ASSERT_TRUE(status.ok());
326
327 status = XfrmController::ipSecDeleteSecurityPolicy(0, 0, "::", "::1", 0, 0);
328 SCOPED_TRACE(status);
329 ASSERT_TRUE(status.ok());
330
331 // Remove Virtual Tunnel Interface.
332 status = netdutils::statusFromErrno(
333 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
334 "removeVirtualTunnelInterface");
335
336 ASSERT_TRUE(status.ok());
337}
338
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900339static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900340 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900341
342 // Output looks like this:
343 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900344 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900345 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900346 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900347 //
348 // or:
349 //
350 // Chain bw_data_saver (1 references)
351 // target prot opt source destination
352 // ... possibly connectivity critical packet rules here ...
353 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900354
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900355 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900356
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900357 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
358 // Data saver disabled.
359 return 0;
360 }
361
362 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
363
364 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
365 // Data saver enabled.
366 return 1;
367 }
368
369 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900370}
371
372bool enableDataSaver(sp<INetd>& netd, bool enable) {
373 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
374 bool ret;
375 netd->bandwidthEnableDataSaver(enable, &ret);
376 return ret;
377}
378
379int getDataSaverState() {
380 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
381 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
382 EXPECT_EQ(enabled4, enabled6);
383 EXPECT_NE(-1, enabled4);
384 EXPECT_NE(-1, enabled6);
385 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
386 return -1;
387 }
388 return enabled6;
389}
390
391TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
392 const int wasEnabled = getDataSaverState();
393 ASSERT_NE(-1, wasEnabled);
394
395 if (wasEnabled) {
396 ASSERT_TRUE(enableDataSaver(mNetd, false));
397 EXPECT_EQ(0, getDataSaverState());
398 }
399
400 ASSERT_TRUE(enableDataSaver(mNetd, false));
401 EXPECT_EQ(0, getDataSaverState());
402
403 ASSERT_TRUE(enableDataSaver(mNetd, true));
404 EXPECT_EQ(1, getDataSaverState());
405
406 ASSERT_TRUE(enableDataSaver(mNetd, true));
407 EXPECT_EQ(1, getDataSaverState());
408
409 if (!wasEnabled) {
410 ASSERT_TRUE(enableDataSaver(mNetd, false));
411 EXPECT_EQ(0, getDataSaverState());
412 }
413}
Robin Leeb8087362016-03-30 18:43:08 +0100414
415static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
416 const std::string& action, const char* ipVersion) {
417 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100418 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100419 std::vector<std::string> rules = listIpRules(ipVersion);
420
421 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
422 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
423 range.getStart(), range.getStop(), action.c_str());
424 for (std::string line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800425 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100426 return true;
427 }
428 }
429 return false;
430}
431
432static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
433 const std::string& action) {
434 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
435 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
436 EXPECT_EQ(existsIp4, existsIp6);
437 return existsIp4;
438}
439
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900440TEST_F(BinderTest, TestNetworkInterfaces) {
441 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
442 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, "").serviceSpecificErrorCode());
443 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
444 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
445
446 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
447 EXPECT_EQ(EBUSY,
448 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
449
450 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
451 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
452 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
453}
454
455TEST_F(BinderTest, TestNetworkUidRules) {
456 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
457
458 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
459 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
460 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
461
462 std::vector<UidRange> uidRanges = {
463 {BASE_UID + 8005, BASE_UID + 8012},
464 {BASE_UID + 8090, BASE_UID + 8099}
465 };
466 UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
467 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
468
469 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
470
471 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
472 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
473 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
474 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
475
476 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
477 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
478 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
479 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
480
481 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
482}
483
Robin Leeb8087362016-03-30 18:43:08 +0100484TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100485 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100486
Robin Leeb8087362016-03-30 18:43:08 +0100487 std::vector<UidRange> uidRanges = {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900488 {BASE_UID + 150, BASE_UID + 224},
489 {BASE_UID + 226, BASE_UID + 300}
Robin Leeb8087362016-03-30 18:43:08 +0100490 };
491
492 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
493 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
494
495 // Create two valid rules.
496 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
497 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
498 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
499 for (auto const& range : uidRanges) {
500 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
501 }
502
503 // Remove the rules.
504 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
505 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
506 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
507 for (auto const& range : uidRanges) {
508 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
509 }
510
511 // Fail to remove the rules a second time after they are already deleted.
512 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
513 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
514 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
515
516 // All rules should be the same as before.
517 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
518 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
519}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900520
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900521// Create a socket pair that isLoopbackSocket won't think is local.
522void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900523 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900524 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900525 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
526
527 socklen_t addrlen = sizeof(server6);
528 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
529 ASSERT_EQ(0, listen(*serverSocket, 10));
530
531 *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900532 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900533 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900534 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
535 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
536
537 *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
538 ASSERT_NE(-1, *acceptedSocket);
539
540 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
541}
542
543void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
544 char buf[4096];
545 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
546 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
547 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
548}
549
550void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
551 // Check that the client socket was closed with ECONNABORTED.
552 int ret = write(clientSocket, "foo", sizeof("foo"));
553 int err = errno;
554 EXPECT_EQ(-1, ret);
555 EXPECT_EQ(ECONNABORTED, err);
556
557 // Check that it sent a RST to the server.
558 ret = write(acceptedSocket, "foo", sizeof("foo"));
559 err = errno;
560 EXPECT_EQ(-1, ret);
561 EXPECT_EQ(ECONNRESET, err);
562}
563
564TEST_F(BinderTest, TestSocketDestroy) {
565 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900566 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900567
568 // Pick a random UID in the system UID range.
569 constexpr int baseUid = AID_APP - 2000;
570 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
571 int uid = baseUid + 500 + arc4random_uniform(1000);
572 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
573
574 // UID ranges that don't contain uid.
575 std::vector<UidRange> uidRanges = {
576 {baseUid + 42, baseUid + 449},
577 {baseUid + 1536, AID_APP - 4},
578 {baseUid + 498, uid - 1},
579 {uid + 1, baseUid + 1520},
580 };
581 // A skip list that doesn't contain UID.
582 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
583
584 // Close sockets. Our test socket should be intact.
585 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
586 checkSocketpairOpen(clientSocket, acceptedSocket);
587
588 // UID ranges that do contain uid.
589 uidRanges = {
590 {baseUid + 42, baseUid + 449},
591 {baseUid + 1536, AID_APP - 4},
592 {baseUid + 498, baseUid + 1520},
593 };
594 // Add uid to the skip list.
595 skipUids.push_back(uid);
596
597 // Close sockets. Our test socket should still be intact because it's in the skip list.
598 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
599 checkSocketpairOpen(clientSocket, acceptedSocket);
600
601 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
602 skipUids.resize(skipUids.size() - 1);
603 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
604 checkSocketpairClosed(clientSocket, acceptedSocket);
605
606 close(clientSocket);
607 close(serverSocket);
608 close(acceptedSocket);
609}
Erik Klinecc4f2732016-08-03 11:24:27 +0900610
611namespace {
612
613int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
614 if (buf == nullptr) return -1;
615
616 int prefixLength = 0;
617 bool endOfContiguousBits = false;
618 for (unsigned int i = 0; i < buflen; i++) {
619 const uint8_t value = buf[i];
620
621 // Bad bit sequence: check for a contiguous set of bits from the high
622 // end by verifying that the inverted value + 1 is a power of 2
623 // (power of 2 iff. (v & (v - 1)) == 0).
624 const uint8_t inverse = ~value + 1;
625 if ((inverse & (inverse - 1)) != 0) return -1;
626
627 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
628
629 // Bogus netmask.
630 if (endOfContiguousBits && value != 0) return -1;
631
632 if (value != 0xff) endOfContiguousBits = true;
633 }
634
635 return prefixLength;
636}
637
638template<typename T>
639int netmaskToPrefixLength(const T *p) {
640 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
641}
642
643
644static bool interfaceHasAddress(
645 const std::string &ifname, const char *addrString, int prefixLength) {
646 struct addrinfo *addrinfoList = nullptr;
647 ScopedAddrinfo addrinfoCleanup(addrinfoList);
648
649 const struct addrinfo hints = {
650 .ai_flags = AI_NUMERICHOST,
651 .ai_family = AF_UNSPEC,
652 .ai_socktype = SOCK_DGRAM,
653 };
654 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
655 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
656 return false;
657 }
658
659 struct ifaddrs *ifaddrsList = nullptr;
660 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
661
662 if (getifaddrs(&ifaddrsList) != 0) {
663 return false;
664 }
665
666 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
667 if (std::string(addr->ifa_name) != ifname ||
668 addr->ifa_addr == nullptr ||
669 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
670 continue;
671 }
672
673 switch (addr->ifa_addr->sa_family) {
674 case AF_INET: {
675 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
676 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
677 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
678 continue;
679 }
680
681 if (prefixLength < 0) return true; // not checking prefix lengths
682
683 if (addr->ifa_netmask == nullptr) return false;
684 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
685 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
686 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
687 }
688 case AF_INET6: {
689 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
690 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
691 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
692 continue;
693 }
694
695 if (prefixLength < 0) return true; // not checking prefix lengths
696
697 if (addr->ifa_netmask == nullptr) return false;
698 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
699 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
700 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
701 }
702 default:
703 // Cannot happen because we have already screened for matching
704 // address families at the top of each iteration.
705 continue;
706 }
707 }
708
709 return false;
710}
711
712} // namespace
713
714TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
715 static const struct TestData {
716 const char *addrString;
717 const int prefixLength;
718 const bool expectSuccess;
719 } kTestData[] = {
720 { "192.0.2.1", 24, true },
721 { "192.0.2.2", 25, true },
722 { "192.0.2.3", 32, true },
723 { "192.0.2.4", 33, false },
724 { "192.not.an.ip", 24, false },
725 { "2001:db8::1", 64, true },
726 { "2001:db8::2", 65, true },
727 { "2001:db8::3", 128, true },
728 { "2001:db8::4", 129, false },
729 { "foo:bar::bad", 64, false },
730 };
731
732 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
733 const auto &td = kTestData[i];
734
735 // [1.a] Add the address.
736 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900737 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900738 if (td.expectSuccess) {
739 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
740 } else {
741 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
742 ASSERT_NE(0, status.serviceSpecificErrorCode());
743 }
744
745 // [1.b] Verify the addition meets the expectation.
746 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900747 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900748 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900749 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900750 }
751
752 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900753 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900754 if (td.expectSuccess) {
755 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
756 } else {
757 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
758 ASSERT_NE(0, status.serviceSpecificErrorCode());
759 }
760
761 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900762 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900763 }
764}
Erik Kline55b06f82016-07-04 09:57:18 +0900765
766TEST_F(BinderTest, TestSetProcSysNet) {
767 static const struct TestData {
768 const int family;
769 const int which;
770 const char *ifname;
771 const char *parameter;
772 const char *value;
773 const int expectedReturnCode;
774 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900775 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
776 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
777 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900778 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
779 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900780 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
781 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900782 };
783
784 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
785 const auto &td = kTestData[i];
786
787 const binder::Status status = mNetd->setProcSysNet(
788 td.family, td.which, td.ifname, td.parameter,
789 td.value);
790
791 if (td.expectedReturnCode == 0) {
792 SCOPED_TRACE(String8::format("test case %d should have passed", i));
793 EXPECT_EQ(0, status.exceptionCode());
794 EXPECT_EQ(0, status.serviceSpecificErrorCode());
795 } else {
796 SCOPED_TRACE(String8::format("test case %d should have failed", i));
797 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
798 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
799 }
800 }
801}
Ben Schwartze7601812017-04-28 16:38:29 -0400802
803static std::string base64Encode(const std::vector<uint8_t>& input) {
804 size_t out_len;
805 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
806 // out_len includes the trailing NULL.
807 uint8_t output_bytes[out_len];
808 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
809 return std::string(reinterpret_cast<char*>(output_bytes));
810}
811
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400812TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900813 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400814 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400815 std::vector<uint8_t> short_fp(1);
816 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
817 std::vector<std::string> test_domains;
818 std::vector<int> test_params = { 300, 25, 8, 8 };
819 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400820 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400821 const std::vector<std::string> servers;
822 const std::string tlsName;
823 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400824 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900825 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400826 { {"192.0.2.1"}, "", {}, 0 },
827 { {"2001:db8::2"}, "host.name", {}, 0 },
828 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
829 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900830 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400831 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900832 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400833 { {"2001:dg8::6"}, "", {}, EINVAL },
834 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
835 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
836 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
837 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400838 };
839
Erik Klinea1476fb2018-03-04 21:01:56 +0900840 for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
841 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400842
843 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400844 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400845 fingerprints.push_back(base64Encode(fingerprint));
846 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400847 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900848 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
849 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400850
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400851 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400852 SCOPED_TRACE(String8::format("test case %d should have passed", i));
853 SCOPED_TRACE(status.toString8());
854 EXPECT_EQ(0, status.exceptionCode());
855 } else {
856 SCOPED_TRACE(String8::format("test case %d should have failed", i));
857 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400858 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400859 }
Ben Schwartze7601812017-04-28 16:38:29 -0400860 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400861 // Ensure TLS is disabled before the start of the next test.
862 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900863 test_netid, kTlsTestData[0].servers, test_domains, test_params,
864 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -0400865}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900866
867void expectNoTestCounterRules() {
868 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
869 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
870 std::string allRules = Join(runCommand(command), "\n");
871 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
872 }
873}
874
875void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
876 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
877 path, if1.c_str(), if2.c_str(), pkt, byte));
878}
879
880void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
881 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
882 path, if1.c_str(), if2.c_str()));
883 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
884 path, if2.c_str(), if1.c_str()));
885}
886
887TEST_F(BinderTest, TestTetherGetStats) {
888 expectNoTestCounterRules();
889
890 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
891 // disabling tethering. We don't check the return value because these commands will fail if
892 // tethering is already enabled.
893 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
894 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
895
896 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
897 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
898 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
899 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
900 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
901
902 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
903 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
904 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
905 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
906 // RX is from external to internal, and TX is from internal to external.
907 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
908 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
909
910 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
911 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
912
913 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
914 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
915
916 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
917 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
918 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
919
920 PersistableBundle stats;
921 binder::Status status = mNetd->tetherGetStats(&stats);
922 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
923
924 std::vector<int64_t> actual1;
925 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
926 EXPECT_EQ(expected1, actual1);
927
928 std::vector<int64_t> actual2;
929 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
930 EXPECT_EQ(expected2, actual2);
931
932 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
933 delTetherCounterValues(path, intIface1, extIface1);
934 delTetherCounterValues(path, intIface2, extIface2);
935 if (path == IP6TABLES_PATH) {
936 delTetherCounterValues(path, intIface3, extIface2);
937 }
938 }
939
940 expectNoTestCounterRules();
941}