blob: 6d2cb816d838c3733533b801b7370013f15dae9a [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>
Luke Huang528af602018-08-29 19:06:05 +080020#include <chrono>
Robin Leeb8087362016-03-30 18:43:08 +010021#include <cinttypes>
Luke Huang528af602018-08-29 19:06:05 +080022#include <condition_variable>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090023#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090024#include <cstdio>
25#include <cstdlib>
Luke Huang528af602018-08-29 19:06:05 +080026#include <mutex>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090027#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090028#include <vector>
29
Luke Huangf7782042018-08-08 13:13:04 +080030#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090032#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070035#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <netdb.h>
37#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040038#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080039#include <sys/socket.h>
40#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090041
Luke Huang531f5d32018-08-03 15:19:05 +080042#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090043#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090045#include <android-base/strings.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080046#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070047#include <bpf/BpfUtils.h>
Robin Leeb8087362016-03-30 18:43:08 +010048#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090049#include <gtest/gtest.h>
50#include <logwrap/logwrap.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080051#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090052#include <netutils/ifc.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053
Nathan Harold21299f72018-03-16 20:13:03 -070054#include "InterfaceController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090055#include "NetdConstants.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090056#include "Stopwatch.h"
Luke Huang528af602018-08-29 19:06:05 +080057#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070058#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090059#include "android/net/INetd.h"
60#include "binder/IServiceManager.h"
Nathan Harold21299f72018-03-16 20:13:03 -070061#include "netdutils/Syscalls.h"
Mike Yu5ae61542018-10-19 22:11:43 +080062#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090063
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090064#define IP_PATH "/system/bin/ip"
65#define IP6TABLES_PATH "/system/bin/ip6tables"
66#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090067#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080068#define RAW_TABLE "raw"
69#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080070#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090071#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090072
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090073namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090074
75using android::IBinder;
76using android::IServiceManager;
77using android::sp;
78using android::String16;
79using android::String8;
80using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080081using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090082using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090083using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080084using android::base::Trim;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090085using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080086using android::net::InterfaceConfigurationParcel;
87using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080088using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090089using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090090using android::net::UidRangeParcel;
Luke Huangf7782042018-08-08 13:13:04 +080091using android::netdutils::sSyscalls;
Robin Leeb8087362016-03-30 18:43:08 +010092
93static const char* IP_RULE_V4 = "-4";
94static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +090095static const int TEST_NETID1 = 65501;
96static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -080097
98// Use maximum reserved appId for applications to avoid conflict with existing
99// uids.
100static const int TEST_UID1 = 99999;
101static const int TEST_UID2 = 99998;
102
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900103constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900104
Benedict Wongb2daefb2017-12-06 22:05:46 -0800105static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
106static const std::string ESP_ALLOW_RULE("esp");
107
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900108class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900109 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900111 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900112 sp<IBinder> binder = sm->getService(String16("netd"));
113 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900114 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115 }
116 }
117
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900118 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900119 ASSERT_NE(nullptr, mNetd.get());
120 }
121
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900122 void TearDown() override {
123 mNetd->networkDestroy(TEST_NETID1);
124 mNetd->networkDestroy(TEST_NETID2);
125 }
126
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900127 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700128
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900129 // Static because setting up the tun interface takes about 40ms.
130 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900131 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900132 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900133 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900134 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900135 }
136
137 static void TearDownTestCase() {
138 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900139 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900140 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900141 }
142
143 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900144
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900145 protected:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900146 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900147 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900148 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900149};
150
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900151TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900152TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900153
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900154class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900155 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700156 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900157 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900158 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900159 }
160
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900161 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900162 std::string mName;
163};
164
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900165TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900166 TimedOperation t("isAlive RPC");
167 bool isAlive = false;
168 mNetd->isAlive(&isAlive);
169 ASSERT_TRUE(isAlive);
170}
171
172static int randomUid() {
173 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
174}
175
Robin Leeb8087362016-03-30 18:43:08 +0100176static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900177 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900178 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
179 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900180 perror("popen");
181 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900182 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900183
184 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100185 size_t bufsize = 0;
186 ssize_t linelen = 0;
187 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900188 lines.push_back(std::string(line, linelen));
189 free(line);
190 line = nullptr;
191 }
192
193 pclose(f);
194 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900195}
196
Robin Leeb8087362016-03-30 18:43:08 +0100197static std::vector<std::string> listIpRules(const char *ipVersion) {
198 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
199 return runCommand(command);
200}
201
202static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900203 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100204 return runCommand(command);
205}
206
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900207static int iptablesRuleLineLength(const char *binary, const char *chainName) {
208 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900209}
210
Benedict Wongb2daefb2017-12-06 22:05:46 -0800211static bool iptablesRuleExists(const char *binary,
212 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900213 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800214 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900215 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800216 if(rule.find(expectedRule) != std::string::npos) {
217 return true;
218 }
219 }
220 return false;
221}
222
223static bool iptablesNoSocketAllowRuleExists(const char *chainName){
224 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
225 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
226}
227
228static bool iptablesEspAllowRuleExists(const char *chainName){
229 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
230 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
231}
232
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900233TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700234 SKIP_IF_BPF_SUPPORTED;
235
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900236 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
237 const int kNumUids = 500;
238 std::vector<int32_t> noUids(0);
239 std::vector<int32_t> uids(kNumUids);
240 for (int i = 0; i < kNumUids; i++) {
241 uids[i] = randomUid();
242 }
243
244 bool ret;
245 {
246 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900247 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900248 }
249 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800250 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
251 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
252 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
253 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900254 {
255 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900256 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900257 }
258 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900259 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
260 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900261
262 {
263 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900264 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900265 }
266 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900267 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
268 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800269 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
270 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900271
272 {
273 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900274 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900275 }
276 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900277 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
278 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900279
280 // Check that the call fails if iptables returns an error.
281 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900282 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900283 EXPECT_EQ(false, ret);
284}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900285
Benedict Wong319f17e2018-05-15 17:06:44 -0700286TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700287 const struct TestData {
288 const std::string family;
289 const std::string deviceName;
290 const std::string localAddress;
291 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800292 int32_t iKey;
293 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700294 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800295 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700296 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
297 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
298 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800299 };
300
Sehee Park8659b8d2018-11-16 10:53:16 +0900301 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700302 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800303
304 binder::Status status;
305
Benedict Wong319f17e2018-05-15 17:06:44 -0700306 // Create Tunnel Interface.
307 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700308 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800309 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
310
Benedict Wonga450e722018-05-07 10:29:02 -0700311 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900312 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700313
Benedict Wong319f17e2018-05-15 17:06:44 -0700314 // Update Tunnel Interface.
315 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700316 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800317 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
318
Benedict Wong319f17e2018-05-15 17:06:44 -0700319 // Remove Tunnel Interface.
320 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800321 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700322
323 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900324 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800325 }
326}
327
Benedict Wong1cb73df2018-12-03 00:54:14 -0800328TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
329 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
330 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
331
332 int sockOptVal = UDP_ENCAP_ESPINUDP;
333 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
334
335 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
336 EXPECT_TRUE(res.isOk());
337
338 struct stat info;
339 EXPECT_EQ(0, fstat(sockFd.get(), &info));
340 EXPECT_EQ(1001, (int) info.st_uid);
341}
342
Nathan Harold2deff322018-05-10 14:03:48 -0700343// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
344// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
345#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900346
347using android::net::XfrmController;
348
Benedict Wonga04ffa72018-05-09 21:42:42 -0700349static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
350 static_cast<int>(android::net::XfrmDirection::OUT)};
351static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
352
Nathan Harold21299f72018-03-16 20:13:03 -0700353#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
354 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900355bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900356 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700357 SCOPED_TRACE(status);
358 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
359
360 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700361 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700362 SCOPED_TRACE(status);
363 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
364
365 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700366 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
367 0xD00D, 0xE00D, false)
368 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700369}
370
Benedict Wonga04ffa72018-05-09 21:42:42 -0700371TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900372 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700373
374 // Repeat to ensure cleanup and recreation works correctly
375 for (int i = 0; i < 2; i++) {
376 for (int direction : XFRM_DIRECTIONS) {
377 for (int addrFamily : ADDRESS_FAMILIES) {
378 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700379 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700380 EXPECT_TRUE(status.isOk())
381 << " family: " << addrFamily << " direction: " << direction;
382 }
383 }
384
385 // Cleanup
386 for (int direction : XFRM_DIRECTIONS) {
387 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700388 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700389 EXPECT_TRUE(status.isOk());
390 }
391 }
392 }
393}
394
395TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
396 binder::Status status;
397
398 // Repeat to ensure cleanup and recreation works correctly
399 for (int i = 0; i < 2; i++) {
400 for (int direction : XFRM_DIRECTIONS) {
401 for (int addrFamily : ADDRESS_FAMILIES) {
402 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700403 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700404 EXPECT_TRUE(status.isOk())
405 << " family: " << addrFamily << " direction: " << direction;
406 }
407 }
408
409 // Cleanup
410 for (int direction : XFRM_DIRECTIONS) {
411 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700412 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700413 EXPECT_TRUE(status.isOk());
414 }
415 }
416 }
417}
418
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900419TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900420 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700421 status = XfrmController::Init();
422 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700423
424 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
425 // feature.
426 if (status.code() == EOPNOTSUPP) return;
427
Nathan Harold21299f72018-03-16 20:13:03 -0700428 ASSERT_TRUE(status.ok());
429
430 int32_t spi = 0;
431
432 ASSERT_TRUE(allocateIpSecResources(true, &spi));
433 ASSERT_TRUE(allocateIpSecResources(false, &spi));
434
435 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700436 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700437 ASSERT_TRUE(allocateIpSecResources(true, &spi));
438
439 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700440 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700441 SCOPED_TRACE(status);
442 ASSERT_TRUE(status.ok());
443
Benedict Wonga450e722018-05-07 10:29:02 -0700444 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700445 SCOPED_TRACE(status);
446 ASSERT_TRUE(status.ok());
447
448 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700449 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700450}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900451
452#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700453
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900454static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900455 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900456
457 // Output looks like this:
458 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900459 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900460 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900461 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900462 //
463 // or:
464 //
465 // Chain bw_data_saver (1 references)
466 // target prot opt source destination
467 // ... possibly connectivity critical packet rules here ...
468 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900469
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900470 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900471
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900472 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
473 // Data saver disabled.
474 return 0;
475 }
476
477 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
478
479 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
480 // Data saver enabled.
481 return 1;
482 }
483
484 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900485}
486
487bool enableDataSaver(sp<INetd>& netd, bool enable) {
488 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
489 bool ret;
490 netd->bandwidthEnableDataSaver(enable, &ret);
491 return ret;
492}
493
494int getDataSaverState() {
495 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
496 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
497 EXPECT_EQ(enabled4, enabled6);
498 EXPECT_NE(-1, enabled4);
499 EXPECT_NE(-1, enabled6);
500 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
501 return -1;
502 }
503 return enabled6;
504}
505
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900506TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900507 const int wasEnabled = getDataSaverState();
508 ASSERT_NE(-1, wasEnabled);
509
510 if (wasEnabled) {
511 ASSERT_TRUE(enableDataSaver(mNetd, false));
512 EXPECT_EQ(0, getDataSaverState());
513 }
514
515 ASSERT_TRUE(enableDataSaver(mNetd, false));
516 EXPECT_EQ(0, getDataSaverState());
517
518 ASSERT_TRUE(enableDataSaver(mNetd, true));
519 EXPECT_EQ(1, getDataSaverState());
520
521 ASSERT_TRUE(enableDataSaver(mNetd, true));
522 EXPECT_EQ(1, getDataSaverState());
523
524 if (!wasEnabled) {
525 ASSERT_TRUE(enableDataSaver(mNetd, false));
526 EXPECT_EQ(0, getDataSaverState());
527 }
528}
Robin Leeb8087362016-03-30 18:43:08 +0100529
Luke Huang94658ac2018-10-18 19:35:12 +0900530static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
531 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100532 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100533 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100534 std::vector<std::string> rules = listIpRules(ipVersion);
535
536 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900537 std::string suffix =
538 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900539 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800540 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100541 return true;
542 }
543 }
544 return false;
545}
546
Luke Huang94658ac2018-10-18 19:35:12 +0900547static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
548 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100549 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
550 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
551 EXPECT_EQ(existsIp4, existsIp6);
552 return existsIp4;
553}
554
Luke Huang94658ac2018-10-18 19:35:12 +0900555namespace {
556
557UidRangeParcel makeUidRangeParcel(int start, int stop) {
558 UidRangeParcel res;
559 res.start = start;
560 res.stop = stop;
561
562 return res;
563}
564
565} // namespace
566
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900567TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800568 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
569 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
570 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900571 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
572 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900573
574 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
575 EXPECT_EQ(EBUSY,
576 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
577
578 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
579 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
580 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800581 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900582}
583
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900584TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900585 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
586
cken67cd14c2018-12-05 17:26:59 +0900587 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
588 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900589 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
590
Luke Huang94658ac2018-10-18 19:35:12 +0900591 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
592 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
593 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900594 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
595
596 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
597
598 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
599 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
600 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
601 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
602
603 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
604 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
605 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
606 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
607
608 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
609}
610
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900611TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100612 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100613
Luke Huang94658ac2018-10-18 19:35:12 +0900614 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
615 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100616
617 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
618 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
619
620 // Create two valid rules.
621 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
622 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
623 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
624 for (auto const& range : uidRanges) {
625 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
626 }
627
628 // Remove the rules.
629 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
630 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
631 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
632 for (auto const& range : uidRanges) {
633 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
634 }
635
636 // Fail to remove the rules a second time after they are already deleted.
637 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
638 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
639 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
640
641 // All rules should be the same as before.
642 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
643 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
644}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900645
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900646// Create a socket pair that isLoopbackSocket won't think is local.
647void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900648 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900649 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900650 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
651
652 socklen_t addrlen = sizeof(server6);
653 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
654 ASSERT_EQ(0, listen(*serverSocket, 10));
655
Bernie Innocentif6918262018-06-11 17:37:35 +0900656 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900657 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900658 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900659 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
660 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
661
Bernie Innocentif6918262018-06-11 17:37:35 +0900662 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900663 ASSERT_NE(-1, *acceptedSocket);
664
665 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
666}
667
668void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
669 char buf[4096];
670 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
671 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
672 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
673}
674
675void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
676 // Check that the client socket was closed with ECONNABORTED.
677 int ret = write(clientSocket, "foo", sizeof("foo"));
678 int err = errno;
679 EXPECT_EQ(-1, ret);
680 EXPECT_EQ(ECONNABORTED, err);
681
682 // Check that it sent a RST to the server.
683 ret = write(acceptedSocket, "foo", sizeof("foo"));
684 err = errno;
685 EXPECT_EQ(-1, ret);
686 EXPECT_EQ(ECONNRESET, err);
687}
688
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900689TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900690 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900691 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900692
693 // Pick a random UID in the system UID range.
694 constexpr int baseUid = AID_APP - 2000;
695 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
696 int uid = baseUid + 500 + arc4random_uniform(1000);
697 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
698
699 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900700 std::vector<UidRangeParcel> uidRanges = {
701 makeUidRangeParcel(baseUid + 42, baseUid + 449),
702 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
703 makeUidRangeParcel(baseUid + 498, uid - 1),
704 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900705 };
706 // A skip list that doesn't contain UID.
707 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
708
709 // Close sockets. Our test socket should be intact.
710 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
711 checkSocketpairOpen(clientSocket, acceptedSocket);
712
713 // UID ranges that do contain uid.
714 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900715 makeUidRangeParcel(baseUid + 42, baseUid + 449),
716 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
717 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900718 };
719 // Add uid to the skip list.
720 skipUids.push_back(uid);
721
722 // Close sockets. Our test socket should still be intact because it's in the skip list.
723 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
724 checkSocketpairOpen(clientSocket, acceptedSocket);
725
726 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
727 skipUids.resize(skipUids.size() - 1);
728 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
729 checkSocketpairClosed(clientSocket, acceptedSocket);
730
731 close(clientSocket);
732 close(serverSocket);
733 close(acceptedSocket);
734}
Erik Klinecc4f2732016-08-03 11:24:27 +0900735
736namespace {
737
738int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
739 if (buf == nullptr) return -1;
740
741 int prefixLength = 0;
742 bool endOfContiguousBits = false;
743 for (unsigned int i = 0; i < buflen; i++) {
744 const uint8_t value = buf[i];
745
746 // Bad bit sequence: check for a contiguous set of bits from the high
747 // end by verifying that the inverted value + 1 is a power of 2
748 // (power of 2 iff. (v & (v - 1)) == 0).
749 const uint8_t inverse = ~value + 1;
750 if ((inverse & (inverse - 1)) != 0) return -1;
751
752 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
753
754 // Bogus netmask.
755 if (endOfContiguousBits && value != 0) return -1;
756
757 if (value != 0xff) endOfContiguousBits = true;
758 }
759
760 return prefixLength;
761}
762
763template<typename T>
764int netmaskToPrefixLength(const T *p) {
765 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
766}
767
768
769static bool interfaceHasAddress(
770 const std::string &ifname, const char *addrString, int prefixLength) {
771 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900772
773 const struct addrinfo hints = {
774 .ai_flags = AI_NUMERICHOST,
775 .ai_family = AF_UNSPEC,
776 .ai_socktype = SOCK_DGRAM,
777 };
778 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
779 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
780 return false;
781 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900782 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900783
784 struct ifaddrs *ifaddrsList = nullptr;
785 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
786
787 if (getifaddrs(&ifaddrsList) != 0) {
788 return false;
789 }
790
791 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
792 if (std::string(addr->ifa_name) != ifname ||
793 addr->ifa_addr == nullptr ||
794 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
795 continue;
796 }
797
798 switch (addr->ifa_addr->sa_family) {
799 case AF_INET: {
800 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
801 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
802 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
803 continue;
804 }
805
806 if (prefixLength < 0) return true; // not checking prefix lengths
807
808 if (addr->ifa_netmask == nullptr) return false;
809 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
810 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
811 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
812 }
813 case AF_INET6: {
814 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
815 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
816 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
817 continue;
818 }
819
820 if (prefixLength < 0) return true; // not checking prefix lengths
821
822 if (addr->ifa_netmask == nullptr) return false;
823 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
824 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
825 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
826 }
827 default:
828 // Cannot happen because we have already screened for matching
829 // address families at the top of each iteration.
830 continue;
831 }
832 }
833
834 return false;
835}
836
837} // namespace
838
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900839TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900840 static const struct TestData {
841 const char *addrString;
842 const int prefixLength;
843 const bool expectSuccess;
844 } kTestData[] = {
845 { "192.0.2.1", 24, true },
846 { "192.0.2.2", 25, true },
847 { "192.0.2.3", 32, true },
848 { "192.0.2.4", 33, false },
849 { "192.not.an.ip", 24, false },
850 { "2001:db8::1", 64, true },
851 { "2001:db8::2", 65, true },
852 { "2001:db8::3", 128, true },
853 { "2001:db8::4", 129, false },
854 { "foo:bar::bad", 64, false },
855 };
856
Sehee Park8659b8d2018-11-16 10:53:16 +0900857 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900858 const auto &td = kTestData[i];
859
860 // [1.a] Add the address.
861 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900862 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900863 if (td.expectSuccess) {
864 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
865 } else {
866 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
867 ASSERT_NE(0, status.serviceSpecificErrorCode());
868 }
869
870 // [1.b] Verify the addition meets the expectation.
871 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900872 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900873 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900874 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900875 }
876
877 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900878 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900879 if (td.expectSuccess) {
880 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
881 } else {
882 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
883 ASSERT_NE(0, status.serviceSpecificErrorCode());
884 }
885
886 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900887 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900888 }
889}
Erik Kline55b06f82016-07-04 09:57:18 +0900890
Erik Kline38e51f12018-09-06 20:14:44 +0900891TEST_F(BinderTest, GetProcSysNet) {
892 const char LOOPBACK[] = "lo";
893 static const struct {
894 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900895 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900896 const char* ifname;
897 const char* parameter;
898 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900899 const int expectedReturnCode;
900 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900901 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
902 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
903 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
904 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
905 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
906 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
907 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900908 };
909
Sehee Park8659b8d2018-11-16 10:53:16 +0900910 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900911 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900912
Erik Kline38e51f12018-09-06 20:14:44 +0900913 std::string value;
914 const binder::Status status =
915 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
916
917 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900918 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900919 EXPECT_EQ(0, status.exceptionCode());
920 EXPECT_EQ(0, status.serviceSpecificErrorCode());
921 EXPECT_EQ(td.expectedValue, value);
922 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900923 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900924 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
925 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
926 }
927 }
928}
929
930TEST_F(BinderTest, SetProcSysNet) {
931 static const struct {
932 const int ipversion;
933 const int which;
934 const char* ifname;
935 const char* parameter;
936 const char* value;
937 const int expectedReturnCode;
938 } kTestData[] = {
939 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
940 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
941 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
942 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
943 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
944 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
945 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
946 };
947
Sehee Park8659b8d2018-11-16 10:53:16 +0900948 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900949 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900950 const binder::Status status =
951 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900952
953 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900954 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900955 EXPECT_EQ(0, status.exceptionCode());
956 EXPECT_EQ(0, status.serviceSpecificErrorCode());
957 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900958 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900959 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
960 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
961 }
962 }
963}
Ben Schwartze7601812017-04-28 16:38:29 -0400964
Erik Kline38e51f12018-09-06 20:14:44 +0900965TEST_F(BinderTest, GetSetProcSysNet) {
966 const int ipversion = INetd::IPV6;
967 const int category = INetd::NEIGH;
968 const std::string& tun = sTun.name();
969 const std::string parameter("ucast_solicit");
970
971 std::string value{};
972 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
973 EXPECT_FALSE(value.empty());
974 const int ival = std::stoi(value);
975 EXPECT_GT(ival, 0);
976 // Try doubling the parameter value (always best!).
977 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
978 .isOk());
979 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
980 EXPECT_EQ(2 * ival, std::stoi(value));
981 // Try resetting the parameter.
982 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
983 .isOk());
984 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
985 EXPECT_EQ(ival, std::stoi(value));
986}
987
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900988namespace {
989
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900990void expectNoTestCounterRules() {
991 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
992 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
993 std::string allRules = Join(runCommand(command), "\n");
994 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
995 }
996}
997
Bernie Innocentif6918262018-06-11 17:37:35 +0900998void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
999 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001000 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1001 path, if1.c_str(), if2.c_str(), pkt, byte));
1002}
1003
Bernie Innocentif6918262018-06-11 17:37:35 +09001004void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001005 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1006 path, if1.c_str(), if2.c_str()));
1007 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1008 path, if2.c_str(), if1.c_str()));
1009}
1010
Luke Huangcaebcbb2018-09-27 20:37:14 +08001011std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1012 const std::string& iface) {
1013 for (auto& stats : statsVec) {
1014 if (stats.iface == iface) {
1015 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1016 }
1017 }
1018 return {};
1019}
1020
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001021} // namespace
1022
1023TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001024 expectNoTestCounterRules();
1025
1026 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1027 // disabling tethering. We don't check the return value because these commands will fail if
1028 // tethering is already enabled.
1029 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1030 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1031
1032 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1033 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1034 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1035 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1036 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1037
1038 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1039 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1040 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1041 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1042 // RX is from external to internal, and TX is from internal to external.
1043 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1044 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1045
1046 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1047 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1048
1049 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1050 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1051
1052 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1053 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1054 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1055
Luke Huangcaebcbb2018-09-27 20:37:14 +08001056 std::vector<TetherStatsParcel> statsVec;
1057 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001058 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1059
Luke Huangcaebcbb2018-09-27 20:37:14 +08001060 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001061
Luke Huangcaebcbb2018-09-27 20:37:14 +08001062 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001063
1064 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1065 delTetherCounterValues(path, intIface1, extIface1);
1066 delTetherCounterValues(path, intIface2, extIface2);
1067 if (path == IP6TABLES_PATH) {
1068 delTetherCounterValues(path, intIface3, extIface2);
1069 }
1070 }
1071
1072 expectNoTestCounterRules();
1073}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001074
Luke Huang0051a622018-07-23 20:30:16 +08001075namespace {
1076
Luke Huanga5211072018-08-01 23:36:29 +08001077constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1078constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001079
1080static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1081 const char* chainName) {
1082 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1083 return runCommand(command);
1084}
1085
Luke Huang19b49c52018-10-22 12:12:05 +09001086// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001087bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001088 const std::string& expectedInterface,
1089 const std::string& expectedRule, const char* table) {
1090 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1091 for (const auto& rule : rules) {
1092 if (rule.find(expectedInterface) != std::string::npos) {
1093 if (rule.find(expectedRule) != std::string::npos) {
1094 return true;
1095 }
1096 }
1097 }
1098 return false;
1099}
1100
1101void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001102 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001103 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001104 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001105 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001106 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1107 IdletimerRule, RAW_TABLE));
1108 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001109 ifname, IdletimerRule, MANGLE_TABLE));
1110 }
1111}
1112
1113void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001114 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001115 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001116 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001117 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001118 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1119 IdletimerRule, RAW_TABLE));
1120 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001121 ifname, IdletimerRule, MANGLE_TABLE));
1122 }
1123}
1124
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001125} // namespace
1126
1127TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001128 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1129 // rule in the table. Because we only check the result after calling remove function. We might
1130 // check the actual rule which is removed by our function (maybe compare the results between
1131 // calling function before and after)
1132 binder::Status status;
1133 const struct TestData {
1134 const std::string ifname;
1135 int32_t timeout;
1136 const std::string classLabel;
1137 } idleTestData[] = {
1138 {"wlan0", 1234, "happyday"},
1139 {"rmnet_data0", 4567, "friday"},
1140 };
1141 for (const auto& td : idleTestData) {
1142 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1143 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1144 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1145
1146 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1147 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1148 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1149 }
1150}
1151
Luke Huanga67dd562018-07-17 19:58:25 +08001152namespace {
1153
1154constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1155constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1156
1157void expectStrictSetUidAccept(const int uid) {
1158 std::string uidRule = StringPrintf("owner UID match %u", uid);
1159 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1160 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001161 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1162 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001163 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1164 }
1165}
1166
1167void expectStrictSetUidLog(const int uid) {
1168 static const char logRule[] = "st_penalty_log all";
1169 std::string uidRule = StringPrintf("owner UID match %u", uid);
1170 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1171 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001172 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1173 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001174 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1175 }
1176}
1177
1178void expectStrictSetUidReject(const int uid) {
1179 static const char rejectRule[] = "st_penalty_reject all";
1180 std::string uidRule = StringPrintf("owner UID match %u", uid);
1181 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1182 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001183 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1184 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001185 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1186 }
1187}
1188
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001189} // namespace
1190
1191TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001192 binder::Status status;
1193 int32_t uid = randomUid();
1194
1195 // setUidCleartextPenalty Policy:Log with randomUid
1196 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1197 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1198 expectStrictSetUidLog(uid);
1199
1200 // setUidCleartextPenalty Policy:Accept with randomUid
1201 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1202 expectStrictSetUidAccept(uid);
1203
1204 // setUidCleartextPenalty Policy:Reject with randomUid
1205 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1206 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1207 expectStrictSetUidReject(uid);
1208
1209 // setUidCleartextPenalty Policy:Accept with randomUid
1210 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1211 expectStrictSetUidAccept(uid);
1212
1213 // test wrong policy
1214 int32_t wrongPolicy = -123;
1215 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1216 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1217}
1218
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001219namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001220
Luke Huangd1675922019-03-11 17:29:27 +08001221std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001222 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001223 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001224 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1225 // ...
1226 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1227
Luke Huangd1675922019-03-11 17:29:27 +08001228 // (dnsmasq)
1229 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1230
1231 if (maxTries == 0) return {};
1232
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001233 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001234 std::vector<std::string> result;
1235 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001236 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001237 if (result.size() || ++run > maxTries) {
1238 break;
1239 }
1240
Luke Huang728cf4c2019-03-14 19:43:02 +08001241 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001242 }
1243 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001244}
1245
Luke Huangd1675922019-03-11 17:29:27 +08001246void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001247 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001248}
1249
Luke Huang728cf4c2019-03-14 19:43:02 +08001250void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001251 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001252}
1253
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001254} // namespace
1255
1256TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001257 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001258
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001259 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1260 std::string clatAddress;
1261 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001262
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001263 // Can't start clatd on an interface that's not part of any network...
1264 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1265 EXPECT_FALSE(status.isOk());
1266 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1267
1268 // ... so create a test physical network and add our tun to it.
1269 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1270 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1271
1272 // Prefix must be 96 bits long.
1273 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1274 EXPECT_FALSE(status.isOk());
1275 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1276
1277 // Can't start clatd unless there's a default route...
1278 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1279 EXPECT_FALSE(status.isOk());
1280 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1281
1282 // so add a default route.
1283 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1284
1285 // Can't start clatd unless there's a global address...
1286 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1287 EXPECT_FALSE(status.isOk());
1288 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1289
1290 // ... so add a global address.
1291 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001292 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001293
1294 // Now expect clatd to start successfully.
1295 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1296 EXPECT_TRUE(status.isOk());
1297 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1298
1299 // Starting it again returns EBUSY.
1300 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1301 EXPECT_FALSE(status.isOk());
1302 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1303
Luke Huangd1675922019-03-11 17:29:27 +08001304 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001305
1306 // Expect clatd to stop successfully.
1307 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001308 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001309 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001310
1311 // Stopping a clatd that doesn't exist returns ENODEV.
1312 status = mNetd->clatdStop(sTun.name());
1313 EXPECT_FALSE(status.isOk());
1314 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001315 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001316
1317 // Clean up.
1318 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1319 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1320 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001321}
Luke Huang457d4702018-08-16 15:39:15 +08001322
1323namespace {
1324
1325bool getIpfwdV4Enable() {
1326 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1327 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1328 EXPECT_TRUE(!result.empty());
1329 int v4Enable = std::stoi(result[0]);
1330 return v4Enable;
1331}
1332
1333bool getIpfwdV6Enable() {
1334 static const char ipv6IpfwdCmd[] = "cat proc/sys/net/ipv6/conf/all/forwarding";
1335 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1336 EXPECT_TRUE(!result.empty());
1337 int v6Enable = std::stoi(result[0]);
1338 return v6Enable;
1339}
1340
1341void expectIpfwdEnable(bool enable) {
1342 int enableIPv4 = getIpfwdV4Enable();
1343 int enableIPv6 = getIpfwdV6Enable();
1344 EXPECT_EQ(enable, enableIPv4);
1345 EXPECT_EQ(enable, enableIPv6);
1346}
1347
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001348bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001349 std::vector<std::string> rules = listIpRules(ipVersion);
1350 for (const auto& rule : rules) {
1351 if (rule.find(ipfwdRule) != std::string::npos) {
1352 return true;
1353 }
1354 }
1355 return false;
1356}
1357
1358void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1359 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1360
1361 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1362 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1363 }
1364}
1365
1366void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1367 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1368
1369 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1370 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1371 }
1372}
1373
1374} // namespace
1375
1376TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001377 // Get ipfwd requester list from Netd
1378 std::vector<std::string> requesterList;
1379 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001381
1382 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001383 if (requesterList.size() == 0) {
1384 // No requester in Netd, ipfwd should be disabled
1385 // So add one test requester and verify
1386 status = mNetd->ipfwdEnableForwarding("TestRequester");
1387 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001388
Luke Huang728cf4c2019-03-14 19:43:02 +08001389 expectIpfwdEnable(true);
1390 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1391 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1392 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001393
Luke Huang728cf4c2019-03-14 19:43:02 +08001394 // Remove test one, verify again
1395 status = mNetd->ipfwdDisableForwarding("TestRequester");
1396 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1397
1398 expectIpfwdEnable(false);
1399 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1400 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1401 EXPECT_FALSE(ipfwdEnabled);
1402 } else {
1403 // Disable all requesters
1404 for (const auto& requester : requesterList) {
1405 status = mNetd->ipfwdDisableForwarding(requester);
1406 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1407 }
1408
1409 // After disable all requester, ipfwd should be disabled
1410 expectIpfwdEnable(false);
1411 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1412 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1413 EXPECT_FALSE(ipfwdEnabled);
1414
1415 // Enable them back
1416 for (const auto& requester : requesterList) {
1417 status = mNetd->ipfwdEnableForwarding(requester);
1418 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1419 }
1420
1421 // ipfwd should be enabled
1422 expectIpfwdEnable(true);
1423 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1424 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1425 EXPECT_TRUE(ipfwdEnabled);
1426 }
Luke Huang457d4702018-08-16 15:39:15 +08001427}
1428
1429TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001430 // Add test physical network
1431 EXPECT_TRUE(
1432 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1433 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1434 EXPECT_TRUE(
1435 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1436 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001437
Luke Huangd1827b82019-02-15 15:03:27 +08001438 binder::Status status =
1439 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1440 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1441 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001442
Luke Huangd1827b82019-02-15 15:03:27 +08001443 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1444 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1445 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001446}
Luke Huang531f5d32018-08-03 15:19:05 +08001447
1448namespace {
1449
1450constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1451constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1452constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1453constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1454constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001455constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001456
Luke Huang19b49c52018-10-22 12:12:05 +09001457// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1458// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001459bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1460 const char* chainName, const std::string& expectedTargetA,
1461 const std::string& expectedTargetB) {
1462 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1463 int matchCount = 0;
1464
1465 for (const auto& rule : rules) {
1466 if (rule.find(expectedTargetA) != std::string::npos) {
1467 if (rule.find(expectedTargetB) != std::string::npos) {
1468 matchCount++;
1469 }
1470 }
1471 }
1472 return matchCount == expectedCount;
1473}
1474
1475void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1476 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1477 std::string result = "";
1478
1479 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001480 // Quota value might be decreased while matching packets
1481 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001482}
1483
1484void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1485 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1486 std::string quotaRule = StringPrintf("quota %s", ifname);
1487
1488 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1489 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1490 BANDWIDTH_COSTLY_IF));
1491 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1492 BANDWIDTH_COSTLY_IF));
1493 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1494 BANDWIDTH_COSTLY_IF));
1495 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1496 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1497 }
1498 expectXtQuotaValueEqual(ifname, quotaBytes);
1499}
1500
1501void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1502 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1503 std::string quotaRule = StringPrintf("quota %s", ifname);
1504
1505 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1506 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1507 BANDWIDTH_COSTLY_IF));
1508 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1509 BANDWIDTH_COSTLY_IF));
1510 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1511 BANDWIDTH_COSTLY_IF));
1512 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1513 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1514 }
1515}
1516
1517void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1518 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1519 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1520 std::string alertName = StringPrintf("%sAlert", ifname);
1521
1522 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1523 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1524 }
1525 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1526}
1527
1528void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1529 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1530 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1531
1532 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1533 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1534 }
1535}
1536
1537void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1538 static const char globalAlertRule[] = "quota globalAlert";
1539 static const char globalAlertName[] = "globalAlert";
1540
1541 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001542 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001543 }
1544 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1545}
1546
1547void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1548 std::string uidRule = StringPrintf("owner UID match %u", uid);
1549
1550 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1551 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1552 }
1553}
1554
1555void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1556 std::string uidRule = StringPrintf("owner UID match %u", uid);
1557
1558 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1559 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1560 }
1561}
1562
1563} // namespace
1564
1565TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1566 long testQuotaBytes = 5550;
1567
1568 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001569 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001570 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1571
1572 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1573 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1574 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1575
1576 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1577 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1578 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1579
1580 // Remove test physical network
1581 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1582}
1583
1584TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1585 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001586 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001587 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001588 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001589 // Need to have a prior interface quota set to set an alert
1590 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1591 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1592 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1593 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1594
1595 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1596 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1597 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1598
1599 // Remove interface quota
1600 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1601 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1602 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1603
1604 // Remove test physical network
1605 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1606}
1607
1608TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1609 long testAlertBytes = 2097149;
1610
1611 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1612 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1613 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1614
1615 testAlertBytes = 2097152;
1616 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1617 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1618 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1619}
1620
1621TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1622 SKIP_IF_BPF_SUPPORTED;
1623
1624 int32_t uid = randomUid();
1625 static const char targetReject[] = "REJECT";
1626 static const char targetReturn[] = "RETURN";
1627
1628 // add NaughtyApp
1629 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1630 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1631 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1632
1633 // remove NaughtyApp
1634 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1635 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1636 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1637
1638 // add NiceApp
1639 status = mNetd->bandwidthAddNiceApp(uid);
1640 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1641 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1642
1643 // remove NiceApp
1644 status = mNetd->bandwidthRemoveNiceApp(uid);
1645 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1646 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1647}
Luke Huangb5733d72018-08-21 17:17:19 +08001648
1649namespace {
1650
Luke Huangb670d162018-08-23 20:01:13 +08001651std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1652 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1653 return runCommand(command);
1654}
1655
Luke Huangc3252cc2018-10-16 15:43:23 +08001656bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001657 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1658 for (const auto& route : routes) {
1659 if (route.find(ipRoute) != std::string::npos) {
1660 return true;
1661 }
1662 }
1663 return false;
1664}
1665
Luke Huangc3252cc2018-10-16 15:43:23 +08001666std::string ipRouteString(const std::string& ifName, const std::string& dst,
1667 const std::string& nextHop) {
1668 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1669
1670 if (!nextHop.empty()) {
1671 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001672 }
1673
Luke Huangc3252cc2018-10-16 15:43:23 +08001674 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001675}
1676
Luke Huangc3252cc2018-10-16 15:43:23 +08001677void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1678 const std::string& dst, const std::string& nextHop,
1679 const char* table) {
1680 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1681}
1682
1683void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001684 const std::string& dst, const std::string& nextHop,
1685 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001686 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001687}
1688
1689bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1690 std::vector<std::string> rules = listIpRules(ipVersion);
1691 for (const auto& rule : rules) {
1692 if (rule.find(ipRule) != std::string::npos) {
1693 return true;
1694 }
1695 }
1696 return false;
1697}
1698
1699void expectNetworkDefaultIpRuleExists(const char* ifName) {
1700 std::string networkDefaultRule =
1701 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1702
1703 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1704 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1705 }
1706}
1707
1708void expectNetworkDefaultIpRuleDoesNotExist() {
1709 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1710
1711 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1712 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1713 }
1714}
1715
1716void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1717 std::string networkPermissionRule = "";
1718 switch (permission) {
1719 case INetd::PERMISSION_NONE:
1720 networkPermissionRule = StringPrintf(
1721 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1722 break;
1723 case INetd::PERMISSION_NETWORK:
1724 networkPermissionRule = StringPrintf(
1725 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1726 break;
1727 case INetd::PERMISSION_SYSTEM:
1728 networkPermissionRule = StringPrintf(
1729 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1730 break;
1731 }
1732
1733 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1734 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1735 }
1736}
1737
1738// TODO: It is a duplicate function, need to remove it
1739bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1740 const std::string& expectedInterface,
1741 const std::string& expectedRule,
1742 const char* table) {
1743 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1744 for (const auto& rule : rules) {
1745 if (rule.find(expectedInterface) != std::string::npos) {
1746 if (rule.find(expectedRule) != std::string::npos) {
1747 return true;
1748 }
1749 }
1750 }
1751 return false;
1752}
1753
1754void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1755 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1756 std::string networkIncomingPacketMarkRule = "";
1757 switch (permission) {
1758 case INetd::PERMISSION_NONE:
1759 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1760 break;
1761 case INetd::PERMISSION_NETWORK:
1762 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1763 break;
1764 case INetd::PERMISSION_SYSTEM:
1765 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1766 break;
1767 }
1768
1769 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1770 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1771 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1772 }
1773}
1774
1775} // namespace
1776
1777TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001778 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001779 const char* ipVersion;
1780 const char* testDest;
1781 const char* testNextHop;
1782 const bool expectSuccess;
1783 } kTestData[] = {
1784 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001785 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1786 {IP_RULE_V4, "10.251.0.0/16", "", true},
1787 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1788 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001789 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001790 {IP_RULE_V6, "::/0", "2001:db8::", true},
1791 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001792 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1793 };
1794
Luke Huangc3252cc2018-10-16 15:43:23 +08001795 static const struct {
1796 const char* ipVersion;
1797 const char* testDest;
1798 const char* testNextHop;
1799 } kTestDataWithNextHop[] = {
1800 {IP_RULE_V4, "10.251.10.0/30", ""},
1801 {IP_RULE_V6, "2001:db8::/32", ""},
1802 };
1803
Luke Huangb670d162018-08-23 20:01:13 +08001804 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001805 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001806 const int testUid = randomUid();
1807 const std::vector<int32_t> testUids = {testUid};
1808
1809 // Add test physical network
1810 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1811 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1812
Luke Huangc3252cc2018-10-16 15:43:23 +08001813 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001814 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001815 const auto& td = kTestDataWithNextHop[i];
1816
1817 // All route for test tun will disappear once the tun interface is deleted.
1818 binder::Status status =
1819 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1820 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1821 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1822 sTun.name().c_str());
1823
1824 // Add system permission for test uid, setup route in legacy system table.
1825 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1826
1827 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1828 testUid);
1829 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1830 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1831 testTableLegacySystem);
1832
1833 // Remove system permission for test uid, setup route in legacy network table.
1834 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1835
1836 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1837 testUid);
1838 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1839 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1840 testTableLegacyNetwork);
1841 }
1842
Sehee Park8659b8d2018-11-16 10:53:16 +09001843 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001844 const auto& td = kTestData[i];
1845
1846 binder::Status status =
1847 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1848 if (td.expectSuccess) {
1849 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001850 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001851 sTun.name().c_str());
1852 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001853 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1854 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001855 }
1856
1857 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1858 if (td.expectSuccess) {
1859 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001860 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1861 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001862 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001863 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1864 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001865 }
1866
Luke Huangc3252cc2018-10-16 15:43:23 +08001867 // Add system permission for test uid, route will be added into legacy system table.
1868 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001869
1870 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1871 testUid);
1872 if (td.expectSuccess) {
1873 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001874 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001875 testTableLegacySystem);
1876 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001877 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1878 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001879 }
1880
1881 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1882 td.testNextHop, testUid);
1883 if (td.expectSuccess) {
1884 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001885 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1886 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001887 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001888 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1889 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001890 }
1891
Luke Huangc3252cc2018-10-16 15:43:23 +08001892 // Remove system permission for test uid, route will be added into legacy network table.
1893 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1894
1895 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1896 testUid);
1897 if (td.expectSuccess) {
1898 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1899 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1900 testTableLegacyNetwork);
1901 } else {
1902 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1903 EXPECT_NE(0, status.serviceSpecificErrorCode());
1904 }
1905
1906 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1907 td.testNextHop, testUid);
1908 if (td.expectSuccess) {
1909 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1910 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1911 testTableLegacyNetwork);
1912 } else {
1913 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1914 EXPECT_NE(0, status.serviceSpecificErrorCode());
1915 }
Luke Huangb670d162018-08-23 20:01:13 +08001916 }
1917
1918 // Remove test physical network
1919 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1920}
1921
1922TEST_F(BinderTest, NetworkPermissionDefault) {
1923 // Add test physical network
1924 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1925 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1926
Luke Huangc3252cc2018-10-16 15:43:23 +08001927 // Get current default network NetId
Luke Huangb670d162018-08-23 20:01:13 +08001928 int currentNetid;
1929 binder::Status status = mNetd->networkGetDefault(&currentNetid);
1930 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1931
1932 // Test SetDefault
1933 status = mNetd->networkSetDefault(TEST_NETID1);
1934 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1935 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1936
1937 status = mNetd->networkClearDefault();
1938 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1939 expectNetworkDefaultIpRuleDoesNotExist();
1940
1941 // Add default network back
1942 status = mNetd->networkSetDefault(currentNetid);
1943 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1944
1945 // Test SetPermission
1946 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1947 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1948 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1949 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1950
1951 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1952 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1953 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1954 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1955
1956 // Remove test physical network
1957 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1958}
1959
1960TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1961 const int testUid = randomUid();
1962 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1963 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1964 bool ret = false;
1965 status = mNetd->networkCanProtect(testUid, &ret);
1966 EXPECT_TRUE(ret);
1967
1968 status = mNetd->networkSetProtectDeny(testUid);
1969 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1970 status = mNetd->networkCanProtect(testUid, &ret);
1971 EXPECT_FALSE(ret);
1972}
1973
1974namespace {
1975
Luke Huangb5733d72018-08-21 17:17:19 +08001976int readIntFromPath(const std::string& path) {
1977 std::string result = "";
1978 EXPECT_TRUE(ReadFileToString(path, &result));
1979 return std::stoi(result);
1980}
1981
1982int getTetherAcceptIPv6Ra(const std::string& ifName) {
1983 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1984 return readIntFromPath(path);
1985}
1986
1987bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1988 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1989 return readIntFromPath(path);
1990}
1991
1992int getTetherIPv6DadTransmits(const std::string& ifName) {
1993 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1994 return readIntFromPath(path);
1995}
1996
1997bool getTetherEnableIPv6(const std::string& ifName) {
1998 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1999 int disableIPv6 = readIntFromPath(path);
2000 return !disableIPv6;
2001}
2002
2003bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2004 for (const auto& iface : ifList) {
2005 if (iface == ifName) {
2006 return true;
2007 }
2008 }
2009 return false;
2010}
2011
2012void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2013 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2014 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2015 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2016 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2017}
2018
2019void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2020 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2021 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2022 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2023 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2024}
2025
2026void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2027 const std::string& ifName) {
2028 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2029}
2030
2031void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2032 const std::string& ifName) {
2033 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2034}
2035
2036void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2037 const std::vector<std::string>& testDnsAddrs) {
2038 EXPECT_TRUE(dnsList == testDnsAddrs);
2039}
2040
2041} // namespace
2042
2043TEST_F(BinderTest, TetherStartStopStatus) {
2044 std::vector<std::string> noDhcpRange = {};
2045 static const char dnsdName[] = "dnsmasq";
2046
2047 binder::Status status = mNetd->tetherStart(noDhcpRange);
2048 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002049 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002050
2051 bool tetherEnabled;
2052 status = mNetd->tetherIsEnabled(&tetherEnabled);
2053 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2054 EXPECT_TRUE(tetherEnabled);
2055
2056 status = mNetd->tetherStop();
2057 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002058 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002059
2060 status = mNetd->tetherIsEnabled(&tetherEnabled);
2061 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2062 EXPECT_FALSE(tetherEnabled);
2063}
2064
2065TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2066 // TODO: verify if dnsmasq update interface successfully
2067
2068 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2069 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2070 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2071
2072 std::vector<std::string> ifList;
2073 status = mNetd->tetherInterfaceList(&ifList);
2074 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2075 expectTetherInterfaceExists(ifList, sTun.name());
2076
2077 status = mNetd->tetherInterfaceRemove(sTun.name());
2078 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2079 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2080
2081 status = mNetd->tetherInterfaceList(&ifList);
2082 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2083 expectTetherInterfaceNotExists(ifList, sTun.name());
2084}
2085
2086TEST_F(BinderTest, TetherDnsSetList) {
2087 // TODO: verify if dnsmasq update dns successfully
2088 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3"};
2089
2090 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2091 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2092
2093 std::vector<std::string> dnsList;
2094 status = mNetd->tetherDnsList(&dnsList);
2095 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2096 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002097}
2098
2099namespace {
2100
2101constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2102constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2103constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2104constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2105constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2106constexpr char FIREWALL_STANDBY[] = "fw_standby";
2107constexpr char targetReturn[] = "RETURN";
2108constexpr char targetDrop[] = "DROP";
2109
2110void expectFirewallWhitelistMode() {
2111 static const char dropRule[] = "DROP all";
2112 static const char rejectRule[] = "REJECT all";
2113 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2114 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2115 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2116 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2117 }
2118}
2119
2120void expectFirewallBlacklistMode() {
2121 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2122 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2123 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2124 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2125 }
2126}
2127
2128bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2129 const std::string& expectedInterface,
2130 const std::string& expectedRule) {
2131 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2132 // Expected rule:
2133 // Chain fw_INPUT (1 references)
2134 // pkts bytes target prot opt in out source destination
2135 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2136 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2137 int firstRuleIndex = 2;
2138 if (rules.size() < 4) return false;
2139 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2140 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2141 return true;
2142 }
2143 }
2144 return false;
2145}
2146
2147// TODO: It is a duplicate function, need to remove it
2148bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2149 const std::string& expectedInterface,
2150 const std::string& expectedRule) {
2151 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2152 for (const auto& rule : rules) {
2153 if (rule.find(expectedInterface) != std::string::npos) {
2154 if (rule.find(expectedRule) != std::string::npos) {
2155 return true;
2156 }
2157 }
2158 }
2159 return false;
2160}
2161
2162void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2163 static const char returnRule[] = "RETURN all";
2164 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2165 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2166 returnRule));
2167 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2168 returnRule));
2169 }
2170}
2171
2172void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2173 static const char returnRule[] = "RETURN all";
2174 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2175 EXPECT_FALSE(
2176 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2177 EXPECT_FALSE(
2178 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2179 }
2180}
2181
2182bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2183 const std::string& expectedTarget,
2184 const std::string& expectedRule) {
2185 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2186 int firstRuleIndex = 2;
2187 if (rules.size() < 4) return false;
2188 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2189 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2190 return true;
2191 }
2192 }
2193 return false;
2194}
2195
2196bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2197 const std::string& expectedTarget,
2198 const std::string& expectedRule) {
2199 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2200 int lastRuleIndex = rules.size() - 1;
2201 if (lastRuleIndex < 0) return false;
2202 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2203 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2204 return true;
2205 }
2206 }
2207 return false;
2208}
2209
2210void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2211 std::string uidRule = StringPrintf("owner UID match %u", uid);
2212 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2213 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2214}
2215
2216void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2217 std::string uidRule = StringPrintf("owner UID match %u", uid);
2218 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2219 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2220}
2221
2222void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2223 std::string uidRule = StringPrintf("owner UID match %u", uid);
2224 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2225 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2226}
2227
2228void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2229 std::string uidRule = StringPrintf("owner UID match %u", uid);
2230 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2231 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2232}
2233
2234bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2235 std::vector<std::string> inputRules =
2236 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2237 std::vector<std::string> outputRules =
2238 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2239 int inputLastRuleIndex = inputRules.size() - 1;
2240 int outputLastRuleIndex = outputRules.size() - 1;
2241
2242 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2243 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2244 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2245 return true;
2246 }
2247 }
2248 return false;
2249}
2250
2251void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2252 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2253 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2254}
2255
2256void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2257 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2258 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2259 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2260 }
2261}
2262
2263} // namespace
2264
2265TEST_F(BinderTest, FirewallSetFirewallType) {
2266 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2267 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2268 expectFirewallWhitelistMode();
2269
2270 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2271 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2272 expectFirewallBlacklistMode();
2273
2274 // set firewall type blacklist twice
2275 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2276 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2277 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2278 expectFirewallBlacklistMode();
2279
2280 // set firewall type whitelist twice
2281 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2282 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2283 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2284 expectFirewallWhitelistMode();
2285
2286 // reset firewall type to default
2287 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2288 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2289 expectFirewallBlacklistMode();
2290}
2291
2292TEST_F(BinderTest, FirewallSetInterfaceRule) {
2293 // setinterfaceRule is not supported in BLACKLIST MODE
2294 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2295 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2296
2297 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2298 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2299
2300 // set WHITELIST mode first
2301 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2302 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2303
2304 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2305 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2306 expectFirewallInterfaceRuleAllowExists(sTun.name());
2307
2308 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2309 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2310 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2311
2312 // reset firewall mode to default
2313 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2314 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2315 expectFirewallBlacklistMode();
2316}
2317
2318TEST_F(BinderTest, FirewallSetUidRule) {
2319 SKIP_IF_BPF_SUPPORTED;
2320
2321 int32_t uid = randomUid();
2322
2323 // Doze allow
2324 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2325 INetd::FIREWALL_RULE_ALLOW);
2326 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2327 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2328
2329 // Doze deny
2330 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2331 INetd::FIREWALL_RULE_DENY);
2332 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2333 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2334
2335 // Powersave allow
2336 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2337 INetd::FIREWALL_RULE_ALLOW);
2338 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2339 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2340
2341 // Powersave deny
2342 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2343 INetd::FIREWALL_RULE_DENY);
2344 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2345 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2346
2347 // Standby deny
2348 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2349 INetd::FIREWALL_RULE_DENY);
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2352
2353 // Standby allow
2354 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2355 INetd::FIREWALL_RULE_ALLOW);
2356 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2357 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2358
2359 // None deny in BLACKLIST
2360 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2361 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2362 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2363 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2364
2365 // None allow in BLACKLIST
2366 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2368 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2369 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2370
2371 // set firewall type whitelist twice
2372 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2373 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2374 expectFirewallWhitelistMode();
2375
2376 // None allow in WHITELIST
2377 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2378 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2379 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2380 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2381
2382 // None deny in WHITELIST
2383 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2384 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2385 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2386 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2387
2388 // reset firewall mode to default
2389 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2390 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2391 expectFirewallBlacklistMode();
2392}
2393
2394TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2395 SKIP_IF_BPF_SUPPORTED;
2396
2397 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2398 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2399 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2400
2401 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2402 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2403 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2404
2405 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2406 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2407 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2408
2409 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2410 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2411 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2412
2413 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2414 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2415 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2416
2417 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2418 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2419 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2420}
Luke Huangf7782042018-08-08 13:13:04 +08002421
2422namespace {
2423
2424std::string hwAddrToStr(unsigned char* hwaddr) {
2425 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2426 hwaddr[4], hwaddr[5]);
2427}
2428
2429int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2430 int prefixLength = 0;
2431 uint32_t m = ntohl(mask);
2432 while (m & (1 << 31)) {
2433 prefixLength++;
2434 m = m << 1;
2435 }
2436 return prefixLength;
2437}
2438
2439std::string toStdString(const String16& s) {
2440 return std::string(String8(s.string()));
2441}
2442
2443android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2444 const auto& sys = sSyscalls.get();
2445 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2446 EXPECT_TRUE(isOk(fd.status()));
2447
2448 struct ifreq ifr = {};
2449 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2450
2451 return sys.ioctl(fd.value(), flag, &ifr);
2452}
2453
2454std::string getInterfaceHwAddr(const std::string& ifName) {
2455 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2456
2457 unsigned char hwaddr[ETH_ALEN] = {};
2458 if (isOk(res.status())) {
2459 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2460 }
2461
2462 return hwAddrToStr(hwaddr);
2463}
2464
2465int getInterfaceIPv4Prefix(const std::string& ifName) {
2466 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2467
2468 int prefixLength = 0;
2469 if (isOk(res.status())) {
2470 prefixLength = ipv4NetmaskToPrefixLength(
2471 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2472 }
2473
2474 return prefixLength;
2475}
2476
2477std::string getInterfaceIPv4Addr(const std::string& ifName) {
2478 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2479
2480 struct in_addr addr = {};
2481 if (isOk(res.status())) {
2482 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2483 }
2484
2485 return std::string(inet_ntoa(addr));
2486}
2487
2488std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2489 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2490
2491 unsigned flags = 0;
2492 if (isOk(res.status())) {
2493 flags = res.value().ifr_flags;
2494 }
2495
2496 std::vector<std::string> ifFlags;
2497 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2498 : toStdString(INetd::IF_STATE_DOWN()));
2499
2500 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2501 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2502 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2503 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2504 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2505
2506 return ifFlags;
2507}
2508
2509bool compareListInterface(const std::vector<std::string>& interfaceList) {
2510 const auto& res = InterfaceController::getIfaceNames();
2511 EXPECT_TRUE(isOk(res));
2512
2513 std::vector<std::string> resIfList;
2514 resIfList.reserve(res.value().size());
2515 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2516
2517 return resIfList == interfaceList;
2518}
2519
2520int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2521 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2522 return readIntFromPath(path);
2523}
2524
2525bool getInterfaceEnableIPv6(const std::string& ifName) {
2526 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2527
2528 int disableIPv6 = readIntFromPath(path);
2529 return !disableIPv6;
2530}
2531
2532int getInterfaceMtu(const std::string& ifName) {
2533 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2534 return readIntFromPath(path);
2535}
2536
2537void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2538 EXPECT_TRUE(compareListInterface(interfaceList));
2539}
2540
2541void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2542 const InterfaceConfigurationParcel& interfaceCfg) {
2543 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2544 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2545 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2546 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2547}
2548
2549void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2550 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2551 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2552
2553 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2554 for (const auto& flag : setCfg.flags) {
2555 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2556 }
2557}
2558
2559void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2560 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2561 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2562}
2563
2564void expectInterfaceNoAddr(const std::string& ifName) {
2565 // noAddr
2566 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2567 // noPrefix
2568 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2569}
2570
2571void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2572 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2573 EXPECT_EQ(enableIPv6, enable);
2574}
2575
2576void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2577 int mtuSize = getInterfaceMtu(ifName);
2578 EXPECT_EQ(mtu, mtuSize);
2579}
2580
2581InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2582 const std::string& addr, int prefixLength,
2583 const std::vector<std::string>& flags) {
2584 InterfaceConfigurationParcel cfg;
2585 cfg.ifName = ifName;
2586 cfg.hwAddr = "";
2587 cfg.ipv4Addr = addr;
2588 cfg.prefixLength = prefixLength;
2589 cfg.flags = flags;
2590 return cfg;
2591}
2592
2593void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2594 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2595 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2596
2597 for (const auto& flag : expectedFlags) {
2598 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2599 interfaceCfg.flags.end());
2600 }
2601
2602 for (const auto& flag : unexpectedFlags) {
2603 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2604 interfaceCfg.flags.end());
2605 }
2606}
2607
2608} // namespace
2609
2610TEST_F(BinderTest, InterfaceList) {
2611 std::vector<std::string> interfaceListResult;
2612
2613 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2614 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2615 expectInterfaceList(interfaceListResult);
2616}
2617
2618TEST_F(BinderTest, InterfaceGetCfg) {
2619 InterfaceConfigurationParcel interfaceCfgResult;
2620
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 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2626 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2627 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2628 expectTunFlags(interfaceCfgResult);
2629
2630 // Remove test physical network
2631 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2632}
2633
2634TEST_F(BinderTest, InterfaceSetCfg) {
2635 const std::string testAddr = "192.0.2.3";
2636 const int testPrefixLength = 24;
2637 std::vector<std::string> upFlags = {"up"};
2638 std::vector<std::string> downFlags = {"down"};
2639
2640 // Add test physical network
2641 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2642 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2643
2644 // Set tun interface down.
2645 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2646 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2647 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2648 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2649
2650 // Set tun interface up again.
2651 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2652 status = mNetd->interfaceSetCfg(interfaceCfg);
2653 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2654 status = mNetd->interfaceClearAddrs(sTun.name());
2655 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2656
2657 // Remove test physical network
2658 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2659}
2660
2661TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2662 // enable
2663 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2664 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2665 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2666
2667 // disable
2668 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2669 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2670 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2671}
2672
2673TEST_F(BinderTest, InterfaceClearAddr) {
2674 const std::string testAddr = "192.0.2.3";
2675 const int testPrefixLength = 24;
2676 std::vector<std::string> noFlags{};
2677
2678 // Add test physical network
2679 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2680 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2681
2682 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2683 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2684 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2685 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2686
2687 status = mNetd->interfaceClearAddrs(sTun.name());
2688 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2689 expectInterfaceNoAddr(sTun.name());
2690
2691 // Remove test physical network
2692 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2693}
2694
2695TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2696 // Add test physical network
2697 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2698 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2699
2700 // disable
2701 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2702 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2703 expectInterfaceEnableIPv6(sTun.name(), false);
2704
2705 // enable
2706 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2707 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2708 expectInterfaceEnableIPv6(sTun.name(), true);
2709
2710 // Remove test physical network
2711 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2712}
2713
2714TEST_F(BinderTest, InterfaceSetMtu) {
2715 const int testMtu = 1200;
2716
2717 // Add test physical network
2718 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2719 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2720
2721 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2722 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2723 expectInterfaceMtu(sTun.name(), testMtu);
2724
2725 // Remove test physical network
2726 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2727}
Luke Huang19b49c52018-10-22 12:12:05 +09002728
2729namespace {
2730
2731constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2732constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002733constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002734constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2735
Luke Huangae038f82018-11-05 11:17:31 +09002736int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002737 return listIptablesRuleByTable(binary, table, chainName).size();
2738}
2739
2740bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2741 const std::vector<std::string>& targetVec) {
2742 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2743 if (targetVec.size() != rules.size() - 2) {
2744 return false;
2745 }
2746
2747 /*
Luke Huangae038f82018-11-05 11:17:31 +09002748 * Check that the rules match. Note that this function matches substrings, not entire rules,
2749 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002750 * Skip first two lines since rules start from third line.
2751 * Chain chainName (x references)
2752 * pkts bytes target prot opt in out source destination
2753 * ...
2754 */
2755 int rIndex = 2;
2756 for (const auto& target : targetVec) {
2757 if (rules[rIndex].find(target) == std::string::npos) {
2758 return false;
2759 }
2760 rIndex++;
2761 }
2762 return true;
2763}
2764
2765void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2766 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2767 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2768 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002769 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002770 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2771 "DROP"};
2772
2773 // V4
2774 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2775 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002776 EXPECT_TRUE(
2777 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002778 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2779
Luke Huangae038f82018-11-05 11:17:31 +09002780 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002781 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2782
2783 // V6
2784 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002785 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2786 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002787
2788 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2789 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2790 extIf));
2791 }
2792}
2793
2794void expectNatDisable() {
2795 // It is the default DROP rule with tethering disable.
2796 // Chain tetherctrl_FORWARD (1 references)
2797 // pkts bytes target prot opt in out source destination
2798 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2799 std::vector<std::string> forwardV4Match = {"DROP"};
2800 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2801
2802 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002803 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2804 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002805
Luke Huangae038f82018-11-05 11:17:31 +09002806 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2807 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002808
2809 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2810}
2811
2812} // namespace
2813
2814TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002815 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2816 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2817 expectNatEnable(sTun.name(), sTun2.name());
2818
2819 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2820 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2821 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002822}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002823
2824namespace {
2825
2826using TripleInt = std::array<int, 3>;
2827
2828TripleInt readProcFileToTripleInt(const std::string& path) {
2829 std::string valueString;
2830 int min, def, max;
2831 EXPECT_TRUE(ReadFileToString(path, &valueString));
2832 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2833 return {min, def, max};
2834}
2835
2836void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2837 std::string testRmemValues =
2838 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2839 std::string testWmemValues =
2840 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2841 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2842
2843 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2844 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2845
2846 for (int i = 0; i < 3; i++) {
2847 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2848 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2849 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2850 }
2851}
2852
2853} // namespace
2854
2855TEST_F(BinderTest, TcpBufferSet) {
2856 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2857 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2858 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2859 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2860
2861 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2862 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2863}
Luke Huang528af602018-08-29 19:06:05 +08002864
Chenbo Feng48eaed32018-12-26 17:40:21 -08002865namespace {
2866
2867void checkUidsExist(std::vector<int32_t>& uids, bool exist) {
2868 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2869 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2870 for (int32_t uid : uids) {
2871 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2872 if (exist) {
2873 EXPECT_TRUE(isOk(permission));
2874 EXPECT_EQ(ALLOW_SOCK_CREATE, permission.value());
2875 } else {
2876 EXPECT_FALSE(isOk(permission));
2877 EXPECT_EQ(ENOENT, permission.status().code());
2878 }
2879 }
2880}
2881
2882} // namespace
2883
2884TEST_F(BinderTest, TestInternetPermission) {
2885 SKIP_IF_BPF_NOT_SUPPORTED;
2886
2887 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2888
2889 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
2890 checkUidsExist(appUids, true);
2891 mNetd->trafficSetNetPermForUids(INetd::NO_PERMISSIONS, appUids);
2892 checkUidsExist(appUids, false);
2893}
2894
Luke Huang528af602018-08-29 19:06:05 +08002895TEST_F(BinderTest, UnsolEvents) {
2896 auto testUnsolService = android::net::TestUnsolService::start();
2897 std::string oldTunName = sTun.name();
2898 std::string newTunName = "unsolTest";
2899 testUnsolService->tarVec.push_back(oldTunName);
2900 testUnsolService->tarVec.push_back(newTunName);
2901 auto& cv = testUnsolService->getCv();
2902 auto& cvMutex = testUnsolService->getCvMutex();
2903 binder::Status status = mNetd->registerUnsolicitedEventListener(
2904 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2905 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2906
2907 // TODO: Add test for below events
2908 // StrictCleartextDetected / InterfaceDnsServersAdded
2909 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2910
2911 {
2912 std::unique_lock lock(cvMutex);
2913
2914 // Re-init test Tun, and we expect that we will get some unsol events.
2915 // Use the test Tun device name to verify if we receive its unsol events.
2916 sTun.destroy();
2917 // Use predefined name
2918 sTun.init(newTunName);
2919
2920 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2921 }
2922
2923 // bit mask 1101101000
2924 // Test only covers below events currently
2925 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2926 InterfaceLinkStatusChanged | RouteChanged;
2927 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Bernie Innocentia5161a02019-01-30 22:40:53 +09002928}