blob: 22301701faa7375e1a004be332abdf6ce784f48b [file] [log] [blame]
Lorenzo Colitti89faa342016-02-26 11:38:47 +09001/*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * binder_test.cpp - unit tests for netd binder RPCs.
17 */
18
Robin Leeb8087362016-03-30 18:43:08 +010019#include <cerrno>
Luke Huang528af602018-08-29 19:06:05 +080020#include <chrono>
Robin Leeb8087362016-03-30 18:43:08 +010021#include <cinttypes>
Luke Huang528af602018-08-29 19:06:05 +080022#include <condition_variable>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090023#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090024#include <cstdlib>
Bernie Innocenti196f1b82019-05-20 16:34:16 +090025#include <iostream>
Luke Huang528af602018-08-29 19:06:05 +080026#include <mutex>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090027#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090028#include <vector>
29
Luke Huangf7782042018-08-08 13:13:04 +080030#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090032#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070035#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <netdb.h>
37#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040038#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080039#include <sys/socket.h>
40#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090041
Luke Huang531f5d32018-08-03 15:19:05 +080042#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090043#include <android-base/macros.h>
Luke Huang33a92792019-05-28 16:59:25 +080044#include <android-base/properties.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090045#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090046#include <android-base/strings.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080047#include <binder/IPCThreadState.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080048#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070049#include <bpf/BpfUtils.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080050#include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
51#include <com/android/internal/net/IOemNetd.h>
Robin Leeb8087362016-03-30 18:43:08 +010052#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include <gtest/gtest.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080054#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090055#include <netutils/ifc.h>
Luke Huangd2861982019-05-17 19:47:28 +080056#include "Fwmark.h"
Nathan Harold21299f72018-03-16 20:13:03 -070057#include "InterfaceController.h"
Luke Huangd2861982019-05-17 19:47:28 +080058#include "NetdClient.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090059#include "NetdConstants.h"
Luke Huang528af602018-08-29 19:06:05 +080060#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070061#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090062#include "android/net/INetd.h"
63#include "binder/IServiceManager.h"
Mike Yue7e332f2019-03-13 17:15:48 +080064#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070065#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080066#include "netid_client.h" // NETID_UNSET
Mike Yu5ae61542018-10-19 22:11:43 +080067#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090068
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090069#define IP_PATH "/system/bin/ip"
70#define IP6TABLES_PATH "/system/bin/ip6tables"
71#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090072#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080073#define RAW_TABLE "raw"
74#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080075#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090076#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090077
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090078namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090079
80using android::IBinder;
81using android::IServiceManager;
82using android::sp;
83using android::String16;
84using android::String8;
85using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080086using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090087using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090088using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080089using android::base::Trim;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090090using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080091using android::net::InterfaceConfigurationParcel;
92using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080093using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090094using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090095using android::net::UidRangeParcel;
Luke Huangf7782042018-08-08 13:13:04 +080096using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +080097using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +010098
Luke Huang33a92792019-05-28 16:59:25 +080099#define SKIP_IF_CUTTLEFISH \
100 do { \
101 if (isCuttleFish()) return; \
102 } while (0)
103
Robin Leeb8087362016-03-30 18:43:08 +0100104static const char* IP_RULE_V4 = "-4";
105static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900106static const int TEST_NETID1 = 65501;
107static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800108
109// Use maximum reserved appId for applications to avoid conflict with existing
110// uids.
111static const int TEST_UID1 = 99999;
112static const int TEST_UID2 = 99998;
113
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900114constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115
Benedict Wongb2daefb2017-12-06 22:05:46 -0800116static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
117static const std::string ESP_ALLOW_RULE("esp");
118
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900119class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900120 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900122 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900123 sp<IBinder> binder = sm->getService(String16("netd"));
124 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900125 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900126 }
127 }
128
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900129 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130 ASSERT_NE(nullptr, mNetd.get());
131 }
132
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900133 void TearDown() override {
134 mNetd->networkDestroy(TEST_NETID1);
135 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800136 setNetworkForProcess(NETID_UNSET);
137 // Restore default network
138 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900139 }
140
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900141 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700142
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900143 // Static because setting up the tun interface takes about 40ms.
144 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900145 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900146 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900147 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900148 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900149 }
150
151 static void TearDownTestCase() {
152 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900153 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900154 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900155 }
156
157 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900158
Luke Huangd2861982019-05-17 19:47:28 +0800159 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
160 int fallthroughNetId = TEST_NETID1);
161
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900162 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800163 // Use -1 to represent that default network was not modified because
164 // real netId must be an unsigned value.
165 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900166 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900167 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900168 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900169};
170
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900171TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900172TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900173
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900174class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900175 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700176 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900177 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900178 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179 }
180
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900181 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900182 std::string mName;
183};
184
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900185TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900186 TimedOperation t("isAlive RPC");
187 bool isAlive = false;
188 mNetd->isAlive(&isAlive);
189 ASSERT_TRUE(isAlive);
190}
191
192static int randomUid() {
193 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
194}
195
Robin Leeb8087362016-03-30 18:43:08 +0100196static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900197 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900198 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
199 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900200 perror("popen");
201 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900202 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900203
204 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100205 size_t bufsize = 0;
206 ssize_t linelen = 0;
207 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900208 lines.push_back(std::string(line, linelen));
209 free(line);
210 line = nullptr;
211 }
212
213 pclose(f);
214 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900215}
216
Robin Leeb8087362016-03-30 18:43:08 +0100217static std::vector<std::string> listIpRules(const char *ipVersion) {
218 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
219 return runCommand(command);
220}
221
222static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900223 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100224 return runCommand(command);
225}
226
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900227static int iptablesRuleLineLength(const char *binary, const char *chainName) {
228 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900229}
230
Benedict Wongb2daefb2017-12-06 22:05:46 -0800231static bool iptablesRuleExists(const char *binary,
232 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900233 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800234 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900235 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800236 if(rule.find(expectedRule) != std::string::npos) {
237 return true;
238 }
239 }
240 return false;
241}
242
243static bool iptablesNoSocketAllowRuleExists(const char *chainName){
244 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
245 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
246}
247
248static bool iptablesEspAllowRuleExists(const char *chainName){
249 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
250 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
251}
252
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900253TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700254 SKIP_IF_BPF_SUPPORTED;
255
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900256 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
257 const int kNumUids = 500;
258 std::vector<int32_t> noUids(0);
259 std::vector<int32_t> uids(kNumUids);
260 for (int i = 0; i < kNumUids; i++) {
261 uids[i] = randomUid();
262 }
263
264 bool ret;
265 {
266 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900267 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900268 }
269 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800270 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
271 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
272 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
273 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900274 {
275 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900276 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900277 }
278 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900279 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
280 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900281
282 {
283 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900284 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900285 }
286 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900287 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
288 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800289 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
290 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900291
292 {
293 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900294 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900295 }
296 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900297 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
298 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900299
300 // Check that the call fails if iptables returns an error.
301 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900302 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900303 EXPECT_EQ(false, ret);
304}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900305
Benedict Wong319f17e2018-05-15 17:06:44 -0700306TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700307 const struct TestData {
308 const std::string family;
309 const std::string deviceName;
310 const std::string localAddress;
311 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800312 int32_t iKey;
313 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700314 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800315 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700316 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
317 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
318 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800319 };
320
Sehee Park8659b8d2018-11-16 10:53:16 +0900321 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700322 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800323
324 binder::Status status;
325
Benedict Wong319f17e2018-05-15 17:06:44 -0700326 // Create Tunnel Interface.
327 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700328 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800329 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
330
Benedict Wonga450e722018-05-07 10:29:02 -0700331 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900332 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700333
Benedict Wong319f17e2018-05-15 17:06:44 -0700334 // Update Tunnel Interface.
335 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700336 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800337 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
338
Benedict Wong319f17e2018-05-15 17:06:44 -0700339 // Remove Tunnel Interface.
340 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800341 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700342
343 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900344 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800345 }
346}
347
Benedict Wong1cb73df2018-12-03 00:54:14 -0800348TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
349 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
350 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
351
352 int sockOptVal = UDP_ENCAP_ESPINUDP;
353 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
354
355 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
356 EXPECT_TRUE(res.isOk());
357
358 struct stat info;
359 EXPECT_EQ(0, fstat(sockFd.get(), &info));
360 EXPECT_EQ(1001, (int) info.st_uid);
361}
362
Nathan Harold2deff322018-05-10 14:03:48 -0700363// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
364// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
365#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900366
367using android::net::XfrmController;
368
Benedict Wonga04ffa72018-05-09 21:42:42 -0700369static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
370 static_cast<int>(android::net::XfrmDirection::OUT)};
371static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
372
Nathan Harold21299f72018-03-16 20:13:03 -0700373#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
374 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900375bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900376 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700377 SCOPED_TRACE(status);
378 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
379
380 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700381 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700382 SCOPED_TRACE(status);
383 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
384
385 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700386 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
387 0xD00D, 0xE00D, false)
388 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700389}
390
Benedict Wonga04ffa72018-05-09 21:42:42 -0700391TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900392 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700393
394 // Repeat to ensure cleanup and recreation works correctly
395 for (int i = 0; i < 2; i++) {
396 for (int direction : XFRM_DIRECTIONS) {
397 for (int addrFamily : ADDRESS_FAMILIES) {
398 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700399 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700400 EXPECT_TRUE(status.isOk())
401 << " family: " << addrFamily << " direction: " << direction;
402 }
403 }
404
405 // Cleanup
406 for (int direction : XFRM_DIRECTIONS) {
407 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700408 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700409 EXPECT_TRUE(status.isOk());
410 }
411 }
412 }
413}
414
415TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
416 binder::Status status;
417
418 // Repeat to ensure cleanup and recreation works correctly
419 for (int i = 0; i < 2; i++) {
420 for (int direction : XFRM_DIRECTIONS) {
421 for (int addrFamily : ADDRESS_FAMILIES) {
422 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700423 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700424 EXPECT_TRUE(status.isOk())
425 << " family: " << addrFamily << " direction: " << direction;
426 }
427 }
428
429 // Cleanup
430 for (int direction : XFRM_DIRECTIONS) {
431 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700432 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700433 EXPECT_TRUE(status.isOk());
434 }
435 }
436 }
437}
438
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900439TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900440 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700441 status = XfrmController::Init();
442 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700443
444 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
445 // feature.
446 if (status.code() == EOPNOTSUPP) return;
447
Nathan Harold21299f72018-03-16 20:13:03 -0700448 ASSERT_TRUE(status.ok());
449
450 int32_t spi = 0;
451
452 ASSERT_TRUE(allocateIpSecResources(true, &spi));
453 ASSERT_TRUE(allocateIpSecResources(false, &spi));
454
455 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700456 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700457 ASSERT_TRUE(allocateIpSecResources(true, &spi));
458
459 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700460 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700461 SCOPED_TRACE(status);
462 ASSERT_TRUE(status.ok());
463
Benedict Wonga450e722018-05-07 10:29:02 -0700464 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700465 SCOPED_TRACE(status);
466 ASSERT_TRUE(status.ok());
467
468 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700469 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700470}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900471
472#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700473
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900474static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900475 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900476
477 // Output looks like this:
478 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900479 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900480 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900481 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900482 //
483 // or:
484 //
485 // Chain bw_data_saver (1 references)
486 // target prot opt source destination
487 // ... possibly connectivity critical packet rules here ...
488 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900489
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900490 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900491
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900492 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
493 // Data saver disabled.
494 return 0;
495 }
496
497 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
498
499 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
500 // Data saver enabled.
501 return 1;
502 }
503
504 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900505}
506
507bool enableDataSaver(sp<INetd>& netd, bool enable) {
508 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
509 bool ret;
510 netd->bandwidthEnableDataSaver(enable, &ret);
511 return ret;
512}
513
514int getDataSaverState() {
515 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
516 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
517 EXPECT_EQ(enabled4, enabled6);
518 EXPECT_NE(-1, enabled4);
519 EXPECT_NE(-1, enabled6);
520 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
521 return -1;
522 }
523 return enabled6;
524}
525
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900526TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900527 const int wasEnabled = getDataSaverState();
528 ASSERT_NE(-1, wasEnabled);
529
530 if (wasEnabled) {
531 ASSERT_TRUE(enableDataSaver(mNetd, false));
532 EXPECT_EQ(0, getDataSaverState());
533 }
534
535 ASSERT_TRUE(enableDataSaver(mNetd, false));
536 EXPECT_EQ(0, getDataSaverState());
537
538 ASSERT_TRUE(enableDataSaver(mNetd, true));
539 EXPECT_EQ(1, getDataSaverState());
540
541 ASSERT_TRUE(enableDataSaver(mNetd, true));
542 EXPECT_EQ(1, getDataSaverState());
543
544 if (!wasEnabled) {
545 ASSERT_TRUE(enableDataSaver(mNetd, false));
546 EXPECT_EQ(0, getDataSaverState());
547 }
548}
Robin Leeb8087362016-03-30 18:43:08 +0100549
Luke Huang94658ac2018-10-18 19:35:12 +0900550static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
551 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100552 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100553 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100554 std::vector<std::string> rules = listIpRules(ipVersion);
555
556 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900557 std::string suffix =
558 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900559 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800560 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100561 return true;
562 }
563 }
564 return false;
565}
566
Luke Huang94658ac2018-10-18 19:35:12 +0900567static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
568 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100569 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
570 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
571 EXPECT_EQ(existsIp4, existsIp6);
572 return existsIp4;
573}
574
Luke Huang94658ac2018-10-18 19:35:12 +0900575namespace {
576
577UidRangeParcel makeUidRangeParcel(int start, int stop) {
578 UidRangeParcel res;
579 res.start = start;
580 res.stop = stop;
581
582 return res;
583}
584
585} // namespace
586
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900587TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800588 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
589 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
590 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900591 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
592 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900593
594 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
595 EXPECT_EQ(EBUSY,
596 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
597
598 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
599 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
600 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800601 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900602}
603
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900604TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900605 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
606
cken67cd14c2018-12-05 17:26:59 +0900607 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
608 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900609 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
610
Luke Huang94658ac2018-10-18 19:35:12 +0900611 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
612 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
613 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900614 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
615
616 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
617
618 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
619 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
620 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
621 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
622
623 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
624 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
625 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
626 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
627
628 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
629}
630
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900631TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100632 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100633
Luke Huang94658ac2018-10-18 19:35:12 +0900634 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
635 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Robin Leeb8087362016-03-30 18:43:08 +0100636
637 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
638 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
639
640 // Create two valid rules.
641 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
642 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
643 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
644 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());
650 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
651 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
652 for (auto const& range : uidRanges) {
653 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
654 }
655
656 // Fail to remove the rules a second time after they are already deleted.
657 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
658 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
659 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
660
661 // All rules should be the same as before.
662 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
663 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
664}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900665
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900666// Create a socket pair that isLoopbackSocket won't think is local.
667void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900668 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900669 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900670 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
671
672 socklen_t addrlen = sizeof(server6);
673 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
674 ASSERT_EQ(0, listen(*serverSocket, 10));
675
Bernie Innocentif6918262018-06-11 17:37:35 +0900676 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900677 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900678 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900679 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
680 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
681
Bernie Innocentif6918262018-06-11 17:37:35 +0900682 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900683 ASSERT_NE(-1, *acceptedSocket);
684
685 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
686}
687
688void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
689 char buf[4096];
690 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
691 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
692 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
693}
694
695void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
696 // Check that the client socket was closed with ECONNABORTED.
697 int ret = write(clientSocket, "foo", sizeof("foo"));
698 int err = errno;
699 EXPECT_EQ(-1, ret);
700 EXPECT_EQ(ECONNABORTED, err);
701
702 // Check that it sent a RST to the server.
703 ret = write(acceptedSocket, "foo", sizeof("foo"));
704 err = errno;
705 EXPECT_EQ(-1, ret);
706 EXPECT_EQ(ECONNRESET, err);
707}
708
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900709TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900710 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900711 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900712
713 // Pick a random UID in the system UID range.
714 constexpr int baseUid = AID_APP - 2000;
715 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
716 int uid = baseUid + 500 + arc4random_uniform(1000);
717 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
718
719 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900720 std::vector<UidRangeParcel> uidRanges = {
721 makeUidRangeParcel(baseUid + 42, baseUid + 449),
722 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
723 makeUidRangeParcel(baseUid + 498, uid - 1),
724 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900725 };
726 // A skip list that doesn't contain UID.
727 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
728
729 // Close sockets. Our test socket should be intact.
730 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
731 checkSocketpairOpen(clientSocket, acceptedSocket);
732
733 // UID ranges that do contain uid.
734 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900735 makeUidRangeParcel(baseUid + 42, baseUid + 449),
736 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
737 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900738 };
739 // Add uid to the skip list.
740 skipUids.push_back(uid);
741
742 // Close sockets. Our test socket should still be intact because it's in the skip list.
743 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
744 checkSocketpairOpen(clientSocket, acceptedSocket);
745
746 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
747 skipUids.resize(skipUids.size() - 1);
748 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
749 checkSocketpairClosed(clientSocket, acceptedSocket);
750
751 close(clientSocket);
752 close(serverSocket);
753 close(acceptedSocket);
754}
Erik Klinecc4f2732016-08-03 11:24:27 +0900755
756namespace {
757
758int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
759 if (buf == nullptr) return -1;
760
761 int prefixLength = 0;
762 bool endOfContiguousBits = false;
763 for (unsigned int i = 0; i < buflen; i++) {
764 const uint8_t value = buf[i];
765
766 // Bad bit sequence: check for a contiguous set of bits from the high
767 // end by verifying that the inverted value + 1 is a power of 2
768 // (power of 2 iff. (v & (v - 1)) == 0).
769 const uint8_t inverse = ~value + 1;
770 if ((inverse & (inverse - 1)) != 0) return -1;
771
772 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
773
774 // Bogus netmask.
775 if (endOfContiguousBits && value != 0) return -1;
776
777 if (value != 0xff) endOfContiguousBits = true;
778 }
779
780 return prefixLength;
781}
782
783template<typename T>
784int netmaskToPrefixLength(const T *p) {
785 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
786}
787
788
789static bool interfaceHasAddress(
790 const std::string &ifname, const char *addrString, int prefixLength) {
791 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900792
793 const struct addrinfo hints = {
794 .ai_flags = AI_NUMERICHOST,
795 .ai_family = AF_UNSPEC,
796 .ai_socktype = SOCK_DGRAM,
797 };
798 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
799 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
800 return false;
801 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900802 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900803
804 struct ifaddrs *ifaddrsList = nullptr;
805 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
806
807 if (getifaddrs(&ifaddrsList) != 0) {
808 return false;
809 }
810
811 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
812 if (std::string(addr->ifa_name) != ifname ||
813 addr->ifa_addr == nullptr ||
814 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
815 continue;
816 }
817
818 switch (addr->ifa_addr->sa_family) {
819 case AF_INET: {
820 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
821 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
822 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
823 continue;
824 }
825
826 if (prefixLength < 0) return true; // not checking prefix lengths
827
828 if (addr->ifa_netmask == nullptr) return false;
829 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
830 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
831 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
832 }
833 case AF_INET6: {
834 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
835 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
836 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
837 continue;
838 }
839
840 if (prefixLength < 0) return true; // not checking prefix lengths
841
842 if (addr->ifa_netmask == nullptr) return false;
843 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
844 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
845 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
846 }
847 default:
848 // Cannot happen because we have already screened for matching
849 // address families at the top of each iteration.
850 continue;
851 }
852 }
853
854 return false;
855}
856
857} // namespace
858
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900859TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900860 static const struct TestData {
861 const char *addrString;
862 const int prefixLength;
863 const bool expectSuccess;
864 } kTestData[] = {
865 { "192.0.2.1", 24, true },
866 { "192.0.2.2", 25, true },
867 { "192.0.2.3", 32, true },
868 { "192.0.2.4", 33, false },
869 { "192.not.an.ip", 24, false },
870 { "2001:db8::1", 64, true },
871 { "2001:db8::2", 65, true },
872 { "2001:db8::3", 128, true },
873 { "2001:db8::4", 129, false },
874 { "foo:bar::bad", 64, false },
875 };
876
Sehee Park8659b8d2018-11-16 10:53:16 +0900877 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900878 const auto &td = kTestData[i];
879
880 // [1.a] Add the address.
881 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900882 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900883 if (td.expectSuccess) {
884 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
885 } else {
886 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
887 ASSERT_NE(0, status.serviceSpecificErrorCode());
888 }
889
890 // [1.b] Verify the addition meets the expectation.
891 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900892 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900893 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900894 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900895 }
896
897 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900898 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900899 if (td.expectSuccess) {
900 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
901 } else {
902 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
903 ASSERT_NE(0, status.serviceSpecificErrorCode());
904 }
905
906 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900907 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900908 }
909}
Erik Kline55b06f82016-07-04 09:57:18 +0900910
Erik Kline38e51f12018-09-06 20:14:44 +0900911TEST_F(BinderTest, GetProcSysNet) {
912 const char LOOPBACK[] = "lo";
913 static const struct {
914 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900915 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900916 const char* ifname;
917 const char* parameter;
918 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900919 const int expectedReturnCode;
920 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900921 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
922 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
923 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
924 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
925 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
926 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
927 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900928 };
929
Sehee Park8659b8d2018-11-16 10:53:16 +0900930 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900931 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900932
Erik Kline38e51f12018-09-06 20:14:44 +0900933 std::string value;
934 const binder::Status status =
935 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
936
937 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900938 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900939 EXPECT_EQ(0, status.exceptionCode());
940 EXPECT_EQ(0, status.serviceSpecificErrorCode());
941 EXPECT_EQ(td.expectedValue, value);
942 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900943 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900944 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
945 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
946 }
947 }
948}
949
950TEST_F(BinderTest, SetProcSysNet) {
951 static const struct {
952 const int ipversion;
953 const int which;
954 const char* ifname;
955 const char* parameter;
956 const char* value;
957 const int expectedReturnCode;
958 } kTestData[] = {
959 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
960 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
961 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
962 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
963 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
964 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
965 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
966 };
967
Sehee Park8659b8d2018-11-16 10:53:16 +0900968 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900969 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900970 const binder::Status status =
971 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900972
973 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900974 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900975 EXPECT_EQ(0, status.exceptionCode());
976 EXPECT_EQ(0, status.serviceSpecificErrorCode());
977 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900978 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900979 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
980 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
981 }
982 }
983}
Ben Schwartze7601812017-04-28 16:38:29 -0400984
Erik Kline38e51f12018-09-06 20:14:44 +0900985TEST_F(BinderTest, GetSetProcSysNet) {
986 const int ipversion = INetd::IPV6;
987 const int category = INetd::NEIGH;
988 const std::string& tun = sTun.name();
989 const std::string parameter("ucast_solicit");
990
991 std::string value{};
992 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700993 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900994 const int ival = std::stoi(value);
995 EXPECT_GT(ival, 0);
996 // Try doubling the parameter value (always best!).
997 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
998 .isOk());
999 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
1000 EXPECT_EQ(2 * ival, std::stoi(value));
1001 // Try resetting the parameter.
1002 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
1003 .isOk());
1004 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
1005 EXPECT_EQ(ival, std::stoi(value));
1006}
1007
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001008namespace {
1009
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001010void expectNoTestCounterRules() {
1011 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1012 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1013 std::string allRules = Join(runCommand(command), "\n");
1014 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1015 }
1016}
1017
Bernie Innocentif6918262018-06-11 17:37:35 +09001018void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1019 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001020 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1021 path, if1.c_str(), if2.c_str(), pkt, byte));
1022}
1023
Bernie Innocentif6918262018-06-11 17:37:35 +09001024void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001025 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1026 path, if1.c_str(), if2.c_str()));
1027 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1028 path, if2.c_str(), if1.c_str()));
1029}
1030
Luke Huangcaebcbb2018-09-27 20:37:14 +08001031std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1032 const std::string& iface) {
1033 for (auto& stats : statsVec) {
1034 if (stats.iface == iface) {
1035 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1036 }
1037 }
1038 return {};
1039}
1040
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001041} // namespace
1042
1043TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001044 expectNoTestCounterRules();
1045
1046 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1047 // disabling tethering. We don't check the return value because these commands will fail if
1048 // tethering is already enabled.
1049 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1050 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1051
1052 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1053 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1054 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001055
1056 // Ensure we won't use the same interface name, otherwise the test will fail.
1057 u_int32_t rNumber = arc4random_uniform(10000);
1058 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1059 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001060
1061 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1062 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1063 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1064 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1065 // RX is from external to internal, and TX is from internal to external.
1066 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1067 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1068
1069 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1070 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1071
1072 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1073 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1074
1075 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1076 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1077 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1078
Luke Huangcaebcbb2018-09-27 20:37:14 +08001079 std::vector<TetherStatsParcel> statsVec;
1080 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001081 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1082
Luke Huangcaebcbb2018-09-27 20:37:14 +08001083 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001084
Luke Huangcaebcbb2018-09-27 20:37:14 +08001085 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001086
1087 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1088 delTetherCounterValues(path, intIface1, extIface1);
1089 delTetherCounterValues(path, intIface2, extIface2);
1090 if (path == IP6TABLES_PATH) {
1091 delTetherCounterValues(path, intIface3, extIface2);
1092 }
1093 }
1094
1095 expectNoTestCounterRules();
1096}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001097
Luke Huang0051a622018-07-23 20:30:16 +08001098namespace {
1099
Luke Huanga5211072018-08-01 23:36:29 +08001100constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1101constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001102
1103static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1104 const char* chainName) {
1105 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1106 return runCommand(command);
1107}
1108
Luke Huang19b49c52018-10-22 12:12:05 +09001109// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001110bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001111 const std::string& expectedInterface,
1112 const std::string& expectedRule, const char* table) {
1113 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1114 for (const auto& rule : rules) {
1115 if (rule.find(expectedInterface) != std::string::npos) {
1116 if (rule.find(expectedRule) != std::string::npos) {
1117 return true;
1118 }
1119 }
1120 }
1121 return false;
1122}
1123
1124void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001125 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001126 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001127 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001128 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001129 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1130 IdletimerRule, RAW_TABLE));
1131 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001132 ifname, IdletimerRule, MANGLE_TABLE));
1133 }
1134}
1135
1136void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001137 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001138 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001139 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001140 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001141 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1142 IdletimerRule, RAW_TABLE));
1143 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001144 ifname, IdletimerRule, MANGLE_TABLE));
1145 }
1146}
1147
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001148} // namespace
1149
1150TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001151 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1152 // rule in the table. Because we only check the result after calling remove function. We might
1153 // check the actual rule which is removed by our function (maybe compare the results between
1154 // calling function before and after)
1155 binder::Status status;
1156 const struct TestData {
1157 const std::string ifname;
1158 int32_t timeout;
1159 const std::string classLabel;
1160 } idleTestData[] = {
1161 {"wlan0", 1234, "happyday"},
1162 {"rmnet_data0", 4567, "friday"},
1163 };
1164 for (const auto& td : idleTestData) {
1165 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1166 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1167 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1168
1169 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1170 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1171 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1172 }
1173}
1174
Luke Huanga67dd562018-07-17 19:58:25 +08001175namespace {
1176
1177constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1178constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1179
1180void expectStrictSetUidAccept(const int uid) {
1181 std::string uidRule = StringPrintf("owner UID match %u", uid);
1182 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1183 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001184 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1185 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001186 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1187 }
1188}
1189
1190void expectStrictSetUidLog(const int uid) {
1191 static const char logRule[] = "st_penalty_log all";
1192 std::string uidRule = StringPrintf("owner UID match %u", uid);
1193 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1194 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001195 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1196 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001197 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1198 }
1199}
1200
1201void expectStrictSetUidReject(const int uid) {
1202 static const char rejectRule[] = "st_penalty_reject all";
1203 std::string uidRule = StringPrintf("owner UID match %u", uid);
1204 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1205 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001206 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1207 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001208 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1209 }
1210}
1211
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001212} // namespace
1213
1214TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001215 binder::Status status;
1216 int32_t uid = randomUid();
1217
1218 // setUidCleartextPenalty Policy:Log with randomUid
1219 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1220 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1221 expectStrictSetUidLog(uid);
1222
1223 // setUidCleartextPenalty Policy:Accept with randomUid
1224 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1225 expectStrictSetUidAccept(uid);
1226
1227 // setUidCleartextPenalty Policy:Reject with randomUid
1228 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1229 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1230 expectStrictSetUidReject(uid);
1231
1232 // setUidCleartextPenalty Policy:Accept with randomUid
1233 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1234 expectStrictSetUidAccept(uid);
1235
1236 // test wrong policy
1237 int32_t wrongPolicy = -123;
1238 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1239 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1240}
1241
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001242namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001243
Luke Huangd1675922019-03-11 17:29:27 +08001244std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001245 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001246 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001247 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1248 // ...
1249 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1250
Luke Huangd1675922019-03-11 17:29:27 +08001251 // (dnsmasq)
1252 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1253
1254 if (maxTries == 0) return {};
1255
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001256 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001257 std::vector<std::string> result;
1258 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001259 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001260 if (result.size() || ++run > maxTries) {
1261 break;
1262 }
1263
Luke Huang728cf4c2019-03-14 19:43:02 +08001264 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001265 }
1266 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001267}
1268
Luke Huangd1675922019-03-11 17:29:27 +08001269void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001270 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001271}
1272
Luke Huang728cf4c2019-03-14 19:43:02 +08001273void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001274 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001275}
1276
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001277} // namespace
1278
1279TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001280 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001281
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001282 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1283 std::string clatAddress;
1284 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001285
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001286 // Can't start clatd on an interface that's not part of any network...
1287 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1288 EXPECT_FALSE(status.isOk());
1289 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1290
1291 // ... so create a test physical network and add our tun to it.
1292 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1293 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1294
1295 // Prefix must be 96 bits long.
1296 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1297 EXPECT_FALSE(status.isOk());
1298 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1299
1300 // Can't start clatd unless there's a default route...
1301 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1302 EXPECT_FALSE(status.isOk());
1303 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1304
1305 // so add a default route.
1306 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1307
1308 // Can't start clatd unless there's a global address...
1309 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1310 EXPECT_FALSE(status.isOk());
1311 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1312
1313 // ... so add a global address.
1314 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001315 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001316
1317 // Now expect clatd to start successfully.
1318 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1319 EXPECT_TRUE(status.isOk());
1320 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1321
1322 // Starting it again returns EBUSY.
1323 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1324 EXPECT_FALSE(status.isOk());
1325 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1326
Luke Huangd1675922019-03-11 17:29:27 +08001327 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001328
1329 // Expect clatd to stop successfully.
1330 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001331 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001332 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001333
1334 // Stopping a clatd that doesn't exist returns ENODEV.
1335 status = mNetd->clatdStop(sTun.name());
1336 EXPECT_FALSE(status.isOk());
1337 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001338 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001339
1340 // Clean up.
1341 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1342 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1343 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001344}
Luke Huang457d4702018-08-16 15:39:15 +08001345
1346namespace {
1347
1348bool getIpfwdV4Enable() {
1349 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1350 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1351 EXPECT_TRUE(!result.empty());
1352 int v4Enable = std::stoi(result[0]);
1353 return v4Enable;
1354}
1355
1356bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001357 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001358 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1359 EXPECT_TRUE(!result.empty());
1360 int v6Enable = std::stoi(result[0]);
1361 return v6Enable;
1362}
1363
1364void expectIpfwdEnable(bool enable) {
1365 int enableIPv4 = getIpfwdV4Enable();
1366 int enableIPv6 = getIpfwdV6Enable();
1367 EXPECT_EQ(enable, enableIPv4);
1368 EXPECT_EQ(enable, enableIPv6);
1369}
1370
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001371bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001372 std::vector<std::string> rules = listIpRules(ipVersion);
1373 for (const auto& rule : rules) {
1374 if (rule.find(ipfwdRule) != std::string::npos) {
1375 return true;
1376 }
1377 }
1378 return false;
1379}
1380
1381void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1382 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1383
1384 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1385 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1386 }
1387}
1388
1389void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1390 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1391
1392 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1393 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1394 }
1395}
1396
1397} // namespace
1398
1399TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001400 // Get ipfwd requester list from Netd
1401 std::vector<std::string> requesterList;
1402 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001403 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001404
1405 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001406 if (requesterList.size() == 0) {
1407 // No requester in Netd, ipfwd should be disabled
1408 // So add one test requester and verify
1409 status = mNetd->ipfwdEnableForwarding("TestRequester");
1410 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001411
Luke Huang728cf4c2019-03-14 19:43:02 +08001412 expectIpfwdEnable(true);
1413 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1414 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1415 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001416
Luke Huang728cf4c2019-03-14 19:43:02 +08001417 // Remove test one, verify again
1418 status = mNetd->ipfwdDisableForwarding("TestRequester");
1419 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1420
1421 expectIpfwdEnable(false);
1422 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1423 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1424 EXPECT_FALSE(ipfwdEnabled);
1425 } else {
1426 // Disable all requesters
1427 for (const auto& requester : requesterList) {
1428 status = mNetd->ipfwdDisableForwarding(requester);
1429 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1430 }
1431
1432 // After disable all requester, ipfwd should be disabled
1433 expectIpfwdEnable(false);
1434 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1435 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1436 EXPECT_FALSE(ipfwdEnabled);
1437
1438 // Enable them back
1439 for (const auto& requester : requesterList) {
1440 status = mNetd->ipfwdEnableForwarding(requester);
1441 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1442 }
1443
1444 // ipfwd should be enabled
1445 expectIpfwdEnable(true);
1446 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1447 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1448 EXPECT_TRUE(ipfwdEnabled);
1449 }
Luke Huang457d4702018-08-16 15:39:15 +08001450}
1451
1452TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001453 // Add test physical network
1454 EXPECT_TRUE(
1455 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1456 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1457 EXPECT_TRUE(
1458 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1459 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001460
Luke Huangd1827b82019-02-15 15:03:27 +08001461 binder::Status status =
1462 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1463 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1464 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001465
Luke Huangd1827b82019-02-15 15:03:27 +08001466 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1467 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1468 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001469}
Luke Huang531f5d32018-08-03 15:19:05 +08001470
1471namespace {
1472
1473constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1474constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1475constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1476constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1477constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001478constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001479
Luke Huang19b49c52018-10-22 12:12:05 +09001480// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1481// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001482bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1483 const char* chainName, const std::string& expectedTargetA,
1484 const std::string& expectedTargetB) {
1485 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1486 int matchCount = 0;
1487
1488 for (const auto& rule : rules) {
1489 if (rule.find(expectedTargetA) != std::string::npos) {
1490 if (rule.find(expectedTargetB) != std::string::npos) {
1491 matchCount++;
1492 }
1493 }
1494 }
1495 return matchCount == expectedCount;
1496}
1497
1498void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1499 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1500 std::string result = "";
1501
1502 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001503 // Quota value might be decreased while matching packets
1504 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001505}
1506
1507void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1508 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1509 std::string quotaRule = StringPrintf("quota %s", ifname);
1510
1511 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1512 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1513 BANDWIDTH_COSTLY_IF));
1514 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1515 BANDWIDTH_COSTLY_IF));
1516 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1517 BANDWIDTH_COSTLY_IF));
1518 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1519 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1520 }
1521 expectXtQuotaValueEqual(ifname, quotaBytes);
1522}
1523
1524void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1525 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1526 std::string quotaRule = StringPrintf("quota %s", ifname);
1527
1528 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1529 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1530 BANDWIDTH_COSTLY_IF));
1531 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1532 BANDWIDTH_COSTLY_IF));
1533 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1534 BANDWIDTH_COSTLY_IF));
1535 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1536 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1537 }
1538}
1539
1540void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1541 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1542 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1543 std::string alertName = StringPrintf("%sAlert", ifname);
1544
1545 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1546 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1547 }
1548 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1549}
1550
1551void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1552 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1553 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1554
1555 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1556 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1557 }
1558}
1559
1560void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1561 static const char globalAlertRule[] = "quota globalAlert";
1562 static const char globalAlertName[] = "globalAlert";
1563
1564 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001565 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001566 }
1567 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1568}
1569
1570void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1571 std::string uidRule = StringPrintf("owner UID match %u", uid);
1572
1573 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1574 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1575 }
1576}
1577
1578void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1579 std::string uidRule = StringPrintf("owner UID match %u", uid);
1580
1581 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1582 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1583 }
1584}
1585
1586} // namespace
1587
1588TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1589 long testQuotaBytes = 5550;
1590
1591 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001592 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001593 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1594
1595 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1596 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1597 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1598
1599 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1600 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1601 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1602
1603 // Remove test physical network
1604 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1605}
1606
1607TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1608 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001609 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001610 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001611 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001612 // Need to have a prior interface quota set to set an alert
1613 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1614 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1615 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1616 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1617
1618 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1619 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1620 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1621
1622 // Remove interface quota
1623 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1624 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1625 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1626
1627 // Remove test physical network
1628 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1629}
1630
1631TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001632 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001633
1634 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1635 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1636 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1637
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001638 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001639 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1640 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1641 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1642}
1643
1644TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1645 SKIP_IF_BPF_SUPPORTED;
1646
1647 int32_t uid = randomUid();
1648 static const char targetReject[] = "REJECT";
1649 static const char targetReturn[] = "RETURN";
1650
1651 // add NaughtyApp
1652 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1653 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1654 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1655
1656 // remove NaughtyApp
1657 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1658 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1659 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1660
1661 // add NiceApp
1662 status = mNetd->bandwidthAddNiceApp(uid);
1663 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1664 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1665
1666 // remove NiceApp
1667 status = mNetd->bandwidthRemoveNiceApp(uid);
1668 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1669 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1670}
Luke Huangb5733d72018-08-21 17:17:19 +08001671
1672namespace {
1673
Luke Huangb670d162018-08-23 20:01:13 +08001674std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1675 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1676 return runCommand(command);
1677}
1678
Luke Huangc3252cc2018-10-16 15:43:23 +08001679bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001680 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1681 for (const auto& route : routes) {
1682 if (route.find(ipRoute) != std::string::npos) {
1683 return true;
1684 }
1685 }
1686 return false;
1687}
1688
Luke Huangc3252cc2018-10-16 15:43:23 +08001689std::string ipRouteString(const std::string& ifName, const std::string& dst,
1690 const std::string& nextHop) {
1691 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1692
1693 if (!nextHop.empty()) {
1694 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001695 }
1696
Luke Huangc3252cc2018-10-16 15:43:23 +08001697 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001698}
1699
Luke Huangc3252cc2018-10-16 15:43:23 +08001700void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1701 const std::string& dst, const std::string& nextHop,
1702 const char* table) {
1703 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1704}
1705
1706void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001707 const std::string& dst, const std::string& nextHop,
1708 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001709 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001710}
1711
1712bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1713 std::vector<std::string> rules = listIpRules(ipVersion);
1714 for (const auto& rule : rules) {
1715 if (rule.find(ipRule) != std::string::npos) {
1716 return true;
1717 }
1718 }
1719 return false;
1720}
1721
1722void expectNetworkDefaultIpRuleExists(const char* ifName) {
1723 std::string networkDefaultRule =
1724 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1725
1726 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1727 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1728 }
1729}
1730
1731void expectNetworkDefaultIpRuleDoesNotExist() {
1732 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1733
1734 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1735 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1736 }
1737}
1738
1739void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1740 std::string networkPermissionRule = "";
1741 switch (permission) {
1742 case INetd::PERMISSION_NONE:
1743 networkPermissionRule = StringPrintf(
1744 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1745 break;
1746 case INetd::PERMISSION_NETWORK:
1747 networkPermissionRule = StringPrintf(
1748 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1749 break;
1750 case INetd::PERMISSION_SYSTEM:
1751 networkPermissionRule = StringPrintf(
1752 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1753 break;
1754 }
1755
1756 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1757 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1758 }
1759}
1760
1761// TODO: It is a duplicate function, need to remove it
1762bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1763 const std::string& expectedInterface,
1764 const std::string& expectedRule,
1765 const char* table) {
1766 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1767 for (const auto& rule : rules) {
1768 if (rule.find(expectedInterface) != std::string::npos) {
1769 if (rule.find(expectedRule) != std::string::npos) {
1770 return true;
1771 }
1772 }
1773 }
1774 return false;
1775}
1776
1777void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1778 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1779 std::string networkIncomingPacketMarkRule = "";
1780 switch (permission) {
1781 case INetd::PERMISSION_NONE:
1782 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1783 break;
1784 case INetd::PERMISSION_NETWORK:
1785 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1786 break;
1787 case INetd::PERMISSION_SYSTEM:
1788 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1789 break;
1790 }
1791
1792 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1793 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1794 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1795 }
1796}
1797
1798} // namespace
1799
1800TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001801 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001802 const char* ipVersion;
1803 const char* testDest;
1804 const char* testNextHop;
1805 const bool expectSuccess;
1806 } kTestData[] = {
1807 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001808 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1809 {IP_RULE_V4, "10.251.0.0/16", "", true},
1810 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1811 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001812 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001813 {IP_RULE_V6, "::/0", "2001:db8::", true},
1814 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001815 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1816 };
1817
Luke Huangc3252cc2018-10-16 15:43:23 +08001818 static const struct {
1819 const char* ipVersion;
1820 const char* testDest;
1821 const char* testNextHop;
1822 } kTestDataWithNextHop[] = {
1823 {IP_RULE_V4, "10.251.10.0/30", ""},
1824 {IP_RULE_V6, "2001:db8::/32", ""},
1825 };
1826
Luke Huangb670d162018-08-23 20:01:13 +08001827 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001828 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001829 const int testUid = randomUid();
1830 const std::vector<int32_t> testUids = {testUid};
1831
1832 // Add test physical network
1833 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1834 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1835
Luke Huangc3252cc2018-10-16 15:43:23 +08001836 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001837 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001838 const auto& td = kTestDataWithNextHop[i];
1839
1840 // All route for test tun will disappear once the tun interface is deleted.
1841 binder::Status status =
1842 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1843 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1844 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1845 sTun.name().c_str());
1846
1847 // Add system permission for test uid, setup route in legacy system table.
1848 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1849
1850 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1851 testUid);
1852 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1853 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1854 testTableLegacySystem);
1855
1856 // Remove system permission for test uid, setup route in legacy network table.
1857 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1858
1859 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1860 testUid);
1861 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1862 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1863 testTableLegacyNetwork);
1864 }
1865
Sehee Park8659b8d2018-11-16 10:53:16 +09001866 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001867 const auto& td = kTestData[i];
1868
1869 binder::Status status =
1870 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1871 if (td.expectSuccess) {
1872 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001873 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001874 sTun.name().c_str());
1875 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001876 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1877 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001878 }
1879
1880 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1881 if (td.expectSuccess) {
1882 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001883 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1884 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001885 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001886 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1887 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001888 }
1889
Luke Huangc3252cc2018-10-16 15:43:23 +08001890 // Add system permission for test uid, route will be added into legacy system table.
1891 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001892
1893 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1894 testUid);
1895 if (td.expectSuccess) {
1896 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001897 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001898 testTableLegacySystem);
1899 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001900 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1901 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001902 }
1903
1904 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1905 td.testNextHop, testUid);
1906 if (td.expectSuccess) {
1907 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001908 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1909 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001910 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001911 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1912 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001913 }
1914
Luke Huangc3252cc2018-10-16 15:43:23 +08001915 // Remove system permission for test uid, route will be added into legacy network table.
1916 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1917
1918 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1919 testUid);
1920 if (td.expectSuccess) {
1921 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1922 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1923 testTableLegacyNetwork);
1924 } else {
1925 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1926 EXPECT_NE(0, status.serviceSpecificErrorCode());
1927 }
1928
1929 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1930 td.testNextHop, testUid);
1931 if (td.expectSuccess) {
1932 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1933 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1934 testTableLegacyNetwork);
1935 } else {
1936 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1937 EXPECT_NE(0, status.serviceSpecificErrorCode());
1938 }
Luke Huangb670d162018-08-23 20:01:13 +08001939 }
1940
1941 // Remove test physical network
1942 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1943}
1944
Luke Huang33a92792019-05-28 16:59:25 +08001945namespace {
1946
1947constexpr char CUTTLEFISH_PRODUCT_DEVICE[] = "vsoc_x86";
1948constexpr char CUTTLEFISH_SYSTEM_NAME[] = "cf_x86_phone";
1949
1950bool isCuttleFish() {
1951 static const std::string sProductDevice = android::base::GetProperty("ro.product.device", "");
1952 static const std::string sSystemName = android::base::GetProperty("ro.product.system.name", "");
1953 return (sProductDevice.find(CUTTLEFISH_PRODUCT_DEVICE) != std::string::npos) &&
1954 (sSystemName.find(CUTTLEFISH_SYSTEM_NAME) != std::string::npos);
1955}
1956
1957} // namespace
1958
Luke Huangb670d162018-08-23 20:01:13 +08001959TEST_F(BinderTest, NetworkPermissionDefault) {
Luke Huang33a92792019-05-28 16:59:25 +08001960 SKIP_IF_CUTTLEFISH;
1961
Luke Huangb670d162018-08-23 20:01:13 +08001962 // Add test physical network
1963 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1964 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1965
Luke Huangc3252cc2018-10-16 15:43:23 +08001966 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001967 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1968 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001969
1970 // Test SetDefault
1971 status = mNetd->networkSetDefault(TEST_NETID1);
1972 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1973 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1974
1975 status = mNetd->networkClearDefault();
1976 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1977 expectNetworkDefaultIpRuleDoesNotExist();
1978
Luke Huangd2861982019-05-17 19:47:28 +08001979 // Set default network back
1980 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001981 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1982
1983 // Test SetPermission
1984 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1985 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1986 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1987 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1988
1989 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1990 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1991 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1992 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1993
1994 // Remove test physical network
1995 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1996}
1997
1998TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001999 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002000 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2001 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08002002 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002003 EXPECT_TRUE(ret);
2004
Luke Huang854e2992019-05-29 16:42:48 +08002005 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002006 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08002007
2008 // Clear uid permission before calling networkCanProtect to ensure
2009 // the call won't be affected by uid permission.
2010 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2011
2012 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002013 EXPECT_FALSE(ret);
2014}
2015
2016namespace {
2017
Luke Huangb5733d72018-08-21 17:17:19 +08002018int readIntFromPath(const std::string& path) {
2019 std::string result = "";
2020 EXPECT_TRUE(ReadFileToString(path, &result));
2021 return std::stoi(result);
2022}
2023
2024int getTetherAcceptIPv6Ra(const std::string& ifName) {
2025 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2026 return readIntFromPath(path);
2027}
2028
2029bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2030 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2031 return readIntFromPath(path);
2032}
2033
2034int getTetherIPv6DadTransmits(const std::string& ifName) {
2035 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2036 return readIntFromPath(path);
2037}
2038
2039bool getTetherEnableIPv6(const std::string& ifName) {
2040 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2041 int disableIPv6 = readIntFromPath(path);
2042 return !disableIPv6;
2043}
2044
2045bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2046 for (const auto& iface : ifList) {
2047 if (iface == ifName) {
2048 return true;
2049 }
2050 }
2051 return false;
2052}
2053
2054void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2055 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2056 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2057 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2058 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2059}
2060
2061void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2062 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2063 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2064 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2065 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2066}
2067
2068void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2069 const std::string& ifName) {
2070 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2071}
2072
2073void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2074 const std::string& ifName) {
2075 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2076}
2077
2078void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2079 const std::vector<std::string>& testDnsAddrs) {
2080 EXPECT_TRUE(dnsList == testDnsAddrs);
2081}
2082
2083} // namespace
2084
2085TEST_F(BinderTest, TetherStartStopStatus) {
2086 std::vector<std::string> noDhcpRange = {};
2087 static const char dnsdName[] = "dnsmasq";
2088
2089 binder::Status status = mNetd->tetherStart(noDhcpRange);
2090 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002091 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002092
2093 bool tetherEnabled;
2094 status = mNetd->tetherIsEnabled(&tetherEnabled);
2095 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2096 EXPECT_TRUE(tetherEnabled);
2097
2098 status = mNetd->tetherStop();
2099 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002100 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002101
2102 status = mNetd->tetherIsEnabled(&tetherEnabled);
2103 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2104 EXPECT_FALSE(tetherEnabled);
2105}
2106
2107TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2108 // TODO: verify if dnsmasq update interface successfully
2109
2110 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2111 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2112 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2113
2114 std::vector<std::string> ifList;
2115 status = mNetd->tetherInterfaceList(&ifList);
2116 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2117 expectTetherInterfaceExists(ifList, sTun.name());
2118
2119 status = mNetd->tetherInterfaceRemove(sTun.name());
2120 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2121 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2122
2123 status = mNetd->tetherInterfaceList(&ifList);
2124 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2125 expectTetherInterfaceNotExists(ifList, sTun.name());
2126}
2127
2128TEST_F(BinderTest, TetherDnsSetList) {
2129 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002130 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2131 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002132
2133 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2134 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2135
2136 std::vector<std::string> dnsList;
2137 status = mNetd->tetherDnsList(&dnsList);
2138 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2139 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002140}
2141
2142namespace {
2143
2144constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2145constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2146constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2147constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2148constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2149constexpr char FIREWALL_STANDBY[] = "fw_standby";
2150constexpr char targetReturn[] = "RETURN";
2151constexpr char targetDrop[] = "DROP";
2152
2153void expectFirewallWhitelistMode() {
2154 static const char dropRule[] = "DROP all";
2155 static const char rejectRule[] = "REJECT all";
2156 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2157 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2158 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2159 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2160 }
2161}
2162
2163void expectFirewallBlacklistMode() {
2164 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2165 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2166 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2167 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2168 }
2169}
2170
2171bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2172 const std::string& expectedInterface,
2173 const std::string& expectedRule) {
2174 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2175 // Expected rule:
2176 // Chain fw_INPUT (1 references)
2177 // pkts bytes target prot opt in out source destination
2178 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2179 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2180 int firstRuleIndex = 2;
2181 if (rules.size() < 4) return false;
2182 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2183 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2184 return true;
2185 }
2186 }
2187 return false;
2188}
2189
2190// TODO: It is a duplicate function, need to remove it
2191bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2192 const std::string& expectedInterface,
2193 const std::string& expectedRule) {
2194 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2195 for (const auto& rule : rules) {
2196 if (rule.find(expectedInterface) != std::string::npos) {
2197 if (rule.find(expectedRule) != std::string::npos) {
2198 return true;
2199 }
2200 }
2201 }
2202 return false;
2203}
2204
2205void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2206 static const char returnRule[] = "RETURN all";
2207 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2208 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2209 returnRule));
2210 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2211 returnRule));
2212 }
2213}
2214
2215void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2216 static const char returnRule[] = "RETURN all";
2217 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2218 EXPECT_FALSE(
2219 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2220 EXPECT_FALSE(
2221 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2222 }
2223}
2224
2225bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2226 const std::string& expectedTarget,
2227 const std::string& expectedRule) {
2228 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2229 int firstRuleIndex = 2;
2230 if (rules.size() < 4) return false;
2231 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2232 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2233 return true;
2234 }
2235 }
2236 return false;
2237}
2238
2239bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2240 const std::string& expectedTarget,
2241 const std::string& expectedRule) {
2242 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2243 int lastRuleIndex = rules.size() - 1;
2244 if (lastRuleIndex < 0) return false;
2245 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2246 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2247 return true;
2248 }
2249 }
2250 return false;
2251}
2252
2253void expectFirewallUidFirstRuleExists(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_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2257}
2258
2259void expectFirewallUidFirstRuleDoesNotExist(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_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2263}
2264
2265void expectFirewallUidLastRuleExists(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_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2269}
2270
2271void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2272 std::string uidRule = StringPrintf("owner UID match %u", uid);
2273 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2274 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2275}
2276
2277bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2278 std::vector<std::string> inputRules =
2279 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2280 std::vector<std::string> outputRules =
2281 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2282 int inputLastRuleIndex = inputRules.size() - 1;
2283 int outputLastRuleIndex = outputRules.size() - 1;
2284
2285 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2286 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2287 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2288 return true;
2289 }
2290 }
2291 return false;
2292}
2293
2294void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2295 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2296 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2297}
2298
2299void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2300 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2301 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2302 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2303 }
2304}
2305
2306} // namespace
2307
2308TEST_F(BinderTest, FirewallSetFirewallType) {
2309 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2310 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2311 expectFirewallWhitelistMode();
2312
2313 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2314 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2315 expectFirewallBlacklistMode();
2316
2317 // set firewall type blacklist twice
2318 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2319 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2320 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2321 expectFirewallBlacklistMode();
2322
2323 // set firewall type whitelist twice
2324 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2325 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2326 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2327 expectFirewallWhitelistMode();
2328
2329 // reset firewall type to default
2330 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2331 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2332 expectFirewallBlacklistMode();
2333}
2334
2335TEST_F(BinderTest, FirewallSetInterfaceRule) {
2336 // setinterfaceRule is not supported in BLACKLIST MODE
2337 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2338 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2339
2340 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2341 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2342
2343 // set WHITELIST mode first
2344 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2345 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2346
2347 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2348 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2349 expectFirewallInterfaceRuleAllowExists(sTun.name());
2350
2351 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2352 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2353 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2354
2355 // reset firewall mode to default
2356 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2357 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2358 expectFirewallBlacklistMode();
2359}
2360
2361TEST_F(BinderTest, FirewallSetUidRule) {
2362 SKIP_IF_BPF_SUPPORTED;
2363
2364 int32_t uid = randomUid();
2365
2366 // Doze allow
2367 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2368 INetd::FIREWALL_RULE_ALLOW);
2369 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2370 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2371
2372 // Doze deny
2373 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2374 INetd::FIREWALL_RULE_DENY);
2375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2376 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2377
2378 // Powersave allow
2379 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2380 INetd::FIREWALL_RULE_ALLOW);
2381 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2382 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2383
2384 // Powersave deny
2385 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2386 INetd::FIREWALL_RULE_DENY);
2387 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2388 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2389
2390 // Standby deny
2391 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2392 INetd::FIREWALL_RULE_DENY);
2393 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2394 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2395
2396 // Standby allow
2397 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2398 INetd::FIREWALL_RULE_ALLOW);
2399 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2400 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2401
2402 // None deny in BLACKLIST
2403 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2405 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2406 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2407
2408 // None allow in BLACKLIST
2409 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2410 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2411 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2412 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2413
2414 // set firewall type whitelist twice
2415 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2416 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2417 expectFirewallWhitelistMode();
2418
2419 // None allow in WHITELIST
2420 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2421 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2422 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2423 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2424
2425 // None deny in WHITELIST
2426 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2427 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2428 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2429 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2430
2431 // reset firewall mode to default
2432 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2433 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2434 expectFirewallBlacklistMode();
2435}
2436
2437TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2438 SKIP_IF_BPF_SUPPORTED;
2439
2440 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2441 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2442 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2443
2444 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2445 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2446 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2447
2448 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2449 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2450 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2451
2452 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2453 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2454 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2455
2456 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2457 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2458 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2459
2460 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2461 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2462 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2463}
Luke Huangf7782042018-08-08 13:13:04 +08002464
2465namespace {
2466
2467std::string hwAddrToStr(unsigned char* hwaddr) {
2468 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2469 hwaddr[4], hwaddr[5]);
2470}
2471
2472int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2473 int prefixLength = 0;
2474 uint32_t m = ntohl(mask);
2475 while (m & (1 << 31)) {
2476 prefixLength++;
2477 m = m << 1;
2478 }
2479 return prefixLength;
2480}
2481
2482std::string toStdString(const String16& s) {
2483 return std::string(String8(s.string()));
2484}
2485
2486android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2487 const auto& sys = sSyscalls.get();
2488 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2489 EXPECT_TRUE(isOk(fd.status()));
2490
2491 struct ifreq ifr = {};
2492 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2493
2494 return sys.ioctl(fd.value(), flag, &ifr);
2495}
2496
2497std::string getInterfaceHwAddr(const std::string& ifName) {
2498 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2499
2500 unsigned char hwaddr[ETH_ALEN] = {};
2501 if (isOk(res.status())) {
2502 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2503 }
2504
2505 return hwAddrToStr(hwaddr);
2506}
2507
2508int getInterfaceIPv4Prefix(const std::string& ifName) {
2509 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2510
2511 int prefixLength = 0;
2512 if (isOk(res.status())) {
2513 prefixLength = ipv4NetmaskToPrefixLength(
2514 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2515 }
2516
2517 return prefixLength;
2518}
2519
2520std::string getInterfaceIPv4Addr(const std::string& ifName) {
2521 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2522
2523 struct in_addr addr = {};
2524 if (isOk(res.status())) {
2525 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2526 }
2527
2528 return std::string(inet_ntoa(addr));
2529}
2530
2531std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2532 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2533
2534 unsigned flags = 0;
2535 if (isOk(res.status())) {
2536 flags = res.value().ifr_flags;
2537 }
2538
2539 std::vector<std::string> ifFlags;
2540 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2541 : toStdString(INetd::IF_STATE_DOWN()));
2542
2543 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2544 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2545 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2546 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2547 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2548
2549 return ifFlags;
2550}
2551
2552bool compareListInterface(const std::vector<std::string>& interfaceList) {
2553 const auto& res = InterfaceController::getIfaceNames();
2554 EXPECT_TRUE(isOk(res));
2555
2556 std::vector<std::string> resIfList;
2557 resIfList.reserve(res.value().size());
2558 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2559
2560 return resIfList == interfaceList;
2561}
2562
2563int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2564 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2565 return readIntFromPath(path);
2566}
2567
2568bool getInterfaceEnableIPv6(const std::string& ifName) {
2569 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2570
2571 int disableIPv6 = readIntFromPath(path);
2572 return !disableIPv6;
2573}
2574
2575int getInterfaceMtu(const std::string& ifName) {
2576 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2577 return readIntFromPath(path);
2578}
2579
2580void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2581 EXPECT_TRUE(compareListInterface(interfaceList));
2582}
2583
2584void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2585 const InterfaceConfigurationParcel& interfaceCfg) {
2586 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2587 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2588 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2589 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2590}
2591
2592void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2593 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2594 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2595
2596 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2597 for (const auto& flag : setCfg.flags) {
2598 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2599 }
2600}
2601
2602void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2603 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2604 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2605}
2606
2607void expectInterfaceNoAddr(const std::string& ifName) {
2608 // noAddr
2609 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2610 // noPrefix
2611 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2612}
2613
2614void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2615 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2616 EXPECT_EQ(enableIPv6, enable);
2617}
2618
2619void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2620 int mtuSize = getInterfaceMtu(ifName);
2621 EXPECT_EQ(mtu, mtuSize);
2622}
2623
2624InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2625 const std::string& addr, int prefixLength,
2626 const std::vector<std::string>& flags) {
2627 InterfaceConfigurationParcel cfg;
2628 cfg.ifName = ifName;
2629 cfg.hwAddr = "";
2630 cfg.ipv4Addr = addr;
2631 cfg.prefixLength = prefixLength;
2632 cfg.flags = flags;
2633 return cfg;
2634}
2635
2636void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2637 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2638 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2639
2640 for (const auto& flag : expectedFlags) {
2641 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2642 interfaceCfg.flags.end());
2643 }
2644
2645 for (const auto& flag : unexpectedFlags) {
2646 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2647 interfaceCfg.flags.end());
2648 }
2649}
2650
2651} // namespace
2652
2653TEST_F(BinderTest, InterfaceList) {
2654 std::vector<std::string> interfaceListResult;
2655
2656 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2657 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2658 expectInterfaceList(interfaceListResult);
2659}
2660
2661TEST_F(BinderTest, InterfaceGetCfg) {
2662 InterfaceConfigurationParcel interfaceCfgResult;
2663
2664 // Add test physical network
2665 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2666 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2667
2668 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2669 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2670 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2671 expectTunFlags(interfaceCfgResult);
2672
2673 // Remove test physical network
2674 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2675}
2676
2677TEST_F(BinderTest, InterfaceSetCfg) {
2678 const std::string testAddr = "192.0.2.3";
2679 const int testPrefixLength = 24;
2680 std::vector<std::string> upFlags = {"up"};
2681 std::vector<std::string> downFlags = {"down"};
2682
2683 // Add test physical network
2684 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2685 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2686
2687 // Set tun interface down.
2688 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2689 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2690 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2691 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2692
2693 // Set tun interface up again.
2694 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2695 status = mNetd->interfaceSetCfg(interfaceCfg);
2696 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2697 status = mNetd->interfaceClearAddrs(sTun.name());
2698 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2699
2700 // Remove test physical network
2701 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2702}
2703
2704TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2705 // enable
2706 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2707 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2708 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2709
2710 // disable
2711 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2712 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2713 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2714}
2715
2716TEST_F(BinderTest, InterfaceClearAddr) {
2717 const std::string testAddr = "192.0.2.3";
2718 const int testPrefixLength = 24;
2719 std::vector<std::string> noFlags{};
2720
2721 // Add test physical network
2722 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2723 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2724
2725 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2726 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2727 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2728 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2729
2730 status = mNetd->interfaceClearAddrs(sTun.name());
2731 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2732 expectInterfaceNoAddr(sTun.name());
2733
2734 // Remove test physical network
2735 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2736}
2737
2738TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2739 // Add test physical network
2740 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2741 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2742
2743 // disable
2744 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2745 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2746 expectInterfaceEnableIPv6(sTun.name(), false);
2747
2748 // enable
2749 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2750 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2751 expectInterfaceEnableIPv6(sTun.name(), true);
2752
2753 // Remove test physical network
2754 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2755}
2756
2757TEST_F(BinderTest, InterfaceSetMtu) {
2758 const int testMtu = 1200;
2759
2760 // Add test physical network
2761 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2762 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2763
2764 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2765 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2766 expectInterfaceMtu(sTun.name(), testMtu);
2767
2768 // Remove test physical network
2769 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2770}
Luke Huang19b49c52018-10-22 12:12:05 +09002771
2772namespace {
2773
2774constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2775constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002776constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002777constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2778
Luke Huangae038f82018-11-05 11:17:31 +09002779int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002780 return listIptablesRuleByTable(binary, table, chainName).size();
2781}
2782
2783bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2784 const std::vector<std::string>& targetVec) {
2785 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2786 if (targetVec.size() != rules.size() - 2) {
2787 return false;
2788 }
2789
2790 /*
Luke Huangae038f82018-11-05 11:17:31 +09002791 * Check that the rules match. Note that this function matches substrings, not entire rules,
2792 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002793 * Skip first two lines since rules start from third line.
2794 * Chain chainName (x references)
2795 * pkts bytes target prot opt in out source destination
2796 * ...
2797 */
2798 int rIndex = 2;
2799 for (const auto& target : targetVec) {
2800 if (rules[rIndex].find(target) == std::string::npos) {
2801 return false;
2802 }
2803 rIndex++;
2804 }
2805 return true;
2806}
2807
2808void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2809 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2810 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2811 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002812 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002813 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2814 "DROP"};
2815
2816 // V4
2817 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2818 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002819 EXPECT_TRUE(
2820 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002821 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2822
Luke Huangae038f82018-11-05 11:17:31 +09002823 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002824 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2825
2826 // V6
2827 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002828 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2829 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002830
2831 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2832 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2833 extIf));
2834 }
2835}
2836
2837void expectNatDisable() {
2838 // It is the default DROP rule with tethering disable.
2839 // Chain tetherctrl_FORWARD (1 references)
2840 // pkts bytes target prot opt in out source destination
2841 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2842 std::vector<std::string> forwardV4Match = {"DROP"};
2843 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2844
2845 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002846 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2847 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002848
Luke Huangae038f82018-11-05 11:17:31 +09002849 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2850 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002851
2852 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2853}
2854
2855} // namespace
2856
2857TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002858 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2859 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2860 expectNatEnable(sTun.name(), sTun2.name());
2861
2862 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2863 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2864 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002865}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002866
2867namespace {
2868
2869using TripleInt = std::array<int, 3>;
2870
2871TripleInt readProcFileToTripleInt(const std::string& path) {
2872 std::string valueString;
2873 int min, def, max;
2874 EXPECT_TRUE(ReadFileToString(path, &valueString));
2875 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2876 return {min, def, max};
2877}
2878
2879void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2880 std::string testRmemValues =
2881 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2882 std::string testWmemValues =
2883 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2884 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2885
2886 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2887 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2888
2889 for (int i = 0; i < 3; i++) {
2890 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2891 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2892 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2893 }
2894}
2895
2896} // namespace
2897
2898TEST_F(BinderTest, TcpBufferSet) {
2899 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2900 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2901 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2902 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2903
2904 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2905 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2906}
Luke Huang528af602018-08-29 19:06:05 +08002907
Chenbo Feng48eaed32018-12-26 17:40:21 -08002908namespace {
2909
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002910void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002911 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2912 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2913 for (int32_t uid : uids) {
2914 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2915 if (exist) {
2916 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002917 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002918 } else {
2919 EXPECT_FALSE(isOk(permission));
2920 EXPECT_EQ(ENOENT, permission.status().code());
2921 }
2922 }
2923}
2924
2925} // namespace
2926
2927TEST_F(BinderTest, TestInternetPermission) {
2928 SKIP_IF_BPF_NOT_SUPPORTED;
2929
2930 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2931
2932 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002933 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002934 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002935 checkUidsInPermissionMap(appUids, true);
2936 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2937 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002938}
2939
Luke Huang528af602018-08-29 19:06:05 +08002940TEST_F(BinderTest, UnsolEvents) {
2941 auto testUnsolService = android::net::TestUnsolService::start();
2942 std::string oldTunName = sTun.name();
2943 std::string newTunName = "unsolTest";
2944 testUnsolService->tarVec.push_back(oldTunName);
2945 testUnsolService->tarVec.push_back(newTunName);
2946 auto& cv = testUnsolService->getCv();
2947 auto& cvMutex = testUnsolService->getCvMutex();
2948 binder::Status status = mNetd->registerUnsolicitedEventListener(
2949 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2950 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2951
2952 // TODO: Add test for below events
2953 // StrictCleartextDetected / InterfaceDnsServersAdded
2954 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2955
2956 {
2957 std::unique_lock lock(cvMutex);
2958
2959 // Re-init test Tun, and we expect that we will get some unsol events.
2960 // Use the test Tun device name to verify if we receive its unsol events.
2961 sTun.destroy();
2962 // Use predefined name
2963 sTun.init(newTunName);
2964
2965 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2966 }
2967
2968 // bit mask 1101101000
2969 // Test only covers below events currently
2970 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2971 InterfaceLinkStatusChanged | RouteChanged;
2972 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002973
2974 // Re-init sTun to clear predefined name
2975 sTun.destroy();
2976 sTun.init();
2977}
2978
2979TEST_F(BinderTest, NDC) {
2980 struct Command {
2981 const std::string cmdString;
2982 const std::string expectedResult;
2983 };
2984
2985 // clang-format off
2986 // Do not change the commands order
2987 const Command networkCmds[] = {
2988 {StringPrintf("ndc network create %d", TEST_NETID1),
2989 "200 0 success"},
2990 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2991 "200 0 success"},
2992 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2993 "200 0 success"},
2994 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2995 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2996 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2997 "200 0 success"},
2998 };
2999
3000 const std::vector<Command> ipfwdCmds = {
3001 {"ndc ipfwd enable " + sTun.name(),
3002 "200 0 ipfwd operation succeeded"},
3003 {"ndc ipfwd disable " + sTun.name(),
3004 "200 0 ipfwd operation succeeded"},
3005 {"ndc ipfwd add lo2 lo3",
3006 "400 0 ipfwd operation failed (No such process)"},
3007 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3008 "200 0 ipfwd operation succeeded"},
3009 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3010 "200 0 ipfwd operation succeeded"},
3011 };
3012
3013 static const struct {
3014 const char* ipVersion;
3015 const char* testDest;
3016 const char* testNextHop;
3017 const bool expectSuccess;
3018 const std::string expectedResult;
3019 } kTestData[] = {
3020 {IP_RULE_V4, "0.0.0.0/0", "", true,
3021 "200 0 success"},
3022 {IP_RULE_V4, "10.251.0.0/16", "", true,
3023 "200 0 success"},
3024 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3025 "400 0 addRoute() failed (Invalid argument)",},
3026 {IP_RULE_V6, "::/0", "", true,
3027 "200 0 success"},
3028 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3029 "200 0 success"},
3030 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3031 "400 0 addRoute() failed (Invalid argument)"},
3032 };
3033 // clang-format on
3034
3035 for (const auto& cmd : networkCmds) {
3036 const std::vector<std::string> result = runCommand(cmd.cmdString);
3037 SCOPED_TRACE(cmd.cmdString);
3038 EXPECT_EQ(result.size(), 1U);
3039 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3040 }
3041
3042 for (const auto& cmd : ipfwdCmds) {
3043 const std::vector<std::string> result = runCommand(cmd.cmdString);
3044 SCOPED_TRACE(cmd.cmdString);
3045 EXPECT_EQ(result.size(), 1U);
3046 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3047 }
3048
3049 // Add test physical network
3050 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3051 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3052
3053 for (const auto& td : kTestData) {
3054 const std::string routeAddCmd =
3055 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3056 td.testDest, td.testNextHop);
3057 const std::string routeRemoveCmd =
3058 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3059 sTun.name().c_str(), td.testDest, td.testNextHop);
3060 std::vector<std::string> result = runCommand(routeAddCmd);
3061 SCOPED_TRACE(routeAddCmd);
3062 EXPECT_EQ(result.size(), 1U);
3063 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3064 if (td.expectSuccess) {
3065 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3066 sTun.name().c_str());
3067 result = runCommand(routeRemoveCmd);
3068 EXPECT_EQ(result.size(), 1U);
3069 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3070 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3071 sTun.name().c_str());
3072 }
3073 }
3074 // Remove test physical network
3075 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003076}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003077
Luke Huang2ff8b342019-04-30 15:33:33 +08003078TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003079 sp<IBinder> binder;
3080 binder::Status status = mNetd->getOemNetd(&binder);
3081 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3082 sp<com::android::internal::net::IOemNetd> oemNetd;
3083 if (binder != nullptr) {
3084 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3085 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003086 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003087
3088 TimedOperation t("OemNetd isAlive RPC");
3089 bool isAlive = false;
3090 oemNetd->isAlive(&isAlive);
3091 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003092
3093 class TestOemUnsolListener
3094 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3095 public:
3096 android::binder::Status onRegistered() override {
3097 std::lock_guard lock(mCvMutex);
3098 mCv.notify_one();
3099 return android::binder::Status::ok();
3100 }
3101 std::condition_variable& getCv() { return mCv; }
3102 std::mutex& getCvMutex() { return mCvMutex; }
3103
3104 private:
3105 std::mutex mCvMutex;
3106 std::condition_variable mCv;
3107 };
3108
3109 // Start the Binder thread pool.
3110 android::ProcessState::self()->startThreadPool();
3111
3112 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3113
3114 auto& cv = testListener->getCv();
3115 auto& cvMutex = testListener->getCvMutex();
3116
3117 {
3118 std::unique_lock lock(cvMutex);
3119
3120 status = oemNetd->registerOemUnsolicitedEventListener(
3121 ::android::interface_cast<
3122 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3123 testListener));
3124 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3125
3126 // Wait for receiving expected events.
3127 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3128 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003129}
Luke Huangd2861982019-05-17 19:47:28 +08003130
3131void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3132 int fallthroughNetId) {
3133 // Re-init sTun* to ensure route rule exists.
3134 sTun.destroy();
3135 sTun.init();
3136 sTun2.destroy();
3137 sTun2.init();
3138
3139 // Create physical network with fallthroughNetId but not set it as default network
3140 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3141 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3142
3143 // Create VPN with vpnNetId
3144 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3145
3146 // Add uid to VPN
3147 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3148 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3149
3150 // Add default route to fallthroughNetwork
3151 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3152 // Add limited route
3153 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3154}
3155
3156namespace {
3157
3158class ScopedUidChange {
3159 public:
3160 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3161 mStoredUid = getuid();
3162 if (mInputUid == mStoredUid) return;
3163 EXPECT_TRUE(seteuid(uid) == 0);
3164 }
3165 ~ScopedUidChange() {
3166 if (mInputUid == mStoredUid) return;
3167 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3168 }
3169
3170 private:
3171 uid_t mInputUid;
3172 uid_t mStoredUid;
3173};
3174
3175constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3176
3177void clearQueue(int tunFd) {
3178 char buf[4096];
3179 int ret;
3180 do {
3181 ret = read(tunFd, buf, sizeof(buf));
3182 } while (ret > 0);
3183}
3184
3185void checkDataReceived(int udpSocket, int tunFd) {
3186 char buf[4096] = {};
3187 // Clear tunFd's queue before write something because there might be some
3188 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3189 clearQueue(tunFd);
3190 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3191 // TODO: extract header and verify data
3192 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3193}
3194
3195bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3196 ScopedUidChange scopedUidChange(uid);
3197 android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3198 if (testSocket < 0) return false;
3199
3200 const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
3201 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3202 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3203 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3204 if (res == -1) return false;
3205
3206 char addr[INET6_ADDRSTRLEN];
3207 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3208 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3209 checkDataReceived(testSocket, tunFd);
3210 return true;
3211}
3212
3213void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3214 std::string vpnFallthroughRule =
3215 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3216 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3217 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3218 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3219 }
3220}
3221
3222void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3223 const TunInterface& fallthroughNetwork,
3224 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3225 int fallthroughNetId = TEST_NETID1) {
3226 // Set default network to NETID_UNSET
3227 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3228
3229 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3230 in6_addr insideVpnAddr = {
3231 {// 2001:db8:cafe::1
3232 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3233 // outsideVpnAddr will hit the route in the fallthrough network route table
3234 // because we added default route in createVpnNetworkWithUid
3235 in6_addr outsideVpnAddr = {
3236 {// 2607:f0d0:1002::4
3237 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3238
3239 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3240 int vpnFd = vpnNetwork.getFdForTesting();
3241 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3242 // default network.
3243 Fwmark fwmark;
3244 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3245 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3246
3247 // Set default network
3248 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3249
3250 // Connections go on the default network because UID 0 is not subject to the VPN.
3251 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3252 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3253 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3254 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3255
3256 // Check if fallthrough rule exists
3257 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3258
3259 // Expect fallthrough to default network
3260 // The fwmark differs depending on whether the VPN is bypassable or not.
3261 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3262 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3263
3264 // Expect connect success, packet will be sent to vpnFd.
3265 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3266 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3267
3268 // Explicitly select vpn network
3269 setNetworkForProcess(vpnNetId);
3270
3271 // Expect fallthrough to default network
3272 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3273 // Expect the mark contains all the bit because we've selected network.
3274 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3275
3276 // Expect connect success, packet will be sent to vpnFd.
3277 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3278 // Expect the mark contains all the bit because we've selected network.
3279 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3280
3281 // Explicitly select fallthrough network
3282 setNetworkForProcess(fallthroughNetId);
3283
3284 // The mark is set to fallthrough network because we've selected it.
3285 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3286 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3287
3288 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3289 if (bypassable) {
3290 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3291 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3292 } else {
3293 // If not, no permission to bypass vpn.
3294 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3295 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3296 }
3297}
3298
3299} // namespace
3300
3301TEST_F(BinderTest, SecureVPNFallthrough) {
3302 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3303 // Get current default network NetId
3304 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3305 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3306}
3307
3308TEST_F(BinderTest, BypassableVPNFallthrough) {
3309 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3310 // Get current default network NetId
3311 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3312 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003313}