blob: e97d1916e42f9ad1816ea072ec6eb4f254fb6f5f [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>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070040#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010041#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090042#include <gtest/gtest.h>
43#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090044#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090045
Nathan Harold21299f72018-03-16 20:13:03 -070046#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090047#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090048#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070049#include "XfrmController.h"
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090050#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090051#include "android/net/INetd.h"
Robin Leeb8087362016-03-30 18:43:08 +010052#include "android/net/UidRange.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070054#include "netdutils/Syscalls.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090055
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090056#define IP_PATH "/system/bin/ip"
57#define IP6TABLES_PATH "/system/bin/ip6tables"
58#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090059#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080060#define RAW_TABLE "raw"
61#define MANGLE_TABLE "mangle"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090062
Lorenzo Colitti89faa342016-02-26 11:38:47 +090063using namespace android;
64using namespace android::base;
65using namespace android::binder;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090066using android::base::StartsWith;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070067using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090068using android::net::INetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090069using android::net::TunInterface;
Robin Leeb8087362016-03-30 18:43:08 +010070using android::net::UidRange;
Nathan Harold21299f72018-03-16 20:13:03 -070071using android::net::XfrmController;
72using android::netdutils::sSyscalls;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090073using android::os::PersistableBundle;
Robin Leeb8087362016-03-30 18:43:08 +010074
Chenbo Feng837ddfc2018-05-08 13:45:08 -070075#define SKIP_IF_BPF_SUPPORTED \
76 do { \
77 if (hasBpfSupport()) return; \
78 } while (0);
79
Robin Leeb8087362016-03-30 18:43:08 +010080static const char* IP_RULE_V4 = "-4";
81static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090082static const int TEST_NETID1 = 65501;
83static const int TEST_NETID2 = 65502;
84constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090085
Benedict Wongb2daefb2017-12-06 22:05:46 -080086static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
87static const std::string ESP_ALLOW_RULE("esp");
88
Lorenzo Colitti89faa342016-02-26 11:38:47 +090089class BinderTest : public ::testing::Test {
90
91public:
92 BinderTest() {
93 sp<IServiceManager> sm = defaultServiceManager();
94 sp<IBinder> binder = sm->getService(String16("netd"));
95 if (binder != nullptr) {
96 mNetd = interface_cast<INetd>(binder);
97 }
98 }
99
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900100 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900101 ASSERT_NE(nullptr, mNetd.get());
102 }
103
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900104 void TearDown() override {
105 mNetd->networkDestroy(TEST_NETID1);
106 mNetd->networkDestroy(TEST_NETID2);
107 }
108
Nathan Harold21299f72018-03-16 20:13:03 -0700109 bool allocateIpSecResources(bool expectOk, int32_t *spi);
110
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900111 // Static because setting up the tun interface takes about 40ms.
112 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900113 ASSERT_EQ(0, sTun.init());
114 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900115 }
116
117 static void TearDownTestCase() {
118 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900119 sTun.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900120 }
121
122 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900123
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900124protected:
125 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900126 static TunInterface sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900127};
128
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900129TunInterface BinderTest::sTun;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900131class TimedOperation : public Stopwatch {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900132public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700133 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900134 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900135 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900136 }
137
138private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900139 std::string mName;
140};
141
142TEST_F(BinderTest, TestIsAlive) {
143 TimedOperation t("isAlive RPC");
144 bool isAlive = false;
145 mNetd->isAlive(&isAlive);
146 ASSERT_TRUE(isAlive);
147}
148
149static int randomUid() {
150 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
151}
152
Robin Leeb8087362016-03-30 18:43:08 +0100153static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900154 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900155 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
156 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900157 perror("popen");
158 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900159 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900160
161 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100162 size_t bufsize = 0;
163 ssize_t linelen = 0;
164 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900165 lines.push_back(std::string(line, linelen));
166 free(line);
167 line = nullptr;
168 }
169
170 pclose(f);
171 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900172}
173
Robin Leeb8087362016-03-30 18:43:08 +0100174static std::vector<std::string> listIpRules(const char *ipVersion) {
175 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
176 return runCommand(command);
177}
178
179static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900180 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100181 return runCommand(command);
182}
183
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900184static int iptablesRuleLineLength(const char *binary, const char *chainName) {
185 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900186}
187
Benedict Wongb2daefb2017-12-06 22:05:46 -0800188static bool iptablesRuleExists(const char *binary,
189 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900190 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800191 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900192 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800193 if(rule.find(expectedRule) != std::string::npos) {
194 return true;
195 }
196 }
197 return false;
198}
199
200static bool iptablesNoSocketAllowRuleExists(const char *chainName){
201 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
202 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
203}
204
205static bool iptablesEspAllowRuleExists(const char *chainName){
206 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
207 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
208}
209
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900210TEST_F(BinderTest, TestFirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700211 SKIP_IF_BPF_SUPPORTED;
212
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900213 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
214 const int kNumUids = 500;
215 std::vector<int32_t> noUids(0);
216 std::vector<int32_t> uids(kNumUids);
217 for (int i = 0; i < kNumUids; i++) {
218 uids[i] = randomUid();
219 }
220
221 bool ret;
222 {
223 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900224 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900225 }
226 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800227 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
228 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
229 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
230 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900231 {
232 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900233 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900234 }
235 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900236 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
237 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900238
239 {
240 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900241 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900242 }
243 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900244 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
245 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800246 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
247 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900248
249 {
250 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900251 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900252 }
253 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900254 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
255 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900256
257 // Check that the call fails if iptables returns an error.
258 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900259 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900260 EXPECT_EQ(false, ret);
261}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900262
manojboopathi8707f232018-01-02 14:45:47 -0800263TEST_F(BinderTest, TestVirtualTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700264 const struct TestData {
265 const std::string family;
266 const std::string deviceName;
267 const std::string localAddress;
268 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800269 int32_t iKey;
270 int32_t oKey;
271 } kTestData[] = {
Nathan Harold21299f72018-03-16 20:13:03 -0700272 {"IPV4", "test_vti", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53},
273 {"IPV6", "test_vti6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50},
manojboopathi8707f232018-01-02 14:45:47 -0800274 };
275
276 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700277 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800278
279 binder::Status status;
280
281 // Create Virtual Tunnel Interface.
Nathan Harold21299f72018-03-16 20:13:03 -0700282 status = mNetd->addVirtualTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
283 td.iKey, td.oKey);
manojboopathi8707f232018-01-02 14:45:47 -0800284 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
285
286 // Update Virtual Tunnel Interface.
287 status = mNetd->updateVirtualTunnelInterface(td.deviceName, td.localAddress,
288 td.remoteAddress, td.iKey, td.oKey);
289 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
290
291 // Remove Virtual Tunnel Interface.
292 status = mNetd->removeVirtualTunnelInterface(td.deviceName);
293 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
294 }
295}
296
Nathan Harold2deff322018-05-10 14:03:48 -0700297// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
298// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
299#if INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700300#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
301 do { if ((_expect_) != (_ret_)) return false; } while(false)
302bool BinderTest::allocateIpSecResources(bool expectOk, int32_t *spi) {
303 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
304 SCOPED_TRACE(status);
305 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
306
307 // Add a policy
308 status = XfrmController::ipSecAddSecurityPolicy(0, 0, "::", "::1", 123, 0, 0);
309 SCOPED_TRACE(status);
310 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
311
312 // Add an ipsec interface
313 status = netdutils::statusFromErrno(
314 XfrmController::addVirtualTunnelInterface(
315 "ipsec_test", "::", "::1", 0xF00D, 0xD00D, false),
316 "addVirtualTunnelInterface");
317 return (status.ok() == expectOk);
318}
319
Nathan Harold21299f72018-03-16 20:13:03 -0700320TEST_F(BinderTest, TestXfrmControllerInit) {
321 netdutils::Status status;
322 status = XfrmController::Init();
323 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700324
325 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
326 // feature.
327 if (status.code() == EOPNOTSUPP) return;
328
Nathan Harold21299f72018-03-16 20:13:03 -0700329 ASSERT_TRUE(status.ok());
330
331 int32_t spi = 0;
332
333 ASSERT_TRUE(allocateIpSecResources(true, &spi));
334 ASSERT_TRUE(allocateIpSecResources(false, &spi));
335
336 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700337 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700338 ASSERT_TRUE(allocateIpSecResources(true, &spi));
339
340 // Clean up
341 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0);
342 SCOPED_TRACE(status);
343 ASSERT_TRUE(status.ok());
344
345 status = XfrmController::ipSecDeleteSecurityPolicy(0, 0, "::", "::1", 0, 0);
346 SCOPED_TRACE(status);
347 ASSERT_TRUE(status.ok());
348
349 // Remove Virtual Tunnel Interface.
350 status = netdutils::statusFromErrno(
351 XfrmController::removeVirtualTunnelInterface("ipsec_test"),
352 "removeVirtualTunnelInterface");
353
354 ASSERT_TRUE(status.ok());
355}
Nathan Harold2deff322018-05-10 14:03:48 -0700356#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700357
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900358static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900359 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900360
361 // Output looks like this:
362 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900363 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900364 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900365 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900366 //
367 // or:
368 //
369 // Chain bw_data_saver (1 references)
370 // target prot opt source destination
371 // ... possibly connectivity critical packet rules here ...
372 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900373
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900374 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900375
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900376 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
377 // Data saver disabled.
378 return 0;
379 }
380
381 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
382
383 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
384 // Data saver enabled.
385 return 1;
386 }
387
388 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900389}
390
391bool enableDataSaver(sp<INetd>& netd, bool enable) {
392 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
393 bool ret;
394 netd->bandwidthEnableDataSaver(enable, &ret);
395 return ret;
396}
397
398int getDataSaverState() {
399 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
400 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
401 EXPECT_EQ(enabled4, enabled6);
402 EXPECT_NE(-1, enabled4);
403 EXPECT_NE(-1, enabled6);
404 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
405 return -1;
406 }
407 return enabled6;
408}
409
410TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
411 const int wasEnabled = getDataSaverState();
412 ASSERT_NE(-1, wasEnabled);
413
414 if (wasEnabled) {
415 ASSERT_TRUE(enableDataSaver(mNetd, false));
416 EXPECT_EQ(0, getDataSaverState());
417 }
418
419 ASSERT_TRUE(enableDataSaver(mNetd, false));
420 EXPECT_EQ(0, getDataSaverState());
421
422 ASSERT_TRUE(enableDataSaver(mNetd, true));
423 EXPECT_EQ(1, getDataSaverState());
424
425 ASSERT_TRUE(enableDataSaver(mNetd, true));
426 EXPECT_EQ(1, getDataSaverState());
427
428 if (!wasEnabled) {
429 ASSERT_TRUE(enableDataSaver(mNetd, false));
430 EXPECT_EQ(0, getDataSaverState());
431 }
432}
Robin Leeb8087362016-03-30 18:43:08 +0100433
434static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
435 const std::string& action, const char* ipVersion) {
436 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100437 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100438 std::vector<std::string> rules = listIpRules(ipVersion);
439
440 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
441 std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
442 range.getStart(), range.getStop(), action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900443 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800444 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100445 return true;
446 }
447 }
448 return false;
449}
450
451static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
452 const std::string& action) {
453 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
454 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
455 EXPECT_EQ(existsIp4, existsIp6);
456 return existsIp4;
457}
458
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900459TEST_F(BinderTest, TestNetworkInterfaces) {
460 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, "").isOk());
461 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, "").serviceSpecificErrorCode());
462 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
463 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
464
465 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
466 EXPECT_EQ(EBUSY,
467 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
468
469 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
470 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
471 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
472}
473
474TEST_F(BinderTest, TestNetworkUidRules) {
475 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
476
477 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
478 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
479 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
480
481 std::vector<UidRange> uidRanges = {
482 {BASE_UID + 8005, BASE_UID + 8012},
483 {BASE_UID + 8090, BASE_UID + 8099}
484 };
485 UidRange otherRange(BASE_UID + 8190, BASE_UID + 8299);
486 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
487
488 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
489
490 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
491 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
492 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
493 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
494
495 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
496 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
497 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
498 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
499
500 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
501}
502
Robin Leeb8087362016-03-30 18:43:08 +0100503TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100504 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100505
Robin Leeb8087362016-03-30 18:43:08 +0100506 std::vector<UidRange> uidRanges = {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900507 {BASE_UID + 150, BASE_UID + 224},
508 {BASE_UID + 226, BASE_UID + 300}
Robin Leeb8087362016-03-30 18:43:08 +0100509 };
510
511 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
512 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
513
514 // Create two valid rules.
515 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
516 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
517 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
518 for (auto const& range : uidRanges) {
519 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
520 }
521
522 // Remove the rules.
523 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
524 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
525 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
526 for (auto const& range : uidRanges) {
527 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
528 }
529
530 // Fail to remove the rules a second time after they are already deleted.
531 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
532 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
533 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
534
535 // All rules should be the same as before.
536 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
537 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
538}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900539
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900540// Create a socket pair that isLoopbackSocket won't think is local.
541void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900542 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900543 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900544 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
545
546 socklen_t addrlen = sizeof(server6);
547 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
548 ASSERT_EQ(0, listen(*serverSocket, 10));
549
Bernie Innocentif6918262018-06-11 17:37:35 +0900550 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900551 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900552 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900553 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
554 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
555
Bernie Innocentif6918262018-06-11 17:37:35 +0900556 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900557 ASSERT_NE(-1, *acceptedSocket);
558
559 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
560}
561
562void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
563 char buf[4096];
564 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
565 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
566 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
567}
568
569void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
570 // Check that the client socket was closed with ECONNABORTED.
571 int ret = write(clientSocket, "foo", sizeof("foo"));
572 int err = errno;
573 EXPECT_EQ(-1, ret);
574 EXPECT_EQ(ECONNABORTED, err);
575
576 // Check that it sent a RST to the server.
577 ret = write(acceptedSocket, "foo", sizeof("foo"));
578 err = errno;
579 EXPECT_EQ(-1, ret);
580 EXPECT_EQ(ECONNRESET, err);
581}
582
583TEST_F(BinderTest, TestSocketDestroy) {
584 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900585 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900586
587 // Pick a random UID in the system UID range.
588 constexpr int baseUid = AID_APP - 2000;
589 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
590 int uid = baseUid + 500 + arc4random_uniform(1000);
591 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
592
593 // UID ranges that don't contain uid.
594 std::vector<UidRange> uidRanges = {
595 {baseUid + 42, baseUid + 449},
596 {baseUid + 1536, AID_APP - 4},
597 {baseUid + 498, uid - 1},
598 {uid + 1, baseUid + 1520},
599 };
600 // A skip list that doesn't contain UID.
601 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
602
603 // Close sockets. Our test socket should be intact.
604 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
605 checkSocketpairOpen(clientSocket, acceptedSocket);
606
607 // UID ranges that do contain uid.
608 uidRanges = {
609 {baseUid + 42, baseUid + 449},
610 {baseUid + 1536, AID_APP - 4},
611 {baseUid + 498, baseUid + 1520},
612 };
613 // Add uid to the skip list.
614 skipUids.push_back(uid);
615
616 // Close sockets. Our test socket should still be intact because it's in the skip list.
617 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
618 checkSocketpairOpen(clientSocket, acceptedSocket);
619
620 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
621 skipUids.resize(skipUids.size() - 1);
622 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
623 checkSocketpairClosed(clientSocket, acceptedSocket);
624
625 close(clientSocket);
626 close(serverSocket);
627 close(acceptedSocket);
628}
Erik Klinecc4f2732016-08-03 11:24:27 +0900629
630namespace {
631
632int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
633 if (buf == nullptr) return -1;
634
635 int prefixLength = 0;
636 bool endOfContiguousBits = false;
637 for (unsigned int i = 0; i < buflen; i++) {
638 const uint8_t value = buf[i];
639
640 // Bad bit sequence: check for a contiguous set of bits from the high
641 // end by verifying that the inverted value + 1 is a power of 2
642 // (power of 2 iff. (v & (v - 1)) == 0).
643 const uint8_t inverse = ~value + 1;
644 if ((inverse & (inverse - 1)) != 0) return -1;
645
646 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
647
648 // Bogus netmask.
649 if (endOfContiguousBits && value != 0) return -1;
650
651 if (value != 0xff) endOfContiguousBits = true;
652 }
653
654 return prefixLength;
655}
656
657template<typename T>
658int netmaskToPrefixLength(const T *p) {
659 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
660}
661
662
663static bool interfaceHasAddress(
664 const std::string &ifname, const char *addrString, int prefixLength) {
665 struct addrinfo *addrinfoList = nullptr;
666 ScopedAddrinfo addrinfoCleanup(addrinfoList);
667
668 const struct addrinfo hints = {
669 .ai_flags = AI_NUMERICHOST,
670 .ai_family = AF_UNSPEC,
671 .ai_socktype = SOCK_DGRAM,
672 };
673 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
674 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
675 return false;
676 }
677
678 struct ifaddrs *ifaddrsList = nullptr;
679 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
680
681 if (getifaddrs(&ifaddrsList) != 0) {
682 return false;
683 }
684
685 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
686 if (std::string(addr->ifa_name) != ifname ||
687 addr->ifa_addr == nullptr ||
688 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
689 continue;
690 }
691
692 switch (addr->ifa_addr->sa_family) {
693 case AF_INET: {
694 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
695 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
696 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
697 continue;
698 }
699
700 if (prefixLength < 0) return true; // not checking prefix lengths
701
702 if (addr->ifa_netmask == nullptr) return false;
703 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
704 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
705 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
706 }
707 case AF_INET6: {
708 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
709 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
710 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
711 continue;
712 }
713
714 if (prefixLength < 0) return true; // not checking prefix lengths
715
716 if (addr->ifa_netmask == nullptr) return false;
717 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
718 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
719 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
720 }
721 default:
722 // Cannot happen because we have already screened for matching
723 // address families at the top of each iteration.
724 continue;
725 }
726 }
727
728 return false;
729}
730
731} // namespace
732
733TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
734 static const struct TestData {
735 const char *addrString;
736 const int prefixLength;
737 const bool expectSuccess;
738 } kTestData[] = {
739 { "192.0.2.1", 24, true },
740 { "192.0.2.2", 25, true },
741 { "192.0.2.3", 32, true },
742 { "192.0.2.4", 33, false },
743 { "192.not.an.ip", 24, false },
744 { "2001:db8::1", 64, true },
745 { "2001:db8::2", 65, true },
746 { "2001:db8::3", 128, true },
747 { "2001:db8::4", 129, false },
748 { "foo:bar::bad", 64, false },
749 };
750
751 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
752 const auto &td = kTestData[i];
753
754 // [1.a] Add the address.
755 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900756 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900757 if (td.expectSuccess) {
758 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
759 } else {
760 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
761 ASSERT_NE(0, status.serviceSpecificErrorCode());
762 }
763
764 // [1.b] Verify the addition meets the expectation.
765 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900766 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900767 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900768 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900769 }
770
771 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900772 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900773 if (td.expectSuccess) {
774 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
775 } else {
776 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
777 ASSERT_NE(0, status.serviceSpecificErrorCode());
778 }
779
780 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900781 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900782 }
783}
Erik Kline55b06f82016-07-04 09:57:18 +0900784
785TEST_F(BinderTest, TestSetProcSysNet) {
786 static const struct TestData {
787 const int family;
788 const int which;
789 const char *ifname;
790 const char *parameter;
791 const char *value;
792 const int expectedReturnCode;
793 } kTestData[] = {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900794 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0 },
795 { -1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT },
796 { INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL },
Erik Kline55b06f82016-07-04 09:57:18 +0900797 { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
798 { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900799 { INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL },
800 { INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0 },
Erik Kline55b06f82016-07-04 09:57:18 +0900801 };
802
803 for (unsigned int i = 0; i < arraysize(kTestData); i++) {
804 const auto &td = kTestData[i];
805
806 const binder::Status status = mNetd->setProcSysNet(
807 td.family, td.which, td.ifname, td.parameter,
808 td.value);
809
810 if (td.expectedReturnCode == 0) {
811 SCOPED_TRACE(String8::format("test case %d should have passed", i));
812 EXPECT_EQ(0, status.exceptionCode());
813 EXPECT_EQ(0, status.serviceSpecificErrorCode());
814 } else {
815 SCOPED_TRACE(String8::format("test case %d should have failed", i));
816 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
817 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
818 }
819 }
820}
Ben Schwartze7601812017-04-28 16:38:29 -0400821
822static std::string base64Encode(const std::vector<uint8_t>& input) {
823 size_t out_len;
824 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
825 // out_len includes the trailing NULL.
826 uint8_t output_bytes[out_len];
827 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
828 return std::string(reinterpret_cast<char*>(output_bytes));
829}
830
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400831TEST_F(BinderTest, TestSetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900832 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400833 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400834 std::vector<uint8_t> short_fp(1);
835 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
836 std::vector<std::string> test_domains;
837 std::vector<int> test_params = { 300, 25, 8, 8 };
838 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400839 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400840 const std::vector<std::string> servers;
841 const std::string tlsName;
842 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400843 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900844 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400845 { {"192.0.2.1"}, "", {}, 0 },
846 { {"2001:db8::2"}, "host.name", {}, 0 },
847 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
848 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900849 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400850 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900851 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400852 { {"2001:dg8::6"}, "", {}, EINVAL },
853 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
854 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
855 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
856 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -0400857 };
858
Erik Klinea1476fb2018-03-04 21:01:56 +0900859 for (unsigned int i = 0; i < arraysize(kTlsTestData); i++) {
860 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -0400861
862 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400863 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -0400864 fingerprints.push_back(base64Encode(fingerprint));
865 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400866 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900867 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
868 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -0400869
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400870 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -0400871 SCOPED_TRACE(String8::format("test case %d should have passed", i));
872 SCOPED_TRACE(status.toString8());
873 EXPECT_EQ(0, status.exceptionCode());
874 } else {
875 SCOPED_TRACE(String8::format("test case %d should have failed", i));
876 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400877 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -0400878 }
Ben Schwartze7601812017-04-28 16:38:29 -0400879 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400880 // Ensure TLS is disabled before the start of the next test.
881 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +0900882 test_netid, kTlsTestData[0].servers, test_domains, test_params,
883 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -0400884}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900885
886void expectNoTestCounterRules() {
887 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
888 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
889 std::string allRules = Join(runCommand(command), "\n");
890 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
891 }
892}
893
Bernie Innocentif6918262018-06-11 17:37:35 +0900894void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
895 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900896 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
897 path, if1.c_str(), if2.c_str(), pkt, byte));
898}
899
Bernie Innocentif6918262018-06-11 17:37:35 +0900900void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900901 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
902 path, if1.c_str(), if2.c_str()));
903 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
904 path, if2.c_str(), if1.c_str()));
905}
906
907TEST_F(BinderTest, TestTetherGetStats) {
908 expectNoTestCounterRules();
909
910 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
911 // disabling tethering. We don't check the return value because these commands will fail if
912 // tethering is already enabled.
913 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
914 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
915
916 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
917 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
918 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
919 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
920 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
921
922 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
923 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
924 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
925 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
926 // RX is from external to internal, and TX is from internal to external.
927 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
928 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
929
930 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
931 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
932
933 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
934 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
935
936 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
937 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
938 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
939
940 PersistableBundle stats;
941 binder::Status status = mNetd->tetherGetStats(&stats);
942 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
943
944 std::vector<int64_t> actual1;
945 EXPECT_TRUE(stats.getLongVector(String16(extIface1.c_str()), &actual1));
946 EXPECT_EQ(expected1, actual1);
947
948 std::vector<int64_t> actual2;
949 EXPECT_TRUE(stats.getLongVector(String16(extIface2.c_str()), &actual2));
950 EXPECT_EQ(expected2, actual2);
951
952 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
953 delTetherCounterValues(path, intIface1, extIface1);
954 delTetherCounterValues(path, intIface2, extIface2);
955 if (path == IP6TABLES_PATH) {
956 delTetherCounterValues(path, intIface3, extIface2);
957 }
958 }
959
960 expectNoTestCounterRules();
961}
Luke Huang0051a622018-07-23 20:30:16 +0800962namespace {
963
964constexpr char chainName_LOCAL_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
965constexpr char chainName_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
966
967static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
968 const char* chainName) {
969 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
970 return runCommand(command);
971}
972
973bool iptablesIdleTimerInterfcaeRuleExists(const char* binary, const char* chainName,
974 const std::string& expectedInterface,
975 const std::string& expectedRule, const char* table) {
976 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
977 for (const auto& rule : rules) {
978 if (rule.find(expectedInterface) != std::string::npos) {
979 if (rule.find(expectedRule) != std::string::npos) {
980 return true;
981 }
982 }
983 }
984 return false;
985}
986
987void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
988 const std::string& classLable) {
989 std::string IdletimerRule =
990 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLable.c_str());
991 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
992 EXPECT_TRUE(iptablesIdleTimerInterfcaeRuleExists(binary, chainName_LOCAL_RAW_PREROUTING,
993 ifname, IdletimerRule, RAW_TABLE));
994 EXPECT_TRUE(iptablesIdleTimerInterfcaeRuleExists(binary, chainName_MANGLE_POSTROUTING,
995 ifname, IdletimerRule, MANGLE_TABLE));
996 }
997}
998
999void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
1000 const std::string& classLable) {
1001 std::string IdletimerRule =
1002 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLable.c_str());
1003 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1004 EXPECT_FALSE(iptablesIdleTimerInterfcaeRuleExists(binary, chainName_LOCAL_RAW_PREROUTING,
1005 ifname, IdletimerRule, RAW_TABLE));
1006 EXPECT_FALSE(iptablesIdleTimerInterfcaeRuleExists(binary, chainName_MANGLE_POSTROUTING,
1007 ifname, IdletimerRule, MANGLE_TABLE));
1008 }
1009}
1010
1011TEST_F(BinderTest, TestIdletimerAddRemoveInterface) {
1012 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1013 // rule in the table. Because we only check the result after calling remove function. We might
1014 // check the actual rule which is removed by our function (maybe compare the results between
1015 // calling function before and after)
1016 binder::Status status;
1017 const struct TestData {
1018 const std::string ifname;
1019 int32_t timeout;
1020 const std::string classLabel;
1021 } idleTestData[] = {
1022 {"wlan0", 1234, "happyday"},
1023 {"rmnet_data0", 4567, "friday"},
1024 };
1025 for (const auto& td : idleTestData) {
1026 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1027 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1028 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1029
1030 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1031 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1032 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1033 }
1034}
1035
1036} // namespace