blob: 6fc6572193a6a177d0505d6fb6ff18c586349e41 [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 Harold2deff322018-05-10 14:03:48 -0700287// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
288// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
289#if INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700290#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
291 do { if ((_expect_) != (_ret_)) return false; } while(false)
292bool BinderTest::allocateIpSecResources(bool expectOk, int32_t *spi) {
293 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
294 SCOPED_TRACE(status);
295 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
296
297 // Add a policy
298 status = XfrmController::ipSecAddSecurityPolicy(0, 0, "::", "::1", 123, 0, 0);
299 SCOPED_TRACE(status);
300 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
301
302 // Add an ipsec interface
303 status = netdutils::statusFromErrno(
304 XfrmController::addVirtualTunnelInterface(
305 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
306 "addVirtualTunnelInterface");
307 return (status.ok() == expectOk);
308}
309
Nathan Harold21299f72018-03-16 20:13:03 -0700310TEST_F(BinderTest, TestXfrmControllerInit) {
311 netdutils::Status status;
312 status = XfrmController::Init();
313 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700314
315 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
316 // feature.
317 if (status.code() == EOPNOTSUPP) return;
318
Nathan Harold21299f72018-03-16 20:13:03 -0700319 ASSERT_TRUE(status.ok());
320
321 int32_t spi = 0;
322
323 ASSERT_TRUE(allocateIpSecResources(true, &spi));
324 ASSERT_TRUE(allocateIpSecResources(false, &spi));
325
326 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700327 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700328 ASSERT_TRUE(allocateIpSecResources(true, &spi));
329
330 // Clean up
331 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
332 SCOPED_TRACE(status);
333 ASSERT_TRUE(status.ok());
334
335 status = XfrmController::ipSecDeleteSecurityPolicy(0, 0, "::", "::1", 0, 0);
336 SCOPED_TRACE(status);
337 ASSERT_TRUE(status.ok());
338
339 // Remove Virtual Tunnel Interface.
340 status = netdutils::statusFromErrno(
341 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
342 "removeVirtualTunnelInterface");
343
344 ASSERT_TRUE(status.ok());
345}
Nathan Harold2deff322018-05-10 14:03:48 -0700346#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700347
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900348static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900349 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900350
351 // Output looks like this:
352 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900353 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900354 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900355 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900356 //
357 // or:
358 //
359 // Chain bw_data_saver (1 references)
360 // target prot opt source destination
361 // ... possibly connectivity critical packet rules here ...
362 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900363
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900364 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900365
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900366 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
367 // Data saver disabled.
368 return 0;
369 }
370
371 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
372
373 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
374 // Data saver enabled.
375 return 1;
376 }
377
378 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900379}
380
381bool enableDataSaver(sp<INetd>& netd, bool enable) {
382 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
383 bool ret;
384 netd->bandwidthEnableDataSaver(enable, &ret);
385 return ret;
386}
387
388int getDataSaverState() {
389 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
390 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
391 EXPECT_EQ(enabled4, enabled6);
392 EXPECT_NE(-1, enabled4);
393 EXPECT_NE(-1, enabled6);
394 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
395 return -1;
396 }
397 return enabled6;
398}
399
400TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
401 const int wasEnabled = getDataSaverState();
402 ASSERT_NE(-1, wasEnabled);
403
404 if (wasEnabled) {
405 ASSERT_TRUE(enableDataSaver(mNetd, false));
406 EXPECT_EQ(0, getDataSaverState());
407 }
408
409 ASSERT_TRUE(enableDataSaver(mNetd, false));
410 EXPECT_EQ(0, getDataSaverState());
411
412 ASSERT_TRUE(enableDataSaver(mNetd, true));
413 EXPECT_EQ(1, getDataSaverState());
414
415 ASSERT_TRUE(enableDataSaver(mNetd, true));
416 EXPECT_EQ(1, getDataSaverState());
417
418 if (!wasEnabled) {
419 ASSERT_TRUE(enableDataSaver(mNetd, false));
420 EXPECT_EQ(0, getDataSaverState());
421 }
422}
Robin Leeb8087362016-03-30 18:43:08 +0100423
424static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
425 const std::string& action, const char* ipVersion) {
426 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100427 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100428 std::vector<std::string> rules = listIpRules(ipVersion);
429
430 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
431 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
432 range.getStart(), range.getStop(), action.c_str());
433 for (std::string line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800434 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100435 return true;
436 }
437 }
438 return false;
439}
440
441static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
442 const std::string& action) {
443 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
444 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
445 EXPECT_EQ(existsIp4, existsIp6);
446 return existsIp4;
447}
448
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900449TEST_F(BinderTest, TestNetworkInterfaces) {
450 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
451 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, "").serviceSpecificErrorCode());
452 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
453 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
454
455 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
456 EXPECT_EQ(EBUSY,
457 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
458
459 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
460 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
461 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
462}
463
464TEST_F(BinderTest, TestNetworkUidRules) {
465 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
466
467 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
468 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
469 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
470
471 std::vector<UidRange> uidRanges = {
472 {BASE_UID + 8005, BASE_UID + 8012},
473 {BASE_UID + 8090, BASE_UID + 8099}
474 };
475 UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
476 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
477
478 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
479
480 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
481 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
482 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
483 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
484
485 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
486 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
487 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
488 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
489
490 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
491}
492
Robin Leeb8087362016-03-30 18:43:08 +0100493TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100494 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100495
Robin Leeb8087362016-03-30 18:43:08 +0100496 std::vector<UidRange> uidRanges = {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900497 {BASE_UID + 150, BASE_UID + 224},
498 {BASE_UID + 226, BASE_UID + 300}
Robin Leeb8087362016-03-30 18:43:08 +0100499 };
500
501 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
502 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
503
504 // Create two valid rules.
505 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
506 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
507 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
508 for (auto const& range : uidRanges) {
509 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
510 }
511
512 // Remove the rules.
513 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
514 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
515 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
516 for (auto const& range : uidRanges) {
517 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
518 }
519
520 // Fail to remove the rules a second time after they are already deleted.
521 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
522 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
523 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
524
525 // All rules should be the same as before.
526 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
527 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
528}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900529
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900530// Create a socket pair that isLoopbackSocket won't think is local.
531void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900532 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900533 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900534 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
535
536 socklen_t addrlen = sizeof(server6);
537 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
538 ASSERT_EQ(0, listen(*serverSocket, 10));
539
540 *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900541 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900542 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900543 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
544 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
545
546 *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
547 ASSERT_NE(-1, *acceptedSocket);
548
549 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
550}
551
552void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
553 char buf[4096];
554 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
555 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
556 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
557}
558
559void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
560 // Check that the client socket was closed with ECONNABORTED.
561 int ret = write(clientSocket, "foo", sizeof("foo"));
562 int err = errno;
563 EXPECT_EQ(-1, ret);
564 EXPECT_EQ(ECONNABORTED, err);
565
566 // Check that it sent a RST to the server.
567 ret = write(acceptedSocket, "foo", sizeof("foo"));
568 err = errno;
569 EXPECT_EQ(-1, ret);
570 EXPECT_EQ(ECONNRESET, err);
571}
572
573TEST_F(BinderTest, TestSocketDestroy) {
574 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900575 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900576
577 // Pick a random UID in the system UID range.
578 constexpr int baseUid = AID_APP - 2000;
579 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
580 int uid = baseUid + 500 + arc4random_uniform(1000);
581 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
582
583 // UID ranges that don't contain uid.
584 std::vector<UidRange> uidRanges = {
585 {baseUid + 42, baseUid + 449},
586 {baseUid + 1536, AID_APP - 4},
587 {baseUid + 498, uid - 1},
588 {uid + 1, baseUid + 1520},
589 };
590 // A skip list that doesn't contain UID.
591 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
592
593 // Close sockets. Our test socket should be intact.
594 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
595 checkSocketpairOpen(clientSocket, acceptedSocket);
596
597 // UID ranges that do contain uid.
598 uidRanges = {
599 {baseUid + 42, baseUid + 449},
600 {baseUid + 1536, AID_APP - 4},
601 {baseUid + 498, baseUid + 1520},
602 };
603 // Add uid to the skip list.
604 skipUids.push_back(uid);
605
606 // Close sockets. Our test socket should still be intact because it's in the skip list.
607 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
608 checkSocketpairOpen(clientSocket, acceptedSocket);
609
610 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
611 skipUids.resize(skipUids.size() - 1);
612 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
613 checkSocketpairClosed(clientSocket, acceptedSocket);
614
615 close(clientSocket);
616 close(serverSocket);
617 close(acceptedSocket);
618}
Erik Klinecc4f2732016-08-03 11:24:27 +0900619
620namespace {
621
622int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
623 if (buf == nullptr) return -1;
624
625 int prefixLength = 0;
626 bool endOfContiguousBits = false;
627 for (unsigned int i = 0; i < buflen; i++) {
628 const uint8_t value = buf[i];
629
630 // Bad bit sequence: check for a contiguous set of bits from the high
631 // end by verifying that the inverted value + 1 is a power of 2
632 // (power of 2 iff. (v & (v - 1)) == 0).
633 const uint8_t inverse = ~value + 1;
634 if ((inverse & (inverse - 1)) != 0) return -1;
635
636 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
637
638 // Bogus netmask.
639 if (endOfContiguousBits && value != 0) return -1;
640
641 if (value != 0xff) endOfContiguousBits = true;
642 }
643
644 return prefixLength;
645}
646
647template<typename T>
648int netmaskToPrefixLength(const T *p) {
649 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
650}
651
652
653static bool interfaceHasAddress(
654 const std::string &ifname, const char *addrString, int prefixLength) {
655 struct addrinfo *addrinfoList = nullptr;
656 ScopedAddrinfo addrinfoCleanup(addrinfoList);
657
658 const struct addrinfo hints = {
659 .ai_flags = AI_NUMERICHOST,
660 .ai_family = AF_UNSPEC,
661 .ai_socktype = SOCK_DGRAM,
662 };
663 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
664 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
665 return false;
666 }
667
668 struct ifaddrs *ifaddrsList = nullptr;
669 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
670
671 if (getifaddrs(&ifaddrsList) != 0) {
672 return false;
673 }
674
675 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
676 if (std::string(addr->ifa_name) != ifname ||
677 addr->ifa_addr == nullptr ||
678 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
679 continue;
680 }
681
682 switch (addr->ifa_addr->sa_family) {
683 case AF_INET: {
684 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
685 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
686 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
687 continue;
688 }
689
690 if (prefixLength < 0) return true; // not checking prefix lengths
691
692 if (addr->ifa_netmask == nullptr) return false;
693 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
694 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
695 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
696 }
697 case AF_INET6: {
698 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
699 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
700 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
701 continue;
702 }
703
704 if (prefixLength < 0) return true; // not checking prefix lengths
705
706 if (addr->ifa_netmask == nullptr) return false;
707 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
708 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
709 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
710 }
711 default:
712 // Cannot happen because we have already screened for matching
713 // address families at the top of each iteration.
714 continue;
715 }
716 }
717
718 return false;
719}
720
721} // namespace
722
723TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
724 static const struct TestData {
725 const char *addrString;
726 const int prefixLength;
727 const bool expectSuccess;
728 } kTestData[] = {
729 { "192.0.2.1", 24, true },
730 { "192.0.2.2", 25, true },
731 { "192.0.2.3", 32, true },
732 { "192.0.2.4", 33, false },
733 { "192.not.an.ip", 24, false },
734 { "2001:db8::1", 64, true },
735 { "2001:db8::2", 65, true },
736 { "2001:db8::3", 128, true },
737 { "2001:db8::4", 129, false },
738 { "foo:bar::bad", 64, false },
739 };
740
741 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
742 const auto &td = kTestData[i];
743
744 // [1.a] Add the address.
745 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900746 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900747 if (td.expectSuccess) {
748 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
749 } else {
750 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
751 ASSERT_NE(0, status.serviceSpecificErrorCode());
752 }
753
754 // [1.b] Verify the addition meets the expectation.
755 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900756 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900757 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900758 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900759 }
760
761 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900762 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900763 if (td.expectSuccess) {
764 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
765 } else {
766 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
767 ASSERT_NE(0, status.serviceSpecificErrorCode());
768 }
769
770 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900771 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900772 }
773}
Erik Kline55b06f82016-07-04 09:57:18 +0900774
775TEST_F(BinderTest, TestSetProcSysNet) {
776 static const struct TestData {
777 const int family;
778 const int which;
779 const char *ifname;
780 const char *parameter;
781 const char *value;
782 const int expectedReturnCode;
783 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900784 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
785 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
786 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900787 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
788 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900789 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
790 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900791 };
792
793 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
794 const auto &td = kTestData[i];
795
796 const binder::Status status = mNetd->setProcSysNet(
797 td.family, td.which, td.ifname, td.parameter,
798 td.value);
799
800 if (td.expectedReturnCode == 0) {
801 SCOPED_TRACE(String8::format("test case %d should have passed", i));
802 EXPECT_EQ(0, status.exceptionCode());
803 EXPECT_EQ(0, status.serviceSpecificErrorCode());
804 } else {
805 SCOPED_TRACE(String8::format("test case %d should have failed", i));
806 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
807 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
808 }
809 }
810}
Ben Schwartze7601812017-04-28 16:38:29 -0400811
812static std::string base64Encode(const std::vector<uint8_t>& input) {
813 size_t out_len;
814 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
815 // out_len includes the trailing NULL.
816 uint8_t output_bytes[out_len];
817 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
818 return std::string(reinterpret_cast<char*>(output_bytes));
819}
820
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400821TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900822 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400823 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400824 std::vector<uint8_t> short_fp(1);
825 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
826 std::vector<std::string> test_domains;
827 std::vector<int> test_params = { 300, 25, 8, 8 };
828 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400829 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400830 const std::vector<std::string> servers;
831 const std::string tlsName;
832 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400833 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900834 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400835 { {"192.0.2.1"}, "", {}, 0 },
836 { {"2001:db8::2"}, "host.name", {}, 0 },
837 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
838 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900839 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400840 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900841 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400842 { {"2001:dg8::6"}, "", {}, EINVAL },
843 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
844 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
845 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
846 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400847 };
848
Erik Klinea1476fb2018-03-04 21:01:56 +0900849 for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
850 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400851
852 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400853 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400854 fingerprints.push_back(base64Encode(fingerprint));
855 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400856 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900857 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
858 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400859
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400860 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400861 SCOPED_TRACE(String8::format("test case %d should have passed", i));
862 SCOPED_TRACE(status.toString8());
863 EXPECT_EQ(0, status.exceptionCode());
864 } else {
865 SCOPED_TRACE(String8::format("test case %d should have failed", i));
866 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400867 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400868 }
Ben Schwartze7601812017-04-28 16:38:29 -0400869 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400870 // Ensure TLS is disabled before the start of the next test.
871 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900872 test_netid, kTlsTestData[0].servers, test_domains, test_params,
873 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -0400874}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900875
876void expectNoTestCounterRules() {
877 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
878 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
879 std::string allRules = Join(runCommand(command), "\n");
880 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
881 }
882}
883
884void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
885 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
886 path, if1.c_str(), if2.c_str(), pkt, byte));
887}
888
889void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
890 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
891 path, if1.c_str(), if2.c_str()));
892 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
893 path, if2.c_str(), if1.c_str()));
894}
895
896TEST_F(BinderTest, TestTetherGetStats) {
897 expectNoTestCounterRules();
898
899 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
900 // disabling tethering. We don't check the return value because these commands will fail if
901 // tethering is already enabled.
902 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
903 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
904
905 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
906 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
907 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
908 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
909 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
910
911 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
912 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
913 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
914 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
915 // RX is from external to internal, and TX is from internal to external.
916 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
917 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
918
919 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
920 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
921
922 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
923 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
924
925 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
926 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
927 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
928
929 PersistableBundle stats;
930 binder::Status status = mNetd->tetherGetStats(&stats);
931 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
932
933 std::vector<int64_t> actual1;
934 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
935 EXPECT_EQ(expected1, actual1);
936
937 std::vector<int64_t> actual2;
938 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
939 EXPECT_EQ(expected2, actual2);
940
941 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
942 delTetherCounterValues(path, intIface1, extIface1);
943 delTetherCounterValues(path, intIface2, extIface2);
944 if (path == IP6TABLES_PATH) {
945 delTetherCounterValues(path, intIface3, extIface2);
946 }
947 }
948
949 expectNoTestCounterRules();
950}