blob: 1cac36f6235301e59319f32aed31d9086168e394 [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
Luke Huangf7782042018-08-08 13:13:04 +080027#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090028#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090029#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090030#include <linux/if.h>
31#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070032#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080033#include <netdb.h>
34#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040035#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <sys/socket.h>
37#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090038
Luke Huang531f5d32018-08-03 15:19:05 +080039#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090040#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090041#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090042#include <android-base/strings.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070043#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010044#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090045#include <gtest/gtest.h>
46#include <logwrap/logwrap.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090047#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048
Nathan Harold21299f72018-03-16 20:13:03 -070049#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090050#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090051#include "Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070052#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include "android/net/INetd.h"
54#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070055#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080056#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090057
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090058#define IP_PATH "/system/bin/ip"
59#define IP6TABLES_PATH "/system/bin/ip6tables"
60#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090061#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080062#define RAW_TABLE "raw"
63#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080064#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090065#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090066
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090067namespace binder = android::binder;
68namespace netdutils = android::netdutils;
69
70using android::IBinder;
71using android::IServiceManager;
72using android::sp;
73using android::String16;
74using android::String8;
75using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080076using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090077using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090078using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080079using android::base::Trim;
Chenbo Feng837ddfc2018-05-08 13:45:08 -070080using android::bpf::hasBpfSupport;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090081using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080082using android::net::InterfaceConfigurationParcel;
83using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080084using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090085using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090086using android::net::UidRangeParcel;
Nathan Harold21299f72018-03-16 20:13:03 -070087using android::net::XfrmController;
Luke Huangf7782042018-08-08 13:13:04 +080088using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010089
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090090#define SKIP_IF_BPF_SUPPORTED \
91 do { \
92 if (hasBpfSupport()) return; \
93 } while (0)
Chenbo Feng837ddfc2018-05-08 13:45:08 -070094
Robin Leeb8087362016-03-30 18:43:08 +010095static const char* IP_RULE_V4 = "-4";
96static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090097static const int TEST_NETID1 = 65501;
98static const int TEST_NETID2 = 65502;
99constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900100
Benedict Wongb2daefb2017-12-06 22:05:46 -0800101static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
102static const std::string ESP_ALLOW_RULE("esp");
103
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900104class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900105 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900106 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900107 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900108 sp<IBinder> binder = sm->getService(String16("netd"));
109 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900110 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900111 }
112 }
113
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900114 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115 ASSERT_NE(nullptr, mNetd.get());
116 }
117
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900118 void TearDown() override {
119 mNetd->networkDestroy(TEST_NETID1);
120 mNetd->networkDestroy(TEST_NETID2);
121 }
122
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900123 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700124
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900125 // Static because setting up the tun interface takes about 40ms.
126 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900127 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900128 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900129 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900130 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900131 }
132
133 static void TearDownTestCase() {
134 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900135 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900136 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900137 }
138
139 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900140
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900141 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900142 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900143 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900144 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900145};
146
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900147TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900148TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900149
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900150class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900151 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700152 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900153 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900154 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900155 }
156
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900157 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900158 std::string mName;
159};
160
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900161TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900162 TimedOperation t("isAlive RPC");
163 bool isAlive = false;
164 mNetd->isAlive(&isAlive);
165 ASSERT_TRUE(isAlive);
166}
167
168static int randomUid() {
169 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
170}
171
Robin Leeb8087362016-03-30 18:43:08 +0100172static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900173 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900174 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
175 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900176 perror("popen");
177 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900178 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900179
180 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100181 size_t bufsize = 0;
182 ssize_t linelen = 0;
183 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900184 lines.push_back(std::string(line, linelen));
185 free(line);
186 line = nullptr;
187 }
188
189 pclose(f);
190 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900191}
192
Robin Leeb8087362016-03-30 18:43:08 +0100193static std::vector<std::string> listIpRules(const char *ipVersion) {
194 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
195 return runCommand(command);
196}
197
198static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900199 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100200 return runCommand(command);
201}
202
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900203static int iptablesRuleLineLength(const char *binary, const char *chainName) {
204 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900205}
206
Benedict Wongb2daefb2017-12-06 22:05:46 -0800207static bool iptablesRuleExists(const char *binary,
208 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900209 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800210 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900211 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800212 if(rule.find(expectedRule) != std::string::npos) {
213 return true;
214 }
215 }
216 return false;
217}
218
219static bool iptablesNoSocketAllowRuleExists(const char *chainName){
220 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
221 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
222}
223
224static bool iptablesEspAllowRuleExists(const char *chainName){
225 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
226 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
227}
228
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900229TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700230 SKIP_IF_BPF_SUPPORTED;
231
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900232 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
233 const int kNumUids = 500;
234 std::vector<int32_t> noUids(0);
235 std::vector<int32_t> uids(kNumUids);
236 for (int i = 0; i < kNumUids; i++) {
237 uids[i] = randomUid();
238 }
239
240 bool ret;
241 {
242 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900243 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900244 }
245 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800246 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
247 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
248 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
249 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900250 {
251 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900252 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900253 }
254 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900255 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
256 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900257
258 {
259 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900260 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900261 }
262 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900263 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
264 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800265 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
266 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900267
268 {
269 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900270 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900271 }
272 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900273 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
274 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900275
276 // Check that the call fails if iptables returns an error.
277 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900278 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900279 EXPECT_EQ(false, ret);
280}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900281
Benedict Wong319f17e2018-05-15 17:06:44 -0700282TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700283 const struct TestData {
284 const std::string family;
285 const std::string deviceName;
286 const std::string localAddress;
287 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800288 int32_t iKey;
289 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700290 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800291 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700292 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
293 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
294 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800295 };
296
Luke Huangc3252cc2018-10-16 15:43:23 +0800297 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700298 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800299
300 binder::Status status;
301
Benedict Wong319f17e2018-05-15 17:06:44 -0700302 // Create Tunnel Interface.
303 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700304 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800305 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
306
Benedict Wonga450e722018-05-07 10:29:02 -0700307 // Check that the interface exists
308 EXPECT_NE(0, if_nametoindex(td.deviceName.c_str()));
309
Benedict Wong319f17e2018-05-15 17:06:44 -0700310 // Update Tunnel Interface.
311 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700312 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800313 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
314
Benedict Wong319f17e2018-05-15 17:06:44 -0700315 // Remove Tunnel Interface.
316 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800317 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700318
319 // Check that the interface no longer exists
320 EXPECT_EQ(0, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800321 }
322}
323
Nathan Harold2deff322018-05-10 14:03:48 -0700324// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
325// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
326#if INTPTR_MAX != INT32_MAX
Benedict Wonga04ffa72018-05-09 21:42:42 -0700327static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
328 static_cast<int>(android::net::XfrmDirection::OUT)};
329static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
330
Nathan Harold21299f72018-03-16 20:13:03 -0700331#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
332 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900333bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Nathan Harold21299f72018-03-16 20:13:03 -0700334 netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
335 SCOPED_TRACE(status);
336 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
337
338 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700339 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700340 SCOPED_TRACE(status);
341 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
342
343 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700344 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
345 0xD00D, 0xE00D, false)
346 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700347}
348
Benedict Wonga04ffa72018-05-09 21:42:42 -0700349TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
350 binder::Status status;
351
352 // Repeat to ensure cleanup and recreation works correctly
353 for (int i = 0; i < 2; i++) {
354 for (int direction : XFRM_DIRECTIONS) {
355 for (int addrFamily : ADDRESS_FAMILIES) {
356 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700357 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700358 EXPECT_TRUE(status.isOk())
359 << " family: " << addrFamily << " direction: " << direction;
360 }
361 }
362
363 // Cleanup
364 for (int direction : XFRM_DIRECTIONS) {
365 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700366 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700367 EXPECT_TRUE(status.isOk());
368 }
369 }
370 }
371}
372
373TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
374 binder::Status status;
375
376 // Repeat to ensure cleanup and recreation works correctly
377 for (int i = 0; i < 2; i++) {
378 for (int direction : XFRM_DIRECTIONS) {
379 for (int addrFamily : ADDRESS_FAMILIES) {
380 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700381 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700382 EXPECT_TRUE(status.isOk())
383 << " family: " << addrFamily << " direction: " << direction;
384 }
385 }
386
387 // Cleanup
388 for (int direction : XFRM_DIRECTIONS) {
389 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700390 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700391 EXPECT_TRUE(status.isOk());
392 }
393 }
394 }
395}
396
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900397TEST_F(BinderTest, XfrmControllerInit) {
Nathan Harold21299f72018-03-16 20:13:03 -0700398 netdutils::Status status;
399 status = XfrmController::Init();
400 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700401
402 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
403 // feature.
404 if (status.code() == EOPNOTSUPP) return;
405
Nathan Harold21299f72018-03-16 20:13:03 -0700406 ASSERT_TRUE(status.ok());
407
408 int32_t spi = 0;
409
410 ASSERT_TRUE(allocateIpSecResources(true, &spi));
411 ASSERT_TRUE(allocateIpSecResources(false, &spi));
412
413 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700414 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700415 ASSERT_TRUE(allocateIpSecResources(true, &spi));
416
417 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700418 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700419 SCOPED_TRACE(status);
420 ASSERT_TRUE(status.ok());
421
Benedict Wonga450e722018-05-07 10:29:02 -0700422 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700423 SCOPED_TRACE(status);
424 ASSERT_TRUE(status.ok());
425
426 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700427 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700428}
Nathan Harold2deff322018-05-10 14:03:48 -0700429#endif
Nathan Harold21299f72018-03-16 20:13:03 -0700430
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900431static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900432 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900433
434 // Output looks like this:
435 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900436 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900437 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900438 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900439 //
440 // or:
441 //
442 // Chain bw_data_saver (1 references)
443 // target prot opt source destination
444 // ... possibly connectivity critical packet rules here ...
445 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900446
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900447 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900448
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900449 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
450 // Data saver disabled.
451 return 0;
452 }
453
454 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
455
456 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
457 // Data saver enabled.
458 return 1;
459 }
460
461 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900462}
463
464bool enableDataSaver(sp<INetd>& netd, bool enable) {
465 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
466 bool ret;
467 netd->bandwidthEnableDataSaver(enable, &ret);
468 return ret;
469}
470
471int getDataSaverState() {
472 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
473 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
474 EXPECT_EQ(enabled4, enabled6);
475 EXPECT_NE(-1, enabled4);
476 EXPECT_NE(-1, enabled6);
477 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
478 return -1;
479 }
480 return enabled6;
481}
482
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900483TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900484 const int wasEnabled = getDataSaverState();
485 ASSERT_NE(-1, wasEnabled);
486
487 if (wasEnabled) {
488 ASSERT_TRUE(enableDataSaver(mNetd, false));
489 EXPECT_EQ(0, getDataSaverState());
490 }
491
492 ASSERT_TRUE(enableDataSaver(mNetd, false));
493 EXPECT_EQ(0, getDataSaverState());
494
495 ASSERT_TRUE(enableDataSaver(mNetd, true));
496 EXPECT_EQ(1, getDataSaverState());
497
498 ASSERT_TRUE(enableDataSaver(mNetd, true));
499 EXPECT_EQ(1, getDataSaverState());
500
501 if (!wasEnabled) {
502 ASSERT_TRUE(enableDataSaver(mNetd, false));
503 EXPECT_EQ(0, getDataSaverState());
504 }
505}
Robin Leeb8087362016-03-30 18:43:08 +0100506
Luke Huang94658ac2018-10-18 19:35:12 +0900507static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
508 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100509 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100510 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100511 std::vector<std::string> rules = listIpRules(ipVersion);
512
513 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900514 std::string suffix =
515 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900516 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800517 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100518 return true;
519 }
520 }
521 return false;
522}
523
Luke Huang94658ac2018-10-18 19:35:12 +0900524static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
525 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100526 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
527 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
528 EXPECT_EQ(existsIp4, existsIp6);
529 return existsIp4;
530}
531
Luke Huang94658ac2018-10-18 19:35:12 +0900532namespace {
533
534UidRangeParcel makeUidRangeParcel(int start, int stop) {
535 UidRangeParcel res;
536 res.start = start;
537 res.stop = stop;
538
539 return res;
540}
541
542} // namespace
543
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900544TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800545 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
546 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
547 .serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900548 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
549 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, false, true).isOk());
550
551 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
552 EXPECT_EQ(EBUSY,
553 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
554
555 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
556 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
557 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800558 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900559}
560
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900561TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900562 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
563
564 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, false, true).isOk());
565 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, false, true).serviceSpecificErrorCode());
566 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
567
Luke Huang94658ac2018-10-18 19:35:12 +0900568 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
569 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
570 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900571 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
572
573 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
574
575 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
576 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
577 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
578 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
579
580 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
581 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
582 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
583 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
584
585 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
586}
587
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900588TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100589 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100590
Luke Huang94658ac2018-10-18 19:35:12 +0900591 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
592 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100593
594 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
595 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
596
597 // Create two valid rules.
598 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
599 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
600 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
601 for (auto const& range : uidRanges) {
602 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
603 }
604
605 // Remove the rules.
606 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
607 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
608 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
609 for (auto const& range : uidRanges) {
610 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
611 }
612
613 // Fail to remove the rules a second time after they are already deleted.
614 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
615 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
616 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
617
618 // All rules should be the same as before.
619 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
620 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
621}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900622
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900623// Create a socket pair that isLoopbackSocket won't think is local.
624void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900625 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900626 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900627 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
628
629 socklen_t addrlen = sizeof(server6);
630 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
631 ASSERT_EQ(0, listen(*serverSocket, 10));
632
Bernie Innocentif6918262018-06-11 17:37:35 +0900633 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900634 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900635 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900636 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
637 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
638
Bernie Innocentif6918262018-06-11 17:37:35 +0900639 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900640 ASSERT_NE(-1, *acceptedSocket);
641
642 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
643}
644
645void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
646 char buf[4096];
647 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
648 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
649 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
650}
651
652void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
653 // Check that the client socket was closed with ECONNABORTED.
654 int ret = write(clientSocket, "foo", sizeof("foo"));
655 int err = errno;
656 EXPECT_EQ(-1, ret);
657 EXPECT_EQ(ECONNABORTED, err);
658
659 // Check that it sent a RST to the server.
660 ret = write(acceptedSocket, "foo", sizeof("foo"));
661 err = errno;
662 EXPECT_EQ(-1, ret);
663 EXPECT_EQ(ECONNRESET, err);
664}
665
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900666TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900667 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900668 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900669
670 // Pick a random UID in the system UID range.
671 constexpr int baseUid = AID_APP - 2000;
672 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
673 int uid = baseUid + 500 + arc4random_uniform(1000);
674 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
675
676 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900677 std::vector<UidRangeParcel> uidRanges = {
678 makeUidRangeParcel(baseUid + 42, baseUid + 449),
679 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
680 makeUidRangeParcel(baseUid + 498, uid - 1),
681 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900682 };
683 // A skip list that doesn't contain UID.
684 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
685
686 // Close sockets. Our test socket should be intact.
687 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
688 checkSocketpairOpen(clientSocket, acceptedSocket);
689
690 // UID ranges that do contain uid.
691 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900692 makeUidRangeParcel(baseUid + 42, baseUid + 449),
693 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
694 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900695 };
696 // Add uid to the skip list.
697 skipUids.push_back(uid);
698
699 // Close sockets. Our test socket should still be intact because it's in the skip list.
700 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
701 checkSocketpairOpen(clientSocket, acceptedSocket);
702
703 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
704 skipUids.resize(skipUids.size() - 1);
705 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
706 checkSocketpairClosed(clientSocket, acceptedSocket);
707
708 close(clientSocket);
709 close(serverSocket);
710 close(acceptedSocket);
711}
Erik Klinecc4f2732016-08-03 11:24:27 +0900712
713namespace {
714
715int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
716 if (buf == nullptr) return -1;
717
718 int prefixLength = 0;
719 bool endOfContiguousBits = false;
720 for (unsigned int i = 0; i < buflen; i++) {
721 const uint8_t value = buf[i];
722
723 // Bad bit sequence: check for a contiguous set of bits from the high
724 // end by verifying that the inverted value + 1 is a power of 2
725 // (power of 2 iff. (v & (v - 1)) == 0).
726 const uint8_t inverse = ~value + 1;
727 if ((inverse & (inverse - 1)) != 0) return -1;
728
729 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
730
731 // Bogus netmask.
732 if (endOfContiguousBits && value != 0) return -1;
733
734 if (value != 0xff) endOfContiguousBits = true;
735 }
736
737 return prefixLength;
738}
739
740template<typename T>
741int netmaskToPrefixLength(const T *p) {
742 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
743}
744
745
746static bool interfaceHasAddress(
747 const std::string &ifname, const char *addrString, int prefixLength) {
748 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900749
750 const struct addrinfo hints = {
751 .ai_flags = AI_NUMERICHOST,
752 .ai_family = AF_UNSPEC,
753 .ai_socktype = SOCK_DGRAM,
754 };
755 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
756 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
757 return false;
758 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900759 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900760
761 struct ifaddrs *ifaddrsList = nullptr;
762 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
763
764 if (getifaddrs(&ifaddrsList) != 0) {
765 return false;
766 }
767
768 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
769 if (std::string(addr->ifa_name) != ifname ||
770 addr->ifa_addr == nullptr ||
771 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
772 continue;
773 }
774
775 switch (addr->ifa_addr->sa_family) {
776 case AF_INET: {
777 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
778 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
779 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
780 continue;
781 }
782
783 if (prefixLength < 0) return true; // not checking prefix lengths
784
785 if (addr->ifa_netmask == nullptr) return false;
786 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
787 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
788 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
789 }
790 case AF_INET6: {
791 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
792 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
793 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
794 continue;
795 }
796
797 if (prefixLength < 0) return true; // not checking prefix lengths
798
799 if (addr->ifa_netmask == nullptr) return false;
800 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
801 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
802 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
803 }
804 default:
805 // Cannot happen because we have already screened for matching
806 // address families at the top of each iteration.
807 continue;
808 }
809 }
810
811 return false;
812}
813
814} // namespace
815
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900816TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900817 static const struct TestData {
818 const char *addrString;
819 const int prefixLength;
820 const bool expectSuccess;
821 } kTestData[] = {
822 { "192.0.2.1", 24, true },
823 { "192.0.2.2", 25, true },
824 { "192.0.2.3", 32, true },
825 { "192.0.2.4", 33, false },
826 { "192.not.an.ip", 24, false },
827 { "2001:db8::1", 64, true },
828 { "2001:db8::2", 65, true },
829 { "2001:db8::3", 128, true },
830 { "2001:db8::4", 129, false },
831 { "foo:bar::bad", 64, false },
832 };
833
Luke Huangc3252cc2018-10-16 15:43:23 +0800834 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900835 const auto &td = kTestData[i];
836
837 // [1.a] Add the address.
838 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900839 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900840 if (td.expectSuccess) {
841 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
842 } else {
843 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
844 ASSERT_NE(0, status.serviceSpecificErrorCode());
845 }
846
847 // [1.b] Verify the addition meets the expectation.
848 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900849 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900850 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900851 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900852 }
853
854 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900855 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900856 if (td.expectSuccess) {
857 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
858 } else {
859 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
860 ASSERT_NE(0, status.serviceSpecificErrorCode());
861 }
862
863 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900864 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900865 }
866}
Erik Kline55b06f82016-07-04 09:57:18 +0900867
Erik Kline38e51f12018-09-06 20:14:44 +0900868TEST_F(BinderTest, GetProcSysNet) {
869 const char LOOPBACK[] = "lo";
870 static const struct {
871 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900872 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900873 const char* ifname;
874 const char* parameter;
875 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900876 const int expectedReturnCode;
877 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900878 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
879 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
880 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
881 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
882 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
883 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
884 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900885 };
886
Luke Huangc3252cc2018-10-16 15:43:23 +0800887 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900888 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900889
Erik Kline38e51f12018-09-06 20:14:44 +0900890 std::string value;
891 const binder::Status status =
892 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
893
894 if (td.expectedReturnCode == 0) {
895 SCOPED_TRACE(String8::format("test case %d should have passed", i));
896 EXPECT_EQ(0, status.exceptionCode());
897 EXPECT_EQ(0, status.serviceSpecificErrorCode());
898 EXPECT_EQ(td.expectedValue, value);
899 } else {
900 SCOPED_TRACE(String8::format("test case %d should have failed", i));
901 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
902 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
903 }
904 }
905}
906
907TEST_F(BinderTest, SetProcSysNet) {
908 static const struct {
909 const int ipversion;
910 const int which;
911 const char* ifname;
912 const char* parameter;
913 const char* value;
914 const int expectedReturnCode;
915 } kTestData[] = {
916 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
917 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
918 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
919 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
920 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
921 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
922 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
923 };
924
Luke Huangc3252cc2018-10-16 15:43:23 +0800925 for (int i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900926 const auto& td = kTestData[i];
927
928 const binder::Status status =
929 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900930
931 if (td.expectedReturnCode == 0) {
932 SCOPED_TRACE(String8::format("test case %d should have passed", i));
933 EXPECT_EQ(0, status.exceptionCode());
934 EXPECT_EQ(0, status.serviceSpecificErrorCode());
935 } else {
936 SCOPED_TRACE(String8::format("test case %d should have failed", i));
937 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
938 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
939 }
940 }
941}
Ben Schwartze7601812017-04-28 16:38:29 -0400942
Erik Kline38e51f12018-09-06 20:14:44 +0900943TEST_F(BinderTest, GetSetProcSysNet) {
944 const int ipversion = INetd::IPV6;
945 const int category = INetd::NEIGH;
946 const std::string& tun = sTun.name();
947 const std::string parameter("ucast_solicit");
948
949 std::string value{};
950 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
951 EXPECT_FALSE(value.empty());
952 const int ival = std::stoi(value);
953 EXPECT_GT(ival, 0);
954 // Try doubling the parameter value (always best!).
955 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
956 .isOk());
957 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
958 EXPECT_EQ(2 * ival, std::stoi(value));
959 // Try resetting the parameter.
960 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
961 .isOk());
962 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
963 EXPECT_EQ(ival, std::stoi(value));
964}
965
Ben Schwartze7601812017-04-28 16:38:29 -0400966static std::string base64Encode(const std::vector<uint8_t>& input) {
967 size_t out_len;
968 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
969 // out_len includes the trailing NULL.
970 uint8_t output_bytes[out_len];
971 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
972 return std::string(reinterpret_cast<char*>(output_bytes));
973}
974
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900975TEST_F(BinderTest, SetResolverConfiguration_Tls) {
Erik Klinea1476fb2018-03-04 21:01:56 +0900976 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
Ben Schwartze7601812017-04-28 16:38:29 -0400977 std::vector<uint8_t> fp(SHA256_SIZE);
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400978 std::vector<uint8_t> short_fp(1);
979 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
980 std::vector<std::string> test_domains;
981 std::vector<int> test_params = { 300, 25, 8, 8 };
982 unsigned test_netid = 0;
Ben Schwartze7601812017-04-28 16:38:29 -0400983 static const struct TestData {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400984 const std::vector<std::string> servers;
985 const std::string tlsName;
986 const std::vector<std::vector<uint8_t>> tlsFingerprints;
Ben Schwartze7601812017-04-28 16:38:29 -0400987 const int expectedReturnCode;
Erik Klinea1476fb2018-03-04 21:01:56 +0900988 } kTlsTestData[] = {
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400989 { {"192.0.2.1"}, "", {}, 0 },
990 { {"2001:db8::2"}, "host.name", {}, 0 },
991 { {"192.0.2.3"}, "@@@@", { fp }, 0 },
992 { {"2001:db8::4"}, "", { fp }, 0 },
Erik Klinea1476fb2018-03-04 21:01:56 +0900993 { {}, "", {}, 0 },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400994 { {""}, "", {}, EINVAL },
Erik Klinea1476fb2018-03-04 21:01:56 +0900995 { {"192.0.*.5"}, "", {}, EINVAL },
Ben Schwartz4204ecf2017-10-02 12:35:48 -0400996 { {"2001:dg8::6"}, "", {}, EINVAL },
997 { {"2001:db8::c"}, "", { short_fp }, EINVAL },
998 { {"192.0.2.12"}, "", { long_fp }, EINVAL },
999 { {"2001:db8::e"}, "", { fp, fp, fp }, 0 },
1000 { {"192.0.2.14"}, "", { fp, short_fp }, EINVAL },
Ben Schwartze7601812017-04-28 16:38:29 -04001001 };
1002
Luke Huangc3252cc2018-10-16 15:43:23 +08001003 for (unsigned int i = 0; i < std::size(kTlsTestData); i++) {
Erik Klinea1476fb2018-03-04 21:01:56 +09001004 const auto &td = kTlsTestData[i];
Ben Schwartze7601812017-04-28 16:38:29 -04001005
1006 std::vector<std::string> fingerprints;
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001007 for (const auto& fingerprint : td.tlsFingerprints) {
Ben Schwartze7601812017-04-28 16:38:29 -04001008 fingerprints.push_back(base64Encode(fingerprint));
1009 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001010 binder::Status status = mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001011 test_netid, LOCALLY_ASSIGNED_DNS, test_domains, test_params,
1012 td.tlsName, td.servers, fingerprints);
Ben Schwartze7601812017-04-28 16:38:29 -04001013
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001014 if (td.expectedReturnCode == 0) {
Ben Schwartze7601812017-04-28 16:38:29 -04001015 SCOPED_TRACE(String8::format("test case %d should have passed", i));
1016 SCOPED_TRACE(status.toString8());
1017 EXPECT_EQ(0, status.exceptionCode());
1018 } else {
1019 SCOPED_TRACE(String8::format("test case %d should have failed", i));
1020 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001021 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
Ben Schwartze7601812017-04-28 16:38:29 -04001022 }
Ben Schwartze7601812017-04-28 16:38:29 -04001023 }
Ben Schwartz4204ecf2017-10-02 12:35:48 -04001024 // Ensure TLS is disabled before the start of the next test.
1025 mNetd->setResolverConfiguration(
Erik Klinea1476fb2018-03-04 21:01:56 +09001026 test_netid, kTlsTestData[0].servers, test_domains, test_params,
1027 "", {}, {});
Ben Schwartze7601812017-04-28 16:38:29 -04001028}
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001029
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001030namespace {
1031
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001032void expectNoTestCounterRules() {
1033 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1034 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1035 std::string allRules = Join(runCommand(command), "\n");
1036 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1037 }
1038}
1039
Bernie Innocentif6918262018-06-11 17:37:35 +09001040void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1041 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001042 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1043 path, if1.c_str(), if2.c_str(), pkt, byte));
1044}
1045
Bernie Innocentif6918262018-06-11 17:37:35 +09001046void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001047 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1048 path, if1.c_str(), if2.c_str()));
1049 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1050 path, if2.c_str(), if1.c_str()));
1051}
1052
Luke Huangcaebcbb2018-09-27 20:37:14 +08001053std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1054 const std::string& iface) {
1055 for (auto& stats : statsVec) {
1056 if (stats.iface == iface) {
1057 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1058 }
1059 }
1060 return {};
1061}
1062
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001063} // namespace
1064
1065TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001066 expectNoTestCounterRules();
1067
1068 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1069 // disabling tethering. We don't check the return value because these commands will fail if
1070 // tethering is already enabled.
1071 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1072 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1073
1074 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1075 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1076 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1077 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1078 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1079
1080 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1081 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1082 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1083 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1084 // RX is from external to internal, and TX is from internal to external.
1085 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1086 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1087
1088 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1089 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1090
1091 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1092 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1093
1094 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1095 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1096 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1097
Luke Huangcaebcbb2018-09-27 20:37:14 +08001098 std::vector<TetherStatsParcel> statsVec;
1099 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001100 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1101
Luke Huangcaebcbb2018-09-27 20:37:14 +08001102 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001103
Luke Huangcaebcbb2018-09-27 20:37:14 +08001104 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001105
1106 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1107 delTetherCounterValues(path, intIface1, extIface1);
1108 delTetherCounterValues(path, intIface2, extIface2);
1109 if (path == IP6TABLES_PATH) {
1110 delTetherCounterValues(path, intIface3, extIface2);
1111 }
1112 }
1113
1114 expectNoTestCounterRules();
1115}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001116
Luke Huang0051a622018-07-23 20:30:16 +08001117namespace {
1118
Luke Huanga5211072018-08-01 23:36:29 +08001119constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1120constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001121
1122static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1123 const char* chainName) {
1124 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1125 return runCommand(command);
1126}
1127
Luke Huang19b49c52018-10-22 12:12:05 +09001128// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001129bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001130 const std::string& expectedInterface,
1131 const std::string& expectedRule, const char* table) {
1132 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1133 for (const auto& rule : rules) {
1134 if (rule.find(expectedInterface) != std::string::npos) {
1135 if (rule.find(expectedRule) != std::string::npos) {
1136 return true;
1137 }
1138 }
1139 }
1140 return false;
1141}
1142
1143void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001144 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001145 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001146 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001147 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001148 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1149 IdletimerRule, RAW_TABLE));
1150 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001151 ifname, IdletimerRule, MANGLE_TABLE));
1152 }
1153}
1154
1155void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001156 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001157 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001158 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001159 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001160 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1161 IdletimerRule, RAW_TABLE));
1162 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001163 ifname, IdletimerRule, MANGLE_TABLE));
1164 }
1165}
1166
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001167} // namespace
1168
1169TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001170 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1171 // rule in the table. Because we only check the result after calling remove function. We might
1172 // check the actual rule which is removed by our function (maybe compare the results between
1173 // calling function before and after)
1174 binder::Status status;
1175 const struct TestData {
1176 const std::string ifname;
1177 int32_t timeout;
1178 const std::string classLabel;
1179 } idleTestData[] = {
1180 {"wlan0", 1234, "happyday"},
1181 {"rmnet_data0", 4567, "friday"},
1182 };
1183 for (const auto& td : idleTestData) {
1184 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1185 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1186 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1187
1188 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1189 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1190 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1191 }
1192}
1193
Luke Huanga67dd562018-07-17 19:58:25 +08001194namespace {
1195
1196constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1197constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1198
1199void expectStrictSetUidAccept(const int uid) {
1200 std::string uidRule = StringPrintf("owner UID match %u", uid);
1201 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1202 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1203 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1204 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1205 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1206 }
1207}
1208
1209void expectStrictSetUidLog(const int uid) {
1210 static const char logRule[] = "st_penalty_log all";
1211 std::string uidRule = StringPrintf("owner UID match %u", uid);
1212 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1213 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1214 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1215 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1216 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1217 }
1218}
1219
1220void expectStrictSetUidReject(const int uid) {
1221 static const char rejectRule[] = "st_penalty_reject all";
1222 std::string uidRule = StringPrintf("owner UID match %u", uid);
1223 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1224 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1225 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule.c_str()));
1226 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule.c_str()));
1227 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1228 }
1229}
1230
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001231} // namespace
1232
1233TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001234 binder::Status status;
1235 int32_t uid = randomUid();
1236
1237 // setUidCleartextPenalty Policy:Log with randomUid
1238 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1239 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1240 expectStrictSetUidLog(uid);
1241
1242 // setUidCleartextPenalty Policy:Accept with randomUid
1243 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1244 expectStrictSetUidAccept(uid);
1245
1246 // setUidCleartextPenalty Policy:Reject with randomUid
1247 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1248 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1249 expectStrictSetUidReject(uid);
1250
1251 // setUidCleartextPenalty Policy:Accept with randomUid
1252 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1253 expectStrictSetUidAccept(uid);
1254
1255 // test wrong policy
1256 int32_t wrongPolicy = -123;
1257 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1258 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1259}
1260
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001261namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001262
Luke Huanga5211072018-08-01 23:36:29 +08001263bool processExists(const std::string& processName) {
Luke Huang6d301232018-08-01 14:05:18 +08001264 std::string cmd = StringPrintf("ps -A | grep '%s'", processName.c_str());
1265 return (runCommand(cmd.c_str()).size()) ? true : false;
1266}
1267
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001268} // namespace
1269
1270TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001271 binder::Status status;
1272 // use dummy0 for test since it is set ready
1273 static const char testIf[] = "dummy0";
1274 const std::string clatdName = StringPrintf("clatd-%s", testIf);
1275
1276 status = mNetd->clatdStart(testIf);
1277 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1278 EXPECT_TRUE(processExists(clatdName));
1279
1280 mNetd->clatdStop(testIf);
1281 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1282 EXPECT_FALSE(processExists(clatdName));
1283}
Luke Huang457d4702018-08-16 15:39:15 +08001284
1285namespace {
1286
1287bool getIpfwdV4Enable() {
1288 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1289 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1290 EXPECT_TRUE(!result.empty());
1291 int v4Enable = std::stoi(result[0]);
1292 return v4Enable;
1293}
1294
1295bool getIpfwdV6Enable() {
1296 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1297 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1298 EXPECT_TRUE(!result.empty());
1299 int v6Enable = std::stoi(result[0]);
1300 return v6Enable;
1301}
1302
1303void expectIpfwdEnable(bool enable) {
1304 int enableIPv4 = getIpfwdV4Enable();
1305 int enableIPv6 = getIpfwdV6Enable();
1306 EXPECT_EQ(enable, enableIPv4);
1307 EXPECT_EQ(enable, enableIPv6);
1308}
1309
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001310bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001311 std::vector<std::string> rules = listIpRules(ipVersion);
1312 for (const auto& rule : rules) {
1313 if (rule.find(ipfwdRule) != std::string::npos) {
1314 return true;
1315 }
1316 }
1317 return false;
1318}
1319
1320void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1321 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1322
1323 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1324 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1325 }
1326}
1327
1328void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1329 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1330
1331 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1332 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1333 }
1334}
1335
1336} // namespace
1337
1338TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
1339 // Netd default enable Ipfwd with requester NetdHwService
1340 const std::string defaultRequester = "NetdHwService";
1341
1342 binder::Status status = mNetd->ipfwdDisableForwarding(defaultRequester);
1343 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1344 expectIpfwdEnable(false);
1345
1346 bool ipfwdEnabled;
1347 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1348 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1349 EXPECT_FALSE(ipfwdEnabled);
1350
1351 status = mNetd->ipfwdEnableForwarding(defaultRequester);
1352 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1353 expectIpfwdEnable(true);
1354
1355 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1356 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1357 EXPECT_TRUE(ipfwdEnabled);
1358}
1359
1360TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
1361 static const char testFromIf[] = "dummy0";
1362 static const char testToIf[] = "dummy0";
1363
1364 binder::Status status = mNetd->ipfwdAddInterfaceForward(testFromIf, testToIf);
1365 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1366 expectIpfwdRuleExists(testFromIf, testToIf);
1367
1368 status = mNetd->ipfwdRemoveInterfaceForward(testFromIf, testToIf);
1369 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1370 expectIpfwdRuleNotExists(testFromIf, testToIf);
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001371}
Luke Huang531f5d32018-08-03 15:19:05 +08001372
1373namespace {
1374
1375constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1376constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1377constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1378constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1379constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001380constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001381
Luke Huang19b49c52018-10-22 12:12:05 +09001382// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1383// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001384bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1385 const char* chainName, const std::string& expectedTargetA,
1386 const std::string& expectedTargetB) {
1387 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1388 int matchCount = 0;
1389
1390 for (const auto& rule : rules) {
1391 if (rule.find(expectedTargetA) != std::string::npos) {
1392 if (rule.find(expectedTargetB) != std::string::npos) {
1393 matchCount++;
1394 }
1395 }
1396 }
1397 return matchCount == expectedCount;
1398}
1399
1400void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1401 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1402 std::string result = "";
1403
1404 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001405 // Quota value might be decreased while matching packets
1406 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001407}
1408
1409void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1410 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1411 std::string quotaRule = StringPrintf("quota %s", ifname);
1412
1413 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1414 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1415 BANDWIDTH_COSTLY_IF));
1416 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1417 BANDWIDTH_COSTLY_IF));
1418 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1419 BANDWIDTH_COSTLY_IF));
1420 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1421 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1422 }
1423 expectXtQuotaValueEqual(ifname, quotaBytes);
1424}
1425
1426void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1427 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1428 std::string quotaRule = StringPrintf("quota %s", ifname);
1429
1430 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1431 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1432 BANDWIDTH_COSTLY_IF));
1433 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1434 BANDWIDTH_COSTLY_IF));
1435 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1436 BANDWIDTH_COSTLY_IF));
1437 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1438 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1439 }
1440}
1441
1442void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1443 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1444 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1445 std::string alertName = StringPrintf("%sAlert", ifname);
1446
1447 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1448 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1449 }
1450 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1451}
1452
1453void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1454 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1455 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1456
1457 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1458 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1459 }
1460}
1461
1462void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1463 static const char globalAlertRule[] = "quota globalAlert";
1464 static const char globalAlertName[] = "globalAlert";
1465
1466 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001467 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001468 }
1469 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1470}
1471
1472void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1473 std::string uidRule = StringPrintf("owner UID match %u", uid);
1474
1475 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1476 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1477 }
1478}
1479
1480void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1481 std::string uidRule = StringPrintf("owner UID match %u", uid);
1482
1483 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1484 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1485 }
1486}
1487
1488} // namespace
1489
1490TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1491 long testQuotaBytes = 5550;
1492
1493 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001494 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001495 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1496
1497 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1498 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1499 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1500
1501 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1502 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1503 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1504
1505 // Remove test physical network
1506 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1507}
1508
1509TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1510 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001511 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001512 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001513 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001514 // Need to have a prior interface quota set to set an alert
1515 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1516 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1517 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1518 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1519
1520 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1521 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1522 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1523
1524 // Remove interface quota
1525 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1526 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1527 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1528
1529 // Remove test physical network
1530 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1531}
1532
1533TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1534 long testAlertBytes = 2097149;
1535
1536 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1537 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1538 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1539
1540 testAlertBytes = 2097152;
1541 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1542 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1543 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1544}
1545
1546TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1547 SKIP_IF_BPF_SUPPORTED;
1548
1549 int32_t uid = randomUid();
1550 static const char targetReject[] = "REJECT";
1551 static const char targetReturn[] = "RETURN";
1552
1553 // add NaughtyApp
1554 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1555 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1556 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1557
1558 // remove NaughtyApp
1559 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1560 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1561 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1562
1563 // add NiceApp
1564 status = mNetd->bandwidthAddNiceApp(uid);
1565 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1566 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1567
1568 // remove NiceApp
1569 status = mNetd->bandwidthRemoveNiceApp(uid);
1570 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1571 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1572}
Luke Huangb5733d72018-08-21 17:17:19 +08001573
1574namespace {
1575
Luke Huangb670d162018-08-23 20:01:13 +08001576std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1577 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1578 return runCommand(command);
1579}
1580
Luke Huangc3252cc2018-10-16 15:43:23 +08001581bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001582 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1583 for (const auto& route : routes) {
1584 if (route.find(ipRoute) != std::string::npos) {
1585 return true;
1586 }
1587 }
1588 return false;
1589}
1590
Luke Huangc3252cc2018-10-16 15:43:23 +08001591std::string ipRouteString(const std::string& ifName, const std::string& dst,
1592 const std::string& nextHop) {
1593 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1594
1595 if (!nextHop.empty()) {
1596 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001597 }
1598
Luke Huangc3252cc2018-10-16 15:43:23 +08001599 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001600}
1601
Luke Huangc3252cc2018-10-16 15:43:23 +08001602void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1603 const std::string& dst, const std::string& nextHop,
1604 const char* table) {
1605 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1606}
1607
1608void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001609 const std::string& dst, const std::string& nextHop,
1610 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001611 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001612}
1613
1614bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1615 std::vector<std::string> rules = listIpRules(ipVersion);
1616 for (const auto& rule : rules) {
1617 if (rule.find(ipRule) != std::string::npos) {
1618 return true;
1619 }
1620 }
1621 return false;
1622}
1623
1624void expectNetworkDefaultIpRuleExists(const char* ifName) {
1625 std::string networkDefaultRule =
1626 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1627
1628 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1629 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1630 }
1631}
1632
1633void expectNetworkDefaultIpRuleDoesNotExist() {
1634 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1635
1636 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1637 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1638 }
1639}
1640
1641void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1642 std::string networkPermissionRule = "";
1643 switch (permission) {
1644 case INetd::PERMISSION_NONE:
1645 networkPermissionRule = StringPrintf(
1646 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1647 break;
1648 case INetd::PERMISSION_NETWORK:
1649 networkPermissionRule = StringPrintf(
1650 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1651 break;
1652 case INetd::PERMISSION_SYSTEM:
1653 networkPermissionRule = StringPrintf(
1654 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1655 break;
1656 }
1657
1658 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1659 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1660 }
1661}
1662
1663// TODO: It is a duplicate function, need to remove it
1664bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1665 const std::string& expectedInterface,
1666 const std::string& expectedRule,
1667 const char* table) {
1668 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1669 for (const auto& rule : rules) {
1670 if (rule.find(expectedInterface) != std::string::npos) {
1671 if (rule.find(expectedRule) != std::string::npos) {
1672 return true;
1673 }
1674 }
1675 }
1676 return false;
1677}
1678
1679void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1680 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1681 std::string networkIncomingPacketMarkRule = "";
1682 switch (permission) {
1683 case INetd::PERMISSION_NONE:
1684 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1685 break;
1686 case INetd::PERMISSION_NETWORK:
1687 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1688 break;
1689 case INetd::PERMISSION_SYSTEM:
1690 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1691 break;
1692 }
1693
1694 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1695 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1696 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1697 }
1698}
1699
1700} // namespace
1701
1702TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001703 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001704 const char* ipVersion;
1705 const char* testDest;
1706 const char* testNextHop;
1707 const bool expectSuccess;
1708 } kTestData[] = {
1709 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001710 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1711 {IP_RULE_V4, "10.251.0.0/16", "", true},
1712 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1713 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001714 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001715 {IP_RULE_V6, "::/0", "2001:db8::", true},
1716 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001717 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1718 };
1719
Luke Huangc3252cc2018-10-16 15:43:23 +08001720 static const struct {
1721 const char* ipVersion;
1722 const char* testDest;
1723 const char* testNextHop;
1724 } kTestDataWithNextHop[] = {
1725 {IP_RULE_V4, "10.251.10.0/30", ""},
1726 {IP_RULE_V6, "2001:db8::/32", ""},
1727 };
1728
Luke Huangb670d162018-08-23 20:01:13 +08001729 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001730 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001731 const int testUid = randomUid();
1732 const std::vector<int32_t> testUids = {testUid};
1733
1734 // Add test physical network
1735 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1736 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1737
Luke Huangc3252cc2018-10-16 15:43:23 +08001738 // Setup route for testing nextHop
1739 for (unsigned int i = 0; i < std::size(kTestDataWithNextHop); i++) {
1740 const auto& td = kTestDataWithNextHop[i];
1741
1742 // All route for test tun will disappear once the tun interface is deleted.
1743 binder::Status status =
1744 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1745 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1746 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1747 sTun.name().c_str());
1748
1749 // Add system permission for test uid, setup route in legacy system table.
1750 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1751
1752 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1753 testUid);
1754 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1755 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1756 testTableLegacySystem);
1757
1758 // Remove system permission for test uid, setup route in legacy network table.
1759 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1760
1761 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1762 testUid);
1763 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1764 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1765 testTableLegacyNetwork);
1766 }
1767
1768 for (unsigned int i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001769 const auto& td = kTestData[i];
1770
1771 binder::Status status =
1772 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1773 if (td.expectSuccess) {
1774 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001775 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001776 sTun.name().c_str());
1777 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001778 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1779 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001780 }
1781
1782 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1783 if (td.expectSuccess) {
1784 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001785 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1786 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001787 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001788 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1789 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001790 }
1791
Luke Huangc3252cc2018-10-16 15:43:23 +08001792 // Add system permission for test uid, route will be added into legacy system table.
1793 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001794
1795 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1796 testUid);
1797 if (td.expectSuccess) {
1798 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001799 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001800 testTableLegacySystem);
1801 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001802 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1803 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001804 }
1805
1806 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1807 td.testNextHop, testUid);
1808 if (td.expectSuccess) {
1809 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001810 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1811 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001812 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001813 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1814 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001815 }
1816
Luke Huangc3252cc2018-10-16 15:43:23 +08001817 // Remove system permission for test uid, route will be added into legacy network table.
1818 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1819
1820 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1821 testUid);
1822 if (td.expectSuccess) {
1823 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1824 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1825 testTableLegacyNetwork);
1826 } else {
1827 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1828 EXPECT_NE(0, status.serviceSpecificErrorCode());
1829 }
1830
1831 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1832 td.testNextHop, testUid);
1833 if (td.expectSuccess) {
1834 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1835 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1836 testTableLegacyNetwork);
1837 } else {
1838 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1839 EXPECT_NE(0, status.serviceSpecificErrorCode());
1840 }
Luke Huangb670d162018-08-23 20:01:13 +08001841 }
1842
1843 // Remove test physical network
1844 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1845}
1846
1847TEST_F(BinderTest, NetworkPermissionDefault) {
1848 // Add test physical network
1849 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1850 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1851
Luke Huangc3252cc2018-10-16 15:43:23 +08001852 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001853 int currentNetid;
1854 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1855 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1856
1857 // Test SetDefault
1858 status = mNetd->networkSetDefault(TEST_NETID1);
1859 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1860 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1861
1862 status = mNetd->networkClearDefault();
1863 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1864 expectNetworkDefaultIpRuleDoesNotExist();
1865
1866 // Add default network back
1867 status = mNetd->networkSetDefault(currentNetid);
1868 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1869
1870 // Test SetPermission
1871 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1872 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1873 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1874 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1875
1876 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1877 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1878 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1879 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1880
1881 // Remove test physical network
1882 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1883}
1884
1885TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1886 const int testUid = randomUid();
1887 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1888 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1889 bool ret = false;
1890 status = mNetd->networkCanProtect(testUid, &ret);
1891 EXPECT_TRUE(ret);
1892
1893 status = mNetd->networkSetProtectDeny(testUid);
1894 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1895 status = mNetd->networkCanProtect(testUid, &ret);
1896 EXPECT_FALSE(ret);
1897}
1898
1899namespace {
1900
Luke Huangb5733d72018-08-21 17:17:19 +08001901int readIntFromPath(const std::string& path) {
1902 std::string result = "";
1903 EXPECT_TRUE(ReadFileToString(path, &result));
1904 return std::stoi(result);
1905}
1906
1907int getTetherAcceptIPv6Ra(const std::string& ifName) {
1908 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1909 return readIntFromPath(path);
1910}
1911
1912bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1913 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1914 return readIntFromPath(path);
1915}
1916
1917int getTetherIPv6DadTransmits(const std::string& ifName) {
1918 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1919 return readIntFromPath(path);
1920}
1921
1922bool getTetherEnableIPv6(const std::string& ifName) {
1923 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1924 int disableIPv6 = readIntFromPath(path);
1925 return !disableIPv6;
1926}
1927
1928bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1929 for (const auto& iface : ifList) {
1930 if (iface == ifName) {
1931 return true;
1932 }
1933 }
1934 return false;
1935}
1936
1937void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1938 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1939 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1940 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1941 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1942}
1943
1944void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1945 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1946 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1947 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1948 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1949}
1950
1951void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1952 const std::string& ifName) {
1953 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1954}
1955
1956void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1957 const std::string& ifName) {
1958 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1959}
1960
1961void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1962 const std::vector<std::string>& testDnsAddrs) {
1963 EXPECT_TRUE(dnsList == testDnsAddrs);
1964}
1965
1966} // namespace
1967
1968TEST_F(BinderTest, TetherStartStopStatus) {
1969 std::vector<std::string> noDhcpRange = {};
1970 static const char dnsdName[] = "dnsmasq";
1971
1972 binder::Status status = mNetd->tetherStart(noDhcpRange);
1973 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1974 EXPECT_TRUE(processExists(dnsdName));
1975
1976 bool tetherEnabled;
1977 status = mNetd->tetherIsEnabled(&tetherEnabled);
1978 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1979 EXPECT_TRUE(tetherEnabled);
1980
1981 status = mNetd->tetherStop();
1982 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1983 EXPECT_FALSE(processExists(dnsdName));
1984
1985 status = mNetd->tetherIsEnabled(&tetherEnabled);
1986 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1987 EXPECT_FALSE(tetherEnabled);
1988}
1989
1990TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
1991 // TODO: verify if dnsmasq update interface successfully
1992
1993 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
1994 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1995 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
1996
1997 std::vector<std::string> ifList;
1998 status = mNetd->tetherInterfaceList(&ifList);
1999 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2000 expectTetherInterfaceExists(ifList, sTun.name());
2001
2002 status = mNetd->tetherInterfaceRemove(sTun.name());
2003 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2004 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2005
2006 status = mNetd->tetherInterfaceList(&ifList);
2007 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2008 expectTetherInterfaceNotExists(ifList, sTun.name());
2009}
2010
2011TEST_F(BinderTest, TetherDnsSetList) {
2012 // TODO: verify if dnsmasq update dns successfully
2013 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2014
2015 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2016 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2017
2018 std::vector<std::string> dnsList;
2019 status = mNetd->tetherDnsList(&dnsList);
2020 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2021 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002022}
2023
2024namespace {
2025
2026constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2027constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2028constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2029constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2030constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2031constexpr char FIREWALL_STANDBY[] = "fw_standby";
2032constexpr char targetReturn[] = "RETURN";
2033constexpr char targetDrop[] = "DROP";
2034
2035void expectFirewallWhitelistMode() {
2036 static const char dropRule[] = "DROP all";
2037 static const char rejectRule[] = "REJECT all";
2038 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2039 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2040 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2041 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2042 }
2043}
2044
2045void expectFirewallBlacklistMode() {
2046 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2047 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2048 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2049 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2050 }
2051}
2052
2053bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2054 const std::string& expectedInterface,
2055 const std::string& expectedRule) {
2056 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2057 // Expected rule:
2058 // Chain fw_INPUT (1 references)
2059 // pkts bytes target prot opt in out source destination
2060 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2061 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2062 int firstRuleIndex = 2;
2063 if (rules.size() < 4) return false;
2064 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2065 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2066 return true;
2067 }
2068 }
2069 return false;
2070}
2071
2072// TODO: It is a duplicate function, need to remove it
2073bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2074 const std::string& expectedInterface,
2075 const std::string& expectedRule) {
2076 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2077 for (const auto& rule : rules) {
2078 if (rule.find(expectedInterface) != std::string::npos) {
2079 if (rule.find(expectedRule) != std::string::npos) {
2080 return true;
2081 }
2082 }
2083 }
2084 return false;
2085}
2086
2087void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2088 static const char returnRule[] = "RETURN all";
2089 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2090 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2091 returnRule));
2092 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2093 returnRule));
2094 }
2095}
2096
2097void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2098 static const char returnRule[] = "RETURN all";
2099 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2100 EXPECT_FALSE(
2101 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2102 EXPECT_FALSE(
2103 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2104 }
2105}
2106
2107bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2108 const std::string& expectedTarget,
2109 const std::string& expectedRule) {
2110 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2111 int firstRuleIndex = 2;
2112 if (rules.size() < 4) return false;
2113 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2114 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2115 return true;
2116 }
2117 }
2118 return false;
2119}
2120
2121bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2122 const std::string& expectedTarget,
2123 const std::string& expectedRule) {
2124 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2125 int lastRuleIndex = rules.size() - 1;
2126 if (lastRuleIndex < 0) return false;
2127 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2128 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2129 return true;
2130 }
2131 }
2132 return false;
2133}
2134
2135void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2136 std::string uidRule = StringPrintf("owner UID match %u", uid);
2137 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2138 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2139}
2140
2141void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2142 std::string uidRule = StringPrintf("owner UID match %u", uid);
2143 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2144 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2145}
2146
2147void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2148 std::string uidRule = StringPrintf("owner UID match %u", uid);
2149 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2150 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2151}
2152
2153void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2154 std::string uidRule = StringPrintf("owner UID match %u", uid);
2155 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2156 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2157}
2158
2159bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2160 std::vector<std::string> inputRules =
2161 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2162 std::vector<std::string> outputRules =
2163 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2164 int inputLastRuleIndex = inputRules.size() - 1;
2165 int outputLastRuleIndex = outputRules.size() - 1;
2166
2167 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2168 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2169 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2170 return true;
2171 }
2172 }
2173 return false;
2174}
2175
2176void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2177 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2178 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2179}
2180
2181void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2182 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2183 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2184 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2185 }
2186}
2187
2188} // namespace
2189
2190TEST_F(BinderTest, FirewallSetFirewallType) {
2191 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2192 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2193 expectFirewallWhitelistMode();
2194
2195 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2196 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2197 expectFirewallBlacklistMode();
2198
2199 // set firewall type blacklist twice
2200 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2201 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2202 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2203 expectFirewallBlacklistMode();
2204
2205 // set firewall type whitelist twice
2206 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2207 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2208 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2209 expectFirewallWhitelistMode();
2210
2211 // reset firewall type to default
2212 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2213 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2214 expectFirewallBlacklistMode();
2215}
2216
2217TEST_F(BinderTest, FirewallSetInterfaceRule) {
2218 // setinterfaceRule is not supported in BLACKLIST MODE
2219 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2220 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2221
2222 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2223 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2224
2225 // set WHITELIST mode first
2226 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2227 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2228
2229 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2230 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2231 expectFirewallInterfaceRuleAllowExists(sTun.name());
2232
2233 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2234 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2235 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2236
2237 // reset firewall mode to default
2238 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2239 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2240 expectFirewallBlacklistMode();
2241}
2242
2243TEST_F(BinderTest, FirewallSetUidRule) {
2244 SKIP_IF_BPF_SUPPORTED;
2245
2246 int32_t uid = randomUid();
2247
2248 // Doze allow
2249 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2250 INetd::FIREWALL_RULE_ALLOW);
2251 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2252 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2253
2254 // Doze deny
2255 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2256 INetd::FIREWALL_RULE_DENY);
2257 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2258 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2259
2260 // Powersave allow
2261 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2262 INetd::FIREWALL_RULE_ALLOW);
2263 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2264 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2265
2266 // Powersave deny
2267 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2268 INetd::FIREWALL_RULE_DENY);
2269 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2270 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2271
2272 // Standby deny
2273 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2274 INetd::FIREWALL_RULE_DENY);
2275 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2276 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2277
2278 // Standby allow
2279 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2280 INetd::FIREWALL_RULE_ALLOW);
2281 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2282 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2283
2284 // None deny in BLACKLIST
2285 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2286 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2287 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2288 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2289
2290 // None allow in BLACKLIST
2291 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2292 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2293 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2294 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2295
2296 // set firewall type whitelist twice
2297 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2298 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2299 expectFirewallWhitelistMode();
2300
2301 // None allow in WHITELIST
2302 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2303 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2304 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2305 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2306
2307 // None deny in WHITELIST
2308 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2309 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2310 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2311 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2312
2313 // reset firewall mode to default
2314 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2315 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2316 expectFirewallBlacklistMode();
2317}
2318
2319TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2320 SKIP_IF_BPF_SUPPORTED;
2321
2322 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2323 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2324 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2325
2326 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2327 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2328 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2329
2330 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2331 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2332 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2333
2334 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2335 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2336 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2337
2338 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2339 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2340 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2341
2342 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2343 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2344 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2345}
Luke Huangf7782042018-08-08 13:13:04 +08002346
2347namespace {
2348
2349std::string hwAddrToStr(unsigned char* hwaddr) {
2350 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2351 hwaddr[4], hwaddr[5]);
2352}
2353
2354int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2355 int prefixLength = 0;
2356 uint32_t m = ntohl(mask);
2357 while (m & (1 << 31)) {
2358 prefixLength++;
2359 m = m << 1;
2360 }
2361 return prefixLength;
2362}
2363
2364std::string toStdString(const String16& s) {
2365 return std::string(String8(s.string()));
2366}
2367
2368android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2369 const auto& sys = sSyscalls.get();
2370 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2371 EXPECT_TRUE(isOk(fd.status()));
2372
2373 struct ifreq ifr = {};
2374 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2375
2376 return sys.ioctl(fd.value(), flag, &ifr);
2377}
2378
2379std::string getInterfaceHwAddr(const std::string& ifName) {
2380 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2381
2382 unsigned char hwaddr[ETH_ALEN] = {};
2383 if (isOk(res.status())) {
2384 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2385 }
2386
2387 return hwAddrToStr(hwaddr);
2388}
2389
2390int getInterfaceIPv4Prefix(const std::string& ifName) {
2391 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2392
2393 int prefixLength = 0;
2394 if (isOk(res.status())) {
2395 prefixLength = ipv4NetmaskToPrefixLength(
2396 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2397 }
2398
2399 return prefixLength;
2400}
2401
2402std::string getInterfaceIPv4Addr(const std::string& ifName) {
2403 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2404
2405 struct in_addr addr = {};
2406 if (isOk(res.status())) {
2407 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2408 }
2409
2410 return std::string(inet_ntoa(addr));
2411}
2412
2413std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2414 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2415
2416 unsigned flags = 0;
2417 if (isOk(res.status())) {
2418 flags = res.value().ifr_flags;
2419 }
2420
2421 std::vector<std::string> ifFlags;
2422 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2423 : toStdString(INetd::IF_STATE_DOWN()));
2424
2425 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2426 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2427 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2428 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2429 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2430
2431 return ifFlags;
2432}
2433
2434bool compareListInterface(const std::vector<std::string>& interfaceList) {
2435 const auto& res = InterfaceController::getIfaceNames();
2436 EXPECT_TRUE(isOk(res));
2437
2438 std::vector<std::string> resIfList;
2439 resIfList.reserve(res.value().size());
2440 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2441
2442 return resIfList == interfaceList;
2443}
2444
2445int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2446 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2447 return readIntFromPath(path);
2448}
2449
2450bool getInterfaceEnableIPv6(const std::string& ifName) {
2451 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2452
2453 int disableIPv6 = readIntFromPath(path);
2454 return !disableIPv6;
2455}
2456
2457int getInterfaceMtu(const std::string& ifName) {
2458 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2459 return readIntFromPath(path);
2460}
2461
2462void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2463 EXPECT_TRUE(compareListInterface(interfaceList));
2464}
2465
2466void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2467 const InterfaceConfigurationParcel& interfaceCfg) {
2468 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2469 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2470 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2471 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2472}
2473
2474void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2475 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2476 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2477
2478 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2479 for (const auto& flag : setCfg.flags) {
2480 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2481 }
2482}
2483
2484void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2485 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2486 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2487}
2488
2489void expectInterfaceNoAddr(const std::string& ifName) {
2490 // noAddr
2491 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2492 // noPrefix
2493 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2494}
2495
2496void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2497 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2498 EXPECT_EQ(enableIPv6, enable);
2499}
2500
2501void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2502 int mtuSize = getInterfaceMtu(ifName);
2503 EXPECT_EQ(mtu, mtuSize);
2504}
2505
2506InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2507 const std::string& addr, int prefixLength,
2508 const std::vector<std::string>& flags) {
2509 InterfaceConfigurationParcel cfg;
2510 cfg.ifName = ifName;
2511 cfg.hwAddr = "";
2512 cfg.ipv4Addr = addr;
2513 cfg.prefixLength = prefixLength;
2514 cfg.flags = flags;
2515 return cfg;
2516}
2517
2518void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2519 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2520 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2521
2522 for (const auto& flag : expectedFlags) {
2523 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2524 interfaceCfg.flags.end());
2525 }
2526
2527 for (const auto& flag : unexpectedFlags) {
2528 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2529 interfaceCfg.flags.end());
2530 }
2531}
2532
2533} // namespace
2534
2535TEST_F(BinderTest, InterfaceList) {
2536 std::vector<std::string> interfaceListResult;
2537
2538 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2539 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2540 expectInterfaceList(interfaceListResult);
2541}
2542
2543TEST_F(BinderTest, InterfaceGetCfg) {
2544 InterfaceConfigurationParcel interfaceCfgResult;
2545
2546 // Add test physical network
2547 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2548 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2549
2550 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2551 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2552 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2553 expectTunFlags(interfaceCfgResult);
2554
2555 // Remove test physical network
2556 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2557}
2558
2559TEST_F(BinderTest, InterfaceSetCfg) {
2560 const std::string testAddr = "192.0.2.3";
2561 const int testPrefixLength = 24;
2562 std::vector<std::string> upFlags = {"up"};
2563 std::vector<std::string> downFlags = {"down"};
2564
2565 // Add test physical network
2566 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2567 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2568
2569 // Set tun interface down.
2570 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2571 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2572 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2573 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2574
2575 // Set tun interface up again.
2576 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2577 status = mNetd->interfaceSetCfg(interfaceCfg);
2578 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2579 status = mNetd->interfaceClearAddrs(sTun.name());
2580 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2581
2582 // Remove test physical network
2583 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2584}
2585
2586TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2587 // enable
2588 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2589 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2590 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2591
2592 // disable
2593 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2594 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2595 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2596}
2597
2598TEST_F(BinderTest, InterfaceClearAddr) {
2599 const std::string testAddr = "192.0.2.3";
2600 const int testPrefixLength = 24;
2601 std::vector<std::string> noFlags{};
2602
2603 // Add test physical network
2604 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2605 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2606
2607 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2608 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2609 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2610 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2611
2612 status = mNetd->interfaceClearAddrs(sTun.name());
2613 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2614 expectInterfaceNoAddr(sTun.name());
2615
2616 // Remove test physical network
2617 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2618}
2619
2620TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2621 // Add test physical network
2622 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2623 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2624
2625 // disable
2626 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2627 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2628 expectInterfaceEnableIPv6(sTun.name(), false);
2629
2630 // enable
2631 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2632 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2633 expectInterfaceEnableIPv6(sTun.name(), true);
2634
2635 // Remove test physical network
2636 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2637}
2638
2639TEST_F(BinderTest, InterfaceSetMtu) {
2640 const int testMtu = 1200;
2641
2642 // Add test physical network
2643 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2644 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2645
2646 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2647 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2648 expectInterfaceMtu(sTun.name(), testMtu);
2649
2650 // Remove test physical network
2651 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2652}
Luke Huang19b49c52018-10-22 12:12:05 +09002653
2654namespace {
2655
2656constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2657constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002658constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002659constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2660
Luke Huangae038f82018-11-05 11:17:31 +09002661int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002662 return listIptablesRuleByTable(binary, table, chainName).size();
2663}
2664
2665bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2666 const std::vector<std::string>& targetVec) {
2667 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2668 if (targetVec.size() != rules.size() - 2) {
2669 return false;
2670 }
2671
2672 /*
Luke Huangae038f82018-11-05 11:17:31 +09002673 * Check that the rules match. Note that this function matches substrings, not entire rules,
2674 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002675 * Skip first two lines since rules start from third line.
2676 * Chain chainName (x references)
2677 * pkts bytes target prot opt in out source destination
2678 * ...
2679 */
2680 int rIndex = 2;
2681 for (const auto& target : targetVec) {
2682 if (rules[rIndex].find(target) == std::string::npos) {
2683 return false;
2684 }
2685 rIndex++;
2686 }
2687 return true;
2688}
2689
2690void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2691 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2692 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2693 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002694 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002695 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2696 "DROP"};
2697
2698 // V4
2699 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2700 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002701 EXPECT_TRUE(
2702 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002703 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2704
Luke Huangae038f82018-11-05 11:17:31 +09002705 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002706 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2707
2708 // V6
2709 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002710 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2711 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002712
2713 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2714 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2715 extIf));
2716 }
2717}
2718
2719void expectNatDisable() {
2720 // It is the default DROP rule with tethering disable.
2721 // Chain tetherctrl_FORWARD (1 references)
2722 // pkts bytes target prot opt in out source destination
2723 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2724 std::vector<std::string> forwardV4Match = {"DROP"};
2725 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2726
2727 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002728 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2729 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002730
Luke Huangae038f82018-11-05 11:17:31 +09002731 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2732 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002733
2734 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2735}
2736
2737} // namespace
2738
2739TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002740 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2741 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2742 expectNatEnable(sTun.name(), sTun2.name());
2743
2744 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2745 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2746 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002747}