blob: b36a7a83cdac3efb8e18f3717e2960f9322b6d54 [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 <cstdlib>
Bernie Innocenti196f1b82019-05-20 16:34:16 +090025#include <iostream>
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>
Luke Huang33a92792019-05-28 16:59:25 +080044#include <android-base/properties.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090045#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090046#include <android-base/strings.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080047#include <binder/IPCThreadState.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080048#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070049#include <bpf/BpfUtils.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080050#include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
51#include <com/android/internal/net/IOemNetd.h>
Robin Leeb8087362016-03-30 18:43:08 +010052#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include <gtest/gtest.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
Luke Huang33a92792019-05-28 16:59:25 +080099#define SKIP_IF_CUTTLEFISH \
100 do { \
101 if (isCuttleFish()) return; \
102 } while (0)
103
Robin Leeb8087362016-03-30 18:43:08 +0100104static const char* IP_RULE_V4 = "-4";
105static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900106static const int TEST_NETID1 = 65501;
107static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800108
109// Use maximum reserved appId for applications to avoid conflict with existing
110// uids.
111static const int TEST_UID1 = 99999;
112static const int TEST_UID2 = 99998;
113
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900114constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115
Benedict Wongb2daefb2017-12-06 22:05:46 -0800116static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
117static const std::string ESP_ALLOW_RULE("esp");
118
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900119class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900120 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900122 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900123 sp<IBinder> binder = sm->getService(String16("netd"));
124 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900125 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900126 }
127 }
128
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900129 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130 ASSERT_NE(nullptr, mNetd.get());
131 }
132
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900133 void TearDown() override {
134 mNetd->networkDestroy(TEST_NETID1);
135 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800136 setNetworkForProcess(NETID_UNSET);
137 // Restore default network
138 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900139 }
140
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900141 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700142
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900143 // Static because setting up the tun interface takes about 40ms.
144 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900145 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900146 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900147 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900148 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900149 }
150
151 static void TearDownTestCase() {
152 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900153 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900154 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900155 }
156
157 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900158
Luke Huangd2861982019-05-17 19:47:28 +0800159 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
160 int fallthroughNetId = TEST_NETID1);
161
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900162 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800163 // Use -1 to represent that default network was not modified because
164 // real netId must be an unsigned value.
165 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900166 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900167 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900168 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900169};
170
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900171TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900172TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900173
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900174class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900175 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700176 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900177 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900178 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179 }
180
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900181 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900182 std::string mName;
183};
184
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900185TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900186 TimedOperation t("isAlive RPC");
187 bool isAlive = false;
188 mNetd->isAlive(&isAlive);
189 ASSERT_TRUE(isAlive);
190}
191
192static int randomUid() {
193 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
194}
195
Robin Leeb8087362016-03-30 18:43:08 +0100196static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900197 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900198 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
199 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900200 perror("popen");
201 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900202 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900203
204 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100205 size_t bufsize = 0;
206 ssize_t linelen = 0;
207 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900208 lines.push_back(std::string(line, linelen));
209 free(line);
210 line = nullptr;
211 }
212
213 pclose(f);
214 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900215}
216
Robin Leeb8087362016-03-30 18:43:08 +0100217static std::vector<std::string> listIpRules(const char *ipVersion) {
218 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
219 return runCommand(command);
220}
221
222static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900223 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100224 return runCommand(command);
225}
226
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900227static int iptablesRuleLineLength(const char *binary, const char *chainName) {
228 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900229}
230
Benedict Wongb2daefb2017-12-06 22:05:46 -0800231static bool iptablesRuleExists(const char *binary,
232 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900233 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800234 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900235 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800236 if(rule.find(expectedRule) != std::string::npos) {
237 return true;
238 }
239 }
240 return false;
241}
242
243static bool iptablesNoSocketAllowRuleExists(const char *chainName){
244 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
245 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
246}
247
248static bool iptablesEspAllowRuleExists(const char *chainName){
249 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
250 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
251}
252
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900253TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700254 SKIP_IF_BPF_SUPPORTED;
255
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900256 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
257 const int kNumUids = 500;
258 std::vector<int32_t> noUids(0);
259 std::vector<int32_t> uids(kNumUids);
260 for (int i = 0; i < kNumUids; i++) {
261 uids[i] = randomUid();
262 }
263
264 bool ret;
265 {
266 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900267 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900268 }
269 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800270 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
271 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
272 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
273 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900274 {
275 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900276 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900277 }
278 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900279 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
280 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900281
282 {
283 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900284 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900285 }
286 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900287 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
288 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800289 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
290 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900291
292 {
293 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900294 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900295 }
296 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900297 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
298 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900299
300 // Check that the call fails if iptables returns an error.
301 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900302 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900303 EXPECT_EQ(false, ret);
304}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900305
Benedict Wong319f17e2018-05-15 17:06:44 -0700306TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700307 const struct TestData {
308 const std::string family;
309 const std::string deviceName;
310 const std::string localAddress;
311 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800312 int32_t iKey;
313 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700314 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800315 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700316 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
317 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
318 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800319 };
320
Sehee Park8659b8d2018-11-16 10:53:16 +0900321 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700322 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800323
324 binder::Status status;
325
Benedict Wong319f17e2018-05-15 17:06:44 -0700326 // Create Tunnel Interface.
327 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700328 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800329 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
330
Benedict Wonga450e722018-05-07 10:29:02 -0700331 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900332 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700333
Benedict Wong319f17e2018-05-15 17:06:44 -0700334 // Update Tunnel Interface.
335 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700336 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800337 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
338
Benedict Wong319f17e2018-05-15 17:06:44 -0700339 // Remove Tunnel Interface.
340 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800341 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700342
343 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900344 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800345 }
346}
347
Benedict Wong1cb73df2018-12-03 00:54:14 -0800348TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
349 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
350 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
351
352 int sockOptVal = UDP_ENCAP_ESPINUDP;
353 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
354
355 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
356 EXPECT_TRUE(res.isOk());
357
358 struct stat info;
359 EXPECT_EQ(0, fstat(sockFd.get(), &info));
360 EXPECT_EQ(1001, (int) info.st_uid);
361}
362
Nathan Harold2deff322018-05-10 14:03:48 -0700363// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
364// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
365#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900366
367using android::net::XfrmController;
368
Benedict Wonga04ffa72018-05-09 21:42:42 -0700369static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
370 static_cast<int>(android::net::XfrmDirection::OUT)};
371static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
372
Nathan Harold21299f72018-03-16 20:13:03 -0700373#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
374 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900375bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900376 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700377 SCOPED_TRACE(status);
378 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
379
380 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700381 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700382 SCOPED_TRACE(status);
383 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
384
385 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700386 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
387 0xD00D, 0xE00D, false)
388 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700389}
390
Benedict Wonga04ffa72018-05-09 21:42:42 -0700391TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900392 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700393
394 // Repeat to ensure cleanup and recreation works correctly
395 for (int i = 0; i < 2; i++) {
396 for (int direction : XFRM_DIRECTIONS) {
397 for (int addrFamily : ADDRESS_FAMILIES) {
398 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700399 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700400 EXPECT_TRUE(status.isOk())
401 << " family: " << addrFamily << " direction: " << direction;
402 }
403 }
404
405 // Cleanup
406 for (int direction : XFRM_DIRECTIONS) {
407 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700408 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700409 EXPECT_TRUE(status.isOk());
410 }
411 }
412 }
413}
414
415TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
416 binder::Status status;
417
418 // Repeat to ensure cleanup and recreation works correctly
419 for (int i = 0; i < 2; i++) {
420 for (int direction : XFRM_DIRECTIONS) {
421 for (int addrFamily : ADDRESS_FAMILIES) {
422 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700423 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700424 EXPECT_TRUE(status.isOk())
425 << " family: " << addrFamily << " direction: " << direction;
426 }
427 }
428
429 // Cleanup
430 for (int direction : XFRM_DIRECTIONS) {
431 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700432 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700433 EXPECT_TRUE(status.isOk());
434 }
435 }
436 }
437}
438
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900439TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900440 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700441 status = XfrmController::Init();
442 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700443
444 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
445 // feature.
446 if (status.code() == EOPNOTSUPP) return;
447
Nathan Harold21299f72018-03-16 20:13:03 -0700448 ASSERT_TRUE(status.ok());
449
450 int32_t spi = 0;
451
452 ASSERT_TRUE(allocateIpSecResources(true, &spi));
453 ASSERT_TRUE(allocateIpSecResources(false, &spi));
454
455 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700456 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700457 ASSERT_TRUE(allocateIpSecResources(true, &spi));
458
459 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700460 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700461 SCOPED_TRACE(status);
462 ASSERT_TRUE(status.ok());
463
Benedict Wonga450e722018-05-07 10:29:02 -0700464 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700465 SCOPED_TRACE(status);
466 ASSERT_TRUE(status.ok());
467
468 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700469 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700470}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900471
472#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700473
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900474static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900475 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900476
477 // Output looks like this:
478 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900479 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900480 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900481 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900482 //
483 // or:
484 //
485 // Chain bw_data_saver (1 references)
486 // target prot opt source destination
487 // ... possibly connectivity critical packet rules here ...
488 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900489
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900490 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900491
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900492 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
493 // Data saver disabled.
494 return 0;
495 }
496
497 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
498
499 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
500 // Data saver enabled.
501 return 1;
502 }
503
504 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900505}
506
507bool enableDataSaver(sp<INetd>& netd, bool enable) {
508 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
509 bool ret;
510 netd->bandwidthEnableDataSaver(enable, &ret);
511 return ret;
512}
513
514int getDataSaverState() {
515 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
516 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
517 EXPECT_EQ(enabled4, enabled6);
518 EXPECT_NE(-1, enabled4);
519 EXPECT_NE(-1, enabled6);
520 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
521 return -1;
522 }
523 return enabled6;
524}
525
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900526TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900527 const int wasEnabled = getDataSaverState();
528 ASSERT_NE(-1, wasEnabled);
529
530 if (wasEnabled) {
531 ASSERT_TRUE(enableDataSaver(mNetd, false));
532 EXPECT_EQ(0, getDataSaverState());
533 }
534
535 ASSERT_TRUE(enableDataSaver(mNetd, false));
536 EXPECT_EQ(0, getDataSaverState());
537
538 ASSERT_TRUE(enableDataSaver(mNetd, true));
539 EXPECT_EQ(1, getDataSaverState());
540
541 ASSERT_TRUE(enableDataSaver(mNetd, true));
542 EXPECT_EQ(1, getDataSaverState());
543
544 if (!wasEnabled) {
545 ASSERT_TRUE(enableDataSaver(mNetd, false));
546 EXPECT_EQ(0, getDataSaverState());
547 }
548}
Robin Leeb8087362016-03-30 18:43:08 +0100549
Luke Huang94658ac2018-10-18 19:35:12 +0900550static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
551 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100552 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100553 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100554 std::vector<std::string> rules = listIpRules(ipVersion);
555
556 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900557 std::string suffix =
558 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900559 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800560 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100561 return true;
562 }
563 }
564 return false;
565}
566
Luke Huang94658ac2018-10-18 19:35:12 +0900567static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
568 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100569 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
570 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
571 EXPECT_EQ(existsIp4, existsIp6);
572 return existsIp4;
573}
574
Luke Huang94658ac2018-10-18 19:35:12 +0900575namespace {
576
577UidRangeParcel makeUidRangeParcel(int start, int stop) {
578 UidRangeParcel res;
579 res.start = start;
580 res.stop = stop;
581
582 return res;
583}
584
585} // namespace
586
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900587TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800588 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
589 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
590 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900591 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
592 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900593
594 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
595 EXPECT_EQ(EBUSY,
596 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
597
598 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
599 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
600 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800601 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900602}
603
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900604TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900605 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
606
cken67cd14c2018-12-05 17:26:59 +0900607 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
608 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900609 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
610
Luke Huang94658ac2018-10-18 19:35:12 +0900611 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
612 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
613 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900614 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
615
616 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
617
618 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
619 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
620 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
621 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
622
623 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
624 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
625 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
626 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
627
628 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
629}
630
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900631TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100632 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100633
Luke Huang94658ac2018-10-18 19:35:12 +0900634 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
635 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800636 // Make sure no rules existed before calling commands.
637 for (auto const& range : uidRanges) {
638 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
639 }
Robin Leeb8087362016-03-30 18:43:08 +0100640 // Create two valid rules.
641 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100642 for (auto const& range : uidRanges) {
643 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
644 }
645
646 // Remove the rules.
647 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100648 for (auto const& range : uidRanges) {
649 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
650 }
651
652 // Fail to remove the rules a second time after they are already deleted.
653 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
654 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
655 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100656}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900657
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900658// Create a socket pair that isLoopbackSocket won't think is local.
659void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900660 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900661 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900662 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
663
664 socklen_t addrlen = sizeof(server6);
665 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
666 ASSERT_EQ(0, listen(*serverSocket, 10));
667
Bernie Innocentif6918262018-06-11 17:37:35 +0900668 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900669 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900670 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900671 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
672 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
673
Bernie Innocentif6918262018-06-11 17:37:35 +0900674 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900675 ASSERT_NE(-1, *acceptedSocket);
676
677 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
678}
679
680void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
681 char buf[4096];
682 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
683 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
684 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
685}
686
687void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
688 // Check that the client socket was closed with ECONNABORTED.
689 int ret = write(clientSocket, "foo", sizeof("foo"));
690 int err = errno;
691 EXPECT_EQ(-1, ret);
692 EXPECT_EQ(ECONNABORTED, err);
693
694 // Check that it sent a RST to the server.
695 ret = write(acceptedSocket, "foo", sizeof("foo"));
696 err = errno;
697 EXPECT_EQ(-1, ret);
698 EXPECT_EQ(ECONNRESET, err);
699}
700
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900701TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900702 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900703 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900704
705 // Pick a random UID in the system UID range.
706 constexpr int baseUid = AID_APP - 2000;
707 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
708 int uid = baseUid + 500 + arc4random_uniform(1000);
709 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
710
711 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900712 std::vector<UidRangeParcel> uidRanges = {
713 makeUidRangeParcel(baseUid + 42, baseUid + 449),
714 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
715 makeUidRangeParcel(baseUid + 498, uid - 1),
716 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900717 };
718 // A skip list that doesn't contain UID.
719 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
720
721 // Close sockets. Our test socket should be intact.
722 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
723 checkSocketpairOpen(clientSocket, acceptedSocket);
724
725 // UID ranges that do contain uid.
726 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900727 makeUidRangeParcel(baseUid + 42, baseUid + 449),
728 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
729 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900730 };
731 // Add uid to the skip list.
732 skipUids.push_back(uid);
733
734 // Close sockets. Our test socket should still be intact because it's in the skip list.
735 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
736 checkSocketpairOpen(clientSocket, acceptedSocket);
737
738 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
739 skipUids.resize(skipUids.size() - 1);
740 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
741 checkSocketpairClosed(clientSocket, acceptedSocket);
742
743 close(clientSocket);
744 close(serverSocket);
745 close(acceptedSocket);
746}
Erik Klinecc4f2732016-08-03 11:24:27 +0900747
748namespace {
749
750int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
751 if (buf == nullptr) return -1;
752
753 int prefixLength = 0;
754 bool endOfContiguousBits = false;
755 for (unsigned int i = 0; i < buflen; i++) {
756 const uint8_t value = buf[i];
757
758 // Bad bit sequence: check for a contiguous set of bits from the high
759 // end by verifying that the inverted value + 1 is a power of 2
760 // (power of 2 iff. (v & (v - 1)) == 0).
761 const uint8_t inverse = ~value + 1;
762 if ((inverse & (inverse - 1)) != 0) return -1;
763
764 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
765
766 // Bogus netmask.
767 if (endOfContiguousBits && value != 0) return -1;
768
769 if (value != 0xff) endOfContiguousBits = true;
770 }
771
772 return prefixLength;
773}
774
775template<typename T>
776int netmaskToPrefixLength(const T *p) {
777 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
778}
779
780
781static bool interfaceHasAddress(
782 const std::string &ifname, const char *addrString, int prefixLength) {
783 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900784
785 const struct addrinfo hints = {
786 .ai_flags = AI_NUMERICHOST,
787 .ai_family = AF_UNSPEC,
788 .ai_socktype = SOCK_DGRAM,
789 };
790 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
791 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
792 return false;
793 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900794 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900795
796 struct ifaddrs *ifaddrsList = nullptr;
797 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
798
799 if (getifaddrs(&ifaddrsList) != 0) {
800 return false;
801 }
802
803 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
804 if (std::string(addr->ifa_name) != ifname ||
805 addr->ifa_addr == nullptr ||
806 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
807 continue;
808 }
809
810 switch (addr->ifa_addr->sa_family) {
811 case AF_INET: {
812 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
813 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
814 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
815 continue;
816 }
817
818 if (prefixLength < 0) return true; // not checking prefix lengths
819
820 if (addr->ifa_netmask == nullptr) return false;
821 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
822 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
823 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
824 }
825 case AF_INET6: {
826 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
827 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
828 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
829 continue;
830 }
831
832 if (prefixLength < 0) return true; // not checking prefix lengths
833
834 if (addr->ifa_netmask == nullptr) return false;
835 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
836 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
837 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
838 }
839 default:
840 // Cannot happen because we have already screened for matching
841 // address families at the top of each iteration.
842 continue;
843 }
844 }
845
846 return false;
847}
848
849} // namespace
850
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900851TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900852 static const struct TestData {
853 const char *addrString;
854 const int prefixLength;
855 const bool expectSuccess;
856 } kTestData[] = {
857 { "192.0.2.1", 24, true },
858 { "192.0.2.2", 25, true },
859 { "192.0.2.3", 32, true },
860 { "192.0.2.4", 33, false },
861 { "192.not.an.ip", 24, false },
862 { "2001:db8::1", 64, true },
863 { "2001:db8::2", 65, true },
864 { "2001:db8::3", 128, true },
865 { "2001:db8::4", 129, false },
866 { "foo:bar::bad", 64, false },
867 };
868
Sehee Park8659b8d2018-11-16 10:53:16 +0900869 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900870 const auto &td = kTestData[i];
871
872 // [1.a] Add the address.
873 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900874 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900875 if (td.expectSuccess) {
876 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
877 } else {
878 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
879 ASSERT_NE(0, status.serviceSpecificErrorCode());
880 }
881
882 // [1.b] Verify the addition meets the expectation.
883 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900884 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900885 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900886 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900887 }
888
889 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900890 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900891 if (td.expectSuccess) {
892 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
893 } else {
894 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
895 ASSERT_NE(0, status.serviceSpecificErrorCode());
896 }
897
898 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900899 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900900 }
901}
Erik Kline55b06f82016-07-04 09:57:18 +0900902
Erik Kline38e51f12018-09-06 20:14:44 +0900903TEST_F(BinderTest, GetProcSysNet) {
904 const char LOOPBACK[] = "lo";
905 static const struct {
906 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900907 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900908 const char* ifname;
909 const char* parameter;
910 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900911 const int expectedReturnCode;
912 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900913 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
914 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
915 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
916 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
917 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
918 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
919 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900920 };
921
Sehee Park8659b8d2018-11-16 10:53:16 +0900922 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900923 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900924
Erik Kline38e51f12018-09-06 20:14:44 +0900925 std::string value;
926 const binder::Status status =
927 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
928
929 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900930 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900931 EXPECT_EQ(0, status.exceptionCode());
932 EXPECT_EQ(0, status.serviceSpecificErrorCode());
933 EXPECT_EQ(td.expectedValue, value);
934 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900935 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900936 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
937 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
938 }
939 }
940}
941
942TEST_F(BinderTest, SetProcSysNet) {
943 static const struct {
944 const int ipversion;
945 const int which;
946 const char* ifname;
947 const char* parameter;
948 const char* value;
949 const int expectedReturnCode;
950 } kTestData[] = {
951 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
952 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
953 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
954 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
955 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
956 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
957 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
958 };
959
Sehee Park8659b8d2018-11-16 10:53:16 +0900960 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900961 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900962 const binder::Status status =
963 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900964
965 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900966 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900967 EXPECT_EQ(0, status.exceptionCode());
968 EXPECT_EQ(0, status.serviceSpecificErrorCode());
969 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900970 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900971 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
972 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
973 }
974 }
975}
Ben Schwartze7601812017-04-28 16:38:29 -0400976
Erik Kline38e51f12018-09-06 20:14:44 +0900977TEST_F(BinderTest, GetSetProcSysNet) {
978 const int ipversion = INetd::IPV6;
979 const int category = INetd::NEIGH;
980 const std::string& tun = sTun.name();
981 const std::string parameter("ucast_solicit");
982
983 std::string value{};
984 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700985 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900986 const int ival = std::stoi(value);
987 EXPECT_GT(ival, 0);
988 // Try doubling the parameter value (always best!).
989 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
990 .isOk());
991 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
992 EXPECT_EQ(2 * ival, std::stoi(value));
993 // Try resetting the parameter.
994 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
995 .isOk());
996 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
997 EXPECT_EQ(ival, std::stoi(value));
998}
999
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001000namespace {
1001
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001002void expectNoTestCounterRules() {
1003 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1004 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1005 std::string allRules = Join(runCommand(command), "\n");
1006 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1007 }
1008}
1009
Bernie Innocentif6918262018-06-11 17:37:35 +09001010void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1011 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001012 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1013 path, if1.c_str(), if2.c_str(), pkt, byte));
1014}
1015
Bernie Innocentif6918262018-06-11 17:37:35 +09001016void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001017 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1018 path, if1.c_str(), if2.c_str()));
1019 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1020 path, if2.c_str(), if1.c_str()));
1021}
1022
Luke Huangcaebcbb2018-09-27 20:37:14 +08001023std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1024 const std::string& iface) {
1025 for (auto& stats : statsVec) {
1026 if (stats.iface == iface) {
1027 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1028 }
1029 }
1030 return {};
1031}
1032
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001033} // namespace
1034
1035TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001036 expectNoTestCounterRules();
1037
1038 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1039 // disabling tethering. We don't check the return value because these commands will fail if
1040 // tethering is already enabled.
1041 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1042 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1043
1044 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1045 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1046 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001047
1048 // Ensure we won't use the same interface name, otherwise the test will fail.
1049 u_int32_t rNumber = arc4random_uniform(10000);
1050 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1051 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001052
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) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001624 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001625
1626 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1627 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1628 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1629
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001630 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001631 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
Luke Huang33a92792019-05-28 16:59:25 +08001937namespace {
1938
1939constexpr char CUTTLEFISH_PRODUCT_DEVICE[] = "vsoc_x86";
1940constexpr char CUTTLEFISH_SYSTEM_NAME[] = "cf_x86_phone";
1941
1942bool isCuttleFish() {
1943 static const std::string sProductDevice = android::base::GetProperty("ro.product.device", "");
1944 static const std::string sSystemName = android::base::GetProperty("ro.product.system.name", "");
1945 return (sProductDevice.find(CUTTLEFISH_PRODUCT_DEVICE) != std::string::npos) &&
1946 (sSystemName.find(CUTTLEFISH_SYSTEM_NAME) != std::string::npos);
1947}
1948
1949} // namespace
1950
Luke Huangb670d162018-08-23 20:01:13 +08001951TEST_F(BinderTest, NetworkPermissionDefault) {
Luke Huang33a92792019-05-28 16:59:25 +08001952 SKIP_IF_CUTTLEFISH;
1953
Luke Huangb670d162018-08-23 20:01:13 +08001954 // Add test physical network
1955 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1956 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1957
Luke Huangc3252cc2018-10-16 15:43:23 +08001958 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001959 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1960 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001961
1962 // Test SetDefault
1963 status = mNetd->networkSetDefault(TEST_NETID1);
1964 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1965 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1966
1967 status = mNetd->networkClearDefault();
1968 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1969 expectNetworkDefaultIpRuleDoesNotExist();
1970
Luke Huangd2861982019-05-17 19:47:28 +08001971 // Set default network back
1972 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001973 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1974
1975 // Test SetPermission
1976 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1977 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1978 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1979 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1980
1981 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1982 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1983 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1984 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1985
1986 // Remove test physical network
1987 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1988}
1989
1990TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001991 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001992 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1993 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001994 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001995 EXPECT_TRUE(ret);
1996
Luke Huang854e2992019-05-29 16:42:48 +08001997 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001998 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08001999
2000 // Clear uid permission before calling networkCanProtect to ensure
2001 // the call won't be affected by uid permission.
2002 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2003
2004 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002005 EXPECT_FALSE(ret);
2006}
2007
2008namespace {
2009
Luke Huangb5733d72018-08-21 17:17:19 +08002010int readIntFromPath(const std::string& path) {
2011 std::string result = "";
2012 EXPECT_TRUE(ReadFileToString(path, &result));
2013 return std::stoi(result);
2014}
2015
2016int getTetherAcceptIPv6Ra(const std::string& ifName) {
2017 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2018 return readIntFromPath(path);
2019}
2020
2021bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2022 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2023 return readIntFromPath(path);
2024}
2025
2026int getTetherIPv6DadTransmits(const std::string& ifName) {
2027 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2028 return readIntFromPath(path);
2029}
2030
2031bool getTetherEnableIPv6(const std::string& ifName) {
2032 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2033 int disableIPv6 = readIntFromPath(path);
2034 return !disableIPv6;
2035}
2036
2037bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2038 for (const auto& iface : ifList) {
2039 if (iface == ifName) {
2040 return true;
2041 }
2042 }
2043 return false;
2044}
2045
2046void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2047 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2048 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2049 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2050 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2051}
2052
2053void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2054 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2055 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2056 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2057 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2058}
2059
2060void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2061 const std::string& ifName) {
2062 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2063}
2064
2065void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2066 const std::string& ifName) {
2067 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2068}
2069
2070void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2071 const std::vector<std::string>& testDnsAddrs) {
2072 EXPECT_TRUE(dnsList == testDnsAddrs);
2073}
2074
2075} // namespace
2076
2077TEST_F(BinderTest, TetherStartStopStatus) {
2078 std::vector<std::string> noDhcpRange = {};
2079 static const char dnsdName[] = "dnsmasq";
2080
2081 binder::Status status = mNetd->tetherStart(noDhcpRange);
2082 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002083 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002084
2085 bool tetherEnabled;
2086 status = mNetd->tetherIsEnabled(&tetherEnabled);
2087 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2088 EXPECT_TRUE(tetherEnabled);
2089
2090 status = mNetd->tetherStop();
2091 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002092 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002093
2094 status = mNetd->tetherIsEnabled(&tetherEnabled);
2095 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2096 EXPECT_FALSE(tetherEnabled);
2097}
2098
2099TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2100 // TODO: verify if dnsmasq update interface successfully
2101
2102 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2103 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2104 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2105
2106 std::vector<std::string> ifList;
2107 status = mNetd->tetherInterfaceList(&ifList);
2108 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2109 expectTetherInterfaceExists(ifList, sTun.name());
2110
2111 status = mNetd->tetherInterfaceRemove(sTun.name());
2112 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2113 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2114
2115 status = mNetd->tetherInterfaceList(&ifList);
2116 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2117 expectTetherInterfaceNotExists(ifList, sTun.name());
2118}
2119
2120TEST_F(BinderTest, TetherDnsSetList) {
2121 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002122 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2123 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002124
2125 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2126 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2127
2128 std::vector<std::string> dnsList;
2129 status = mNetd->tetherDnsList(&dnsList);
2130 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2131 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002132}
2133
2134namespace {
2135
2136constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2137constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2138constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2139constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2140constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2141constexpr char FIREWALL_STANDBY[] = "fw_standby";
2142constexpr char targetReturn[] = "RETURN";
2143constexpr char targetDrop[] = "DROP";
2144
2145void expectFirewallWhitelistMode() {
2146 static const char dropRule[] = "DROP all";
2147 static const char rejectRule[] = "REJECT all";
2148 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2149 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2150 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2151 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2152 }
2153}
2154
2155void expectFirewallBlacklistMode() {
2156 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2157 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2158 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2159 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2160 }
2161}
2162
2163bool iptablesFirewallInterfaceFirstRuleExists(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 // Expected rule:
2168 // Chain fw_INPUT (1 references)
2169 // pkts bytes target prot opt in out source destination
2170 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2171 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2172 int firstRuleIndex = 2;
2173 if (rules.size() < 4) return false;
2174 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2175 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2176 return true;
2177 }
2178 }
2179 return false;
2180}
2181
2182// TODO: It is a duplicate function, need to remove it
2183bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2184 const std::string& expectedInterface,
2185 const std::string& expectedRule) {
2186 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2187 for (const auto& rule : rules) {
2188 if (rule.find(expectedInterface) != std::string::npos) {
2189 if (rule.find(expectedRule) != std::string::npos) {
2190 return true;
2191 }
2192 }
2193 }
2194 return false;
2195}
2196
2197void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2198 static const char returnRule[] = "RETURN all";
2199 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2200 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2201 returnRule));
2202 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2203 returnRule));
2204 }
2205}
2206
2207void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2208 static const char returnRule[] = "RETURN all";
2209 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2210 EXPECT_FALSE(
2211 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2212 EXPECT_FALSE(
2213 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2214 }
2215}
2216
2217bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2218 const std::string& expectedTarget,
2219 const std::string& expectedRule) {
2220 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2221 int firstRuleIndex = 2;
2222 if (rules.size() < 4) return false;
2223 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2224 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2225 return true;
2226 }
2227 }
2228 return false;
2229}
2230
2231bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2232 const std::string& expectedTarget,
2233 const std::string& expectedRule) {
2234 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2235 int lastRuleIndex = rules.size() - 1;
2236 if (lastRuleIndex < 0) return false;
2237 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2238 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2239 return true;
2240 }
2241 }
2242 return false;
2243}
2244
2245void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2246 std::string uidRule = StringPrintf("owner UID match %u", uid);
2247 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2248 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2249}
2250
2251void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2252 std::string uidRule = StringPrintf("owner UID match %u", uid);
2253 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2254 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2255}
2256
2257void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2258 std::string uidRule = StringPrintf("owner UID match %u", uid);
2259 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2260 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2261}
2262
2263void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2264 std::string uidRule = StringPrintf("owner UID match %u", uid);
2265 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2266 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2267}
2268
2269bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2270 std::vector<std::string> inputRules =
2271 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2272 std::vector<std::string> outputRules =
2273 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2274 int inputLastRuleIndex = inputRules.size() - 1;
2275 int outputLastRuleIndex = outputRules.size() - 1;
2276
2277 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2278 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2279 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2280 return true;
2281 }
2282 }
2283 return false;
2284}
2285
2286void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2287 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2288 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2289}
2290
2291void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2292 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2293 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2294 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2295 }
2296}
2297
2298} // namespace
2299
2300TEST_F(BinderTest, FirewallSetFirewallType) {
2301 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2302 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2303 expectFirewallWhitelistMode();
2304
2305 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2306 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2307 expectFirewallBlacklistMode();
2308
2309 // set firewall type blacklist twice
2310 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2311 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2312 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2313 expectFirewallBlacklistMode();
2314
2315 // set firewall type whitelist twice
2316 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2317 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2318 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2319 expectFirewallWhitelistMode();
2320
2321 // reset firewall type to default
2322 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2323 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2324 expectFirewallBlacklistMode();
2325}
2326
2327TEST_F(BinderTest, FirewallSetInterfaceRule) {
2328 // setinterfaceRule is not supported in BLACKLIST MODE
2329 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2330 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2331
2332 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2333 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2334
2335 // set WHITELIST mode first
2336 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2337 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2338
2339 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2340 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2341 expectFirewallInterfaceRuleAllowExists(sTun.name());
2342
2343 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2344 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2345 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2346
2347 // reset firewall mode to default
2348 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2349 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2350 expectFirewallBlacklistMode();
2351}
2352
2353TEST_F(BinderTest, FirewallSetUidRule) {
2354 SKIP_IF_BPF_SUPPORTED;
2355
2356 int32_t uid = randomUid();
2357
2358 // Doze allow
2359 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2360 INetd::FIREWALL_RULE_ALLOW);
2361 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2362 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2363
2364 // Doze deny
2365 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2366 INetd::FIREWALL_RULE_DENY);
2367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2368 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2369
2370 // Powersave allow
2371 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2372 INetd::FIREWALL_RULE_ALLOW);
2373 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2374 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2375
2376 // Powersave deny
2377 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2378 INetd::FIREWALL_RULE_DENY);
2379 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2380 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2381
2382 // Standby deny
2383 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2384 INetd::FIREWALL_RULE_DENY);
2385 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2386 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2387
2388 // Standby allow
2389 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2390 INetd::FIREWALL_RULE_ALLOW);
2391 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2392 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2393
2394 // None deny in BLACKLIST
2395 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2396 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2397 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2398 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2399
2400 // None allow in BLACKLIST
2401 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2402 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2403 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2404 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2405
2406 // set firewall type whitelist twice
2407 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2408 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2409 expectFirewallWhitelistMode();
2410
2411 // None allow in WHITELIST
2412 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2413 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2414 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2415 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2416
2417 // None deny in WHITELIST
2418 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2419 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2420 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2421 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2422
2423 // reset firewall mode to default
2424 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2425 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2426 expectFirewallBlacklistMode();
2427}
2428
2429TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2430 SKIP_IF_BPF_SUPPORTED;
2431
2432 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2433 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2434 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2435
2436 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2437 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2438 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2439
2440 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2441 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2442 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2443
2444 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2445 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2446 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2447
2448 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2449 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2450 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2451
2452 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2453 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2454 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2455}
Luke Huangf7782042018-08-08 13:13:04 +08002456
2457namespace {
2458
2459std::string hwAddrToStr(unsigned char* hwaddr) {
2460 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2461 hwaddr[4], hwaddr[5]);
2462}
2463
2464int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2465 int prefixLength = 0;
2466 uint32_t m = ntohl(mask);
2467 while (m & (1 << 31)) {
2468 prefixLength++;
2469 m = m << 1;
2470 }
2471 return prefixLength;
2472}
2473
2474std::string toStdString(const String16& s) {
2475 return std::string(String8(s.string()));
2476}
2477
2478android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2479 const auto& sys = sSyscalls.get();
2480 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2481 EXPECT_TRUE(isOk(fd.status()));
2482
2483 struct ifreq ifr = {};
2484 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2485
2486 return sys.ioctl(fd.value(), flag, &ifr);
2487}
2488
2489std::string getInterfaceHwAddr(const std::string& ifName) {
2490 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2491
2492 unsigned char hwaddr[ETH_ALEN] = {};
2493 if (isOk(res.status())) {
2494 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2495 }
2496
2497 return hwAddrToStr(hwaddr);
2498}
2499
2500int getInterfaceIPv4Prefix(const std::string& ifName) {
2501 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2502
2503 int prefixLength = 0;
2504 if (isOk(res.status())) {
2505 prefixLength = ipv4NetmaskToPrefixLength(
2506 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2507 }
2508
2509 return prefixLength;
2510}
2511
2512std::string getInterfaceIPv4Addr(const std::string& ifName) {
2513 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2514
2515 struct in_addr addr = {};
2516 if (isOk(res.status())) {
2517 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2518 }
2519
2520 return std::string(inet_ntoa(addr));
2521}
2522
2523std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2524 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2525
2526 unsigned flags = 0;
2527 if (isOk(res.status())) {
2528 flags = res.value().ifr_flags;
2529 }
2530
2531 std::vector<std::string> ifFlags;
2532 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2533 : toStdString(INetd::IF_STATE_DOWN()));
2534
2535 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2536 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2537 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2538 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2539 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2540
2541 return ifFlags;
2542}
2543
2544bool compareListInterface(const std::vector<std::string>& interfaceList) {
2545 const auto& res = InterfaceController::getIfaceNames();
2546 EXPECT_TRUE(isOk(res));
2547
2548 std::vector<std::string> resIfList;
2549 resIfList.reserve(res.value().size());
2550 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2551
2552 return resIfList == interfaceList;
2553}
2554
2555int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2556 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2557 return readIntFromPath(path);
2558}
2559
2560bool getInterfaceEnableIPv6(const std::string& ifName) {
2561 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2562
2563 int disableIPv6 = readIntFromPath(path);
2564 return !disableIPv6;
2565}
2566
2567int getInterfaceMtu(const std::string& ifName) {
2568 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2569 return readIntFromPath(path);
2570}
2571
2572void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2573 EXPECT_TRUE(compareListInterface(interfaceList));
2574}
2575
2576void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2577 const InterfaceConfigurationParcel& interfaceCfg) {
2578 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2579 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2580 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2581 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2582}
2583
2584void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2585 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2586 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2587
2588 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2589 for (const auto& flag : setCfg.flags) {
2590 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2591 }
2592}
2593
2594void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2595 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2596 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2597}
2598
2599void expectInterfaceNoAddr(const std::string& ifName) {
2600 // noAddr
2601 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2602 // noPrefix
2603 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2604}
2605
2606void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2607 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2608 EXPECT_EQ(enableIPv6, enable);
2609}
2610
2611void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2612 int mtuSize = getInterfaceMtu(ifName);
2613 EXPECT_EQ(mtu, mtuSize);
2614}
2615
2616InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2617 const std::string& addr, int prefixLength,
2618 const std::vector<std::string>& flags) {
2619 InterfaceConfigurationParcel cfg;
2620 cfg.ifName = ifName;
2621 cfg.hwAddr = "";
2622 cfg.ipv4Addr = addr;
2623 cfg.prefixLength = prefixLength;
2624 cfg.flags = flags;
2625 return cfg;
2626}
2627
2628void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2629 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2630 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2631
2632 for (const auto& flag : expectedFlags) {
2633 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2634 interfaceCfg.flags.end());
2635 }
2636
2637 for (const auto& flag : unexpectedFlags) {
2638 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2639 interfaceCfg.flags.end());
2640 }
2641}
2642
2643} // namespace
2644
2645TEST_F(BinderTest, InterfaceList) {
2646 std::vector<std::string> interfaceListResult;
2647
2648 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2649 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2650 expectInterfaceList(interfaceListResult);
2651}
2652
2653TEST_F(BinderTest, InterfaceGetCfg) {
2654 InterfaceConfigurationParcel interfaceCfgResult;
2655
2656 // Add test physical network
2657 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2658 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2659
2660 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2661 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2662 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2663 expectTunFlags(interfaceCfgResult);
2664
2665 // Remove test physical network
2666 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2667}
2668
2669TEST_F(BinderTest, InterfaceSetCfg) {
2670 const std::string testAddr = "192.0.2.3";
2671 const int testPrefixLength = 24;
2672 std::vector<std::string> upFlags = {"up"};
2673 std::vector<std::string> downFlags = {"down"};
2674
2675 // Add test physical network
2676 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2677 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2678
2679 // Set tun interface down.
2680 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2681 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2682 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2683 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2684
2685 // Set tun interface up again.
2686 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2687 status = mNetd->interfaceSetCfg(interfaceCfg);
2688 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2689 status = mNetd->interfaceClearAddrs(sTun.name());
2690 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2691
2692 // Remove test physical network
2693 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2694}
2695
2696TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2697 // enable
2698 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2699 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2700 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2701
2702 // disable
2703 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2704 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2705 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2706}
2707
2708TEST_F(BinderTest, InterfaceClearAddr) {
2709 const std::string testAddr = "192.0.2.3";
2710 const int testPrefixLength = 24;
2711 std::vector<std::string> noFlags{};
2712
2713 // Add test physical network
2714 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2715 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2716
2717 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2718 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2719 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2720 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2721
2722 status = mNetd->interfaceClearAddrs(sTun.name());
2723 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2724 expectInterfaceNoAddr(sTun.name());
2725
2726 // Remove test physical network
2727 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2728}
2729
2730TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2731 // Add test physical network
2732 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2733 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2734
2735 // disable
2736 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2737 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2738 expectInterfaceEnableIPv6(sTun.name(), false);
2739
2740 // enable
2741 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2742 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2743 expectInterfaceEnableIPv6(sTun.name(), true);
2744
2745 // Remove test physical network
2746 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2747}
2748
2749TEST_F(BinderTest, InterfaceSetMtu) {
2750 const int testMtu = 1200;
2751
2752 // Add test physical network
2753 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2754 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2755
2756 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2757 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2758 expectInterfaceMtu(sTun.name(), testMtu);
2759
2760 // Remove test physical network
2761 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2762}
Luke Huang19b49c52018-10-22 12:12:05 +09002763
2764namespace {
2765
2766constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2767constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002768constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002769constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2770
Luke Huangae038f82018-11-05 11:17:31 +09002771int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002772 return listIptablesRuleByTable(binary, table, chainName).size();
2773}
2774
2775bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2776 const std::vector<std::string>& targetVec) {
2777 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2778 if (targetVec.size() != rules.size() - 2) {
2779 return false;
2780 }
2781
2782 /*
Luke Huangae038f82018-11-05 11:17:31 +09002783 * Check that the rules match. Note that this function matches substrings, not entire rules,
2784 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002785 * Skip first two lines since rules start from third line.
2786 * Chain chainName (x references)
2787 * pkts bytes target prot opt in out source destination
2788 * ...
2789 */
2790 int rIndex = 2;
2791 for (const auto& target : targetVec) {
2792 if (rules[rIndex].find(target) == std::string::npos) {
2793 return false;
2794 }
2795 rIndex++;
2796 }
2797 return true;
2798}
2799
2800void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2801 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2802 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2803 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002804 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002805 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2806 "DROP"};
2807
2808 // V4
2809 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2810 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002811 EXPECT_TRUE(
2812 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002813 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2814
Luke Huangae038f82018-11-05 11:17:31 +09002815 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002816 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2817
2818 // V6
2819 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002820 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2821 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002822
2823 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2824 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2825 extIf));
2826 }
2827}
2828
2829void expectNatDisable() {
2830 // It is the default DROP rule with tethering disable.
2831 // Chain tetherctrl_FORWARD (1 references)
2832 // pkts bytes target prot opt in out source destination
2833 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2834 std::vector<std::string> forwardV4Match = {"DROP"};
2835 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2836
2837 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002838 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2839 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002840
Luke Huangae038f82018-11-05 11:17:31 +09002841 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2842 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002843
2844 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2845}
2846
2847} // namespace
2848
2849TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002850 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2851 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2852 expectNatEnable(sTun.name(), sTun2.name());
2853
2854 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2855 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2856 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002857}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002858
2859namespace {
2860
2861using TripleInt = std::array<int, 3>;
2862
2863TripleInt readProcFileToTripleInt(const std::string& path) {
2864 std::string valueString;
2865 int min, def, max;
2866 EXPECT_TRUE(ReadFileToString(path, &valueString));
2867 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2868 return {min, def, max};
2869}
2870
2871void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2872 std::string testRmemValues =
2873 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2874 std::string testWmemValues =
2875 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2876 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2877
2878 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2879 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2880
2881 for (int i = 0; i < 3; i++) {
2882 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2883 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2884 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2885 }
2886}
2887
2888} // namespace
2889
2890TEST_F(BinderTest, TcpBufferSet) {
2891 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2892 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2893 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2894 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2895
2896 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2897 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2898}
Luke Huang528af602018-08-29 19:06:05 +08002899
Chenbo Feng48eaed32018-12-26 17:40:21 -08002900namespace {
2901
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002902void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002903 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2904 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2905 for (int32_t uid : uids) {
2906 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2907 if (exist) {
2908 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002909 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002910 } else {
2911 EXPECT_FALSE(isOk(permission));
2912 EXPECT_EQ(ENOENT, permission.status().code());
2913 }
2914 }
2915}
2916
2917} // namespace
2918
2919TEST_F(BinderTest, TestInternetPermission) {
2920 SKIP_IF_BPF_NOT_SUPPORTED;
2921
2922 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2923
2924 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002925 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002926 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002927 checkUidsInPermissionMap(appUids, true);
2928 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2929 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002930}
2931
Luke Huang528af602018-08-29 19:06:05 +08002932TEST_F(BinderTest, UnsolEvents) {
2933 auto testUnsolService = android::net::TestUnsolService::start();
2934 std::string oldTunName = sTun.name();
2935 std::string newTunName = "unsolTest";
2936 testUnsolService->tarVec.push_back(oldTunName);
2937 testUnsolService->tarVec.push_back(newTunName);
2938 auto& cv = testUnsolService->getCv();
2939 auto& cvMutex = testUnsolService->getCvMutex();
2940 binder::Status status = mNetd->registerUnsolicitedEventListener(
2941 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2942 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2943
2944 // TODO: Add test for below events
2945 // StrictCleartextDetected / InterfaceDnsServersAdded
2946 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2947
2948 {
2949 std::unique_lock lock(cvMutex);
2950
2951 // Re-init test Tun, and we expect that we will get some unsol events.
2952 // Use the test Tun device name to verify if we receive its unsol events.
2953 sTun.destroy();
2954 // Use predefined name
2955 sTun.init(newTunName);
2956
2957 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2958 }
2959
2960 // bit mask 1101101000
2961 // Test only covers below events currently
2962 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2963 InterfaceLinkStatusChanged | RouteChanged;
2964 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002965
2966 // Re-init sTun to clear predefined name
2967 sTun.destroy();
2968 sTun.init();
2969}
2970
2971TEST_F(BinderTest, NDC) {
2972 struct Command {
2973 const std::string cmdString;
2974 const std::string expectedResult;
2975 };
2976
2977 // clang-format off
2978 // Do not change the commands order
2979 const Command networkCmds[] = {
2980 {StringPrintf("ndc network create %d", TEST_NETID1),
2981 "200 0 success"},
2982 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2983 "200 0 success"},
2984 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2985 "200 0 success"},
2986 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2987 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2988 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2989 "200 0 success"},
2990 };
2991
2992 const std::vector<Command> ipfwdCmds = {
2993 {"ndc ipfwd enable " + sTun.name(),
2994 "200 0 ipfwd operation succeeded"},
2995 {"ndc ipfwd disable " + sTun.name(),
2996 "200 0 ipfwd operation succeeded"},
2997 {"ndc ipfwd add lo2 lo3",
2998 "400 0 ipfwd operation failed (No such process)"},
2999 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3000 "200 0 ipfwd operation succeeded"},
3001 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3002 "200 0 ipfwd operation succeeded"},
3003 };
3004
3005 static const struct {
3006 const char* ipVersion;
3007 const char* testDest;
3008 const char* testNextHop;
3009 const bool expectSuccess;
3010 const std::string expectedResult;
3011 } kTestData[] = {
3012 {IP_RULE_V4, "0.0.0.0/0", "", true,
3013 "200 0 success"},
3014 {IP_RULE_V4, "10.251.0.0/16", "", true,
3015 "200 0 success"},
3016 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3017 "400 0 addRoute() failed (Invalid argument)",},
3018 {IP_RULE_V6, "::/0", "", true,
3019 "200 0 success"},
3020 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3021 "200 0 success"},
3022 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3023 "400 0 addRoute() failed (Invalid argument)"},
3024 };
3025 // clang-format on
3026
3027 for (const auto& cmd : networkCmds) {
3028 const std::vector<std::string> result = runCommand(cmd.cmdString);
3029 SCOPED_TRACE(cmd.cmdString);
3030 EXPECT_EQ(result.size(), 1U);
3031 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3032 }
3033
3034 for (const auto& cmd : ipfwdCmds) {
3035 const std::vector<std::string> result = runCommand(cmd.cmdString);
3036 SCOPED_TRACE(cmd.cmdString);
3037 EXPECT_EQ(result.size(), 1U);
3038 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3039 }
3040
3041 // Add test physical network
3042 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3043 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3044
3045 for (const auto& td : kTestData) {
3046 const std::string routeAddCmd =
3047 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3048 td.testDest, td.testNextHop);
3049 const std::string routeRemoveCmd =
3050 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3051 sTun.name().c_str(), td.testDest, td.testNextHop);
3052 std::vector<std::string> result = runCommand(routeAddCmd);
3053 SCOPED_TRACE(routeAddCmd);
3054 EXPECT_EQ(result.size(), 1U);
3055 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3056 if (td.expectSuccess) {
3057 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3058 sTun.name().c_str());
3059 result = runCommand(routeRemoveCmd);
3060 EXPECT_EQ(result.size(), 1U);
3061 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3062 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3063 sTun.name().c_str());
3064 }
3065 }
3066 // Remove test physical network
3067 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003068}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003069
Luke Huang2ff8b342019-04-30 15:33:33 +08003070TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003071 sp<IBinder> binder;
3072 binder::Status status = mNetd->getOemNetd(&binder);
3073 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3074 sp<com::android::internal::net::IOemNetd> oemNetd;
3075 if (binder != nullptr) {
3076 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3077 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003078 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003079
3080 TimedOperation t("OemNetd isAlive RPC");
3081 bool isAlive = false;
3082 oemNetd->isAlive(&isAlive);
3083 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003084
3085 class TestOemUnsolListener
3086 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3087 public:
3088 android::binder::Status onRegistered() override {
3089 std::lock_guard lock(mCvMutex);
3090 mCv.notify_one();
3091 return android::binder::Status::ok();
3092 }
3093 std::condition_variable& getCv() { return mCv; }
3094 std::mutex& getCvMutex() { return mCvMutex; }
3095
3096 private:
3097 std::mutex mCvMutex;
3098 std::condition_variable mCv;
3099 };
3100
3101 // Start the Binder thread pool.
3102 android::ProcessState::self()->startThreadPool();
3103
3104 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3105
3106 auto& cv = testListener->getCv();
3107 auto& cvMutex = testListener->getCvMutex();
3108
3109 {
3110 std::unique_lock lock(cvMutex);
3111
3112 status = oemNetd->registerOemUnsolicitedEventListener(
3113 ::android::interface_cast<
3114 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3115 testListener));
3116 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3117
3118 // Wait for receiving expected events.
3119 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3120 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003121}
Luke Huangd2861982019-05-17 19:47:28 +08003122
3123void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3124 int fallthroughNetId) {
3125 // Re-init sTun* to ensure route rule exists.
3126 sTun.destroy();
3127 sTun.init();
3128 sTun2.destroy();
3129 sTun2.init();
3130
3131 // Create physical network with fallthroughNetId but not set it as default network
3132 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3133 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3134
3135 // Create VPN with vpnNetId
3136 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3137
3138 // Add uid to VPN
3139 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3140 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3141
3142 // Add default route to fallthroughNetwork
3143 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3144 // Add limited route
3145 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3146}
3147
3148namespace {
3149
3150class ScopedUidChange {
3151 public:
3152 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3153 mStoredUid = getuid();
3154 if (mInputUid == mStoredUid) return;
3155 EXPECT_TRUE(seteuid(uid) == 0);
3156 }
3157 ~ScopedUidChange() {
3158 if (mInputUid == mStoredUid) return;
3159 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3160 }
3161
3162 private:
3163 uid_t mInputUid;
3164 uid_t mStoredUid;
3165};
3166
3167constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3168
3169void clearQueue(int tunFd) {
3170 char buf[4096];
3171 int ret;
3172 do {
3173 ret = read(tunFd, buf, sizeof(buf));
3174 } while (ret > 0);
3175}
3176
3177void checkDataReceived(int udpSocket, int tunFd) {
3178 char buf[4096] = {};
3179 // Clear tunFd's queue before write something because there might be some
3180 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3181 clearQueue(tunFd);
3182 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3183 // TODO: extract header and verify data
3184 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3185}
3186
3187bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3188 ScopedUidChange scopedUidChange(uid);
3189 android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3190 if (testSocket < 0) return false;
3191
3192 const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
3193 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3194 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3195 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3196 if (res == -1) return false;
3197
3198 char addr[INET6_ADDRSTRLEN];
3199 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3200 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3201 checkDataReceived(testSocket, tunFd);
3202 return true;
3203}
3204
3205void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3206 std::string vpnFallthroughRule =
3207 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3208 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3209 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3210 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3211 }
3212}
3213
3214void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3215 const TunInterface& fallthroughNetwork,
3216 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3217 int fallthroughNetId = TEST_NETID1) {
3218 // Set default network to NETID_UNSET
3219 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3220
3221 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3222 in6_addr insideVpnAddr = {
3223 {// 2001:db8:cafe::1
3224 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3225 // outsideVpnAddr will hit the route in the fallthrough network route table
3226 // because we added default route in createVpnNetworkWithUid
3227 in6_addr outsideVpnAddr = {
3228 {// 2607:f0d0:1002::4
3229 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3230
3231 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3232 int vpnFd = vpnNetwork.getFdForTesting();
3233 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3234 // default network.
3235 Fwmark fwmark;
3236 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3237 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3238
3239 // Set default network
3240 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3241
3242 // Connections go on the default network because UID 0 is not subject to the VPN.
3243 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3244 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3245 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3246 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3247
3248 // Check if fallthrough rule exists
3249 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3250
3251 // Expect fallthrough to default network
3252 // The fwmark differs depending on whether the VPN is bypassable or not.
3253 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3254 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3255
3256 // Expect connect success, packet will be sent to vpnFd.
3257 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3258 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3259
3260 // Explicitly select vpn network
3261 setNetworkForProcess(vpnNetId);
3262
3263 // Expect fallthrough to default network
3264 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3265 // Expect the mark contains all the bit because we've selected network.
3266 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3267
3268 // Expect connect success, packet will be sent to vpnFd.
3269 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3270 // Expect the mark contains all the bit because we've selected network.
3271 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3272
3273 // Explicitly select fallthrough network
3274 setNetworkForProcess(fallthroughNetId);
3275
3276 // The mark is set to fallthrough network because we've selected it.
3277 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3278 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3279
3280 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3281 if (bypassable) {
3282 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3283 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3284 } else {
3285 // If not, no permission to bypass vpn.
3286 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3287 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3288 }
3289}
3290
3291} // namespace
3292
3293TEST_F(BinderTest, SecureVPNFallthrough) {
3294 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3295 // Get current default network NetId
3296 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3297 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3298}
3299
3300TEST_F(BinderTest, BypassableVPNFallthrough) {
3301 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3302 // Get current default network NetId
3303 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3304 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003305}