blob: 2cd17fb293182aa701ce6deacb979f7349172ab8 [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"
Luke Huang25599322019-06-14 00:34:05 +080064#include "netdutils/InternetAddresses.h"
Mike Yue7e332f2019-03-13 17:15:48 +080065#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070066#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080067#include "netid_client.h" // NETID_UNSET
Mike Yu5ae61542018-10-19 22:11:43 +080068#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090069
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090070#define IP_PATH "/system/bin/ip"
71#define IP6TABLES_PATH "/system/bin/ip6tables"
72#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090073#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080074#define RAW_TABLE "raw"
75#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080076#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090077#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090078
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090079namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090080
81using android::IBinder;
82using android::IServiceManager;
83using android::sp;
84using android::String16;
85using android::String8;
86using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080087using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090088using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090089using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080090using android::base::Trim;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090091using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080092using android::net::InterfaceConfigurationParcel;
93using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080094using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090095using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090096using android::net::UidRangeParcel;
Luke Huang25599322019-06-14 00:34:05 +080097using android::netdutils::ScopedAddrinfo;
Luke Huangf7782042018-08-08 13:13:04 +080098using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +080099using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +0100100
Luke Huang33a92792019-05-28 16:59:25 +0800101#define SKIP_IF_CUTTLEFISH \
102 do { \
103 if (isCuttleFish()) return; \
104 } while (0)
105
Robin Leeb8087362016-03-30 18:43:08 +0100106static const char* IP_RULE_V4 = "-4";
107static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900108static const int TEST_NETID1 = 65501;
109static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800110
111// Use maximum reserved appId for applications to avoid conflict with existing
112// uids.
113static const int TEST_UID1 = 99999;
114static const int TEST_UID2 = 99998;
115
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900116constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900117
Benedict Wongb2daefb2017-12-06 22:05:46 -0800118static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
119static const std::string ESP_ALLOW_RULE("esp");
120
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900122 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900123 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900124 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900125 sp<IBinder> binder = sm->getService(String16("netd"));
126 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900127 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900128 }
129 }
130
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900131 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900132 ASSERT_NE(nullptr, mNetd.get());
133 }
134
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900135 void TearDown() override {
136 mNetd->networkDestroy(TEST_NETID1);
137 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800138 setNetworkForProcess(NETID_UNSET);
139 // Restore default network
140 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900141 }
142
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900143 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700144
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900145 // Static because setting up the tun interface takes about 40ms.
146 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900147 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900148 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900149 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900150 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900151 }
152
153 static void TearDownTestCase() {
154 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900155 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900156 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900157 }
158
159 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900160
Luke Huangd2861982019-05-17 19:47:28 +0800161 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
162 int fallthroughNetId = TEST_NETID1);
163
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900164 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800165 // Use -1 to represent that default network was not modified because
166 // real netId must be an unsigned value.
167 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900168 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900169 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900170 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900171};
172
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900173TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900174TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900175
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900176class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900177 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700178 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900180 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900181 }
182
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900183 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900184 std::string mName;
185};
186
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900187TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900188 TimedOperation t("isAlive RPC");
189 bool isAlive = false;
190 mNetd->isAlive(&isAlive);
191 ASSERT_TRUE(isAlive);
192}
193
194static int randomUid() {
195 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
196}
197
Robin Leeb8087362016-03-30 18:43:08 +0100198static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900199 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900200 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
201 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900202 perror("popen");
203 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900204 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900205
206 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100207 size_t bufsize = 0;
208 ssize_t linelen = 0;
209 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900210 lines.push_back(std::string(line, linelen));
211 free(line);
212 line = nullptr;
213 }
214
215 pclose(f);
216 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900217}
218
Robin Leeb8087362016-03-30 18:43:08 +0100219static std::vector<std::string> listIpRules(const char *ipVersion) {
220 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
221 return runCommand(command);
222}
223
224static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900225 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100226 return runCommand(command);
227}
228
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900229static int iptablesRuleLineLength(const char *binary, const char *chainName) {
230 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900231}
232
Benedict Wongb2daefb2017-12-06 22:05:46 -0800233static bool iptablesRuleExists(const char *binary,
234 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900235 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800236 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900237 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800238 if(rule.find(expectedRule) != std::string::npos) {
239 return true;
240 }
241 }
242 return false;
243}
244
245static bool iptablesNoSocketAllowRuleExists(const char *chainName){
246 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
247 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
248}
249
250static bool iptablesEspAllowRuleExists(const char *chainName){
251 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
252 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
253}
254
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900255TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700256 SKIP_IF_BPF_SUPPORTED;
257
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900258 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
259 const int kNumUids = 500;
260 std::vector<int32_t> noUids(0);
261 std::vector<int32_t> uids(kNumUids);
262 for (int i = 0; i < kNumUids; i++) {
263 uids[i] = randomUid();
264 }
265
266 bool ret;
267 {
268 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900269 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900270 }
271 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800272 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
273 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
274 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
275 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900276 {
277 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900278 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900279 }
280 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900281 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
282 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900283
284 {
285 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900286 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900287 }
288 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900289 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
290 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800291 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
292 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900293
294 {
295 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900296 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900297 }
298 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900299 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
300 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900301
302 // Check that the call fails if iptables returns an error.
303 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900304 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900305 EXPECT_EQ(false, ret);
306}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900307
Benedict Wong319f17e2018-05-15 17:06:44 -0700308TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700309 const struct TestData {
310 const std::string family;
311 const std::string deviceName;
312 const std::string localAddress;
313 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800314 int32_t iKey;
315 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700316 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800317 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700318 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
319 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
320 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800321 };
322
Sehee Park8659b8d2018-11-16 10:53:16 +0900323 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700324 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800325
326 binder::Status status;
327
Benedict Wong319f17e2018-05-15 17:06:44 -0700328 // Create Tunnel Interface.
329 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700330 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800331 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
332
Benedict Wonga450e722018-05-07 10:29:02 -0700333 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900334 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700335
Benedict Wong319f17e2018-05-15 17:06:44 -0700336 // Update Tunnel Interface.
337 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700338 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800339 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
340
Benedict Wong319f17e2018-05-15 17:06:44 -0700341 // Remove Tunnel Interface.
342 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800343 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700344
345 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900346 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800347 }
348}
349
Benedict Wong1cb73df2018-12-03 00:54:14 -0800350TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
351 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
352 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
353
354 int sockOptVal = UDP_ENCAP_ESPINUDP;
355 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
356
357 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
358 EXPECT_TRUE(res.isOk());
359
360 struct stat info;
361 EXPECT_EQ(0, fstat(sockFd.get(), &info));
362 EXPECT_EQ(1001, (int) info.st_uid);
363}
364
Nathan Harold2deff322018-05-10 14:03:48 -0700365// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
366// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
367#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900368
369using android::net::XfrmController;
370
Benedict Wonga04ffa72018-05-09 21:42:42 -0700371static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
372 static_cast<int>(android::net::XfrmDirection::OUT)};
373static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
374
Nathan Harold21299f72018-03-16 20:13:03 -0700375#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
376 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900377bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900378 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700379 SCOPED_TRACE(status);
380 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
381
382 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700383 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700384 SCOPED_TRACE(status);
385 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
386
387 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700388 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
389 0xD00D, 0xE00D, false)
390 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700391}
392
Benedict Wonga04ffa72018-05-09 21:42:42 -0700393TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900394 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700395
396 // Repeat to ensure cleanup and recreation works correctly
397 for (int i = 0; i < 2; i++) {
398 for (int direction : XFRM_DIRECTIONS) {
399 for (int addrFamily : ADDRESS_FAMILIES) {
400 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700401 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700402 EXPECT_TRUE(status.isOk())
403 << " family: " << addrFamily << " direction: " << direction;
404 }
405 }
406
407 // Cleanup
408 for (int direction : XFRM_DIRECTIONS) {
409 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700410 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700411 EXPECT_TRUE(status.isOk());
412 }
413 }
414 }
415}
416
417TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
418 binder::Status status;
419
420 // Repeat to ensure cleanup and recreation works correctly
421 for (int i = 0; i < 2; i++) {
422 for (int direction : XFRM_DIRECTIONS) {
423 for (int addrFamily : ADDRESS_FAMILIES) {
424 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700425 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700426 EXPECT_TRUE(status.isOk())
427 << " family: " << addrFamily << " direction: " << direction;
428 }
429 }
430
431 // Cleanup
432 for (int direction : XFRM_DIRECTIONS) {
433 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700434 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700435 EXPECT_TRUE(status.isOk());
436 }
437 }
438 }
439}
440
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900441TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900442 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700443 status = XfrmController::Init();
444 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700445
446 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
447 // feature.
448 if (status.code() == EOPNOTSUPP) return;
449
Nathan Harold21299f72018-03-16 20:13:03 -0700450 ASSERT_TRUE(status.ok());
451
452 int32_t spi = 0;
453
454 ASSERT_TRUE(allocateIpSecResources(true, &spi));
455 ASSERT_TRUE(allocateIpSecResources(false, &spi));
456
457 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700458 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700459 ASSERT_TRUE(allocateIpSecResources(true, &spi));
460
461 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700462 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700463 SCOPED_TRACE(status);
464 ASSERT_TRUE(status.ok());
465
Benedict Wonga450e722018-05-07 10:29:02 -0700466 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700467 SCOPED_TRACE(status);
468 ASSERT_TRUE(status.ok());
469
470 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700471 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700472}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900473
474#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700475
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900476static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900477 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900478
479 // Output looks like this:
480 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900481 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900482 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900483 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900484 //
485 // or:
486 //
487 // Chain bw_data_saver (1 references)
488 // target prot opt source destination
489 // ... possibly connectivity critical packet rules here ...
490 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900491
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900492 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900493
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900494 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
495 // Data saver disabled.
496 return 0;
497 }
498
499 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
500
501 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
502 // Data saver enabled.
503 return 1;
504 }
505
506 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900507}
508
509bool enableDataSaver(sp<INetd>& netd, bool enable) {
510 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
511 bool ret;
512 netd->bandwidthEnableDataSaver(enable, &ret);
513 return ret;
514}
515
516int getDataSaverState() {
517 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
518 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
519 EXPECT_EQ(enabled4, enabled6);
520 EXPECT_NE(-1, enabled4);
521 EXPECT_NE(-1, enabled6);
522 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
523 return -1;
524 }
525 return enabled6;
526}
527
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900528TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900529 const int wasEnabled = getDataSaverState();
530 ASSERT_NE(-1, wasEnabled);
531
532 if (wasEnabled) {
533 ASSERT_TRUE(enableDataSaver(mNetd, false));
534 EXPECT_EQ(0, getDataSaverState());
535 }
536
537 ASSERT_TRUE(enableDataSaver(mNetd, false));
538 EXPECT_EQ(0, getDataSaverState());
539
540 ASSERT_TRUE(enableDataSaver(mNetd, true));
541 EXPECT_EQ(1, getDataSaverState());
542
543 ASSERT_TRUE(enableDataSaver(mNetd, true));
544 EXPECT_EQ(1, getDataSaverState());
545
546 if (!wasEnabled) {
547 ASSERT_TRUE(enableDataSaver(mNetd, false));
548 EXPECT_EQ(0, getDataSaverState());
549 }
550}
Robin Leeb8087362016-03-30 18:43:08 +0100551
Luke Huang94658ac2018-10-18 19:35:12 +0900552static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
553 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100554 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100555 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100556 std::vector<std::string> rules = listIpRules(ipVersion);
557
558 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900559 std::string suffix =
560 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900561 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800562 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100563 return true;
564 }
565 }
566 return false;
567}
568
Luke Huang94658ac2018-10-18 19:35:12 +0900569static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
570 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100571 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
572 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
573 EXPECT_EQ(existsIp4, existsIp6);
574 return existsIp4;
575}
576
Luke Huang94658ac2018-10-18 19:35:12 +0900577namespace {
578
579UidRangeParcel makeUidRangeParcel(int start, int stop) {
580 UidRangeParcel res;
581 res.start = start;
582 res.stop = stop;
583
584 return res;
585}
586
587} // namespace
588
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900589TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800590 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
591 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
592 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900593 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
594 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900595
596 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
597 EXPECT_EQ(EBUSY,
598 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
599
600 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
601 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
602 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800603 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900604}
605
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900606TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900607 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
608
cken67cd14c2018-12-05 17:26:59 +0900609 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
610 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900611 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
612
Luke Huang94658ac2018-10-18 19:35:12 +0900613 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
614 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
615 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900616 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
617
618 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
619
620 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
621 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
622 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
623 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
624
625 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
626 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
627 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
628 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
629
630 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
631}
632
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900633TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100634 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100635
Luke Huang94658ac2018-10-18 19:35:12 +0900636 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
637 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800638 // Make sure no rules existed before calling commands.
639 for (auto const& range : uidRanges) {
640 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
641 }
Robin Leeb8087362016-03-30 18:43:08 +0100642 // Create two valid rules.
643 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100644 for (auto const& range : uidRanges) {
645 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
646 }
647
648 // Remove the rules.
649 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100650 for (auto const& range : uidRanges) {
651 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
652 }
653
654 // Fail to remove the rules a second time after they are already deleted.
655 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
656 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
657 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100658}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900659
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900660// Create a socket pair that isLoopbackSocket won't think is local.
661void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900662 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900663 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900664 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
665
666 socklen_t addrlen = sizeof(server6);
667 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
668 ASSERT_EQ(0, listen(*serverSocket, 10));
669
Bernie Innocentif6918262018-06-11 17:37:35 +0900670 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900671 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900672 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900673 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
674 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
675
Bernie Innocentif6918262018-06-11 17:37:35 +0900676 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900677 ASSERT_NE(-1, *acceptedSocket);
678
679 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
680}
681
682void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
683 char buf[4096];
684 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
685 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
686 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
687}
688
689void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
690 // Check that the client socket was closed with ECONNABORTED.
691 int ret = write(clientSocket, "foo", sizeof("foo"));
692 int err = errno;
693 EXPECT_EQ(-1, ret);
694 EXPECT_EQ(ECONNABORTED, err);
695
696 // Check that it sent a RST to the server.
697 ret = write(acceptedSocket, "foo", sizeof("foo"));
698 err = errno;
699 EXPECT_EQ(-1, ret);
700 EXPECT_EQ(ECONNRESET, err);
701}
702
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900703TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900704 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900705 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900706
707 // Pick a random UID in the system UID range.
708 constexpr int baseUid = AID_APP - 2000;
709 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
710 int uid = baseUid + 500 + arc4random_uniform(1000);
711 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
712
713 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900714 std::vector<UidRangeParcel> uidRanges = {
715 makeUidRangeParcel(baseUid + 42, baseUid + 449),
716 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
717 makeUidRangeParcel(baseUid + 498, uid - 1),
718 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900719 };
720 // A skip list that doesn't contain UID.
721 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
722
723 // Close sockets. Our test socket should be intact.
724 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
725 checkSocketpairOpen(clientSocket, acceptedSocket);
726
727 // UID ranges that do contain uid.
728 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900729 makeUidRangeParcel(baseUid + 42, baseUid + 449),
730 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
731 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900732 };
733 // Add uid to the skip list.
734 skipUids.push_back(uid);
735
736 // Close sockets. Our test socket should still be intact because it's in the skip list.
737 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
738 checkSocketpairOpen(clientSocket, acceptedSocket);
739
740 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
741 skipUids.resize(skipUids.size() - 1);
742 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
743 checkSocketpairClosed(clientSocket, acceptedSocket);
744
745 close(clientSocket);
746 close(serverSocket);
747 close(acceptedSocket);
748}
Erik Klinecc4f2732016-08-03 11:24:27 +0900749
750namespace {
751
752int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
753 if (buf == nullptr) return -1;
754
755 int prefixLength = 0;
756 bool endOfContiguousBits = false;
757 for (unsigned int i = 0; i < buflen; i++) {
758 const uint8_t value = buf[i];
759
760 // Bad bit sequence: check for a contiguous set of bits from the high
761 // end by verifying that the inverted value + 1 is a power of 2
762 // (power of 2 iff. (v & (v - 1)) == 0).
763 const uint8_t inverse = ~value + 1;
764 if ((inverse & (inverse - 1)) != 0) return -1;
765
766 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
767
768 // Bogus netmask.
769 if (endOfContiguousBits && value != 0) return -1;
770
771 if (value != 0xff) endOfContiguousBits = true;
772 }
773
774 return prefixLength;
775}
776
777template<typename T>
778int netmaskToPrefixLength(const T *p) {
779 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
780}
781
782
783static bool interfaceHasAddress(
784 const std::string &ifname, const char *addrString, int prefixLength) {
785 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900786
787 const struct addrinfo hints = {
788 .ai_flags = AI_NUMERICHOST,
789 .ai_family = AF_UNSPEC,
790 .ai_socktype = SOCK_DGRAM,
791 };
792 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
793 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
794 return false;
795 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900796 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900797
798 struct ifaddrs *ifaddrsList = nullptr;
799 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
800
801 if (getifaddrs(&ifaddrsList) != 0) {
802 return false;
803 }
804
805 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
806 if (std::string(addr->ifa_name) != ifname ||
807 addr->ifa_addr == nullptr ||
808 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
809 continue;
810 }
811
812 switch (addr->ifa_addr->sa_family) {
813 case AF_INET: {
814 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
815 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
816 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
817 continue;
818 }
819
820 if (prefixLength < 0) return true; // not checking prefix lengths
821
822 if (addr->ifa_netmask == nullptr) return false;
823 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
824 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
825 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
826 }
827 case AF_INET6: {
828 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
829 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
830 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
831 continue;
832 }
833
834 if (prefixLength < 0) return true; // not checking prefix lengths
835
836 if (addr->ifa_netmask == nullptr) return false;
837 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
838 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
839 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
840 }
841 default:
842 // Cannot happen because we have already screened for matching
843 // address families at the top of each iteration.
844 continue;
845 }
846 }
847
848 return false;
849}
850
851} // namespace
852
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900853TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900854 static const struct TestData {
855 const char *addrString;
856 const int prefixLength;
857 const bool expectSuccess;
858 } kTestData[] = {
859 { "192.0.2.1", 24, true },
860 { "192.0.2.2", 25, true },
861 { "192.0.2.3", 32, true },
862 { "192.0.2.4", 33, false },
863 { "192.not.an.ip", 24, false },
864 { "2001:db8::1", 64, true },
865 { "2001:db8::2", 65, true },
866 { "2001:db8::3", 128, true },
867 { "2001:db8::4", 129, false },
868 { "foo:bar::bad", 64, false },
869 };
870
Sehee Park8659b8d2018-11-16 10:53:16 +0900871 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900872 const auto &td = kTestData[i];
873
874 // [1.a] Add the address.
875 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900876 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900877 if (td.expectSuccess) {
878 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
879 } else {
880 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
881 ASSERT_NE(0, status.serviceSpecificErrorCode());
882 }
883
884 // [1.b] Verify the addition meets the expectation.
885 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900886 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900887 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900888 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900889 }
890
891 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900892 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900893 if (td.expectSuccess) {
894 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
895 } else {
896 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
897 ASSERT_NE(0, status.serviceSpecificErrorCode());
898 }
899
900 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900901 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900902 }
903}
Erik Kline55b06f82016-07-04 09:57:18 +0900904
Erik Kline38e51f12018-09-06 20:14:44 +0900905TEST_F(BinderTest, GetProcSysNet) {
906 const char LOOPBACK[] = "lo";
907 static const struct {
908 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900909 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900910 const char* ifname;
911 const char* parameter;
912 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900913 const int expectedReturnCode;
914 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900915 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
916 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
917 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
918 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
919 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
920 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
921 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900922 };
923
Sehee Park8659b8d2018-11-16 10:53:16 +0900924 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900925 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900926
Erik Kline38e51f12018-09-06 20:14:44 +0900927 std::string value;
928 const binder::Status status =
929 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
930
931 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900932 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900933 EXPECT_EQ(0, status.exceptionCode());
934 EXPECT_EQ(0, status.serviceSpecificErrorCode());
935 EXPECT_EQ(td.expectedValue, value);
936 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900937 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900938 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
939 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
940 }
941 }
942}
943
944TEST_F(BinderTest, SetProcSysNet) {
945 static const struct {
946 const int ipversion;
947 const int which;
948 const char* ifname;
949 const char* parameter;
950 const char* value;
951 const int expectedReturnCode;
952 } kTestData[] = {
953 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
954 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
955 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
956 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
957 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
958 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
959 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
960 };
961
Sehee Park8659b8d2018-11-16 10:53:16 +0900962 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900963 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900964 const binder::Status status =
965 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900966
967 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900968 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900969 EXPECT_EQ(0, status.exceptionCode());
970 EXPECT_EQ(0, status.serviceSpecificErrorCode());
971 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900972 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900973 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
974 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
975 }
976 }
977}
Ben Schwartze7601812017-04-28 16:38:29 -0400978
Erik Kline38e51f12018-09-06 20:14:44 +0900979TEST_F(BinderTest, GetSetProcSysNet) {
980 const int ipversion = INetd::IPV6;
981 const int category = INetd::NEIGH;
982 const std::string& tun = sTun.name();
983 const std::string parameter("ucast_solicit");
984
985 std::string value{};
986 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700987 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900988 const int ival = std::stoi(value);
989 EXPECT_GT(ival, 0);
990 // Try doubling the parameter value (always best!).
991 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
992 .isOk());
993 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
994 EXPECT_EQ(2 * ival, std::stoi(value));
995 // Try resetting the parameter.
996 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
997 .isOk());
998 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
999 EXPECT_EQ(ival, std::stoi(value));
1000}
1001
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001002namespace {
1003
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001004void expectNoTestCounterRules() {
1005 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1006 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1007 std::string allRules = Join(runCommand(command), "\n");
1008 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1009 }
1010}
1011
Bernie Innocentif6918262018-06-11 17:37:35 +09001012void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1013 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001014 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1015 path, if1.c_str(), if2.c_str(), pkt, byte));
1016}
1017
Bernie Innocentif6918262018-06-11 17:37:35 +09001018void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001019 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1020 path, if1.c_str(), if2.c_str()));
1021 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1022 path, if2.c_str(), if1.c_str()));
1023}
1024
Luke Huangcaebcbb2018-09-27 20:37:14 +08001025std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1026 const std::string& iface) {
1027 for (auto& stats : statsVec) {
1028 if (stats.iface == iface) {
1029 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1030 }
1031 }
1032 return {};
1033}
1034
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001035} // namespace
1036
1037TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001038 expectNoTestCounterRules();
1039
1040 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1041 // disabling tethering. We don't check the return value because these commands will fail if
1042 // tethering is already enabled.
1043 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1044 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1045
1046 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1047 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1048 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001049
1050 // Ensure we won't use the same interface name, otherwise the test will fail.
1051 u_int32_t rNumber = arc4random_uniform(10000);
1052 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1053 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001054
1055 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1056 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1057 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1058 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1059 // RX is from external to internal, and TX is from internal to external.
1060 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1061 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1062
1063 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1064 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1065
1066 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1067 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1068
1069 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1070 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1071 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1072
Luke Huangcaebcbb2018-09-27 20:37:14 +08001073 std::vector<TetherStatsParcel> statsVec;
1074 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001075 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1076
Luke Huangcaebcbb2018-09-27 20:37:14 +08001077 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001078
Luke Huangcaebcbb2018-09-27 20:37:14 +08001079 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001080
1081 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1082 delTetherCounterValues(path, intIface1, extIface1);
1083 delTetherCounterValues(path, intIface2, extIface2);
1084 if (path == IP6TABLES_PATH) {
1085 delTetherCounterValues(path, intIface3, extIface2);
1086 }
1087 }
1088
1089 expectNoTestCounterRules();
1090}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001091
Luke Huang0051a622018-07-23 20:30:16 +08001092namespace {
1093
Luke Huanga5211072018-08-01 23:36:29 +08001094constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1095constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001096
1097static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1098 const char* chainName) {
1099 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1100 return runCommand(command);
1101}
1102
Luke Huang19b49c52018-10-22 12:12:05 +09001103// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001104bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001105 const std::string& expectedInterface,
1106 const std::string& expectedRule, const char* table) {
1107 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1108 for (const auto& rule : rules) {
1109 if (rule.find(expectedInterface) != std::string::npos) {
1110 if (rule.find(expectedRule) != std::string::npos) {
1111 return true;
1112 }
1113 }
1114 }
1115 return false;
1116}
1117
1118void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001119 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001120 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001121 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001122 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001123 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1124 IdletimerRule, RAW_TABLE));
1125 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001126 ifname, IdletimerRule, MANGLE_TABLE));
1127 }
1128}
1129
1130void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001131 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001132 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001133 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001134 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001135 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1136 IdletimerRule, RAW_TABLE));
1137 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001138 ifname, IdletimerRule, MANGLE_TABLE));
1139 }
1140}
1141
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001142} // namespace
1143
1144TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001145 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1146 // rule in the table. Because we only check the result after calling remove function. We might
1147 // check the actual rule which is removed by our function (maybe compare the results between
1148 // calling function before and after)
1149 binder::Status status;
1150 const struct TestData {
1151 const std::string ifname;
1152 int32_t timeout;
1153 const std::string classLabel;
1154 } idleTestData[] = {
1155 {"wlan0", 1234, "happyday"},
1156 {"rmnet_data0", 4567, "friday"},
1157 };
1158 for (const auto& td : idleTestData) {
1159 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1160 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1161 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1162
1163 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1164 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1165 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1166 }
1167}
1168
Luke Huanga67dd562018-07-17 19:58:25 +08001169namespace {
1170
1171constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1172constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1173
1174void expectStrictSetUidAccept(const int uid) {
1175 std::string uidRule = StringPrintf("owner UID match %u", uid);
1176 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1177 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001178 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1179 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001180 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1181 }
1182}
1183
1184void expectStrictSetUidLog(const int uid) {
1185 static const char logRule[] = "st_penalty_log all";
1186 std::string uidRule = StringPrintf("owner UID match %u", uid);
1187 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1188 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001189 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1190 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001191 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1192 }
1193}
1194
1195void expectStrictSetUidReject(const int uid) {
1196 static const char rejectRule[] = "st_penalty_reject all";
1197 std::string uidRule = StringPrintf("owner UID match %u", uid);
1198 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1199 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001200 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1201 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001202 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1203 }
1204}
1205
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001206} // namespace
1207
1208TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001209 binder::Status status;
1210 int32_t uid = randomUid();
1211
1212 // setUidCleartextPenalty Policy:Log with randomUid
1213 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1214 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1215 expectStrictSetUidLog(uid);
1216
1217 // setUidCleartextPenalty Policy:Accept with randomUid
1218 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1219 expectStrictSetUidAccept(uid);
1220
1221 // setUidCleartextPenalty Policy:Reject with randomUid
1222 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1223 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1224 expectStrictSetUidReject(uid);
1225
1226 // setUidCleartextPenalty Policy:Accept with randomUid
1227 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1228 expectStrictSetUidAccept(uid);
1229
1230 // test wrong policy
1231 int32_t wrongPolicy = -123;
1232 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1233 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1234}
1235
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001236namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001237
Luke Huangd1675922019-03-11 17:29:27 +08001238std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001239 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001240 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001241 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1242 // ...
1243 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1244
Luke Huangd1675922019-03-11 17:29:27 +08001245 // (dnsmasq)
1246 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1247
1248 if (maxTries == 0) return {};
1249
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001250 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001251 std::vector<std::string> result;
1252 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001253 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001254 if (result.size() || ++run > maxTries) {
1255 break;
1256 }
1257
Luke Huang728cf4c2019-03-14 19:43:02 +08001258 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001259 }
1260 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001261}
1262
Luke Huangd1675922019-03-11 17:29:27 +08001263void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001264 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001265}
1266
Luke Huang728cf4c2019-03-14 19:43:02 +08001267void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001268 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001269}
1270
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001271} // namespace
1272
1273TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001274 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001275
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001276 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1277 std::string clatAddress;
1278 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001279
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001280 // Can't start clatd on an interface that's not part of any network...
1281 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1282 EXPECT_FALSE(status.isOk());
1283 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1284
1285 // ... so create a test physical network and add our tun to it.
1286 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1287 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1288
1289 // Prefix must be 96 bits long.
1290 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1291 EXPECT_FALSE(status.isOk());
1292 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1293
1294 // Can't start clatd unless there's a default route...
1295 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1296 EXPECT_FALSE(status.isOk());
1297 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1298
1299 // so add a default route.
1300 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1301
1302 // Can't start clatd unless there's a global address...
1303 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1304 EXPECT_FALSE(status.isOk());
1305 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1306
1307 // ... so add a global address.
1308 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001309 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001310
1311 // Now expect clatd to start successfully.
1312 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1313 EXPECT_TRUE(status.isOk());
1314 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1315
1316 // Starting it again returns EBUSY.
1317 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1318 EXPECT_FALSE(status.isOk());
1319 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1320
Luke Huangd1675922019-03-11 17:29:27 +08001321 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001322
1323 // Expect clatd to stop successfully.
1324 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001325 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001326 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001327
1328 // Stopping a clatd that doesn't exist returns ENODEV.
1329 status = mNetd->clatdStop(sTun.name());
1330 EXPECT_FALSE(status.isOk());
1331 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001332 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001333
1334 // Clean up.
1335 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1336 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1337 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001338}
Luke Huang457d4702018-08-16 15:39:15 +08001339
1340namespace {
1341
1342bool getIpfwdV4Enable() {
1343 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1344 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1345 EXPECT_TRUE(!result.empty());
1346 int v4Enable = std::stoi(result[0]);
1347 return v4Enable;
1348}
1349
1350bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001351 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001352 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1353 EXPECT_TRUE(!result.empty());
1354 int v6Enable = std::stoi(result[0]);
1355 return v6Enable;
1356}
1357
1358void expectIpfwdEnable(bool enable) {
1359 int enableIPv4 = getIpfwdV4Enable();
1360 int enableIPv6 = getIpfwdV6Enable();
1361 EXPECT_EQ(enable, enableIPv4);
1362 EXPECT_EQ(enable, enableIPv6);
1363}
1364
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001365bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001366 std::vector<std::string> rules = listIpRules(ipVersion);
1367 for (const auto& rule : rules) {
1368 if (rule.find(ipfwdRule) != std::string::npos) {
1369 return true;
1370 }
1371 }
1372 return false;
1373}
1374
1375void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1376 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1377
1378 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1379 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1380 }
1381}
1382
1383void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1384 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1385
1386 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1387 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1388 }
1389}
1390
1391} // namespace
1392
1393TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001394 // Get ipfwd requester list from Netd
1395 std::vector<std::string> requesterList;
1396 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001397 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001398
1399 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001400 if (requesterList.size() == 0) {
1401 // No requester in Netd, ipfwd should be disabled
1402 // So add one test requester and verify
1403 status = mNetd->ipfwdEnableForwarding("TestRequester");
1404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001405
Luke Huang728cf4c2019-03-14 19:43:02 +08001406 expectIpfwdEnable(true);
1407 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1408 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1409 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001410
Luke Huang728cf4c2019-03-14 19:43:02 +08001411 // Remove test one, verify again
1412 status = mNetd->ipfwdDisableForwarding("TestRequester");
1413 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1414
1415 expectIpfwdEnable(false);
1416 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1417 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1418 EXPECT_FALSE(ipfwdEnabled);
1419 } else {
1420 // Disable all requesters
1421 for (const auto& requester : requesterList) {
1422 status = mNetd->ipfwdDisableForwarding(requester);
1423 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1424 }
1425
1426 // After disable all requester, ipfwd should be disabled
1427 expectIpfwdEnable(false);
1428 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1429 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1430 EXPECT_FALSE(ipfwdEnabled);
1431
1432 // Enable them back
1433 for (const auto& requester : requesterList) {
1434 status = mNetd->ipfwdEnableForwarding(requester);
1435 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1436 }
1437
1438 // ipfwd should be enabled
1439 expectIpfwdEnable(true);
1440 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1441 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1442 EXPECT_TRUE(ipfwdEnabled);
1443 }
Luke Huang457d4702018-08-16 15:39:15 +08001444}
1445
1446TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001447 // Add test physical network
1448 EXPECT_TRUE(
1449 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1450 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1451 EXPECT_TRUE(
1452 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1453 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001454
Luke Huangd1827b82019-02-15 15:03:27 +08001455 binder::Status status =
1456 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1457 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1458 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001459
Luke Huangd1827b82019-02-15 15:03:27 +08001460 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1461 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1462 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001463}
Luke Huang531f5d32018-08-03 15:19:05 +08001464
1465namespace {
1466
1467constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1468constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1469constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1470constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1471constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001472constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001473
Luke Huang19b49c52018-10-22 12:12:05 +09001474// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1475// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001476bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1477 const char* chainName, const std::string& expectedTargetA,
1478 const std::string& expectedTargetB) {
1479 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1480 int matchCount = 0;
1481
1482 for (const auto& rule : rules) {
1483 if (rule.find(expectedTargetA) != std::string::npos) {
1484 if (rule.find(expectedTargetB) != std::string::npos) {
1485 matchCount++;
1486 }
1487 }
1488 }
1489 return matchCount == expectedCount;
1490}
1491
1492void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1493 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1494 std::string result = "";
1495
1496 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001497 // Quota value might be decreased while matching packets
1498 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001499}
1500
1501void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1502 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1503 std::string quotaRule = StringPrintf("quota %s", ifname);
1504
1505 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1506 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1507 BANDWIDTH_COSTLY_IF));
1508 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1509 BANDWIDTH_COSTLY_IF));
1510 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1511 BANDWIDTH_COSTLY_IF));
1512 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1513 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1514 }
1515 expectXtQuotaValueEqual(ifname, quotaBytes);
1516}
1517
1518void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1519 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1520 std::string quotaRule = StringPrintf("quota %s", ifname);
1521
1522 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1523 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1524 BANDWIDTH_COSTLY_IF));
1525 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1526 BANDWIDTH_COSTLY_IF));
1527 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1528 BANDWIDTH_COSTLY_IF));
1529 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1530 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1531 }
1532}
1533
1534void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1535 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1536 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1537 std::string alertName = StringPrintf("%sAlert", ifname);
1538
1539 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1540 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1541 }
1542 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1543}
1544
1545void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1546 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1547 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1548
1549 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1550 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1551 }
1552}
1553
1554void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1555 static const char globalAlertRule[] = "quota globalAlert";
1556 static const char globalAlertName[] = "globalAlert";
1557
1558 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001559 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001560 }
1561 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1562}
1563
1564void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1565 std::string uidRule = StringPrintf("owner UID match %u", uid);
1566
1567 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1568 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1569 }
1570}
1571
1572void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1573 std::string uidRule = StringPrintf("owner UID match %u", uid);
1574
1575 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1576 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1577 }
1578}
1579
1580} // namespace
1581
1582TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1583 long testQuotaBytes = 5550;
1584
1585 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001586 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001587 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1588
1589 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1590 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1591 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1592
1593 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1594 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1595 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1596
1597 // Remove test physical network
1598 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1599}
1600
1601TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1602 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001603 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001604 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001605 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001606 // Need to have a prior interface quota set to set an alert
1607 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1608 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1609 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1610 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1611
1612 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1613 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1614 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1615
1616 // Remove interface quota
1617 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1618 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1619 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1620
1621 // Remove test physical network
1622 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1623}
1624
1625TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001626 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001627
1628 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1629 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1630 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1631
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001632 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001633 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1634 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1635 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1636}
1637
1638TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1639 SKIP_IF_BPF_SUPPORTED;
1640
1641 int32_t uid = randomUid();
1642 static const char targetReject[] = "REJECT";
1643 static const char targetReturn[] = "RETURN";
1644
1645 // add NaughtyApp
1646 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1647 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1648 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1649
1650 // remove NaughtyApp
1651 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1652 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1653 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1654
1655 // add NiceApp
1656 status = mNetd->bandwidthAddNiceApp(uid);
1657 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1658 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1659
1660 // remove NiceApp
1661 status = mNetd->bandwidthRemoveNiceApp(uid);
1662 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1663 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1664}
Luke Huangb5733d72018-08-21 17:17:19 +08001665
1666namespace {
1667
Luke Huangb670d162018-08-23 20:01:13 +08001668std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1669 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1670 return runCommand(command);
1671}
1672
Luke Huangc3252cc2018-10-16 15:43:23 +08001673bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001674 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1675 for (const auto& route : routes) {
1676 if (route.find(ipRoute) != std::string::npos) {
1677 return true;
1678 }
1679 }
1680 return false;
1681}
1682
Luke Huangc3252cc2018-10-16 15:43:23 +08001683std::string ipRouteString(const std::string& ifName, const std::string& dst,
1684 const std::string& nextHop) {
1685 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1686
1687 if (!nextHop.empty()) {
1688 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001689 }
1690
Luke Huangc3252cc2018-10-16 15:43:23 +08001691 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001692}
1693
Luke Huangc3252cc2018-10-16 15:43:23 +08001694void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1695 const std::string& dst, const std::string& nextHop,
1696 const char* table) {
1697 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1698}
1699
1700void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001701 const std::string& dst, const std::string& nextHop,
1702 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001703 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001704}
1705
1706bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1707 std::vector<std::string> rules = listIpRules(ipVersion);
1708 for (const auto& rule : rules) {
1709 if (rule.find(ipRule) != std::string::npos) {
1710 return true;
1711 }
1712 }
1713 return false;
1714}
1715
1716void expectNetworkDefaultIpRuleExists(const char* ifName) {
1717 std::string networkDefaultRule =
1718 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1719
1720 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1721 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1722 }
1723}
1724
1725void expectNetworkDefaultIpRuleDoesNotExist() {
1726 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1727
1728 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1729 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1730 }
1731}
1732
1733void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1734 std::string networkPermissionRule = "";
1735 switch (permission) {
1736 case INetd::PERMISSION_NONE:
1737 networkPermissionRule = StringPrintf(
1738 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1739 break;
1740 case INetd::PERMISSION_NETWORK:
1741 networkPermissionRule = StringPrintf(
1742 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1743 break;
1744 case INetd::PERMISSION_SYSTEM:
1745 networkPermissionRule = StringPrintf(
1746 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1747 break;
1748 }
1749
1750 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1751 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1752 }
1753}
1754
1755// TODO: It is a duplicate function, need to remove it
1756bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1757 const std::string& expectedInterface,
1758 const std::string& expectedRule,
1759 const char* table) {
1760 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1761 for (const auto& rule : rules) {
1762 if (rule.find(expectedInterface) != std::string::npos) {
1763 if (rule.find(expectedRule) != std::string::npos) {
1764 return true;
1765 }
1766 }
1767 }
1768 return false;
1769}
1770
1771void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1772 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1773 std::string networkIncomingPacketMarkRule = "";
1774 switch (permission) {
1775 case INetd::PERMISSION_NONE:
1776 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1777 break;
1778 case INetd::PERMISSION_NETWORK:
1779 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1780 break;
1781 case INetd::PERMISSION_SYSTEM:
1782 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1783 break;
1784 }
1785
1786 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1787 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1788 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1789 }
1790}
1791
1792} // namespace
1793
1794TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001795 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001796 const char* ipVersion;
1797 const char* testDest;
1798 const char* testNextHop;
1799 const bool expectSuccess;
1800 } kTestData[] = {
1801 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001802 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1803 {IP_RULE_V4, "10.251.0.0/16", "", true},
1804 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1805 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001806 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001807 {IP_RULE_V6, "::/0", "2001:db8::", true},
1808 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001809 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1810 };
1811
Luke Huangc3252cc2018-10-16 15:43:23 +08001812 static const struct {
1813 const char* ipVersion;
1814 const char* testDest;
1815 const char* testNextHop;
1816 } kTestDataWithNextHop[] = {
1817 {IP_RULE_V4, "10.251.10.0/30", ""},
1818 {IP_RULE_V6, "2001:db8::/32", ""},
1819 };
1820
Luke Huangb670d162018-08-23 20:01:13 +08001821 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001822 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001823 const int testUid = randomUid();
1824 const std::vector<int32_t> testUids = {testUid};
1825
1826 // Add test physical network
1827 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1828 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1829
Luke Huangc3252cc2018-10-16 15:43:23 +08001830 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001831 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001832 const auto& td = kTestDataWithNextHop[i];
1833
1834 // All route for test tun will disappear once the tun interface is deleted.
1835 binder::Status status =
1836 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1837 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1838 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1839 sTun.name().c_str());
1840
1841 // Add system permission for test uid, setup route in legacy system table.
1842 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1843
1844 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1845 testUid);
1846 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1847 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1848 testTableLegacySystem);
1849
1850 // Remove system permission for test uid, setup route in legacy network table.
1851 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1852
1853 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1854 testUid);
1855 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1856 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1857 testTableLegacyNetwork);
1858 }
1859
Sehee Park8659b8d2018-11-16 10:53:16 +09001860 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001861 const auto& td = kTestData[i];
1862
1863 binder::Status status =
1864 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1865 if (td.expectSuccess) {
1866 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001867 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001868 sTun.name().c_str());
1869 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001870 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1871 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001872 }
1873
1874 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1875 if (td.expectSuccess) {
1876 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001877 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1878 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001879 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001880 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1881 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001882 }
1883
Luke Huangc3252cc2018-10-16 15:43:23 +08001884 // Add system permission for test uid, route will be added into legacy system table.
1885 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001886
1887 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1888 testUid);
1889 if (td.expectSuccess) {
1890 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001891 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001892 testTableLegacySystem);
1893 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001894 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1895 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001896 }
1897
1898 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1899 td.testNextHop, testUid);
1900 if (td.expectSuccess) {
1901 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001902 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1903 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001904 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001905 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1906 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001907 }
1908
Luke Huangc3252cc2018-10-16 15:43:23 +08001909 // Remove system permission for test uid, route will be added into legacy network table.
1910 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1911
1912 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1913 testUid);
1914 if (td.expectSuccess) {
1915 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1916 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1917 testTableLegacyNetwork);
1918 } else {
1919 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1920 EXPECT_NE(0, status.serviceSpecificErrorCode());
1921 }
1922
1923 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1924 td.testNextHop, testUid);
1925 if (td.expectSuccess) {
1926 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1927 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1928 testTableLegacyNetwork);
1929 } else {
1930 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1931 EXPECT_NE(0, status.serviceSpecificErrorCode());
1932 }
Luke Huangb670d162018-08-23 20:01:13 +08001933 }
1934
1935 // Remove test physical network
1936 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1937}
1938
Luke Huang33a92792019-05-28 16:59:25 +08001939namespace {
1940
1941constexpr char CUTTLEFISH_PRODUCT_DEVICE[] = "vsoc_x86";
1942constexpr char CUTTLEFISH_SYSTEM_NAME[] = "cf_x86_phone";
1943
1944bool isCuttleFish() {
1945 static const std::string sProductDevice = android::base::GetProperty("ro.product.device", "");
1946 static const std::string sSystemName = android::base::GetProperty("ro.product.system.name", "");
1947 return (sProductDevice.find(CUTTLEFISH_PRODUCT_DEVICE) != std::string::npos) &&
1948 (sSystemName.find(CUTTLEFISH_SYSTEM_NAME) != std::string::npos);
1949}
1950
1951} // namespace
1952
Luke Huangb670d162018-08-23 20:01:13 +08001953TEST_F(BinderTest, NetworkPermissionDefault) {
Luke Huang33a92792019-05-28 16:59:25 +08001954 SKIP_IF_CUTTLEFISH;
1955
Luke Huangb670d162018-08-23 20:01:13 +08001956 // Add test physical network
1957 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1958 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1959
Luke Huangc3252cc2018-10-16 15:43:23 +08001960 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001961 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1962 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001963
1964 // Test SetDefault
1965 status = mNetd->networkSetDefault(TEST_NETID1);
1966 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1967 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1968
1969 status = mNetd->networkClearDefault();
1970 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1971 expectNetworkDefaultIpRuleDoesNotExist();
1972
Luke Huangd2861982019-05-17 19:47:28 +08001973 // Set default network back
1974 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001975 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1976
1977 // Test SetPermission
1978 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1979 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1980 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1981 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1982
1983 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1984 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1985 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1986 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1987
1988 // Remove test physical network
1989 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1990}
1991
1992TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001993 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001994 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1995 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001996 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001997 EXPECT_TRUE(ret);
1998
Luke Huang854e2992019-05-29 16:42:48 +08001999 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002000 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08002001
2002 // Clear uid permission before calling networkCanProtect to ensure
2003 // the call won't be affected by uid permission.
2004 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2005
2006 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002007 EXPECT_FALSE(ret);
2008}
2009
2010namespace {
2011
Luke Huangb5733d72018-08-21 17:17:19 +08002012int readIntFromPath(const std::string& path) {
2013 std::string result = "";
2014 EXPECT_TRUE(ReadFileToString(path, &result));
2015 return std::stoi(result);
2016}
2017
2018int getTetherAcceptIPv6Ra(const std::string& ifName) {
2019 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2020 return readIntFromPath(path);
2021}
2022
2023bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2024 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2025 return readIntFromPath(path);
2026}
2027
2028int getTetherIPv6DadTransmits(const std::string& ifName) {
2029 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2030 return readIntFromPath(path);
2031}
2032
2033bool getTetherEnableIPv6(const std::string& ifName) {
2034 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2035 int disableIPv6 = readIntFromPath(path);
2036 return !disableIPv6;
2037}
2038
2039bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2040 for (const auto& iface : ifList) {
2041 if (iface == ifName) {
2042 return true;
2043 }
2044 }
2045 return false;
2046}
2047
2048void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2049 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2050 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2051 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2052 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2053}
2054
2055void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2056 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2057 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2058 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2059 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2060}
2061
2062void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2063 const std::string& ifName) {
2064 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2065}
2066
2067void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2068 const std::string& ifName) {
2069 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2070}
2071
2072void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2073 const std::vector<std::string>& testDnsAddrs) {
2074 EXPECT_TRUE(dnsList == testDnsAddrs);
2075}
2076
2077} // namespace
2078
2079TEST_F(BinderTest, TetherStartStopStatus) {
2080 std::vector<std::string> noDhcpRange = {};
2081 static const char dnsdName[] = "dnsmasq";
2082
2083 binder::Status status = mNetd->tetherStart(noDhcpRange);
2084 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002085 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002086
2087 bool tetherEnabled;
2088 status = mNetd->tetherIsEnabled(&tetherEnabled);
2089 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2090 EXPECT_TRUE(tetherEnabled);
2091
2092 status = mNetd->tetherStop();
2093 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002094 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002095
2096 status = mNetd->tetherIsEnabled(&tetherEnabled);
2097 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2098 EXPECT_FALSE(tetherEnabled);
2099}
2100
2101TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2102 // TODO: verify if dnsmasq update interface successfully
2103
2104 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2105 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2106 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2107
2108 std::vector<std::string> ifList;
2109 status = mNetd->tetherInterfaceList(&ifList);
2110 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2111 expectTetherInterfaceExists(ifList, sTun.name());
2112
2113 status = mNetd->tetherInterfaceRemove(sTun.name());
2114 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2115 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2116
2117 status = mNetd->tetherInterfaceList(&ifList);
2118 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2119 expectTetherInterfaceNotExists(ifList, sTun.name());
2120}
2121
2122TEST_F(BinderTest, TetherDnsSetList) {
2123 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002124 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2125 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002126
2127 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2128 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2129
2130 std::vector<std::string> dnsList;
2131 status = mNetd->tetherDnsList(&dnsList);
2132 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2133 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002134}
2135
2136namespace {
2137
2138constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2139constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2140constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2141constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2142constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2143constexpr char FIREWALL_STANDBY[] = "fw_standby";
2144constexpr char targetReturn[] = "RETURN";
2145constexpr char targetDrop[] = "DROP";
2146
2147void expectFirewallWhitelistMode() {
2148 static const char dropRule[] = "DROP all";
2149 static const char rejectRule[] = "REJECT all";
2150 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2151 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2152 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2153 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2154 }
2155}
2156
2157void expectFirewallBlacklistMode() {
2158 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2159 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2160 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2161 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2162 }
2163}
2164
2165bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2166 const std::string& expectedInterface,
2167 const std::string& expectedRule) {
2168 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2169 // Expected rule:
2170 // Chain fw_INPUT (1 references)
2171 // pkts bytes target prot opt in out source destination
2172 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2173 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2174 int firstRuleIndex = 2;
2175 if (rules.size() < 4) return false;
2176 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2177 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2178 return true;
2179 }
2180 }
2181 return false;
2182}
2183
2184// TODO: It is a duplicate function, need to remove it
2185bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2186 const std::string& expectedInterface,
2187 const std::string& expectedRule) {
2188 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2189 for (const auto& rule : rules) {
2190 if (rule.find(expectedInterface) != std::string::npos) {
2191 if (rule.find(expectedRule) != std::string::npos) {
2192 return true;
2193 }
2194 }
2195 }
2196 return false;
2197}
2198
2199void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2200 static const char returnRule[] = "RETURN all";
2201 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2202 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2203 returnRule));
2204 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2205 returnRule));
2206 }
2207}
2208
2209void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2210 static const char returnRule[] = "RETURN all";
2211 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2212 EXPECT_FALSE(
2213 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2214 EXPECT_FALSE(
2215 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2216 }
2217}
2218
2219bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2220 const std::string& expectedTarget,
2221 const std::string& expectedRule) {
2222 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2223 int firstRuleIndex = 2;
2224 if (rules.size() < 4) return false;
2225 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2226 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2227 return true;
2228 }
2229 }
2230 return false;
2231}
2232
2233bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2234 const std::string& expectedTarget,
2235 const std::string& expectedRule) {
2236 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2237 int lastRuleIndex = rules.size() - 1;
2238 if (lastRuleIndex < 0) return false;
2239 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2240 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2241 return true;
2242 }
2243 }
2244 return false;
2245}
2246
2247void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2248 std::string uidRule = StringPrintf("owner UID match %u", uid);
2249 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2250 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2251}
2252
2253void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2254 std::string uidRule = StringPrintf("owner UID match %u", uid);
2255 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2256 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2257}
2258
2259void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2260 std::string uidRule = StringPrintf("owner UID match %u", uid);
2261 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2262 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2263}
2264
2265void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2266 std::string uidRule = StringPrintf("owner UID match %u", uid);
2267 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2268 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2269}
2270
2271bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2272 std::vector<std::string> inputRules =
2273 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2274 std::vector<std::string> outputRules =
2275 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2276 int inputLastRuleIndex = inputRules.size() - 1;
2277 int outputLastRuleIndex = outputRules.size() - 1;
2278
2279 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2280 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2281 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2282 return true;
2283 }
2284 }
2285 return false;
2286}
2287
2288void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2289 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2290 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2291}
2292
2293void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2294 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2295 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2296 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2297 }
2298}
2299
2300} // namespace
2301
2302TEST_F(BinderTest, FirewallSetFirewallType) {
2303 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2304 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2305 expectFirewallWhitelistMode();
2306
2307 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2308 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2309 expectFirewallBlacklistMode();
2310
2311 // set firewall type blacklist twice
2312 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2313 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2314 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2315 expectFirewallBlacklistMode();
2316
2317 // set firewall type whitelist twice
2318 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2319 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2320 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2321 expectFirewallWhitelistMode();
2322
2323 // reset firewall type to default
2324 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2325 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2326 expectFirewallBlacklistMode();
2327}
2328
2329TEST_F(BinderTest, FirewallSetInterfaceRule) {
2330 // setinterfaceRule is not supported in BLACKLIST MODE
2331 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2332 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2333
2334 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2335 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2336
2337 // set WHITELIST mode first
2338 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2339 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2340
2341 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2342 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2343 expectFirewallInterfaceRuleAllowExists(sTun.name());
2344
2345 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2347 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2348
2349 // reset firewall mode to default
2350 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2351 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2352 expectFirewallBlacklistMode();
2353}
2354
2355TEST_F(BinderTest, FirewallSetUidRule) {
2356 SKIP_IF_BPF_SUPPORTED;
2357
2358 int32_t uid = randomUid();
2359
2360 // Doze allow
2361 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2362 INetd::FIREWALL_RULE_ALLOW);
2363 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2364 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2365
2366 // Doze deny
2367 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2368 INetd::FIREWALL_RULE_DENY);
2369 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2370 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2371
2372 // Powersave allow
2373 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2374 INetd::FIREWALL_RULE_ALLOW);
2375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2376 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2377
2378 // Powersave deny
2379 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2380 INetd::FIREWALL_RULE_DENY);
2381 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2382 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2383
2384 // Standby deny
2385 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2386 INetd::FIREWALL_RULE_DENY);
2387 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2388 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2389
2390 // Standby allow
2391 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2392 INetd::FIREWALL_RULE_ALLOW);
2393 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2394 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2395
2396 // None deny in BLACKLIST
2397 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2398 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2399 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2400 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2401
2402 // None allow in BLACKLIST
2403 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2405 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2406 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2407
2408 // set firewall type whitelist twice
2409 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2410 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2411 expectFirewallWhitelistMode();
2412
2413 // None allow in WHITELIST
2414 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2415 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2416 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2417 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2418
2419 // None deny in WHITELIST
2420 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2421 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2422 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2423 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2424
2425 // reset firewall mode to default
2426 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2427 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2428 expectFirewallBlacklistMode();
2429}
2430
2431TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2432 SKIP_IF_BPF_SUPPORTED;
2433
2434 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2435 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2436 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2437
2438 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2439 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2440 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2441
2442 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2443 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2444 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2445
2446 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2447 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2448 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2449
2450 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2451 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2452 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2453
2454 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2455 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2456 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2457}
Luke Huangf7782042018-08-08 13:13:04 +08002458
2459namespace {
2460
2461std::string hwAddrToStr(unsigned char* hwaddr) {
2462 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2463 hwaddr[4], hwaddr[5]);
2464}
2465
2466int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2467 int prefixLength = 0;
2468 uint32_t m = ntohl(mask);
2469 while (m & (1 << 31)) {
2470 prefixLength++;
2471 m = m << 1;
2472 }
2473 return prefixLength;
2474}
2475
2476std::string toStdString(const String16& s) {
2477 return std::string(String8(s.string()));
2478}
2479
2480android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2481 const auto& sys = sSyscalls.get();
2482 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2483 EXPECT_TRUE(isOk(fd.status()));
2484
2485 struct ifreq ifr = {};
2486 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2487
2488 return sys.ioctl(fd.value(), flag, &ifr);
2489}
2490
2491std::string getInterfaceHwAddr(const std::string& ifName) {
2492 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2493
2494 unsigned char hwaddr[ETH_ALEN] = {};
2495 if (isOk(res.status())) {
2496 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2497 }
2498
2499 return hwAddrToStr(hwaddr);
2500}
2501
2502int getInterfaceIPv4Prefix(const std::string& ifName) {
2503 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2504
2505 int prefixLength = 0;
2506 if (isOk(res.status())) {
2507 prefixLength = ipv4NetmaskToPrefixLength(
2508 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2509 }
2510
2511 return prefixLength;
2512}
2513
2514std::string getInterfaceIPv4Addr(const std::string& ifName) {
2515 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2516
2517 struct in_addr addr = {};
2518 if (isOk(res.status())) {
2519 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2520 }
2521
2522 return std::string(inet_ntoa(addr));
2523}
2524
2525std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2526 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2527
2528 unsigned flags = 0;
2529 if (isOk(res.status())) {
2530 flags = res.value().ifr_flags;
2531 }
2532
2533 std::vector<std::string> ifFlags;
2534 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2535 : toStdString(INetd::IF_STATE_DOWN()));
2536
2537 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2538 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2539 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2540 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2541 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2542
2543 return ifFlags;
2544}
2545
2546bool compareListInterface(const std::vector<std::string>& interfaceList) {
2547 const auto& res = InterfaceController::getIfaceNames();
2548 EXPECT_TRUE(isOk(res));
2549
2550 std::vector<std::string> resIfList;
2551 resIfList.reserve(res.value().size());
2552 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2553
2554 return resIfList == interfaceList;
2555}
2556
2557int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2558 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2559 return readIntFromPath(path);
2560}
2561
2562bool getInterfaceEnableIPv6(const std::string& ifName) {
2563 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2564
2565 int disableIPv6 = readIntFromPath(path);
2566 return !disableIPv6;
2567}
2568
2569int getInterfaceMtu(const std::string& ifName) {
2570 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2571 return readIntFromPath(path);
2572}
2573
2574void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2575 EXPECT_TRUE(compareListInterface(interfaceList));
2576}
2577
2578void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2579 const InterfaceConfigurationParcel& interfaceCfg) {
2580 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2581 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2582 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2583 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2584}
2585
2586void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2587 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2588 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2589
2590 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2591 for (const auto& flag : setCfg.flags) {
2592 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2593 }
2594}
2595
2596void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2597 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2598 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2599}
2600
2601void expectInterfaceNoAddr(const std::string& ifName) {
2602 // noAddr
2603 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2604 // noPrefix
2605 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2606}
2607
2608void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2609 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2610 EXPECT_EQ(enableIPv6, enable);
2611}
2612
2613void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2614 int mtuSize = getInterfaceMtu(ifName);
2615 EXPECT_EQ(mtu, mtuSize);
2616}
2617
2618InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2619 const std::string& addr, int prefixLength,
2620 const std::vector<std::string>& flags) {
2621 InterfaceConfigurationParcel cfg;
2622 cfg.ifName = ifName;
2623 cfg.hwAddr = "";
2624 cfg.ipv4Addr = addr;
2625 cfg.prefixLength = prefixLength;
2626 cfg.flags = flags;
2627 return cfg;
2628}
2629
2630void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2631 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2632 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2633
2634 for (const auto& flag : expectedFlags) {
2635 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2636 interfaceCfg.flags.end());
2637 }
2638
2639 for (const auto& flag : unexpectedFlags) {
2640 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2641 interfaceCfg.flags.end());
2642 }
2643}
2644
2645} // namespace
2646
2647TEST_F(BinderTest, InterfaceList) {
2648 std::vector<std::string> interfaceListResult;
2649
2650 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2651 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2652 expectInterfaceList(interfaceListResult);
2653}
2654
2655TEST_F(BinderTest, InterfaceGetCfg) {
2656 InterfaceConfigurationParcel interfaceCfgResult;
2657
2658 // Add test physical network
2659 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2660 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2661
2662 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2663 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2664 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2665 expectTunFlags(interfaceCfgResult);
2666
2667 // Remove test physical network
2668 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2669}
2670
2671TEST_F(BinderTest, InterfaceSetCfg) {
2672 const std::string testAddr = "192.0.2.3";
2673 const int testPrefixLength = 24;
2674 std::vector<std::string> upFlags = {"up"};
2675 std::vector<std::string> downFlags = {"down"};
2676
2677 // Add test physical network
2678 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2679 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2680
2681 // Set tun interface down.
2682 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2683 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2684 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2685 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2686
2687 // Set tun interface up again.
2688 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2689 status = mNetd->interfaceSetCfg(interfaceCfg);
2690 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2691 status = mNetd->interfaceClearAddrs(sTun.name());
2692 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2693
2694 // Remove test physical network
2695 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2696}
2697
2698TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2699 // enable
2700 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2701 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2702 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2703
2704 // disable
2705 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2706 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2707 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2708}
2709
2710TEST_F(BinderTest, InterfaceClearAddr) {
2711 const std::string testAddr = "192.0.2.3";
2712 const int testPrefixLength = 24;
2713 std::vector<std::string> noFlags{};
2714
2715 // Add test physical network
2716 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2717 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2718
2719 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2720 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2721 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2722 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2723
2724 status = mNetd->interfaceClearAddrs(sTun.name());
2725 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2726 expectInterfaceNoAddr(sTun.name());
2727
2728 // Remove test physical network
2729 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2730}
2731
2732TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2733 // Add test physical network
2734 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2735 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2736
2737 // disable
2738 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2739 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2740 expectInterfaceEnableIPv6(sTun.name(), false);
2741
2742 // enable
2743 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2744 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2745 expectInterfaceEnableIPv6(sTun.name(), true);
2746
2747 // Remove test physical network
2748 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2749}
2750
2751TEST_F(BinderTest, InterfaceSetMtu) {
2752 const int testMtu = 1200;
2753
2754 // Add test physical network
2755 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2756 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2757
2758 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2759 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2760 expectInterfaceMtu(sTun.name(), testMtu);
2761
2762 // Remove test physical network
2763 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2764}
Luke Huang19b49c52018-10-22 12:12:05 +09002765
2766namespace {
2767
2768constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2769constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002770constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002771constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2772
Luke Huangae038f82018-11-05 11:17:31 +09002773int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002774 return listIptablesRuleByTable(binary, table, chainName).size();
2775}
2776
2777bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2778 const std::vector<std::string>& targetVec) {
2779 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2780 if (targetVec.size() != rules.size() - 2) {
2781 return false;
2782 }
2783
2784 /*
Luke Huangae038f82018-11-05 11:17:31 +09002785 * Check that the rules match. Note that this function matches substrings, not entire rules,
2786 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002787 * Skip first two lines since rules start from third line.
2788 * Chain chainName (x references)
2789 * pkts bytes target prot opt in out source destination
2790 * ...
2791 */
2792 int rIndex = 2;
2793 for (const auto& target : targetVec) {
2794 if (rules[rIndex].find(target) == std::string::npos) {
2795 return false;
2796 }
2797 rIndex++;
2798 }
2799 return true;
2800}
2801
2802void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2803 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2804 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2805 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002806 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002807 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2808 "DROP"};
2809
2810 // V4
2811 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2812 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002813 EXPECT_TRUE(
2814 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002815 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2816
Luke Huangae038f82018-11-05 11:17:31 +09002817 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002818 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2819
2820 // V6
2821 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002822 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2823 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002824
2825 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2826 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2827 extIf));
2828 }
2829}
2830
2831void expectNatDisable() {
2832 // It is the default DROP rule with tethering disable.
2833 // Chain tetherctrl_FORWARD (1 references)
2834 // pkts bytes target prot opt in out source destination
2835 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2836 std::vector<std::string> forwardV4Match = {"DROP"};
2837 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2838
2839 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002840 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2841 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002842
Luke Huangae038f82018-11-05 11:17:31 +09002843 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2844 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002845
2846 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2847}
2848
2849} // namespace
2850
2851TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002852 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2853 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2854 expectNatEnable(sTun.name(), sTun2.name());
2855
2856 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2857 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2858 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002859}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002860
2861namespace {
2862
2863using TripleInt = std::array<int, 3>;
2864
2865TripleInt readProcFileToTripleInt(const std::string& path) {
2866 std::string valueString;
2867 int min, def, max;
2868 EXPECT_TRUE(ReadFileToString(path, &valueString));
2869 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2870 return {min, def, max};
2871}
2872
2873void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2874 std::string testRmemValues =
2875 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2876 std::string testWmemValues =
2877 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2878 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2879
2880 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2881 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2882
2883 for (int i = 0; i < 3; i++) {
2884 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2885 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2886 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2887 }
2888}
2889
2890} // namespace
2891
2892TEST_F(BinderTest, TcpBufferSet) {
2893 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2894 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2895 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2896 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2897
2898 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2899 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2900}
Luke Huang528af602018-08-29 19:06:05 +08002901
Chenbo Feng48eaed32018-12-26 17:40:21 -08002902namespace {
2903
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002904void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002905 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2906 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2907 for (int32_t uid : uids) {
2908 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2909 if (exist) {
2910 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002911 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002912 } else {
2913 EXPECT_FALSE(isOk(permission));
2914 EXPECT_EQ(ENOENT, permission.status().code());
2915 }
2916 }
2917}
2918
2919} // namespace
2920
2921TEST_F(BinderTest, TestInternetPermission) {
2922 SKIP_IF_BPF_NOT_SUPPORTED;
2923
2924 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2925
2926 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002927 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002928 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002929 checkUidsInPermissionMap(appUids, true);
2930 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2931 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002932}
2933
Luke Huang528af602018-08-29 19:06:05 +08002934TEST_F(BinderTest, UnsolEvents) {
2935 auto testUnsolService = android::net::TestUnsolService::start();
2936 std::string oldTunName = sTun.name();
2937 std::string newTunName = "unsolTest";
2938 testUnsolService->tarVec.push_back(oldTunName);
2939 testUnsolService->tarVec.push_back(newTunName);
2940 auto& cv = testUnsolService->getCv();
2941 auto& cvMutex = testUnsolService->getCvMutex();
2942 binder::Status status = mNetd->registerUnsolicitedEventListener(
2943 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2944 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2945
2946 // TODO: Add test for below events
2947 // StrictCleartextDetected / InterfaceDnsServersAdded
2948 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2949
2950 {
2951 std::unique_lock lock(cvMutex);
2952
2953 // Re-init test Tun, and we expect that we will get some unsol events.
2954 // Use the test Tun device name to verify if we receive its unsol events.
2955 sTun.destroy();
2956 // Use predefined name
2957 sTun.init(newTunName);
2958
2959 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2960 }
2961
2962 // bit mask 1101101000
2963 // Test only covers below events currently
2964 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2965 InterfaceLinkStatusChanged | RouteChanged;
2966 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002967
2968 // Re-init sTun to clear predefined name
2969 sTun.destroy();
2970 sTun.init();
2971}
2972
2973TEST_F(BinderTest, NDC) {
2974 struct Command {
2975 const std::string cmdString;
2976 const std::string expectedResult;
2977 };
2978
2979 // clang-format off
2980 // Do not change the commands order
2981 const Command networkCmds[] = {
2982 {StringPrintf("ndc network create %d", TEST_NETID1),
2983 "200 0 success"},
2984 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2985 "200 0 success"},
2986 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2987 "200 0 success"},
2988 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2989 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2990 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2991 "200 0 success"},
2992 };
2993
2994 const std::vector<Command> ipfwdCmds = {
2995 {"ndc ipfwd enable " + sTun.name(),
2996 "200 0 ipfwd operation succeeded"},
2997 {"ndc ipfwd disable " + sTun.name(),
2998 "200 0 ipfwd operation succeeded"},
2999 {"ndc ipfwd add lo2 lo3",
3000 "400 0 ipfwd operation failed (No such process)"},
3001 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3002 "200 0 ipfwd operation succeeded"},
3003 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3004 "200 0 ipfwd operation succeeded"},
3005 };
3006
3007 static const struct {
3008 const char* ipVersion;
3009 const char* testDest;
3010 const char* testNextHop;
3011 const bool expectSuccess;
3012 const std::string expectedResult;
3013 } kTestData[] = {
3014 {IP_RULE_V4, "0.0.0.0/0", "", true,
3015 "200 0 success"},
3016 {IP_RULE_V4, "10.251.0.0/16", "", true,
3017 "200 0 success"},
3018 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3019 "400 0 addRoute() failed (Invalid argument)",},
3020 {IP_RULE_V6, "::/0", "", true,
3021 "200 0 success"},
3022 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3023 "200 0 success"},
3024 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3025 "400 0 addRoute() failed (Invalid argument)"},
3026 };
3027 // clang-format on
3028
3029 for (const auto& cmd : networkCmds) {
3030 const std::vector<std::string> result = runCommand(cmd.cmdString);
3031 SCOPED_TRACE(cmd.cmdString);
3032 EXPECT_EQ(result.size(), 1U);
3033 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3034 }
3035
3036 for (const auto& cmd : ipfwdCmds) {
3037 const std::vector<std::string> result = runCommand(cmd.cmdString);
3038 SCOPED_TRACE(cmd.cmdString);
3039 EXPECT_EQ(result.size(), 1U);
3040 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3041 }
3042
3043 // Add test physical network
3044 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3045 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3046
3047 for (const auto& td : kTestData) {
3048 const std::string routeAddCmd =
3049 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3050 td.testDest, td.testNextHop);
3051 const std::string routeRemoveCmd =
3052 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3053 sTun.name().c_str(), td.testDest, td.testNextHop);
3054 std::vector<std::string> result = runCommand(routeAddCmd);
3055 SCOPED_TRACE(routeAddCmd);
3056 EXPECT_EQ(result.size(), 1U);
3057 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3058 if (td.expectSuccess) {
3059 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3060 sTun.name().c_str());
3061 result = runCommand(routeRemoveCmd);
3062 EXPECT_EQ(result.size(), 1U);
3063 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3064 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3065 sTun.name().c_str());
3066 }
3067 }
3068 // Remove test physical network
3069 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003070}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003071
Luke Huang2ff8b342019-04-30 15:33:33 +08003072TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003073 sp<IBinder> binder;
3074 binder::Status status = mNetd->getOemNetd(&binder);
3075 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3076 sp<com::android::internal::net::IOemNetd> oemNetd;
3077 if (binder != nullptr) {
3078 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3079 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003080 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003081
3082 TimedOperation t("OemNetd isAlive RPC");
3083 bool isAlive = false;
3084 oemNetd->isAlive(&isAlive);
3085 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003086
3087 class TestOemUnsolListener
3088 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3089 public:
3090 android::binder::Status onRegistered() override {
3091 std::lock_guard lock(mCvMutex);
3092 mCv.notify_one();
3093 return android::binder::Status::ok();
3094 }
3095 std::condition_variable& getCv() { return mCv; }
3096 std::mutex& getCvMutex() { return mCvMutex; }
3097
3098 private:
3099 std::mutex mCvMutex;
3100 std::condition_variable mCv;
3101 };
3102
3103 // Start the Binder thread pool.
3104 android::ProcessState::self()->startThreadPool();
3105
3106 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3107
3108 auto& cv = testListener->getCv();
3109 auto& cvMutex = testListener->getCvMutex();
3110
3111 {
3112 std::unique_lock lock(cvMutex);
3113
3114 status = oemNetd->registerOemUnsolicitedEventListener(
3115 ::android::interface_cast<
3116 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3117 testListener));
3118 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3119
3120 // Wait for receiving expected events.
3121 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3122 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003123}
Luke Huangd2861982019-05-17 19:47:28 +08003124
3125void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3126 int fallthroughNetId) {
3127 // Re-init sTun* to ensure route rule exists.
3128 sTun.destroy();
3129 sTun.init();
3130 sTun2.destroy();
3131 sTun2.init();
3132
3133 // Create physical network with fallthroughNetId but not set it as default network
3134 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3135 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3136
3137 // Create VPN with vpnNetId
3138 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3139
3140 // Add uid to VPN
3141 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3142 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3143
3144 // Add default route to fallthroughNetwork
3145 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3146 // Add limited route
3147 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3148}
3149
3150namespace {
3151
3152class ScopedUidChange {
3153 public:
3154 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3155 mStoredUid = getuid();
3156 if (mInputUid == mStoredUid) return;
3157 EXPECT_TRUE(seteuid(uid) == 0);
3158 }
3159 ~ScopedUidChange() {
3160 if (mInputUid == mStoredUid) return;
3161 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3162 }
3163
3164 private:
3165 uid_t mInputUid;
3166 uid_t mStoredUid;
3167};
3168
3169constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3170
3171void clearQueue(int tunFd) {
3172 char buf[4096];
3173 int ret;
3174 do {
3175 ret = read(tunFd, buf, sizeof(buf));
3176 } while (ret > 0);
3177}
3178
3179void checkDataReceived(int udpSocket, int tunFd) {
3180 char buf[4096] = {};
3181 // Clear tunFd's queue before write something because there might be some
3182 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3183 clearQueue(tunFd);
3184 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3185 // TODO: extract header and verify data
3186 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3187}
3188
3189bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3190 ScopedUidChange scopedUidChange(uid);
3191 android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3192 if (testSocket < 0) return false;
3193
3194 const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
3195 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3196 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3197 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3198 if (res == -1) return false;
3199
3200 char addr[INET6_ADDRSTRLEN];
3201 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3202 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3203 checkDataReceived(testSocket, tunFd);
3204 return true;
3205}
3206
3207void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3208 std::string vpnFallthroughRule =
3209 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3210 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3211 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3212 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3213 }
3214}
3215
3216void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3217 const TunInterface& fallthroughNetwork,
3218 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3219 int fallthroughNetId = TEST_NETID1) {
3220 // Set default network to NETID_UNSET
3221 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3222
3223 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3224 in6_addr insideVpnAddr = {
3225 {// 2001:db8:cafe::1
3226 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3227 // outsideVpnAddr will hit the route in the fallthrough network route table
3228 // because we added default route in createVpnNetworkWithUid
3229 in6_addr outsideVpnAddr = {
3230 {// 2607:f0d0:1002::4
3231 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3232
3233 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3234 int vpnFd = vpnNetwork.getFdForTesting();
3235 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3236 // default network.
3237 Fwmark fwmark;
3238 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3239 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3240
3241 // Set default network
3242 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3243
3244 // Connections go on the default network because UID 0 is not subject to the VPN.
3245 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3246 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3247 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3248 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3249
3250 // Check if fallthrough rule exists
3251 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3252
3253 // Expect fallthrough to default network
3254 // The fwmark differs depending on whether the VPN is bypassable or not.
3255 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3256 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3257
3258 // Expect connect success, packet will be sent to vpnFd.
3259 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3260 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3261
3262 // Explicitly select vpn network
3263 setNetworkForProcess(vpnNetId);
3264
3265 // Expect fallthrough to default network
3266 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3267 // Expect the mark contains all the bit because we've selected network.
3268 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3269
3270 // Expect connect success, packet will be sent to vpnFd.
3271 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3272 // Expect the mark contains all the bit because we've selected network.
3273 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3274
3275 // Explicitly select fallthrough network
3276 setNetworkForProcess(fallthroughNetId);
3277
3278 // The mark is set to fallthrough network because we've selected it.
3279 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3280 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3281
3282 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3283 if (bypassable) {
3284 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3285 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3286 } else {
3287 // If not, no permission to bypass vpn.
3288 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3289 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3290 }
3291}
3292
3293} // namespace
3294
3295TEST_F(BinderTest, SecureVPNFallthrough) {
3296 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3297 // Get current default network NetId
3298 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3299 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3300}
3301
3302TEST_F(BinderTest, BypassableVPNFallthrough) {
3303 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3304 // Get current default network NetId
3305 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3306 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003307}