blob: a099620ab0c0cca3030a7f772c9e10f024c47305 [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();
Nathan Harold39ad6622018-04-25 12:56:56 -0700320 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700321 ASSERT_TRUE(allocateIpSecResources(true, &spi));
322
323 // Clean up
324 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
325 SCOPED_TRACE(status);
326 ASSERT_TRUE(status.ok());
327
328 status = XfrmController::ipSecDeleteSecurityPolicy(0, 0, "::", "::1", 0, 0);
329 SCOPED_TRACE(status);
330 ASSERT_TRUE(status.ok());
331
332 // Remove Virtual Tunnel Interface.
333 status = netdutils::statusFromErrno(
334 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
335 "removeVirtualTunnelInterface");
336
337 ASSERT_TRUE(status.ok());
338}
339
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900340static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900341 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900342
343 // Output looks like this:
344 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900345 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900346 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900347 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900348 //
349 // or:
350 //
351 // Chain bw_data_saver (1 references)
352 // target prot opt source destination
353 // ... possibly connectivity critical packet rules here ...
354 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900355
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900356 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900357
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900358 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
359 // Data saver disabled.
360 return 0;
361 }
362
363 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
364
365 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
366 // Data saver enabled.
367 return 1;
368 }
369
370 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900371}
372
373bool enableDataSaver(sp<INetd>& netd, bool enable) {
374 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
375 bool ret;
376 netd->bandwidthEnableDataSaver(enable, &ret);
377 return ret;
378}
379
380int getDataSaverState() {
381 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
382 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
383 EXPECT_EQ(enabled4, enabled6);
384 EXPECT_NE(-1, enabled4);
385 EXPECT_NE(-1, enabled6);
386 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
387 return -1;
388 }
389 return enabled6;
390}
391
392TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
393 const int wasEnabled = getDataSaverState();
394 ASSERT_NE(-1, wasEnabled);
395
396 if (wasEnabled) {
397 ASSERT_TRUE(enableDataSaver(mNetd, false));
398 EXPECT_EQ(0, getDataSaverState());
399 }
400
401 ASSERT_TRUE(enableDataSaver(mNetd, false));
402 EXPECT_EQ(0, getDataSaverState());
403
404 ASSERT_TRUE(enableDataSaver(mNetd, true));
405 EXPECT_EQ(1, getDataSaverState());
406
407 ASSERT_TRUE(enableDataSaver(mNetd, true));
408 EXPECT_EQ(1, getDataSaverState());
409
410 if (!wasEnabled) {
411 ASSERT_TRUE(enableDataSaver(mNetd, false));
412 EXPECT_EQ(0, getDataSaverState());
413 }
414}
Robin Leeb8087362016-03-30 18:43:08 +0100415
416static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
417 const std::string& action, const char* ipVersion) {
418 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100419 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100420 std::vector<std::string> rules = listIpRules(ipVersion);
421
422 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
423 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
424 range.getStart(), range.getStop(), action.c_str());
425 for (std::string line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800426 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100427 return true;
428 }
429 }
430 return false;
431}
432
433static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
434 const std::string& action) {
435 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
436 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
437 EXPECT_EQ(existsIp4, existsIp6);
438 return existsIp4;
439}
440
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900441TEST_F(BinderTest, TestNetworkInterfaces) {
442 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
443 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, "").serviceSpecificErrorCode());
444 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
445 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
446
447 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
448 EXPECT_EQ(EBUSY,
449 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
450
451 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
452 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
453 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
454}
455
456TEST_F(BinderTest, TestNetworkUidRules) {
457 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
458
459 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
460 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
461 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
462
463 std::vector<UidRange> uidRanges = {
464 {BASE_UID + 8005, BASE_UID + 8012},
465 {BASE_UID + 8090, BASE_UID + 8099}
466 };
467 UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
468 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
469
470 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
471
472 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
473 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
474 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
475 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
476
477 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
478 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
479 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
480 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
481
482 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
483}
484
Robin Leeb8087362016-03-30 18:43:08 +0100485TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100486 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100487
Robin Leeb8087362016-03-30 18:43:08 +0100488 std::vector<UidRange> uidRanges = {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900489 {BASE_UID + 150, BASE_UID + 224},
490 {BASE_UID + 226, BASE_UID + 300}
Robin Leeb8087362016-03-30 18:43:08 +0100491 };
492
493 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
494 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
495
496 // Create two valid rules.
497 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
498 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
499 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
500 for (auto const& range : uidRanges) {
501 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
502 }
503
504 // Remove the rules.
505 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
506 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
507 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
508 for (auto const& range : uidRanges) {
509 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
510 }
511
512 // Fail to remove the rules a second time after they are already deleted.
513 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
514 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
515 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
516
517 // All rules should be the same as before.
518 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
519 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
520}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900521
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900522// Create a socket pair that isLoopbackSocket won't think is local.
523void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900524 *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900525 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900526 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
527
528 socklen_t addrlen = sizeof(server6);
529 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
530 ASSERT_EQ(0, listen(*serverSocket, 10));
531
532 *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900533 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900534 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900535 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
536 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
537
538 *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
539 ASSERT_NE(-1, *acceptedSocket);
540
541 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
542}
543
544void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
545 char buf[4096];
546 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
547 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
548 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
549}
550
551void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
552 // Check that the client socket was closed with ECONNABORTED.
553 int ret = write(clientSocket, "foo", sizeof("foo"));
554 int err = errno;
555 EXPECT_EQ(-1, ret);
556 EXPECT_EQ(ECONNABORTED, err);
557
558 // Check that it sent a RST to the server.
559 ret = write(acceptedSocket, "foo", sizeof("foo"));
560 err = errno;
561 EXPECT_EQ(-1, ret);
562 EXPECT_EQ(ECONNRESET, err);
563}
564
565TEST_F(BinderTest, TestSocketDestroy) {
566 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900567 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900568
569 // Pick a random UID in the system UID range.
570 constexpr int baseUid = AID_APP - 2000;
571 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
572 int uid = baseUid + 500 + arc4random_uniform(1000);
573 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
574
575 // UID ranges that don't contain uid.
576 std::vector<UidRange> uidRanges = {
577 {baseUid + 42, baseUid + 449},
578 {baseUid + 1536, AID_APP - 4},
579 {baseUid + 498, uid - 1},
580 {uid + 1, baseUid + 1520},
581 };
582 // A skip list that doesn't contain UID.
583 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
584
585 // Close sockets. Our test socket should be intact.
586 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
587 checkSocketpairOpen(clientSocket, acceptedSocket);
588
589 // UID ranges that do contain uid.
590 uidRanges = {
591 {baseUid + 42, baseUid + 449},
592 {baseUid + 1536, AID_APP - 4},
593 {baseUid + 498, baseUid + 1520},
594 };
595 // Add uid to the skip list.
596 skipUids.push_back(uid);
597
598 // Close sockets. Our test socket should still be intact because it's in the skip list.
599 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
600 checkSocketpairOpen(clientSocket, acceptedSocket);
601
602 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
603 skipUids.resize(skipUids.size() - 1);
604 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
605 checkSocketpairClosed(clientSocket, acceptedSocket);
606
607 close(clientSocket);
608 close(serverSocket);
609 close(acceptedSocket);
610}
Erik Klinecc4f2732016-08-03 11:24:27 +0900611
612namespace {
613
614int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
615 if (buf == nullptr) return -1;
616
617 int prefixLength = 0;
618 bool endOfContiguousBits = false;
619 for (unsigned int i = 0; i < buflen; i++) {
620 const uint8_t value = buf[i];
621
622 // Bad bit sequence: check for a contiguous set of bits from the high
623 // end by verifying that the inverted value + 1 is a power of 2
624 // (power of 2 iff. (v & (v - 1)) == 0).
625 const uint8_t inverse = ~value + 1;
626 if ((inverse & (inverse - 1)) != 0) return -1;
627
628 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
629
630 // Bogus netmask.
631 if (endOfContiguousBits && value != 0) return -1;
632
633 if (value != 0xff) endOfContiguousBits = true;
634 }
635
636 return prefixLength;
637}
638
639template<typename T>
640int netmaskToPrefixLength(const T *p) {
641 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
642}
643
644
645static bool interfaceHasAddress(
646 const std::string &ifname, const char *addrString, int prefixLength) {
647 struct addrinfo *addrinfoList = nullptr;
648 ScopedAddrinfo addrinfoCleanup(addrinfoList);
649
650 const struct addrinfo hints = {
651 .ai_flags = AI_NUMERICHOST,
652 .ai_family = AF_UNSPEC,
653 .ai_socktype = SOCK_DGRAM,
654 };
655 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
656 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
657 return false;
658 }
659
660 struct ifaddrs *ifaddrsList = nullptr;
661 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
662
663 if (getifaddrs(&ifaddrsList) != 0) {
664 return false;
665 }
666
667 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
668 if (std::string(addr->ifa_name) != ifname ||
669 addr->ifa_addr == nullptr ||
670 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
671 continue;
672 }
673
674 switch (addr->ifa_addr->sa_family) {
675 case AF_INET: {
676 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
677 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
678 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
679 continue;
680 }
681
682 if (prefixLength < 0) return true; // not checking prefix lengths
683
684 if (addr->ifa_netmask == nullptr) return false;
685 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
686 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
687 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
688 }
689 case AF_INET6: {
690 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
691 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
692 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
693 continue;
694 }
695
696 if (prefixLength < 0) return true; // not checking prefix lengths
697
698 if (addr->ifa_netmask == nullptr) return false;
699 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
700 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
701 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
702 }
703 default:
704 // Cannot happen because we have already screened for matching
705 // address families at the top of each iteration.
706 continue;
707 }
708 }
709
710 return false;
711}
712
713} // namespace
714
715TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
716 static const struct TestData {
717 const char *addrString;
718 const int prefixLength;
719 const bool expectSuccess;
720 } kTestData[] = {
721 { "192.0.2.1", 24, true },
722 { "192.0.2.2", 25, true },
723 { "192.0.2.3", 32, true },
724 { "192.0.2.4", 33, false },
725 { "192.not.an.ip", 24, false },
726 { "2001:db8::1", 64, true },
727 { "2001:db8::2", 65, true },
728 { "2001:db8::3", 128, true },
729 { "2001:db8::4", 129, false },
730 { "foo:bar::bad", 64, false },
731 };
732
733 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
734 const auto &td = kTestData[i];
735
736 // [1.a] Add the address.
737 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900738 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900739 if (td.expectSuccess) {
740 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
741 } else {
742 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
743 ASSERT_NE(0, status.serviceSpecificErrorCode());
744 }
745
746 // [1.b] Verify the addition meets the expectation.
747 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900748 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900749 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900750 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900751 }
752
753 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900754 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900755 if (td.expectSuccess) {
756 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
757 } else {
758 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
759 ASSERT_NE(0, status.serviceSpecificErrorCode());
760 }
761
762 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900763 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900764 }
765}
Erik Kline55b06f82016-07-04 09:57:18 +0900766
767TEST_F(BinderTest, TestSetProcSysNet) {
768 static const struct TestData {
769 const int family;
770 const int which;
771 const char *ifname;
772 const char *parameter;
773 const char *value;
774 const int expectedReturnCode;
775 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900776 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
777 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
778 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900779 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
780 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900781 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
782 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900783 };
784
785 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
786 const auto &td = kTestData[i];
787
788 const binder::Status status = mNetd->setProcSysNet(
789 td.family, td.which, td.ifname, td.parameter,
790 td.value);
791
792 if (td.expectedReturnCode == 0) {
793 SCOPED_TRACE(String8::format("test case %d should have passed", i));
794 EXPECT_EQ(0, status.exceptionCode());
795 EXPECT_EQ(0, status.serviceSpecificErrorCode());
796 } else {
797 SCOPED_TRACE(String8::format("test case %d should have failed", i));
798 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
799 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
800 }
801 }
802}
Ben Schwartze7601812017-04-28 16:38:29 -0400803
804static std::string base64Encode(const std::vector<uint8_t>& input) {
805 size_t out_len;
806 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
807 // out_len includes the trailing NULL.
808 uint8_t output_bytes[out_len];
809 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
810 return std::string(reinterpret_cast<char*>(output_bytes));
811}
812
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400813TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900814 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400815 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400816 std::vector<uint8_t> short_fp(1);
817 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
818 std::vector<std::string> test_domains;
819 std::vector<int> test_params = { 300, 25, 8, 8 };
820 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400821 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400822 const std::vector<std::string> servers;
823 const std::string tlsName;
824 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400825 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900826 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400827 { {"192.0.2.1"}, "", {}, 0 },
828 { {"2001:db8::2"}, "host.name", {}, 0 },
829 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
830 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900831 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400832 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900833 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400834 { {"2001:dg8::6"}, "", {}, EINVAL },
835 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
836 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
837 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
838 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400839 };
840
Erik Klinea1476fb2018-03-04 21:01:56 +0900841 for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
842 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400843
844 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400845 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400846 fingerprints.push_back(base64Encode(fingerprint));
847 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400848 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900849 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
850 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400851
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400852 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400853 SCOPED_TRACE(String8::format("test case %d should have passed", i));
854 SCOPED_TRACE(status.toString8());
855 EXPECT_EQ(0, status.exceptionCode());
856 } else {
857 SCOPED_TRACE(String8::format("test case %d should have failed", i));
858 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400859 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400860 }
Ben Schwartze7601812017-04-28 16:38:29 -0400861 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400862 // Ensure TLS is disabled before the start of the next test.
863 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900864 test_netid, kTlsTestData[0].servers, test_domains, test_params,
865 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -0400866}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900867
868void expectNoTestCounterRules() {
869 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
870 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
871 std::string allRules = Join(runCommand(command), "\n");
872 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
873 }
874}
875
876void addTetherCounterValues(const char *path, std::string if1, std::string if2, int byte, int pkt) {
877 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
878 path, if1.c_str(), if2.c_str(), pkt, byte));
879}
880
881void delTetherCounterValues(const char *path, std::string if1, std::string if2) {
882 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
883 path, if1.c_str(), if2.c_str()));
884 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
885 path, if2.c_str(), if1.c_str()));
886}
887
888TEST_F(BinderTest, TestTetherGetStats) {
889 expectNoTestCounterRules();
890
891 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
892 // disabling tethering. We don't check the return value because these commands will fail if
893 // tethering is already enabled.
894 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
895 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
896
897 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
898 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
899 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
900 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
901 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
902
903 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
904 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
905 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
906 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
907 // RX is from external to internal, and TX is from internal to external.
908 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
909 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
910
911 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
912 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
913
914 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
915 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
916
917 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
918 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
919 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
920
921 PersistableBundle stats;
922 binder::Status status = mNetd->tetherGetStats(&stats);
923 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
924
925 std::vector<int64_t> actual1;
926 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
927 EXPECT_EQ(expected1, actual1);
928
929 std::vector<int64_t> actual2;
930 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
931 EXPECT_EQ(expected2, actual2);
932
933 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
934 delTetherCounterValues(path, intIface1, extIface1);
935 delTetherCounterValues(path, intIface2, extIface2);
936 if (path == IP6TABLES_PATH) {
937 delTetherCounterValues(path, intIface3, extIface2);
938 }
939 }
940
941 expectNoTestCounterRules();
942}