blob: 917bf5d3baf8e757ffd025ed29ca7cd879d9106d [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>
Luke Huang2ff8b342019-04-30 15:33:33 +080046#include <binder/IPCThreadState.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080047#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070048#include <bpf/BpfUtils.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080049#include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
50#include <com/android/internal/net/IOemNetd.h>
Robin Leeb8087362016-03-30 18:43:08 +010051#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090052#include <gtest/gtest.h>
53#include <logwrap/logwrap.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080054#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090055#include <netutils/ifc.h>
Luke Huangd2861982019-05-17 19:47:28 +080056#include "Fwmark.h"
Nathan Harold21299f72018-03-16 20:13:03 -070057#include "InterfaceController.h"
Luke Huangd2861982019-05-17 19:47:28 +080058#include "NetdClient.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090059#include "NetdConstants.h"
Luke Huang528af602018-08-29 19:06:05 +080060#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070061#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090062#include "android/net/INetd.h"
63#include "binder/IServiceManager.h"
Mike Yue7e332f2019-03-13 17:15:48 +080064#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070065#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080066#include "netid_client.h" // NETID_UNSET
Mike Yu5ae61542018-10-19 22:11:43 +080067#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090068
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090069#define IP_PATH "/system/bin/ip"
70#define IP6TABLES_PATH "/system/bin/ip6tables"
71#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090072#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080073#define RAW_TABLE "raw"
74#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080075#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090076#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090077
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090078namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090079
80using android::IBinder;
81using android::IServiceManager;
82using android::sp;
83using android::String16;
84using android::String8;
85using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080086using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090087using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090088using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080089using android::base::Trim;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090090using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080091using android::net::InterfaceConfigurationParcel;
92using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080093using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090094using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090095using android::net::UidRangeParcel;
Luke Huangf7782042018-08-08 13:13:04 +080096using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +080097using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +010098
99static const char* IP_RULE_V4 = "-4";
100static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900101static const int TEST_NETID1 = 65501;
102static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800103
104// Use maximum reserved appId for applications to avoid conflict with existing
105// uids.
106static const int TEST_UID1 = 99999;
107static const int TEST_UID2 = 99998;
108
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900109constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900110
Benedict Wongb2daefb2017-12-06 22:05:46 -0800111static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
112static const std::string ESP_ALLOW_RULE("esp");
113
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900114class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900115 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900117 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900118 sp<IBinder> binder = sm->getService(String16("netd"));
119 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900120 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121 }
122 }
123
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900124 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900125 ASSERT_NE(nullptr, mNetd.get());
126 }
127
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900128 void TearDown() override {
129 mNetd->networkDestroy(TEST_NETID1);
130 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800131 setNetworkForProcess(NETID_UNSET);
132 // Restore default network
133 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900134 }
135
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900136 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700137
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900138 // Static because setting up the tun interface takes about 40ms.
139 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900140 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900141 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900142 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900143 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900144 }
145
146 static void TearDownTestCase() {
147 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900148 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900149 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900150 }
151
152 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900153
Luke Huangd2861982019-05-17 19:47:28 +0800154 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
155 int fallthroughNetId = TEST_NETID1);
156
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900157 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800158 // Use -1 to represent that default network was not modified because
159 // real netId must be an unsigned value.
160 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900161 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900162 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900163 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900164};
165
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900166TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900167TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900168
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900169class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900170 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700171 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900172 virtual ~TimedOperation() {
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900173 fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900174 }
175
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900176 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900177 std::string mName;
178};
179
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900180TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900181 TimedOperation t("isAlive RPC");
182 bool isAlive = false;
183 mNetd->isAlive(&isAlive);
184 ASSERT_TRUE(isAlive);
185}
186
187static int randomUid() {
188 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
189}
190
Robin Leeb8087362016-03-30 18:43:08 +0100191static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900192 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900193 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
194 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900195 perror("popen");
196 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900197 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900198
199 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100200 size_t bufsize = 0;
201 ssize_t linelen = 0;
202 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900203 lines.push_back(std::string(line, linelen));
204 free(line);
205 line = nullptr;
206 }
207
208 pclose(f);
209 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900210}
211
Robin Leeb8087362016-03-30 18:43:08 +0100212static std::vector<std::string> listIpRules(const char *ipVersion) {
213 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
214 return runCommand(command);
215}
216
217static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900218 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100219 return runCommand(command);
220}
221
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900222static int iptablesRuleLineLength(const char *binary, const char *chainName) {
223 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900224}
225
Benedict Wongb2daefb2017-12-06 22:05:46 -0800226static bool iptablesRuleExists(const char *binary,
227 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900228 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800229 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900230 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800231 if(rule.find(expectedRule) != std::string::npos) {
232 return true;
233 }
234 }
235 return false;
236}
237
238static bool iptablesNoSocketAllowRuleExists(const char *chainName){
239 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
240 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
241}
242
243static bool iptablesEspAllowRuleExists(const char *chainName){
244 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
245 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
246}
247
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900248TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700249 SKIP_IF_BPF_SUPPORTED;
250
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900251 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
252 const int kNumUids = 500;
253 std::vector<int32_t> noUids(0);
254 std::vector<int32_t> uids(kNumUids);
255 for (int i = 0; i < kNumUids; i++) {
256 uids[i] = randomUid();
257 }
258
259 bool ret;
260 {
261 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900262 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900263 }
264 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800265 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
266 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
267 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
268 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900269 {
270 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900271 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900272 }
273 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900274 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
275 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900276
277 {
278 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900279 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900280 }
281 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900282 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
283 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800284 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
285 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900286
287 {
288 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900289 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900290 }
291 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900292 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
293 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900294
295 // Check that the call fails if iptables returns an error.
296 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900297 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900298 EXPECT_EQ(false, ret);
299}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900300
Benedict Wong319f17e2018-05-15 17:06:44 -0700301TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700302 const struct TestData {
303 const std::string family;
304 const std::string deviceName;
305 const std::string localAddress;
306 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800307 int32_t iKey;
308 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700309 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800310 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700311 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
312 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
313 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800314 };
315
Sehee Park8659b8d2018-11-16 10:53:16 +0900316 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700317 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800318
319 binder::Status status;
320
Benedict Wong319f17e2018-05-15 17:06:44 -0700321 // Create Tunnel Interface.
322 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700323 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800324 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
325
Benedict Wonga450e722018-05-07 10:29:02 -0700326 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900327 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700328
Benedict Wong319f17e2018-05-15 17:06:44 -0700329 // Update Tunnel Interface.
330 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700331 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800332 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
333
Benedict Wong319f17e2018-05-15 17:06:44 -0700334 // Remove Tunnel Interface.
335 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800336 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700337
338 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900339 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800340 }
341}
342
Benedict Wong1cb73df2018-12-03 00:54:14 -0800343TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
344 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
345 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
346
347 int sockOptVal = UDP_ENCAP_ESPINUDP;
348 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
349
350 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
351 EXPECT_TRUE(res.isOk());
352
353 struct stat info;
354 EXPECT_EQ(0, fstat(sockFd.get(), &info));
355 EXPECT_EQ(1001, (int) info.st_uid);
356}
357
Nathan Harold2deff322018-05-10 14:03:48 -0700358// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
359// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
360#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900361
362using android::net::XfrmController;
363
Benedict Wonga04ffa72018-05-09 21:42:42 -0700364static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
365 static_cast<int>(android::net::XfrmDirection::OUT)};
366static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
367
Nathan Harold21299f72018-03-16 20:13:03 -0700368#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
369 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900370bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900371 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700372 SCOPED_TRACE(status);
373 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
374
375 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700376 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700377 SCOPED_TRACE(status);
378 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
379
380 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700381 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
382 0xD00D, 0xE00D, false)
383 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700384}
385
Benedict Wonga04ffa72018-05-09 21:42:42 -0700386TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900387 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700388
389 // Repeat to ensure cleanup and recreation works correctly
390 for (int i = 0; i < 2; i++) {
391 for (int direction : XFRM_DIRECTIONS) {
392 for (int addrFamily : ADDRESS_FAMILIES) {
393 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700394 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700395 EXPECT_TRUE(status.isOk())
396 << " family: " << addrFamily << " direction: " << direction;
397 }
398 }
399
400 // Cleanup
401 for (int direction : XFRM_DIRECTIONS) {
402 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700403 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700404 EXPECT_TRUE(status.isOk());
405 }
406 }
407 }
408}
409
410TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
411 binder::Status status;
412
413 // Repeat to ensure cleanup and recreation works correctly
414 for (int i = 0; i < 2; i++) {
415 for (int direction : XFRM_DIRECTIONS) {
416 for (int addrFamily : ADDRESS_FAMILIES) {
417 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700418 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700419 EXPECT_TRUE(status.isOk())
420 << " family: " << addrFamily << " direction: " << direction;
421 }
422 }
423
424 // Cleanup
425 for (int direction : XFRM_DIRECTIONS) {
426 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700427 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700428 EXPECT_TRUE(status.isOk());
429 }
430 }
431 }
432}
433
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900434TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900435 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700436 status = XfrmController::Init();
437 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700438
439 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
440 // feature.
441 if (status.code() == EOPNOTSUPP) return;
442
Nathan Harold21299f72018-03-16 20:13:03 -0700443 ASSERT_TRUE(status.ok());
444
445 int32_t spi = 0;
446
447 ASSERT_TRUE(allocateIpSecResources(true, &spi));
448 ASSERT_TRUE(allocateIpSecResources(false, &spi));
449
450 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700451 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700452 ASSERT_TRUE(allocateIpSecResources(true, &spi));
453
454 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700455 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700456 SCOPED_TRACE(status);
457 ASSERT_TRUE(status.ok());
458
Benedict Wonga450e722018-05-07 10:29:02 -0700459 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700460 SCOPED_TRACE(status);
461 ASSERT_TRUE(status.ok());
462
463 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700464 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700465}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900466
467#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700468
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900469static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900470 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900471
472 // Output looks like this:
473 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900474 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900475 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900476 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900477 //
478 // or:
479 //
480 // Chain bw_data_saver (1 references)
481 // target prot opt source destination
482 // ... possibly connectivity critical packet rules here ...
483 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900484
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900485 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900486
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900487 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
488 // Data saver disabled.
489 return 0;
490 }
491
492 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
493
494 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
495 // Data saver enabled.
496 return 1;
497 }
498
499 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900500}
501
502bool enableDataSaver(sp<INetd>& netd, bool enable) {
503 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
504 bool ret;
505 netd->bandwidthEnableDataSaver(enable, &ret);
506 return ret;
507}
508
509int getDataSaverState() {
510 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
511 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
512 EXPECT_EQ(enabled4, enabled6);
513 EXPECT_NE(-1, enabled4);
514 EXPECT_NE(-1, enabled6);
515 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
516 return -1;
517 }
518 return enabled6;
519}
520
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900521TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900522 const int wasEnabled = getDataSaverState();
523 ASSERT_NE(-1, wasEnabled);
524
525 if (wasEnabled) {
526 ASSERT_TRUE(enableDataSaver(mNetd, false));
527 EXPECT_EQ(0, getDataSaverState());
528 }
529
530 ASSERT_TRUE(enableDataSaver(mNetd, false));
531 EXPECT_EQ(0, getDataSaverState());
532
533 ASSERT_TRUE(enableDataSaver(mNetd, true));
534 EXPECT_EQ(1, getDataSaverState());
535
536 ASSERT_TRUE(enableDataSaver(mNetd, true));
537 EXPECT_EQ(1, getDataSaverState());
538
539 if (!wasEnabled) {
540 ASSERT_TRUE(enableDataSaver(mNetd, false));
541 EXPECT_EQ(0, getDataSaverState());
542 }
543}
Robin Leeb8087362016-03-30 18:43:08 +0100544
Luke Huang94658ac2018-10-18 19:35:12 +0900545static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
546 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100547 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100548 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100549 std::vector<std::string> rules = listIpRules(ipVersion);
550
551 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900552 std::string suffix =
553 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900554 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800555 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100556 return true;
557 }
558 }
559 return false;
560}
561
Luke Huang94658ac2018-10-18 19:35:12 +0900562static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
563 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100564 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
565 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
566 EXPECT_EQ(existsIp4, existsIp6);
567 return existsIp4;
568}
569
Luke Huang94658ac2018-10-18 19:35:12 +0900570namespace {
571
572UidRangeParcel makeUidRangeParcel(int start, int stop) {
573 UidRangeParcel res;
574 res.start = start;
575 res.stop = stop;
576
577 return res;
578}
579
580} // namespace
581
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900582TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800583 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
584 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
585 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900586 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
587 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900588
589 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
590 EXPECT_EQ(EBUSY,
591 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
592
593 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
594 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
595 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800596 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900597}
598
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900599TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900600 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
601
cken67cd14c2018-12-05 17:26:59 +0900602 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
603 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900604 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
605
Luke Huang94658ac2018-10-18 19:35:12 +0900606 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
607 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
608 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900609 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
610
611 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
612
613 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
614 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
615 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
616 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
617
618 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
619 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
620 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
621 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
622
623 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
624}
625
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900626TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100627 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100628
Luke Huang94658ac2018-10-18 19:35:12 +0900629 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
630 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100631
632 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
633 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
634
635 // Create two valid rules.
636 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
637 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
638 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
639 for (auto const& range : uidRanges) {
640 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
641 }
642
643 // Remove the rules.
644 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
645 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
646 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
647 for (auto const& range : uidRanges) {
648 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
649 }
650
651 // Fail to remove the rules a second time after they are already deleted.
652 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
653 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
654 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
655
656 // All rules should be the same as before.
657 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
658 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
659}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900660
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900661// Create a socket pair that isLoopbackSocket won't think is local.
662void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900663 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900664 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900665 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
666
667 socklen_t addrlen = sizeof(server6);
668 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
669 ASSERT_EQ(0, listen(*serverSocket, 10));
670
Bernie Innocentif6918262018-06-11 17:37:35 +0900671 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900672 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900673 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900674 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
675 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
676
Bernie Innocentif6918262018-06-11 17:37:35 +0900677 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900678 ASSERT_NE(-1, *acceptedSocket);
679
680 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
681}
682
683void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
684 char buf[4096];
685 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
686 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
687 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
688}
689
690void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
691 // Check that the client socket was closed with ECONNABORTED.
692 int ret = write(clientSocket, "foo", sizeof("foo"));
693 int err = errno;
694 EXPECT_EQ(-1, ret);
695 EXPECT_EQ(ECONNABORTED, err);
696
697 // Check that it sent a RST to the server.
698 ret = write(acceptedSocket, "foo", sizeof("foo"));
699 err = errno;
700 EXPECT_EQ(-1, ret);
701 EXPECT_EQ(ECONNRESET, err);
702}
703
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900704TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900705 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900706 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900707
708 // Pick a random UID in the system UID range.
709 constexpr int baseUid = AID_APP - 2000;
710 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
711 int uid = baseUid + 500 + arc4random_uniform(1000);
712 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
713
714 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900715 std::vector<UidRangeParcel> uidRanges = {
716 makeUidRangeParcel(baseUid + 42, baseUid + 449),
717 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
718 makeUidRangeParcel(baseUid + 498, uid - 1),
719 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900720 };
721 // A skip list that doesn't contain UID.
722 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
723
724 // Close sockets. Our test socket should be intact.
725 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
726 checkSocketpairOpen(clientSocket, acceptedSocket);
727
728 // UID ranges that do contain uid.
729 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900730 makeUidRangeParcel(baseUid + 42, baseUid + 449),
731 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
732 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900733 };
734 // Add uid to the skip list.
735 skipUids.push_back(uid);
736
737 // Close sockets. Our test socket should still be intact because it's in the skip list.
738 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
739 checkSocketpairOpen(clientSocket, acceptedSocket);
740
741 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
742 skipUids.resize(skipUids.size() - 1);
743 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
744 checkSocketpairClosed(clientSocket, acceptedSocket);
745
746 close(clientSocket);
747 close(serverSocket);
748 close(acceptedSocket);
749}
Erik Klinecc4f2732016-08-03 11:24:27 +0900750
751namespace {
752
753int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
754 if (buf == nullptr) return -1;
755
756 int prefixLength = 0;
757 bool endOfContiguousBits = false;
758 for (unsigned int i = 0; i < buflen; i++) {
759 const uint8_t value = buf[i];
760
761 // Bad bit sequence: check for a contiguous set of bits from the high
762 // end by verifying that the inverted value + 1 is a power of 2
763 // (power of 2 iff. (v & (v - 1)) == 0).
764 const uint8_t inverse = ~value + 1;
765 if ((inverse & (inverse - 1)) != 0) return -1;
766
767 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
768
769 // Bogus netmask.
770 if (endOfContiguousBits && value != 0) return -1;
771
772 if (value != 0xff) endOfContiguousBits = true;
773 }
774
775 return prefixLength;
776}
777
778template<typename T>
779int netmaskToPrefixLength(const T *p) {
780 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
781}
782
783
784static bool interfaceHasAddress(
785 const std::string &ifname, const char *addrString, int prefixLength) {
786 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900787
788 const struct addrinfo hints = {
789 .ai_flags = AI_NUMERICHOST,
790 .ai_family = AF_UNSPEC,
791 .ai_socktype = SOCK_DGRAM,
792 };
793 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
794 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
795 return false;
796 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900797 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900798
799 struct ifaddrs *ifaddrsList = nullptr;
800 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
801
802 if (getifaddrs(&ifaddrsList) != 0) {
803 return false;
804 }
805
806 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
807 if (std::string(addr->ifa_name) != ifname ||
808 addr->ifa_addr == nullptr ||
809 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
810 continue;
811 }
812
813 switch (addr->ifa_addr->sa_family) {
814 case AF_INET: {
815 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
816 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
817 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
818 continue;
819 }
820
821 if (prefixLength < 0) return true; // not checking prefix lengths
822
823 if (addr->ifa_netmask == nullptr) return false;
824 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
825 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
826 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
827 }
828 case AF_INET6: {
829 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
830 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
831 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
832 continue;
833 }
834
835 if (prefixLength < 0) return true; // not checking prefix lengths
836
837 if (addr->ifa_netmask == nullptr) return false;
838 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
839 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
840 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
841 }
842 default:
843 // Cannot happen because we have already screened for matching
844 // address families at the top of each iteration.
845 continue;
846 }
847 }
848
849 return false;
850}
851
852} // namespace
853
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900854TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900855 static const struct TestData {
856 const char *addrString;
857 const int prefixLength;
858 const bool expectSuccess;
859 } kTestData[] = {
860 { "192.0.2.1", 24, true },
861 { "192.0.2.2", 25, true },
862 { "192.0.2.3", 32, true },
863 { "192.0.2.4", 33, false },
864 { "192.not.an.ip", 24, false },
865 { "2001:db8::1", 64, true },
866 { "2001:db8::2", 65, true },
867 { "2001:db8::3", 128, true },
868 { "2001:db8::4", 129, false },
869 { "foo:bar::bad", 64, false },
870 };
871
Sehee Park8659b8d2018-11-16 10:53:16 +0900872 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900873 const auto &td = kTestData[i];
874
875 // [1.a] Add the address.
876 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900877 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900878 if (td.expectSuccess) {
879 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
880 } else {
881 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
882 ASSERT_NE(0, status.serviceSpecificErrorCode());
883 }
884
885 // [1.b] Verify the addition meets the expectation.
886 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900887 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900888 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900889 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900890 }
891
892 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900893 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900894 if (td.expectSuccess) {
895 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
896 } else {
897 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
898 ASSERT_NE(0, status.serviceSpecificErrorCode());
899 }
900
901 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900902 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900903 }
904}
Erik Kline55b06f82016-07-04 09:57:18 +0900905
Erik Kline38e51f12018-09-06 20:14:44 +0900906TEST_F(BinderTest, GetProcSysNet) {
907 const char LOOPBACK[] = "lo";
908 static const struct {
909 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900910 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900911 const char* ifname;
912 const char* parameter;
913 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900914 const int expectedReturnCode;
915 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900916 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
917 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
918 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
919 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
920 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
921 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
922 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900923 };
924
Sehee Park8659b8d2018-11-16 10:53:16 +0900925 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900926 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900927
Erik Kline38e51f12018-09-06 20:14:44 +0900928 std::string value;
929 const binder::Status status =
930 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
931
932 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900933 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900934 EXPECT_EQ(0, status.exceptionCode());
935 EXPECT_EQ(0, status.serviceSpecificErrorCode());
936 EXPECT_EQ(td.expectedValue, value);
937 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900938 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900939 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
940 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
941 }
942 }
943}
944
945TEST_F(BinderTest, SetProcSysNet) {
946 static const struct {
947 const int ipversion;
948 const int which;
949 const char* ifname;
950 const char* parameter;
951 const char* value;
952 const int expectedReturnCode;
953 } kTestData[] = {
954 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
955 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
956 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
957 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
958 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
959 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
960 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
961 };
962
Sehee Park8659b8d2018-11-16 10:53:16 +0900963 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900964 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900965 const binder::Status status =
966 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900967
968 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900969 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900970 EXPECT_EQ(0, status.exceptionCode());
971 EXPECT_EQ(0, status.serviceSpecificErrorCode());
972 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900973 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900974 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
975 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
976 }
977 }
978}
Ben Schwartze7601812017-04-28 16:38:29 -0400979
Erik Kline38e51f12018-09-06 20:14:44 +0900980TEST_F(BinderTest, GetSetProcSysNet) {
981 const int ipversion = INetd::IPV6;
982 const int category = INetd::NEIGH;
983 const std::string& tun = sTun.name();
984 const std::string parameter("ucast_solicit");
985
986 std::string value{};
987 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700988 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900989 const int ival = std::stoi(value);
990 EXPECT_GT(ival, 0);
991 // Try doubling the parameter value (always best!).
992 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
993 .isOk());
994 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
995 EXPECT_EQ(2 * ival, std::stoi(value));
996 // Try resetting the parameter.
997 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
998 .isOk());
999 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
1000 EXPECT_EQ(ival, std::stoi(value));
1001}
1002
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001003namespace {
1004
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001005void expectNoTestCounterRules() {
1006 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1007 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1008 std::string allRules = Join(runCommand(command), "\n");
1009 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1010 }
1011}
1012
Bernie Innocentif6918262018-06-11 17:37:35 +09001013void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1014 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001015 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1016 path, if1.c_str(), if2.c_str(), pkt, byte));
1017}
1018
Bernie Innocentif6918262018-06-11 17:37:35 +09001019void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001020 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1021 path, if1.c_str(), if2.c_str()));
1022 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1023 path, if2.c_str(), if1.c_str()));
1024}
1025
Luke Huangcaebcbb2018-09-27 20:37:14 +08001026std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1027 const std::string& iface) {
1028 for (auto& stats : statsVec) {
1029 if (stats.iface == iface) {
1030 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1031 }
1032 }
1033 return {};
1034}
1035
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001036} // namespace
1037
1038TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001039 expectNoTestCounterRules();
1040
1041 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1042 // disabling tethering. We don't check the return value because these commands will fail if
1043 // tethering is already enabled.
1044 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1045 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1046
1047 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1048 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1049 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1050 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1051 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1052
1053 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1054 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1055 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1056 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1057 // RX is from external to internal, and TX is from internal to external.
1058 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1059 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1060
1061 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1062 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1063
1064 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1065 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1066
1067 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1068 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1069 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1070
Luke Huangcaebcbb2018-09-27 20:37:14 +08001071 std::vector<TetherStatsParcel> statsVec;
1072 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001073 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1074
Luke Huangcaebcbb2018-09-27 20:37:14 +08001075 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001076
Luke Huangcaebcbb2018-09-27 20:37:14 +08001077 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001078
1079 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1080 delTetherCounterValues(path, intIface1, extIface1);
1081 delTetherCounterValues(path, intIface2, extIface2);
1082 if (path == IP6TABLES_PATH) {
1083 delTetherCounterValues(path, intIface3, extIface2);
1084 }
1085 }
1086
1087 expectNoTestCounterRules();
1088}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001089
Luke Huang0051a622018-07-23 20:30:16 +08001090namespace {
1091
Luke Huanga5211072018-08-01 23:36:29 +08001092constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1093constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001094
1095static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1096 const char* chainName) {
1097 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1098 return runCommand(command);
1099}
1100
Luke Huang19b49c52018-10-22 12:12:05 +09001101// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001102bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001103 const std::string& expectedInterface,
1104 const std::string& expectedRule, const char* table) {
1105 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1106 for (const auto& rule : rules) {
1107 if (rule.find(expectedInterface) != std::string::npos) {
1108 if (rule.find(expectedRule) != std::string::npos) {
1109 return true;
1110 }
1111 }
1112 }
1113 return false;
1114}
1115
1116void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001117 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001118 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001119 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001120 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001121 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1122 IdletimerRule, RAW_TABLE));
1123 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001124 ifname, IdletimerRule, MANGLE_TABLE));
1125 }
1126}
1127
1128void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001129 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001130 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001131 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001132 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001133 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1134 IdletimerRule, RAW_TABLE));
1135 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001136 ifname, IdletimerRule, MANGLE_TABLE));
1137 }
1138}
1139
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001140} // namespace
1141
1142TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001143 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1144 // rule in the table. Because we only check the result after calling remove function. We might
1145 // check the actual rule which is removed by our function (maybe compare the results between
1146 // calling function before and after)
1147 binder::Status status;
1148 const struct TestData {
1149 const std::string ifname;
1150 int32_t timeout;
1151 const std::string classLabel;
1152 } idleTestData[] = {
1153 {"wlan0", 1234, "happyday"},
1154 {"rmnet_data0", 4567, "friday"},
1155 };
1156 for (const auto& td : idleTestData) {
1157 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1158 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1159 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1160
1161 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1162 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1163 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1164 }
1165}
1166
Luke Huanga67dd562018-07-17 19:58:25 +08001167namespace {
1168
1169constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1170constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1171
1172void expectStrictSetUidAccept(const int uid) {
1173 std::string uidRule = StringPrintf("owner UID match %u", uid);
1174 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1175 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001176 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1177 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001178 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1179 }
1180}
1181
1182void expectStrictSetUidLog(const int uid) {
1183 static const char logRule[] = "st_penalty_log all";
1184 std::string uidRule = StringPrintf("owner UID match %u", uid);
1185 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1186 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001187 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1188 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001189 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1190 }
1191}
1192
1193void expectStrictSetUidReject(const int uid) {
1194 static const char rejectRule[] = "st_penalty_reject all";
1195 std::string uidRule = StringPrintf("owner UID match %u", uid);
1196 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1197 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001198 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1199 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001200 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1201 }
1202}
1203
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001204} // namespace
1205
1206TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001207 binder::Status status;
1208 int32_t uid = randomUid();
1209
1210 // setUidCleartextPenalty Policy:Log with randomUid
1211 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1212 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1213 expectStrictSetUidLog(uid);
1214
1215 // setUidCleartextPenalty Policy:Accept with randomUid
1216 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1217 expectStrictSetUidAccept(uid);
1218
1219 // setUidCleartextPenalty Policy:Reject with randomUid
1220 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1221 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1222 expectStrictSetUidReject(uid);
1223
1224 // setUidCleartextPenalty Policy:Accept with randomUid
1225 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1226 expectStrictSetUidAccept(uid);
1227
1228 // test wrong policy
1229 int32_t wrongPolicy = -123;
1230 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1231 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1232}
1233
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001234namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001235
Luke Huangd1675922019-03-11 17:29:27 +08001236std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001237 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001238 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001239 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1240 // ...
1241 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1242
Luke Huangd1675922019-03-11 17:29:27 +08001243 // (dnsmasq)
1244 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1245
1246 if (maxTries == 0) return {};
1247
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001248 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001249 std::vector<std::string> result;
1250 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001251 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001252 if (result.size() || ++run > maxTries) {
1253 break;
1254 }
1255
Luke Huang728cf4c2019-03-14 19:43:02 +08001256 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001257 }
1258 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001259}
1260
Luke Huangd1675922019-03-11 17:29:27 +08001261void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001262 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001263}
1264
Luke Huang728cf4c2019-03-14 19:43:02 +08001265void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001266 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001267}
1268
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001269} // namespace
1270
1271TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001272 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001273
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001274 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1275 std::string clatAddress;
1276 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001277
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001278 // Can't start clatd on an interface that's not part of any network...
1279 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1280 EXPECT_FALSE(status.isOk());
1281 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1282
1283 // ... so create a test physical network and add our tun to it.
1284 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1285 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1286
1287 // Prefix must be 96 bits long.
1288 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1289 EXPECT_FALSE(status.isOk());
1290 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1291
1292 // Can't start clatd unless there's a default route...
1293 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1294 EXPECT_FALSE(status.isOk());
1295 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1296
1297 // so add a default route.
1298 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1299
1300 // Can't start clatd unless there's a global address...
1301 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1302 EXPECT_FALSE(status.isOk());
1303 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1304
1305 // ... so add a global address.
1306 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001307 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001308
1309 // Now expect clatd to start successfully.
1310 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1311 EXPECT_TRUE(status.isOk());
1312 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1313
1314 // Starting it again returns EBUSY.
1315 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1316 EXPECT_FALSE(status.isOk());
1317 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1318
Luke Huangd1675922019-03-11 17:29:27 +08001319 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001320
1321 // Expect clatd to stop successfully.
1322 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001323 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001324 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001325
1326 // Stopping a clatd that doesn't exist returns ENODEV.
1327 status = mNetd->clatdStop(sTun.name());
1328 EXPECT_FALSE(status.isOk());
1329 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001330 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001331
1332 // Clean up.
1333 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1334 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1335 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001336}
Luke Huang457d4702018-08-16 15:39:15 +08001337
1338namespace {
1339
1340bool getIpfwdV4Enable() {
1341 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1342 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1343 EXPECT_TRUE(!result.empty());
1344 int v4Enable = std::stoi(result[0]);
1345 return v4Enable;
1346}
1347
1348bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001349 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001350 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1351 EXPECT_TRUE(!result.empty());
1352 int v6Enable = std::stoi(result[0]);
1353 return v6Enable;
1354}
1355
1356void expectIpfwdEnable(bool enable) {
1357 int enableIPv4 = getIpfwdV4Enable();
1358 int enableIPv6 = getIpfwdV6Enable();
1359 EXPECT_EQ(enable, enableIPv4);
1360 EXPECT_EQ(enable, enableIPv6);
1361}
1362
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001363bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001364 std::vector<std::string> rules = listIpRules(ipVersion);
1365 for (const auto& rule : rules) {
1366 if (rule.find(ipfwdRule) != std::string::npos) {
1367 return true;
1368 }
1369 }
1370 return false;
1371}
1372
1373void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1374 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1375
1376 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1377 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1378 }
1379}
1380
1381void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1382 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1383
1384 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1385 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1386 }
1387}
1388
1389} // namespace
1390
1391TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001392 // Get ipfwd requester list from Netd
1393 std::vector<std::string> requesterList;
1394 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001395 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001396
1397 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001398 if (requesterList.size() == 0) {
1399 // No requester in Netd, ipfwd should be disabled
1400 // So add one test requester and verify
1401 status = mNetd->ipfwdEnableForwarding("TestRequester");
1402 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001403
Luke Huang728cf4c2019-03-14 19:43:02 +08001404 expectIpfwdEnable(true);
1405 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1406 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1407 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001408
Luke Huang728cf4c2019-03-14 19:43:02 +08001409 // Remove test one, verify again
1410 status = mNetd->ipfwdDisableForwarding("TestRequester");
1411 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1412
1413 expectIpfwdEnable(false);
1414 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1415 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1416 EXPECT_FALSE(ipfwdEnabled);
1417 } else {
1418 // Disable all requesters
1419 for (const auto& requester : requesterList) {
1420 status = mNetd->ipfwdDisableForwarding(requester);
1421 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1422 }
1423
1424 // After disable all requester, ipfwd should be disabled
1425 expectIpfwdEnable(false);
1426 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1427 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1428 EXPECT_FALSE(ipfwdEnabled);
1429
1430 // Enable them back
1431 for (const auto& requester : requesterList) {
1432 status = mNetd->ipfwdEnableForwarding(requester);
1433 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1434 }
1435
1436 // ipfwd should be enabled
1437 expectIpfwdEnable(true);
1438 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1439 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1440 EXPECT_TRUE(ipfwdEnabled);
1441 }
Luke Huang457d4702018-08-16 15:39:15 +08001442}
1443
1444TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001445 // Add test physical network
1446 EXPECT_TRUE(
1447 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1448 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1449 EXPECT_TRUE(
1450 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1451 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001452
Luke Huangd1827b82019-02-15 15:03:27 +08001453 binder::Status status =
1454 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1455 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1456 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001457
Luke Huangd1827b82019-02-15 15:03:27 +08001458 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1459 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1460 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001461}
Luke Huang531f5d32018-08-03 15:19:05 +08001462
1463namespace {
1464
1465constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1466constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1467constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1468constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1469constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001470constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001471
Luke Huang19b49c52018-10-22 12:12:05 +09001472// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1473// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001474bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1475 const char* chainName, const std::string& expectedTargetA,
1476 const std::string& expectedTargetB) {
1477 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1478 int matchCount = 0;
1479
1480 for (const auto& rule : rules) {
1481 if (rule.find(expectedTargetA) != std::string::npos) {
1482 if (rule.find(expectedTargetB) != std::string::npos) {
1483 matchCount++;
1484 }
1485 }
1486 }
1487 return matchCount == expectedCount;
1488}
1489
1490void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1491 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1492 std::string result = "";
1493
1494 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001495 // Quota value might be decreased while matching packets
1496 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001497}
1498
1499void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1500 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1501 std::string quotaRule = StringPrintf("quota %s", ifname);
1502
1503 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1504 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1505 BANDWIDTH_COSTLY_IF));
1506 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1507 BANDWIDTH_COSTLY_IF));
1508 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1509 BANDWIDTH_COSTLY_IF));
1510 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1511 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1512 }
1513 expectXtQuotaValueEqual(ifname, quotaBytes);
1514}
1515
1516void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1517 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1518 std::string quotaRule = StringPrintf("quota %s", ifname);
1519
1520 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1521 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1522 BANDWIDTH_COSTLY_IF));
1523 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1524 BANDWIDTH_COSTLY_IF));
1525 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1526 BANDWIDTH_COSTLY_IF));
1527 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1528 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1529 }
1530}
1531
1532void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1533 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1534 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1535 std::string alertName = StringPrintf("%sAlert", ifname);
1536
1537 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1538 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1539 }
1540 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1541}
1542
1543void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1544 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1545 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1546
1547 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1548 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1549 }
1550}
1551
1552void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1553 static const char globalAlertRule[] = "quota globalAlert";
1554 static const char globalAlertName[] = "globalAlert";
1555
1556 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001557 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001558 }
1559 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1560}
1561
1562void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1563 std::string uidRule = StringPrintf("owner UID match %u", uid);
1564
1565 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1566 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1567 }
1568}
1569
1570void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1571 std::string uidRule = StringPrintf("owner UID match %u", uid);
1572
1573 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1574 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1575 }
1576}
1577
1578} // namespace
1579
1580TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1581 long testQuotaBytes = 5550;
1582
1583 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001584 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001585 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1586
1587 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1588 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1589 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1590
1591 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1592 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1593 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1594
1595 // Remove test physical network
1596 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1597}
1598
1599TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1600 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001601 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001602 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001603 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001604 // Need to have a prior interface quota set to set an alert
1605 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1606 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1607 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1608 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1609
1610 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1611 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1612 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1613
1614 // Remove interface quota
1615 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1616 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1617 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1618
1619 // Remove test physical network
1620 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1621}
1622
1623TEST_F(BinderTest, BandwidthSetGlobalAlert) {
1624 long testAlertBytes = 2097149;
1625
1626 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1627 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1628 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1629
1630 testAlertBytes = 2097152;
1631 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1632 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1633 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1634}
1635
1636TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1637 SKIP_IF_BPF_SUPPORTED;
1638
1639 int32_t uid = randomUid();
1640 static const char targetReject[] = "REJECT";
1641 static const char targetReturn[] = "RETURN";
1642
1643 // add NaughtyApp
1644 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1645 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1646 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1647
1648 // remove NaughtyApp
1649 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1650 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1651 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1652
1653 // add NiceApp
1654 status = mNetd->bandwidthAddNiceApp(uid);
1655 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1656 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1657
1658 // remove NiceApp
1659 status = mNetd->bandwidthRemoveNiceApp(uid);
1660 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1661 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1662}
Luke Huangb5733d72018-08-21 17:17:19 +08001663
1664namespace {
1665
Luke Huangb670d162018-08-23 20:01:13 +08001666std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1667 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1668 return runCommand(command);
1669}
1670
Luke Huangc3252cc2018-10-16 15:43:23 +08001671bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001672 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1673 for (const auto& route : routes) {
1674 if (route.find(ipRoute) != std::string::npos) {
1675 return true;
1676 }
1677 }
1678 return false;
1679}
1680
Luke Huangc3252cc2018-10-16 15:43:23 +08001681std::string ipRouteString(const std::string& ifName, const std::string& dst,
1682 const std::string& nextHop) {
1683 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1684
1685 if (!nextHop.empty()) {
1686 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001687 }
1688
Luke Huangc3252cc2018-10-16 15:43:23 +08001689 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001690}
1691
Luke Huangc3252cc2018-10-16 15:43:23 +08001692void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1693 const std::string& dst, const std::string& nextHop,
1694 const char* table) {
1695 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1696}
1697
1698void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001699 const std::string& dst, const std::string& nextHop,
1700 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001701 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001702}
1703
1704bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1705 std::vector<std::string> rules = listIpRules(ipVersion);
1706 for (const auto& rule : rules) {
1707 if (rule.find(ipRule) != std::string::npos) {
1708 return true;
1709 }
1710 }
1711 return false;
1712}
1713
1714void expectNetworkDefaultIpRuleExists(const char* ifName) {
1715 std::string networkDefaultRule =
1716 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1717
1718 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1719 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1720 }
1721}
1722
1723void expectNetworkDefaultIpRuleDoesNotExist() {
1724 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1725
1726 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1727 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1728 }
1729}
1730
1731void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1732 std::string networkPermissionRule = "";
1733 switch (permission) {
1734 case INetd::PERMISSION_NONE:
1735 networkPermissionRule = StringPrintf(
1736 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1737 break;
1738 case INetd::PERMISSION_NETWORK:
1739 networkPermissionRule = StringPrintf(
1740 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1741 break;
1742 case INetd::PERMISSION_SYSTEM:
1743 networkPermissionRule = StringPrintf(
1744 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1745 break;
1746 }
1747
1748 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1749 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1750 }
1751}
1752
1753// TODO: It is a duplicate function, need to remove it
1754bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1755 const std::string& expectedInterface,
1756 const std::string& expectedRule,
1757 const char* table) {
1758 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1759 for (const auto& rule : rules) {
1760 if (rule.find(expectedInterface) != std::string::npos) {
1761 if (rule.find(expectedRule) != std::string::npos) {
1762 return true;
1763 }
1764 }
1765 }
1766 return false;
1767}
1768
1769void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1770 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1771 std::string networkIncomingPacketMarkRule = "";
1772 switch (permission) {
1773 case INetd::PERMISSION_NONE:
1774 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1775 break;
1776 case INetd::PERMISSION_NETWORK:
1777 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1778 break;
1779 case INetd::PERMISSION_SYSTEM:
1780 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1781 break;
1782 }
1783
1784 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1785 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1786 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1787 }
1788}
1789
1790} // namespace
1791
1792TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001793 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001794 const char* ipVersion;
1795 const char* testDest;
1796 const char* testNextHop;
1797 const bool expectSuccess;
1798 } kTestData[] = {
1799 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001800 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1801 {IP_RULE_V4, "10.251.0.0/16", "", true},
1802 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1803 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001804 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001805 {IP_RULE_V6, "::/0", "2001:db8::", true},
1806 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001807 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1808 };
1809
Luke Huangc3252cc2018-10-16 15:43:23 +08001810 static const struct {
1811 const char* ipVersion;
1812 const char* testDest;
1813 const char* testNextHop;
1814 } kTestDataWithNextHop[] = {
1815 {IP_RULE_V4, "10.251.10.0/30", ""},
1816 {IP_RULE_V6, "2001:db8::/32", ""},
1817 };
1818
Luke Huangb670d162018-08-23 20:01:13 +08001819 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001820 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001821 const int testUid = randomUid();
1822 const std::vector<int32_t> testUids = {testUid};
1823
1824 // Add test physical network
1825 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1826 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1827
Luke Huangc3252cc2018-10-16 15:43:23 +08001828 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001829 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001830 const auto& td = kTestDataWithNextHop[i];
1831
1832 // All route for test tun will disappear once the tun interface is deleted.
1833 binder::Status status =
1834 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1835 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1836 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1837 sTun.name().c_str());
1838
1839 // Add system permission for test uid, setup route in legacy system table.
1840 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1841
1842 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1843 testUid);
1844 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1845 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1846 testTableLegacySystem);
1847
1848 // Remove system permission for test uid, setup route in legacy network table.
1849 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1850
1851 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1852 testUid);
1853 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1854 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1855 testTableLegacyNetwork);
1856 }
1857
Sehee Park8659b8d2018-11-16 10:53:16 +09001858 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001859 const auto& td = kTestData[i];
1860
1861 binder::Status status =
1862 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1863 if (td.expectSuccess) {
1864 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001865 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001866 sTun.name().c_str());
1867 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001868 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1869 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001870 }
1871
1872 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1873 if (td.expectSuccess) {
1874 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001875 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1876 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001877 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001878 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1879 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001880 }
1881
Luke Huangc3252cc2018-10-16 15:43:23 +08001882 // Add system permission for test uid, route will be added into legacy system table.
1883 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001884
1885 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1886 testUid);
1887 if (td.expectSuccess) {
1888 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001889 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001890 testTableLegacySystem);
1891 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001892 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1893 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001894 }
1895
1896 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1897 td.testNextHop, testUid);
1898 if (td.expectSuccess) {
1899 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001900 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1901 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001902 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001903 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1904 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001905 }
1906
Luke Huangc3252cc2018-10-16 15:43:23 +08001907 // Remove system permission for test uid, route will be added into legacy network table.
1908 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1909
1910 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1911 testUid);
1912 if (td.expectSuccess) {
1913 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1914 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1915 testTableLegacyNetwork);
1916 } else {
1917 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1918 EXPECT_NE(0, status.serviceSpecificErrorCode());
1919 }
1920
1921 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1922 td.testNextHop, testUid);
1923 if (td.expectSuccess) {
1924 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1925 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1926 testTableLegacyNetwork);
1927 } else {
1928 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1929 EXPECT_NE(0, status.serviceSpecificErrorCode());
1930 }
Luke Huangb670d162018-08-23 20:01:13 +08001931 }
1932
1933 // Remove test physical network
1934 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1935}
1936
1937TEST_F(BinderTest, NetworkPermissionDefault) {
1938 // Add test physical network
1939 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1940 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1941
Luke Huangc3252cc2018-10-16 15:43:23 +08001942 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001943 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1944 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001945
1946 // Test SetDefault
1947 status = mNetd->networkSetDefault(TEST_NETID1);
1948 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1949 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1950
1951 status = mNetd->networkClearDefault();
1952 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1953 expectNetworkDefaultIpRuleDoesNotExist();
1954
Luke Huangd2861982019-05-17 19:47:28 +08001955 // Set default network back
1956 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001957 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1958
1959 // Test SetPermission
1960 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1961 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1962 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1963 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1964
1965 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1966 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1967 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1968 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1969
1970 // Remove test physical network
1971 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1972}
1973
1974TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
1975 const int testUid = randomUid();
1976 binder::Status status = mNetd->networkSetProtectAllow(testUid);
1977 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1978 bool ret = false;
1979 status = mNetd->networkCanProtect(testUid, &ret);
1980 EXPECT_TRUE(ret);
1981
1982 status = mNetd->networkSetProtectDeny(testUid);
1983 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984 status = mNetd->networkCanProtect(testUid, &ret);
1985 EXPECT_FALSE(ret);
1986}
1987
1988namespace {
1989
Luke Huangb5733d72018-08-21 17:17:19 +08001990int readIntFromPath(const std::string& path) {
1991 std::string result = "";
1992 EXPECT_TRUE(ReadFileToString(path, &result));
1993 return std::stoi(result);
1994}
1995
1996int getTetherAcceptIPv6Ra(const std::string& ifName) {
1997 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1998 return readIntFromPath(path);
1999}
2000
2001bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2002 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2003 return readIntFromPath(path);
2004}
2005
2006int getTetherIPv6DadTransmits(const std::string& ifName) {
2007 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2008 return readIntFromPath(path);
2009}
2010
2011bool getTetherEnableIPv6(const std::string& ifName) {
2012 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2013 int disableIPv6 = readIntFromPath(path);
2014 return !disableIPv6;
2015}
2016
2017bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2018 for (const auto& iface : ifList) {
2019 if (iface == ifName) {
2020 return true;
2021 }
2022 }
2023 return false;
2024}
2025
2026void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2027 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2028 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2029 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2030 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2031}
2032
2033void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2034 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2035 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2036 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2037 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2038}
2039
2040void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2041 const std::string& ifName) {
2042 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2043}
2044
2045void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2046 const std::string& ifName) {
2047 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2048}
2049
2050void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2051 const std::vector<std::string>& testDnsAddrs) {
2052 EXPECT_TRUE(dnsList == testDnsAddrs);
2053}
2054
2055} // namespace
2056
2057TEST_F(BinderTest, TetherStartStopStatus) {
2058 std::vector<std::string> noDhcpRange = {};
2059 static const char dnsdName[] = "dnsmasq";
2060
2061 binder::Status status = mNetd->tetherStart(noDhcpRange);
2062 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002063 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002064
2065 bool tetherEnabled;
2066 status = mNetd->tetherIsEnabled(&tetherEnabled);
2067 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2068 EXPECT_TRUE(tetherEnabled);
2069
2070 status = mNetd->tetherStop();
2071 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002072 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002073
2074 status = mNetd->tetherIsEnabled(&tetherEnabled);
2075 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2076 EXPECT_FALSE(tetherEnabled);
2077}
2078
2079TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2080 // TODO: verify if dnsmasq update interface successfully
2081
2082 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2083 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2084 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2085
2086 std::vector<std::string> ifList;
2087 status = mNetd->tetherInterfaceList(&ifList);
2088 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2089 expectTetherInterfaceExists(ifList, sTun.name());
2090
2091 status = mNetd->tetherInterfaceRemove(sTun.name());
2092 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2093 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2094
2095 status = mNetd->tetherInterfaceList(&ifList);
2096 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2097 expectTetherInterfaceNotExists(ifList, sTun.name());
2098}
2099
2100TEST_F(BinderTest, TetherDnsSetList) {
2101 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002102 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2103 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002104
2105 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2106 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2107
2108 std::vector<std::string> dnsList;
2109 status = mNetd->tetherDnsList(&dnsList);
2110 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2111 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002112}
2113
2114namespace {
2115
2116constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2117constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2118constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2119constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2120constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2121constexpr char FIREWALL_STANDBY[] = "fw_standby";
2122constexpr char targetReturn[] = "RETURN";
2123constexpr char targetDrop[] = "DROP";
2124
2125void expectFirewallWhitelistMode() {
2126 static const char dropRule[] = "DROP all";
2127 static const char rejectRule[] = "REJECT all";
2128 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2129 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2130 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2131 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2132 }
2133}
2134
2135void expectFirewallBlacklistMode() {
2136 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2137 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2138 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2139 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2140 }
2141}
2142
2143bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2144 const std::string& expectedInterface,
2145 const std::string& expectedRule) {
2146 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2147 // Expected rule:
2148 // Chain fw_INPUT (1 references)
2149 // pkts bytes target prot opt in out source destination
2150 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2151 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2152 int firstRuleIndex = 2;
2153 if (rules.size() < 4) return false;
2154 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2155 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2156 return true;
2157 }
2158 }
2159 return false;
2160}
2161
2162// TODO: It is a duplicate function, need to remove it
2163bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2164 const std::string& expectedInterface,
2165 const std::string& expectedRule) {
2166 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2167 for (const auto& rule : rules) {
2168 if (rule.find(expectedInterface) != std::string::npos) {
2169 if (rule.find(expectedRule) != std::string::npos) {
2170 return true;
2171 }
2172 }
2173 }
2174 return false;
2175}
2176
2177void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2178 static const char returnRule[] = "RETURN all";
2179 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2180 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2181 returnRule));
2182 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2183 returnRule));
2184 }
2185}
2186
2187void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2188 static const char returnRule[] = "RETURN all";
2189 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2190 EXPECT_FALSE(
2191 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2192 EXPECT_FALSE(
2193 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2194 }
2195}
2196
2197bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2198 const std::string& expectedTarget,
2199 const std::string& expectedRule) {
2200 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2201 int firstRuleIndex = 2;
2202 if (rules.size() < 4) return false;
2203 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2204 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2205 return true;
2206 }
2207 }
2208 return false;
2209}
2210
2211bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2212 const std::string& expectedTarget,
2213 const std::string& expectedRule) {
2214 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2215 int lastRuleIndex = rules.size() - 1;
2216 if (lastRuleIndex < 0) return false;
2217 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2218 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2219 return true;
2220 }
2221 }
2222 return false;
2223}
2224
2225void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2226 std::string uidRule = StringPrintf("owner UID match %u", uid);
2227 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2228 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2229}
2230
2231void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2232 std::string uidRule = StringPrintf("owner UID match %u", uid);
2233 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2234 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2235}
2236
2237void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2238 std::string uidRule = StringPrintf("owner UID match %u", uid);
2239 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2240 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2241}
2242
2243void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2244 std::string uidRule = StringPrintf("owner UID match %u", uid);
2245 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2246 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2247}
2248
2249bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2250 std::vector<std::string> inputRules =
2251 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2252 std::vector<std::string> outputRules =
2253 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2254 int inputLastRuleIndex = inputRules.size() - 1;
2255 int outputLastRuleIndex = outputRules.size() - 1;
2256
2257 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2258 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2259 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2260 return true;
2261 }
2262 }
2263 return false;
2264}
2265
2266void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2267 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2268 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2269}
2270
2271void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2272 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2273 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2274 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2275 }
2276}
2277
2278} // namespace
2279
2280TEST_F(BinderTest, FirewallSetFirewallType) {
2281 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2282 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2283 expectFirewallWhitelistMode();
2284
2285 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2286 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2287 expectFirewallBlacklistMode();
2288
2289 // set firewall type blacklist twice
2290 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2291 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2292 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2293 expectFirewallBlacklistMode();
2294
2295 // set firewall type whitelist twice
2296 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2297 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2298 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2299 expectFirewallWhitelistMode();
2300
2301 // reset firewall type to default
2302 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2303 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2304 expectFirewallBlacklistMode();
2305}
2306
2307TEST_F(BinderTest, FirewallSetInterfaceRule) {
2308 // setinterfaceRule is not supported in BLACKLIST MODE
2309 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2310 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2311
2312 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2313 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2314
2315 // set WHITELIST mode first
2316 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2317 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2318
2319 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2320 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2321 expectFirewallInterfaceRuleAllowExists(sTun.name());
2322
2323 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2326
2327 // reset firewall mode to default
2328 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2329 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2330 expectFirewallBlacklistMode();
2331}
2332
2333TEST_F(BinderTest, FirewallSetUidRule) {
2334 SKIP_IF_BPF_SUPPORTED;
2335
2336 int32_t uid = randomUid();
2337
2338 // Doze allow
2339 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2340 INetd::FIREWALL_RULE_ALLOW);
2341 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2342 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2343
2344 // Doze deny
2345 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2346 INetd::FIREWALL_RULE_DENY);
2347 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2348 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2349
2350 // Powersave allow
2351 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2352 INetd::FIREWALL_RULE_ALLOW);
2353 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2354 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2355
2356 // Powersave deny
2357 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2358 INetd::FIREWALL_RULE_DENY);
2359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2360 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2361
2362 // Standby deny
2363 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2364 INetd::FIREWALL_RULE_DENY);
2365 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2366 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2367
2368 // Standby allow
2369 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2370 INetd::FIREWALL_RULE_ALLOW);
2371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2372 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2373
2374 // None deny in BLACKLIST
2375 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2376 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2377 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2378 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2379
2380 // None allow in BLACKLIST
2381 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2382 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2383 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2384 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2385
2386 // set firewall type whitelist twice
2387 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2388 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2389 expectFirewallWhitelistMode();
2390
2391 // None allow in WHITELIST
2392 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2393 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2394 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2395 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2396
2397 // None deny in WHITELIST
2398 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2399 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2400 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2401 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2402
2403 // reset firewall mode to default
2404 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2405 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2406 expectFirewallBlacklistMode();
2407}
2408
2409TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2410 SKIP_IF_BPF_SUPPORTED;
2411
2412 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2413 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2414 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2415
2416 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2417 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2418 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2419
2420 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2421 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2422 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2423
2424 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2425 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2426 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2427
2428 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2429 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2430 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2431
2432 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2433 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2434 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2435}
Luke Huangf7782042018-08-08 13:13:04 +08002436
2437namespace {
2438
2439std::string hwAddrToStr(unsigned char* hwaddr) {
2440 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2441 hwaddr[4], hwaddr[5]);
2442}
2443
2444int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2445 int prefixLength = 0;
2446 uint32_t m = ntohl(mask);
2447 while (m & (1 << 31)) {
2448 prefixLength++;
2449 m = m << 1;
2450 }
2451 return prefixLength;
2452}
2453
2454std::string toStdString(const String16& s) {
2455 return std::string(String8(s.string()));
2456}
2457
2458android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2459 const auto& sys = sSyscalls.get();
2460 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2461 EXPECT_TRUE(isOk(fd.status()));
2462
2463 struct ifreq ifr = {};
2464 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2465
2466 return sys.ioctl(fd.value(), flag, &ifr);
2467}
2468
2469std::string getInterfaceHwAddr(const std::string& ifName) {
2470 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2471
2472 unsigned char hwaddr[ETH_ALEN] = {};
2473 if (isOk(res.status())) {
2474 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2475 }
2476
2477 return hwAddrToStr(hwaddr);
2478}
2479
2480int getInterfaceIPv4Prefix(const std::string& ifName) {
2481 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2482
2483 int prefixLength = 0;
2484 if (isOk(res.status())) {
2485 prefixLength = ipv4NetmaskToPrefixLength(
2486 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2487 }
2488
2489 return prefixLength;
2490}
2491
2492std::string getInterfaceIPv4Addr(const std::string& ifName) {
2493 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2494
2495 struct in_addr addr = {};
2496 if (isOk(res.status())) {
2497 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2498 }
2499
2500 return std::string(inet_ntoa(addr));
2501}
2502
2503std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2504 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2505
2506 unsigned flags = 0;
2507 if (isOk(res.status())) {
2508 flags = res.value().ifr_flags;
2509 }
2510
2511 std::vector<std::string> ifFlags;
2512 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2513 : toStdString(INetd::IF_STATE_DOWN()));
2514
2515 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2516 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2517 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2518 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2519 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2520
2521 return ifFlags;
2522}
2523
2524bool compareListInterface(const std::vector<std::string>& interfaceList) {
2525 const auto& res = InterfaceController::getIfaceNames();
2526 EXPECT_TRUE(isOk(res));
2527
2528 std::vector<std::string> resIfList;
2529 resIfList.reserve(res.value().size());
2530 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2531
2532 return resIfList == interfaceList;
2533}
2534
2535int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2536 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2537 return readIntFromPath(path);
2538}
2539
2540bool getInterfaceEnableIPv6(const std::string& ifName) {
2541 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2542
2543 int disableIPv6 = readIntFromPath(path);
2544 return !disableIPv6;
2545}
2546
2547int getInterfaceMtu(const std::string& ifName) {
2548 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2549 return readIntFromPath(path);
2550}
2551
2552void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2553 EXPECT_TRUE(compareListInterface(interfaceList));
2554}
2555
2556void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2557 const InterfaceConfigurationParcel& interfaceCfg) {
2558 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2559 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2560 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2561 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2562}
2563
2564void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2565 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2566 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2567
2568 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2569 for (const auto& flag : setCfg.flags) {
2570 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2571 }
2572}
2573
2574void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2575 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2576 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2577}
2578
2579void expectInterfaceNoAddr(const std::string& ifName) {
2580 // noAddr
2581 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2582 // noPrefix
2583 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2584}
2585
2586void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2587 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2588 EXPECT_EQ(enableIPv6, enable);
2589}
2590
2591void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2592 int mtuSize = getInterfaceMtu(ifName);
2593 EXPECT_EQ(mtu, mtuSize);
2594}
2595
2596InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2597 const std::string& addr, int prefixLength,
2598 const std::vector<std::string>& flags) {
2599 InterfaceConfigurationParcel cfg;
2600 cfg.ifName = ifName;
2601 cfg.hwAddr = "";
2602 cfg.ipv4Addr = addr;
2603 cfg.prefixLength = prefixLength;
2604 cfg.flags = flags;
2605 return cfg;
2606}
2607
2608void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2609 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2610 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2611
2612 for (const auto& flag : expectedFlags) {
2613 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2614 interfaceCfg.flags.end());
2615 }
2616
2617 for (const auto& flag : unexpectedFlags) {
2618 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2619 interfaceCfg.flags.end());
2620 }
2621}
2622
2623} // namespace
2624
2625TEST_F(BinderTest, InterfaceList) {
2626 std::vector<std::string> interfaceListResult;
2627
2628 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2629 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2630 expectInterfaceList(interfaceListResult);
2631}
2632
2633TEST_F(BinderTest, InterfaceGetCfg) {
2634 InterfaceConfigurationParcel interfaceCfgResult;
2635
2636 // Add test physical network
2637 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2638 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2639
2640 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2641 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2642 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2643 expectTunFlags(interfaceCfgResult);
2644
2645 // Remove test physical network
2646 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2647}
2648
2649TEST_F(BinderTest, InterfaceSetCfg) {
2650 const std::string testAddr = "192.0.2.3";
2651 const int testPrefixLength = 24;
2652 std::vector<std::string> upFlags = {"up"};
2653 std::vector<std::string> downFlags = {"down"};
2654
2655 // Add test physical network
2656 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2657 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2658
2659 // Set tun interface down.
2660 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2661 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2662 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2663 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2664
2665 // Set tun interface up again.
2666 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2667 status = mNetd->interfaceSetCfg(interfaceCfg);
2668 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2669 status = mNetd->interfaceClearAddrs(sTun.name());
2670 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2671
2672 // Remove test physical network
2673 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2674}
2675
2676TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2677 // enable
2678 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2679 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2680 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2681
2682 // disable
2683 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2684 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2685 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2686}
2687
2688TEST_F(BinderTest, InterfaceClearAddr) {
2689 const std::string testAddr = "192.0.2.3";
2690 const int testPrefixLength = 24;
2691 std::vector<std::string> noFlags{};
2692
2693 // Add test physical network
2694 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2695 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2696
2697 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2698 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2699 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2700 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2701
2702 status = mNetd->interfaceClearAddrs(sTun.name());
2703 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2704 expectInterfaceNoAddr(sTun.name());
2705
2706 // Remove test physical network
2707 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2708}
2709
2710TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2711 // Add test physical network
2712 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2713 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2714
2715 // disable
2716 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2717 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2718 expectInterfaceEnableIPv6(sTun.name(), false);
2719
2720 // enable
2721 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2722 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2723 expectInterfaceEnableIPv6(sTun.name(), true);
2724
2725 // Remove test physical network
2726 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2727}
2728
2729TEST_F(BinderTest, InterfaceSetMtu) {
2730 const int testMtu = 1200;
2731
2732 // Add test physical network
2733 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2734 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2735
2736 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2737 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2738 expectInterfaceMtu(sTun.name(), testMtu);
2739
2740 // Remove test physical network
2741 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2742}
Luke Huang19b49c52018-10-22 12:12:05 +09002743
2744namespace {
2745
2746constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2747constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002748constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002749constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2750
Luke Huangae038f82018-11-05 11:17:31 +09002751int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002752 return listIptablesRuleByTable(binary, table, chainName).size();
2753}
2754
2755bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2756 const std::vector<std::string>& targetVec) {
2757 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2758 if (targetVec.size() != rules.size() - 2) {
2759 return false;
2760 }
2761
2762 /*
Luke Huangae038f82018-11-05 11:17:31 +09002763 * Check that the rules match. Note that this function matches substrings, not entire rules,
2764 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002765 * Skip first two lines since rules start from third line.
2766 * Chain chainName (x references)
2767 * pkts bytes target prot opt in out source destination
2768 * ...
2769 */
2770 int rIndex = 2;
2771 for (const auto& target : targetVec) {
2772 if (rules[rIndex].find(target) == std::string::npos) {
2773 return false;
2774 }
2775 rIndex++;
2776 }
2777 return true;
2778}
2779
2780void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2781 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2782 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2783 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002784 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002785 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2786 "DROP"};
2787
2788 // V4
2789 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2790 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002791 EXPECT_TRUE(
2792 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002793 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2794
Luke Huangae038f82018-11-05 11:17:31 +09002795 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002796 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2797
2798 // V6
2799 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002800 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2801 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002802
2803 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2804 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2805 extIf));
2806 }
2807}
2808
2809void expectNatDisable() {
2810 // It is the default DROP rule with tethering disable.
2811 // Chain tetherctrl_FORWARD (1 references)
2812 // pkts bytes target prot opt in out source destination
2813 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2814 std::vector<std::string> forwardV4Match = {"DROP"};
2815 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2816
2817 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002818 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2819 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002820
Luke Huangae038f82018-11-05 11:17:31 +09002821 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2822 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002823
2824 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2825}
2826
2827} // namespace
2828
2829TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002830 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2831 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2832 expectNatEnable(sTun.name(), sTun2.name());
2833
2834 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2835 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2836 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002837}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002838
2839namespace {
2840
2841using TripleInt = std::array<int, 3>;
2842
2843TripleInt readProcFileToTripleInt(const std::string& path) {
2844 std::string valueString;
2845 int min, def, max;
2846 EXPECT_TRUE(ReadFileToString(path, &valueString));
2847 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2848 return {min, def, max};
2849}
2850
2851void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2852 std::string testRmemValues =
2853 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2854 std::string testWmemValues =
2855 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2856 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2857
2858 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2859 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2860
2861 for (int i = 0; i < 3; i++) {
2862 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2863 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2864 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2865 }
2866}
2867
2868} // namespace
2869
2870TEST_F(BinderTest, TcpBufferSet) {
2871 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2872 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2873 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2874 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2875
2876 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2877 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2878}
Luke Huang528af602018-08-29 19:06:05 +08002879
Chenbo Feng48eaed32018-12-26 17:40:21 -08002880namespace {
2881
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002882void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002883 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2884 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2885 for (int32_t uid : uids) {
2886 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2887 if (exist) {
2888 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002889 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002890 } else {
2891 EXPECT_FALSE(isOk(permission));
2892 EXPECT_EQ(ENOENT, permission.status().code());
2893 }
2894 }
2895}
2896
2897} // namespace
2898
2899TEST_F(BinderTest, TestInternetPermission) {
2900 SKIP_IF_BPF_NOT_SUPPORTED;
2901
2902 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2903
2904 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002905 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002906 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002907 checkUidsInPermissionMap(appUids, true);
2908 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2909 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002910}
2911
Luke Huang528af602018-08-29 19:06:05 +08002912TEST_F(BinderTest, UnsolEvents) {
2913 auto testUnsolService = android::net::TestUnsolService::start();
2914 std::string oldTunName = sTun.name();
2915 std::string newTunName = "unsolTest";
2916 testUnsolService->tarVec.push_back(oldTunName);
2917 testUnsolService->tarVec.push_back(newTunName);
2918 auto& cv = testUnsolService->getCv();
2919 auto& cvMutex = testUnsolService->getCvMutex();
2920 binder::Status status = mNetd->registerUnsolicitedEventListener(
2921 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2922 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2923
2924 // TODO: Add test for below events
2925 // StrictCleartextDetected / InterfaceDnsServersAdded
2926 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2927
2928 {
2929 std::unique_lock lock(cvMutex);
2930
2931 // Re-init test Tun, and we expect that we will get some unsol events.
2932 // Use the test Tun device name to verify if we receive its unsol events.
2933 sTun.destroy();
2934 // Use predefined name
2935 sTun.init(newTunName);
2936
2937 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2938 }
2939
2940 // bit mask 1101101000
2941 // Test only covers below events currently
2942 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2943 InterfaceLinkStatusChanged | RouteChanged;
2944 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002945
2946 // Re-init sTun to clear predefined name
2947 sTun.destroy();
2948 sTun.init();
2949}
2950
2951TEST_F(BinderTest, NDC) {
2952 struct Command {
2953 const std::string cmdString;
2954 const std::string expectedResult;
2955 };
2956
2957 // clang-format off
2958 // Do not change the commands order
2959 const Command networkCmds[] = {
2960 {StringPrintf("ndc network create %d", TEST_NETID1),
2961 "200 0 success"},
2962 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2963 "200 0 success"},
2964 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2965 "200 0 success"},
2966 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2967 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2968 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2969 "200 0 success"},
2970 };
2971
2972 const std::vector<Command> ipfwdCmds = {
2973 {"ndc ipfwd enable " + sTun.name(),
2974 "200 0 ipfwd operation succeeded"},
2975 {"ndc ipfwd disable " + sTun.name(),
2976 "200 0 ipfwd operation succeeded"},
2977 {"ndc ipfwd add lo2 lo3",
2978 "400 0 ipfwd operation failed (No such process)"},
2979 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
2980 "200 0 ipfwd operation succeeded"},
2981 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
2982 "200 0 ipfwd operation succeeded"},
2983 };
2984
2985 static const struct {
2986 const char* ipVersion;
2987 const char* testDest;
2988 const char* testNextHop;
2989 const bool expectSuccess;
2990 const std::string expectedResult;
2991 } kTestData[] = {
2992 {IP_RULE_V4, "0.0.0.0/0", "", true,
2993 "200 0 success"},
2994 {IP_RULE_V4, "10.251.0.0/16", "", true,
2995 "200 0 success"},
2996 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
2997 "400 0 addRoute() failed (Invalid argument)",},
2998 {IP_RULE_V6, "::/0", "", true,
2999 "200 0 success"},
3000 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3001 "200 0 success"},
3002 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3003 "400 0 addRoute() failed (Invalid argument)"},
3004 };
3005 // clang-format on
3006
3007 for (const auto& cmd : networkCmds) {
3008 const std::vector<std::string> result = runCommand(cmd.cmdString);
3009 SCOPED_TRACE(cmd.cmdString);
3010 EXPECT_EQ(result.size(), 1U);
3011 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3012 }
3013
3014 for (const auto& cmd : ipfwdCmds) {
3015 const std::vector<std::string> result = runCommand(cmd.cmdString);
3016 SCOPED_TRACE(cmd.cmdString);
3017 EXPECT_EQ(result.size(), 1U);
3018 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3019 }
3020
3021 // Add test physical network
3022 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3023 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3024
3025 for (const auto& td : kTestData) {
3026 const std::string routeAddCmd =
3027 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3028 td.testDest, td.testNextHop);
3029 const std::string routeRemoveCmd =
3030 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3031 sTun.name().c_str(), td.testDest, td.testNextHop);
3032 std::vector<std::string> result = runCommand(routeAddCmd);
3033 SCOPED_TRACE(routeAddCmd);
3034 EXPECT_EQ(result.size(), 1U);
3035 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3036 if (td.expectSuccess) {
3037 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3038 sTun.name().c_str());
3039 result = runCommand(routeRemoveCmd);
3040 EXPECT_EQ(result.size(), 1U);
3041 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3042 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3043 sTun.name().c_str());
3044 }
3045 }
3046 // Remove test physical network
3047 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003048}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003049
Luke Huang2ff8b342019-04-30 15:33:33 +08003050TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003051 sp<IBinder> binder;
3052 binder::Status status = mNetd->getOemNetd(&binder);
3053 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3054 sp<com::android::internal::net::IOemNetd> oemNetd;
3055 if (binder != nullptr) {
3056 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3057 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003058 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003059
3060 TimedOperation t("OemNetd isAlive RPC");
3061 bool isAlive = false;
3062 oemNetd->isAlive(&isAlive);
3063 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003064
3065 class TestOemUnsolListener
3066 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3067 public:
3068 android::binder::Status onRegistered() override {
3069 std::lock_guard lock(mCvMutex);
3070 mCv.notify_one();
3071 return android::binder::Status::ok();
3072 }
3073 std::condition_variable& getCv() { return mCv; }
3074 std::mutex& getCvMutex() { return mCvMutex; }
3075
3076 private:
3077 std::mutex mCvMutex;
3078 std::condition_variable mCv;
3079 };
3080
3081 // Start the Binder thread pool.
3082 android::ProcessState::self()->startThreadPool();
3083
3084 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3085
3086 auto& cv = testListener->getCv();
3087 auto& cvMutex = testListener->getCvMutex();
3088
3089 {
3090 std::unique_lock lock(cvMutex);
3091
3092 status = oemNetd->registerOemUnsolicitedEventListener(
3093 ::android::interface_cast<
3094 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3095 testListener));
3096 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3097
3098 // Wait for receiving expected events.
3099 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3100 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003101}
Luke Huangd2861982019-05-17 19:47:28 +08003102
3103void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3104 int fallthroughNetId) {
3105 // Re-init sTun* to ensure route rule exists.
3106 sTun.destroy();
3107 sTun.init();
3108 sTun2.destroy();
3109 sTun2.init();
3110
3111 // Create physical network with fallthroughNetId but not set it as default network
3112 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3113 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3114
3115 // Create VPN with vpnNetId
3116 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3117
3118 // Add uid to VPN
3119 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3120 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3121
3122 // Add default route to fallthroughNetwork
3123 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3124 // Add limited route
3125 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3126}
3127
3128namespace {
3129
3130class ScopedUidChange {
3131 public:
3132 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3133 mStoredUid = getuid();
3134 if (mInputUid == mStoredUid) return;
3135 EXPECT_TRUE(seteuid(uid) == 0);
3136 }
3137 ~ScopedUidChange() {
3138 if (mInputUid == mStoredUid) return;
3139 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3140 }
3141
3142 private:
3143 uid_t mInputUid;
3144 uid_t mStoredUid;
3145};
3146
3147constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3148
3149void clearQueue(int tunFd) {
3150 char buf[4096];
3151 int ret;
3152 do {
3153 ret = read(tunFd, buf, sizeof(buf));
3154 } while (ret > 0);
3155}
3156
3157void checkDataReceived(int udpSocket, int tunFd) {
3158 char buf[4096] = {};
3159 // Clear tunFd's queue before write something because there might be some
3160 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3161 clearQueue(tunFd);
3162 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3163 // TODO: extract header and verify data
3164 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3165}
3166
3167bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3168 ScopedUidChange scopedUidChange(uid);
3169 android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3170 if (testSocket < 0) return false;
3171
3172 const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
3173 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3174 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3175 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3176 if (res == -1) return false;
3177
3178 char addr[INET6_ADDRSTRLEN];
3179 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3180 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3181 checkDataReceived(testSocket, tunFd);
3182 return true;
3183}
3184
3185void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3186 std::string vpnFallthroughRule =
3187 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3188 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3189 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3190 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3191 }
3192}
3193
3194void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3195 const TunInterface& fallthroughNetwork,
3196 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3197 int fallthroughNetId = TEST_NETID1) {
3198 // Set default network to NETID_UNSET
3199 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3200
3201 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3202 in6_addr insideVpnAddr = {
3203 {// 2001:db8:cafe::1
3204 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3205 // outsideVpnAddr will hit the route in the fallthrough network route table
3206 // because we added default route in createVpnNetworkWithUid
3207 in6_addr outsideVpnAddr = {
3208 {// 2607:f0d0:1002::4
3209 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3210
3211 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3212 int vpnFd = vpnNetwork.getFdForTesting();
3213 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3214 // default network.
3215 Fwmark fwmark;
3216 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3217 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3218
3219 // Set default network
3220 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3221
3222 // Connections go on the default network because UID 0 is not subject to the VPN.
3223 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3224 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3225 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3226 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3227
3228 // Check if fallthrough rule exists
3229 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3230
3231 // Expect fallthrough to default network
3232 // The fwmark differs depending on whether the VPN is bypassable or not.
3233 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3234 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3235
3236 // Expect connect success, packet will be sent to vpnFd.
3237 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3238 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3239
3240 // Explicitly select vpn network
3241 setNetworkForProcess(vpnNetId);
3242
3243 // Expect fallthrough to default network
3244 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3245 // Expect the mark contains all the bit because we've selected network.
3246 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3247
3248 // Expect connect success, packet will be sent to vpnFd.
3249 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3250 // Expect the mark contains all the bit because we've selected network.
3251 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3252
3253 // Explicitly select fallthrough network
3254 setNetworkForProcess(fallthroughNetId);
3255
3256 // The mark is set to fallthrough network because we've selected it.
3257 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3258 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3259
3260 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3261 if (bypassable) {
3262 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3263 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3264 } else {
3265 // If not, no permission to bypass vpn.
3266 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3267 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3268 }
3269}
3270
3271} // namespace
3272
3273TEST_F(BinderTest, SecureVPNFallthrough) {
3274 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3275 // Get current default network NetId
3276 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3277 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3278}
3279
3280TEST_F(BinderTest, BypassableVPNFallthrough) {
3281 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3282 // Get current default network NetId
3283 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3284 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
3285}