blob: cb4b8bedce142acbf9bafb003f6559ae81708c1f [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>
54#include <logwrap/logwrap.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080055#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090056#include <netutils/ifc.h>
Luke Huangd2861982019-05-17 19:47:28 +080057#include "Fwmark.h"
Nathan Harold21299f72018-03-16 20:13:03 -070058#include "InterfaceController.h"
Luke Huangd2861982019-05-17 19:47:28 +080059#include "NetdClient.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090060#include "NetdConstants.h"
Luke Huang528af602018-08-29 19:06:05 +080061#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070062#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090063#include "android/net/INetd.h"
64#include "binder/IServiceManager.h"
Mike Yue7e332f2019-03-13 17:15:48 +080065#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070066#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080067#include "netid_client.h" // NETID_UNSET
Mike Yu5ae61542018-10-19 22:11:43 +080068#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090069
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090070#define IP_PATH "/system/bin/ip"
71#define IP6TABLES_PATH "/system/bin/ip6tables"
72#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090073#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080074#define RAW_TABLE "raw"
75#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080076#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090077#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090078
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090079namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090080
81using android::IBinder;
82using android::IServiceManager;
83using android::sp;
84using android::String16;
85using android::String8;
86using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080087using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090088using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090089using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080090using android::base::Trim;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090091using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080092using android::net::InterfaceConfigurationParcel;
93using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080094using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090095using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090096using android::net::UidRangeParcel;
Luke Huangf7782042018-08-08 13:13:04 +080097using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +080098using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +010099
Luke Huang33a92792019-05-28 16:59:25 +0800100#define SKIP_IF_CUTTLEFISH \
101 do { \
102 if (isCuttleFish()) return; \
103 } while (0)
104
Robin Leeb8087362016-03-30 18:43:08 +0100105static const char* IP_RULE_V4 = "-4";
106static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900107static const int TEST_NETID1 = 65501;
108static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800109
110// Use maximum reserved appId for applications to avoid conflict with existing
111// uids.
112static const int TEST_UID1 = 99999;
113static const int TEST_UID2 = 99998;
114
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900115constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116
Benedict Wongb2daefb2017-12-06 22:05:46 -0800117static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
118static const std::string ESP_ALLOW_RULE("esp");
119
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900120class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900121 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900122 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900123 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900124 sp<IBinder> binder = sm->getService(String16("netd"));
125 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900126 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900127 }
128 }
129
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900130 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900131 ASSERT_NE(nullptr, mNetd.get());
132 }
133
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900134 void TearDown() override {
135 mNetd->networkDestroy(TEST_NETID1);
136 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800137 setNetworkForProcess(NETID_UNSET);
138 // Restore default network
139 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900140 }
141
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900142 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700143
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900144 // Static because setting up the tun interface takes about 40ms.
145 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900146 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900147 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900148 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900149 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900150 }
151
152 static void TearDownTestCase() {
153 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900154 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900155 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900156 }
157
158 static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900159
Luke Huangd2861982019-05-17 19:47:28 +0800160 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
161 int fallthroughNetId = TEST_NETID1);
162
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900163 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800164 // Use -1 to represent that default network was not modified because
165 // real netId must be an unsigned value.
166 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900167 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900168 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900169 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900170};
171
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900172TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900173TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900174
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900175class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900176 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700177 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900178 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900179 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900180 }
181
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900182 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900183 std::string mName;
184};
185
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900186TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900187 TimedOperation t("isAlive RPC");
188 bool isAlive = false;
189 mNetd->isAlive(&isAlive);
190 ASSERT_TRUE(isAlive);
191}
192
193static int randomUid() {
194 return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
195}
196
Robin Leeb8087362016-03-30 18:43:08 +0100197static std::vector<std::string> runCommand(const std::string& command) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900198 std::vector<std::string> lines;
Bernie Innocentif6918262018-06-11 17:37:35 +0900199 FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
200 if (f == nullptr) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900201 perror("popen");
202 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900203 }
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900204
205 char *line = nullptr;
Robin Leeb8087362016-03-30 18:43:08 +0100206 size_t bufsize = 0;
207 ssize_t linelen = 0;
208 while ((linelen = getline(&line, &bufsize, f)) >= 0) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900209 lines.push_back(std::string(line, linelen));
210 free(line);
211 line = nullptr;
212 }
213
214 pclose(f);
215 return lines;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900216}
217
Robin Leeb8087362016-03-30 18:43:08 +0100218static std::vector<std::string> listIpRules(const char *ipVersion) {
219 std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
220 return runCommand(command);
221}
222
223static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
Lorenzo Colitti80545772016-06-09 14:20:08 +0900224 std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
Robin Leeb8087362016-03-30 18:43:08 +0100225 return runCommand(command);
226}
227
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900228static int iptablesRuleLineLength(const char *binary, const char *chainName) {
229 return listIptablesRule(binary, chainName).size();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900230}
231
Benedict Wongb2daefb2017-12-06 22:05:46 -0800232static bool iptablesRuleExists(const char *binary,
233 const char *chainName,
Bernie Innocentif6918262018-06-11 17:37:35 +0900234 const std::string& expectedRule) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800235 std::vector<std::string> rules = listIptablesRule(binary, chainName);
Bernie Innocentif6918262018-06-11 17:37:35 +0900236 for (const auto& rule : rules) {
Benedict Wongb2daefb2017-12-06 22:05:46 -0800237 if(rule.find(expectedRule) != std::string::npos) {
238 return true;
239 }
240 }
241 return false;
242}
243
244static bool iptablesNoSocketAllowRuleExists(const char *chainName){
245 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
246 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
247}
248
249static bool iptablesEspAllowRuleExists(const char *chainName){
250 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
251 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
252}
253
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900254TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700255 SKIP_IF_BPF_SUPPORTED;
256
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900257 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
258 const int kNumUids = 500;
259 std::vector<int32_t> noUids(0);
260 std::vector<int32_t> uids(kNumUids);
261 for (int i = 0; i < kNumUids; i++) {
262 uids[i] = randomUid();
263 }
264
265 bool ret;
266 {
267 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900268 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900269 }
270 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800271 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
272 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
273 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
274 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900275 {
276 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900277 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900278 }
279 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900280 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
281 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900282
283 {
284 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900285 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900286 }
287 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900288 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
289 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800290 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
291 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900292
293 {
294 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900295 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900296 }
297 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900298 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
299 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900300
301 // Check that the call fails if iptables returns an error.
302 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900303 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900304 EXPECT_EQ(false, ret);
305}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900306
Benedict Wong319f17e2018-05-15 17:06:44 -0700307TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700308 const struct TestData {
309 const std::string family;
310 const std::string deviceName;
311 const std::string localAddress;
312 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800313 int32_t iKey;
314 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700315 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800316 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700317 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
318 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
319 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800320 };
321
Sehee Park8659b8d2018-11-16 10:53:16 +0900322 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700323 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800324
325 binder::Status status;
326
Benedict Wong319f17e2018-05-15 17:06:44 -0700327 // Create Tunnel Interface.
328 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700329 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800330 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
331
Benedict Wonga450e722018-05-07 10:29:02 -0700332 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900333 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700334
Benedict Wong319f17e2018-05-15 17:06:44 -0700335 // Update Tunnel Interface.
336 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700337 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800338 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
339
Benedict Wong319f17e2018-05-15 17:06:44 -0700340 // Remove Tunnel Interface.
341 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800342 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700343
344 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900345 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800346 }
347}
348
Benedict Wong1cb73df2018-12-03 00:54:14 -0800349TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
350 android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
351 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
352
353 int sockOptVal = UDP_ENCAP_ESPINUDP;
354 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
355
356 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
357 EXPECT_TRUE(res.isOk());
358
359 struct stat info;
360 EXPECT_EQ(0, fstat(sockFd.get(), &info));
361 EXPECT_EQ(1001, (int) info.st_uid);
362}
363
Nathan Harold2deff322018-05-10 14:03:48 -0700364// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
365// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
366#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900367
368using android::net::XfrmController;
369
Benedict Wonga04ffa72018-05-09 21:42:42 -0700370static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
371 static_cast<int>(android::net::XfrmDirection::OUT)};
372static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
373
Nathan Harold21299f72018-03-16 20:13:03 -0700374#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
375 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900376bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900377 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700378 SCOPED_TRACE(status);
379 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
380
381 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700382 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700383 SCOPED_TRACE(status);
384 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
385
386 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700387 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
388 0xD00D, 0xE00D, false)
389 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700390}
391
Benedict Wonga04ffa72018-05-09 21:42:42 -0700392TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900393 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700394
395 // Repeat to ensure cleanup and recreation works correctly
396 for (int i = 0; i < 2; i++) {
397 for (int direction : XFRM_DIRECTIONS) {
398 for (int addrFamily : ADDRESS_FAMILIES) {
399 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700400 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700401 EXPECT_TRUE(status.isOk())
402 << " family: " << addrFamily << " direction: " << direction;
403 }
404 }
405
406 // Cleanup
407 for (int direction : XFRM_DIRECTIONS) {
408 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700409 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700410 EXPECT_TRUE(status.isOk());
411 }
412 }
413 }
414}
415
416TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
417 binder::Status status;
418
419 // Repeat to ensure cleanup and recreation works correctly
420 for (int i = 0; i < 2; i++) {
421 for (int direction : XFRM_DIRECTIONS) {
422 for (int addrFamily : ADDRESS_FAMILIES) {
423 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700424 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700425 EXPECT_TRUE(status.isOk())
426 << " family: " << addrFamily << " direction: " << direction;
427 }
428 }
429
430 // Cleanup
431 for (int direction : XFRM_DIRECTIONS) {
432 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700433 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700434 EXPECT_TRUE(status.isOk());
435 }
436 }
437 }
438}
439
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900440TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900441 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700442 status = XfrmController::Init();
443 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700444
445 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
446 // feature.
447 if (status.code() == EOPNOTSUPP) return;
448
Nathan Harold21299f72018-03-16 20:13:03 -0700449 ASSERT_TRUE(status.ok());
450
451 int32_t spi = 0;
452
453 ASSERT_TRUE(allocateIpSecResources(true, &spi));
454 ASSERT_TRUE(allocateIpSecResources(false, &spi));
455
456 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700457 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700458 ASSERT_TRUE(allocateIpSecResources(true, &spi));
459
460 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700461 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700462 SCOPED_TRACE(status);
463 ASSERT_TRUE(status.ok());
464
Benedict Wonga450e722018-05-07 10:29:02 -0700465 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700466 SCOPED_TRACE(status);
467 ASSERT_TRUE(status.ok());
468
469 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700470 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700471}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900472
473#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700474
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900475static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900476 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900477
478 // Output looks like this:
479 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900480 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900481 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900482 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900483 //
484 // or:
485 //
486 // Chain bw_data_saver (1 references)
487 // target prot opt source destination
488 // ... possibly connectivity critical packet rules here ...
489 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900490
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900491 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900492
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900493 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
494 // Data saver disabled.
495 return 0;
496 }
497
498 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
499
500 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
501 // Data saver enabled.
502 return 1;
503 }
504
505 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900506}
507
508bool enableDataSaver(sp<INetd>& netd, bool enable) {
509 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
510 bool ret;
511 netd->bandwidthEnableDataSaver(enable, &ret);
512 return ret;
513}
514
515int getDataSaverState() {
516 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
517 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
518 EXPECT_EQ(enabled4, enabled6);
519 EXPECT_NE(-1, enabled4);
520 EXPECT_NE(-1, enabled6);
521 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
522 return -1;
523 }
524 return enabled6;
525}
526
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900527TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900528 const int wasEnabled = getDataSaverState();
529 ASSERT_NE(-1, wasEnabled);
530
531 if (wasEnabled) {
532 ASSERT_TRUE(enableDataSaver(mNetd, false));
533 EXPECT_EQ(0, getDataSaverState());
534 }
535
536 ASSERT_TRUE(enableDataSaver(mNetd, false));
537 EXPECT_EQ(0, getDataSaverState());
538
539 ASSERT_TRUE(enableDataSaver(mNetd, true));
540 EXPECT_EQ(1, getDataSaverState());
541
542 ASSERT_TRUE(enableDataSaver(mNetd, true));
543 EXPECT_EQ(1, getDataSaverState());
544
545 if (!wasEnabled) {
546 ASSERT_TRUE(enableDataSaver(mNetd, false));
547 EXPECT_EQ(0, getDataSaverState());
548 }
549}
Robin Leeb8087362016-03-30 18:43:08 +0100550
Luke Huang94658ac2018-10-18 19:35:12 +0900551static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
552 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100553 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100554 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100555 std::vector<std::string> rules = listIpRules(ipVersion);
556
557 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900558 std::string suffix =
559 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900560 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800561 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100562 return true;
563 }
564 }
565 return false;
566}
567
Luke Huang94658ac2018-10-18 19:35:12 +0900568static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
569 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100570 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
571 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
572 EXPECT_EQ(existsIp4, existsIp6);
573 return existsIp4;
574}
575
Luke Huang94658ac2018-10-18 19:35:12 +0900576namespace {
577
578UidRangeParcel makeUidRangeParcel(int start, int stop) {
579 UidRangeParcel res;
580 res.start = start;
581 res.stop = stop;
582
583 return res;
584}
585
586} // namespace
587
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900588TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800589 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
590 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
591 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900592 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
593 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900594
595 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
596 EXPECT_EQ(EBUSY,
597 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
598
599 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
600 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
601 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800602 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900603}
604
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900605TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900606 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
607
cken67cd14c2018-12-05 17:26:59 +0900608 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
609 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900610 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
611
Luke Huang94658ac2018-10-18 19:35:12 +0900612 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
613 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
614 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900615 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
616
617 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
618
619 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
620 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
621 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
622 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
623
624 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
625 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
626 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
627 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
628
629 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
630}
631
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900632TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100633 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100634
Luke Huang94658ac2018-10-18 19:35:12 +0900635 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
636 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800637 // Make sure no rules existed before calling commands.
638 for (auto const& range : uidRanges) {
639 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
640 }
Robin Leeb8087362016-03-30 18:43:08 +0100641 // Create two valid rules.
642 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100643 for (auto const& range : uidRanges) {
644 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
645 }
646
647 // Remove the rules.
648 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100649 for (auto const& range : uidRanges) {
650 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
651 }
652
653 // Fail to remove the rules a second time after they are already deleted.
654 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
655 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
656 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100657}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900658
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900659// Create a socket pair that isLoopbackSocket won't think is local.
660void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900661 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900662 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900663 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
664
665 socklen_t addrlen = sizeof(server6);
666 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
667 ASSERT_EQ(0, listen(*serverSocket, 10));
668
Bernie Innocentif6918262018-06-11 17:37:35 +0900669 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900670 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900671 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900672 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
673 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
674
Bernie Innocentif6918262018-06-11 17:37:35 +0900675 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900676 ASSERT_NE(-1, *acceptedSocket);
677
678 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
679}
680
681void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
682 char buf[4096];
683 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
684 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
685 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
686}
687
688void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
689 // Check that the client socket was closed with ECONNABORTED.
690 int ret = write(clientSocket, "foo", sizeof("foo"));
691 int err = errno;
692 EXPECT_EQ(-1, ret);
693 EXPECT_EQ(ECONNABORTED, err);
694
695 // Check that it sent a RST to the server.
696 ret = write(acceptedSocket, "foo", sizeof("foo"));
697 err = errno;
698 EXPECT_EQ(-1, ret);
699 EXPECT_EQ(ECONNRESET, err);
700}
701
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900702TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900703 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900704 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900705
706 // Pick a random UID in the system UID range.
707 constexpr int baseUid = AID_APP - 2000;
708 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
709 int uid = baseUid + 500 + arc4random_uniform(1000);
710 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
711
712 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900713 std::vector<UidRangeParcel> uidRanges = {
714 makeUidRangeParcel(baseUid + 42, baseUid + 449),
715 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
716 makeUidRangeParcel(baseUid + 498, uid - 1),
717 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900718 };
719 // A skip list that doesn't contain UID.
720 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
721
722 // Close sockets. Our test socket should be intact.
723 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
724 checkSocketpairOpen(clientSocket, acceptedSocket);
725
726 // UID ranges that do contain uid.
727 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900728 makeUidRangeParcel(baseUid + 42, baseUid + 449),
729 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
730 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900731 };
732 // Add uid to the skip list.
733 skipUids.push_back(uid);
734
735 // Close sockets. Our test socket should still be intact because it's in the skip list.
736 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
737 checkSocketpairOpen(clientSocket, acceptedSocket);
738
739 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
740 skipUids.resize(skipUids.size() - 1);
741 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
742 checkSocketpairClosed(clientSocket, acceptedSocket);
743
744 close(clientSocket);
745 close(serverSocket);
746 close(acceptedSocket);
747}
Erik Klinecc4f2732016-08-03 11:24:27 +0900748
749namespace {
750
751int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
752 if (buf == nullptr) return -1;
753
754 int prefixLength = 0;
755 bool endOfContiguousBits = false;
756 for (unsigned int i = 0; i < buflen; i++) {
757 const uint8_t value = buf[i];
758
759 // Bad bit sequence: check for a contiguous set of bits from the high
760 // end by verifying that the inverted value + 1 is a power of 2
761 // (power of 2 iff. (v & (v - 1)) == 0).
762 const uint8_t inverse = ~value + 1;
763 if ((inverse & (inverse - 1)) != 0) return -1;
764
765 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
766
767 // Bogus netmask.
768 if (endOfContiguousBits && value != 0) return -1;
769
770 if (value != 0xff) endOfContiguousBits = true;
771 }
772
773 return prefixLength;
774}
775
776template<typename T>
777int netmaskToPrefixLength(const T *p) {
778 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
779}
780
781
782static bool interfaceHasAddress(
783 const std::string &ifname, const char *addrString, int prefixLength) {
784 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900785
786 const struct addrinfo hints = {
787 .ai_flags = AI_NUMERICHOST,
788 .ai_family = AF_UNSPEC,
789 .ai_socktype = SOCK_DGRAM,
790 };
791 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
792 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
793 return false;
794 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900795 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900796
797 struct ifaddrs *ifaddrsList = nullptr;
798 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
799
800 if (getifaddrs(&ifaddrsList) != 0) {
801 return false;
802 }
803
804 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
805 if (std::string(addr->ifa_name) != ifname ||
806 addr->ifa_addr == nullptr ||
807 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
808 continue;
809 }
810
811 switch (addr->ifa_addr->sa_family) {
812 case AF_INET: {
813 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
814 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
815 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
816 continue;
817 }
818
819 if (prefixLength < 0) return true; // not checking prefix lengths
820
821 if (addr->ifa_netmask == nullptr) return false;
822 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
823 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
824 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
825 }
826 case AF_INET6: {
827 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
828 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
829 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
830 continue;
831 }
832
833 if (prefixLength < 0) return true; // not checking prefix lengths
834
835 if (addr->ifa_netmask == nullptr) return false;
836 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
837 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
838 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
839 }
840 default:
841 // Cannot happen because we have already screened for matching
842 // address families at the top of each iteration.
843 continue;
844 }
845 }
846
847 return false;
848}
849
850} // namespace
851
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900852TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900853 static const struct TestData {
854 const char *addrString;
855 const int prefixLength;
856 const bool expectSuccess;
857 } kTestData[] = {
858 { "192.0.2.1", 24, true },
859 { "192.0.2.2", 25, true },
860 { "192.0.2.3", 32, true },
861 { "192.0.2.4", 33, false },
862 { "192.not.an.ip", 24, false },
863 { "2001:db8::1", 64, true },
864 { "2001:db8::2", 65, true },
865 { "2001:db8::3", 128, true },
866 { "2001:db8::4", 129, false },
867 { "foo:bar::bad", 64, false },
868 };
869
Sehee Park8659b8d2018-11-16 10:53:16 +0900870 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900871 const auto &td = kTestData[i];
872
873 // [1.a] Add the address.
874 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900875 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900876 if (td.expectSuccess) {
877 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
878 } else {
879 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
880 ASSERT_NE(0, status.serviceSpecificErrorCode());
881 }
882
883 // [1.b] Verify the addition meets the expectation.
884 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900885 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900886 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900887 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900888 }
889
890 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900891 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900892 if (td.expectSuccess) {
893 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
894 } else {
895 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
896 ASSERT_NE(0, status.serviceSpecificErrorCode());
897 }
898
899 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900900 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900901 }
902}
Erik Kline55b06f82016-07-04 09:57:18 +0900903
Erik Kline38e51f12018-09-06 20:14:44 +0900904TEST_F(BinderTest, GetProcSysNet) {
905 const char LOOPBACK[] = "lo";
906 static const struct {
907 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900908 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900909 const char* ifname;
910 const char* parameter;
911 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900912 const int expectedReturnCode;
913 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900914 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
915 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
916 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
917 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
918 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
919 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
920 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900921 };
922
Sehee Park8659b8d2018-11-16 10:53:16 +0900923 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900924 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900925
Erik Kline38e51f12018-09-06 20:14:44 +0900926 std::string value;
927 const binder::Status status =
928 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
929
930 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900931 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900932 EXPECT_EQ(0, status.exceptionCode());
933 EXPECT_EQ(0, status.serviceSpecificErrorCode());
934 EXPECT_EQ(td.expectedValue, value);
935 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900936 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900937 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
938 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
939 }
940 }
941}
942
943TEST_F(BinderTest, SetProcSysNet) {
944 static const struct {
945 const int ipversion;
946 const int which;
947 const char* ifname;
948 const char* parameter;
949 const char* value;
950 const int expectedReturnCode;
951 } kTestData[] = {
952 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
953 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
954 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
955 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
956 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
957 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
958 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
959 };
960
Sehee Park8659b8d2018-11-16 10:53:16 +0900961 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900962 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900963 const binder::Status status =
964 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900965
966 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900967 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900968 EXPECT_EQ(0, status.exceptionCode());
969 EXPECT_EQ(0, status.serviceSpecificErrorCode());
970 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900971 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900972 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
973 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
974 }
975 }
976}
Ben Schwartze7601812017-04-28 16:38:29 -0400977
Erik Kline38e51f12018-09-06 20:14:44 +0900978TEST_F(BinderTest, GetSetProcSysNet) {
979 const int ipversion = INetd::IPV6;
980 const int category = INetd::NEIGH;
981 const std::string& tun = sTun.name();
982 const std::string parameter("ucast_solicit");
983
984 std::string value{};
985 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700986 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900987 const int ival = std::stoi(value);
988 EXPECT_GT(ival, 0);
989 // Try doubling the parameter value (always best!).
990 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
991 .isOk());
992 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
993 EXPECT_EQ(2 * ival, std::stoi(value));
994 // Try resetting the parameter.
995 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
996 .isOk());
997 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
998 EXPECT_EQ(ival, std::stoi(value));
999}
1000
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001001namespace {
1002
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001003void expectNoTestCounterRules() {
1004 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1005 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1006 std::string allRules = Join(runCommand(command), "\n");
1007 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1008 }
1009}
1010
Bernie Innocentif6918262018-06-11 17:37:35 +09001011void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1012 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001013 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1014 path, if1.c_str(), if2.c_str(), pkt, byte));
1015}
1016
Bernie Innocentif6918262018-06-11 17:37:35 +09001017void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001018 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1019 path, if1.c_str(), if2.c_str()));
1020 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1021 path, if2.c_str(), if1.c_str()));
1022}
1023
Luke Huangcaebcbb2018-09-27 20:37:14 +08001024std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1025 const std::string& iface) {
1026 for (auto& stats : statsVec) {
1027 if (stats.iface == iface) {
1028 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1029 }
1030 }
1031 return {};
1032}
1033
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001034} // namespace
1035
1036TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001037 expectNoTestCounterRules();
1038
1039 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1040 // disabling tethering. We don't check the return value because these commands will fail if
1041 // tethering is already enabled.
1042 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1043 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1044
1045 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1046 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1047 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001048
1049 // Ensure we won't use the same interface name, otherwise the test will fail.
1050 u_int32_t rNumber = arc4random_uniform(10000);
1051 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1052 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001053
1054 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1055 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1056 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1057 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1058 // RX is from external to internal, and TX is from internal to external.
1059 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1060 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1061
1062 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1063 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1064
1065 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1066 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1067
1068 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1069 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1070 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1071
Luke Huangcaebcbb2018-09-27 20:37:14 +08001072 std::vector<TetherStatsParcel> statsVec;
1073 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001074 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1075
Luke Huangcaebcbb2018-09-27 20:37:14 +08001076 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001077
Luke Huangcaebcbb2018-09-27 20:37:14 +08001078 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001079
1080 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1081 delTetherCounterValues(path, intIface1, extIface1);
1082 delTetherCounterValues(path, intIface2, extIface2);
1083 if (path == IP6TABLES_PATH) {
1084 delTetherCounterValues(path, intIface3, extIface2);
1085 }
1086 }
1087
1088 expectNoTestCounterRules();
1089}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001090
Luke Huang0051a622018-07-23 20:30:16 +08001091namespace {
1092
Luke Huanga5211072018-08-01 23:36:29 +08001093constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1094constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001095
1096static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1097 const char* chainName) {
1098 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1099 return runCommand(command);
1100}
1101
Luke Huang19b49c52018-10-22 12:12:05 +09001102// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001103bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001104 const std::string& expectedInterface,
1105 const std::string& expectedRule, const char* table) {
1106 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1107 for (const auto& rule : rules) {
1108 if (rule.find(expectedInterface) != std::string::npos) {
1109 if (rule.find(expectedRule) != std::string::npos) {
1110 return true;
1111 }
1112 }
1113 }
1114 return false;
1115}
1116
1117void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001118 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001119 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001120 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001121 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001122 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1123 IdletimerRule, RAW_TABLE));
1124 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001125 ifname, IdletimerRule, MANGLE_TABLE));
1126 }
1127}
1128
1129void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001130 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001131 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001132 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001133 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001134 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1135 IdletimerRule, RAW_TABLE));
1136 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001137 ifname, IdletimerRule, MANGLE_TABLE));
1138 }
1139}
1140
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001141} // namespace
1142
1143TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001144 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1145 // rule in the table. Because we only check the result after calling remove function. We might
1146 // check the actual rule which is removed by our function (maybe compare the results between
1147 // calling function before and after)
1148 binder::Status status;
1149 const struct TestData {
1150 const std::string ifname;
1151 int32_t timeout;
1152 const std::string classLabel;
1153 } idleTestData[] = {
1154 {"wlan0", 1234, "happyday"},
1155 {"rmnet_data0", 4567, "friday"},
1156 };
1157 for (const auto& td : idleTestData) {
1158 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1159 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1160 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1161
1162 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1163 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1164 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1165 }
1166}
1167
Luke Huanga67dd562018-07-17 19:58:25 +08001168namespace {
1169
1170constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1171constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1172
1173void expectStrictSetUidAccept(const int uid) {
1174 std::string uidRule = StringPrintf("owner UID match %u", uid);
1175 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1176 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001177 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1178 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001179 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1180 }
1181}
1182
1183void expectStrictSetUidLog(const int uid) {
1184 static const char logRule[] = "st_penalty_log all";
1185 std::string uidRule = StringPrintf("owner UID match %u", uid);
1186 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1187 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001188 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1189 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001190 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1191 }
1192}
1193
1194void expectStrictSetUidReject(const int uid) {
1195 static const char rejectRule[] = "st_penalty_reject all";
1196 std::string uidRule = StringPrintf("owner UID match %u", uid);
1197 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1198 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001199 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1200 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001201 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1202 }
1203}
1204
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001205} // namespace
1206
1207TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001208 binder::Status status;
1209 int32_t uid = randomUid();
1210
1211 // setUidCleartextPenalty Policy:Log with randomUid
1212 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1213 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1214 expectStrictSetUidLog(uid);
1215
1216 // setUidCleartextPenalty Policy:Accept with randomUid
1217 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1218 expectStrictSetUidAccept(uid);
1219
1220 // setUidCleartextPenalty Policy:Reject with randomUid
1221 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1222 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1223 expectStrictSetUidReject(uid);
1224
1225 // setUidCleartextPenalty Policy:Accept with randomUid
1226 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1227 expectStrictSetUidAccept(uid);
1228
1229 // test wrong policy
1230 int32_t wrongPolicy = -123;
1231 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1232 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1233}
1234
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001235namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001236
Luke Huangd1675922019-03-11 17:29:27 +08001237std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001238 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001239 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001240 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1241 // ...
1242 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1243
Luke Huangd1675922019-03-11 17:29:27 +08001244 // (dnsmasq)
1245 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1246
1247 if (maxTries == 0) return {};
1248
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001249 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001250 std::vector<std::string> result;
1251 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001252 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001253 if (result.size() || ++run > maxTries) {
1254 break;
1255 }
1256
Luke Huang728cf4c2019-03-14 19:43:02 +08001257 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001258 }
1259 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001260}
1261
Luke Huangd1675922019-03-11 17:29:27 +08001262void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001263 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001264}
1265
Luke Huang728cf4c2019-03-14 19:43:02 +08001266void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001267 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001268}
1269
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001270} // namespace
1271
1272TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001273 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001274
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001275 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1276 std::string clatAddress;
1277 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001278
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001279 // Can't start clatd on an interface that's not part of any network...
1280 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1281 EXPECT_FALSE(status.isOk());
1282 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1283
1284 // ... so create a test physical network and add our tun to it.
1285 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1286 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1287
1288 // Prefix must be 96 bits long.
1289 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1290 EXPECT_FALSE(status.isOk());
1291 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1292
1293 // Can't start clatd unless there's a default route...
1294 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1295 EXPECT_FALSE(status.isOk());
1296 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1297
1298 // so add a default route.
1299 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1300
1301 // Can't start clatd unless there's a global address...
1302 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1303 EXPECT_FALSE(status.isOk());
1304 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1305
1306 // ... so add a global address.
1307 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001308 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001309
1310 // Now expect clatd to start successfully.
1311 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1312 EXPECT_TRUE(status.isOk());
1313 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1314
1315 // Starting it again returns EBUSY.
1316 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1317 EXPECT_FALSE(status.isOk());
1318 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1319
Luke Huangd1675922019-03-11 17:29:27 +08001320 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001321
1322 // Expect clatd to stop successfully.
1323 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001325 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001326
1327 // Stopping a clatd that doesn't exist returns ENODEV.
1328 status = mNetd->clatdStop(sTun.name());
1329 EXPECT_FALSE(status.isOk());
1330 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001331 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001332
1333 // Clean up.
1334 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1335 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1336 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001337}
Luke Huang457d4702018-08-16 15:39:15 +08001338
1339namespace {
1340
1341bool getIpfwdV4Enable() {
1342 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1343 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1344 EXPECT_TRUE(!result.empty());
1345 int v4Enable = std::stoi(result[0]);
1346 return v4Enable;
1347}
1348
1349bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001350 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001351 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1352 EXPECT_TRUE(!result.empty());
1353 int v6Enable = std::stoi(result[0]);
1354 return v6Enable;
1355}
1356
1357void expectIpfwdEnable(bool enable) {
1358 int enableIPv4 = getIpfwdV4Enable();
1359 int enableIPv6 = getIpfwdV6Enable();
1360 EXPECT_EQ(enable, enableIPv4);
1361 EXPECT_EQ(enable, enableIPv6);
1362}
1363
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001364bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001365 std::vector<std::string> rules = listIpRules(ipVersion);
1366 for (const auto& rule : rules) {
1367 if (rule.find(ipfwdRule) != std::string::npos) {
1368 return true;
1369 }
1370 }
1371 return false;
1372}
1373
1374void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1375 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1376
1377 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1378 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1379 }
1380}
1381
1382void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1383 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1384
1385 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1386 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1387 }
1388}
1389
1390} // namespace
1391
1392TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001393 // Get ipfwd requester list from Netd
1394 std::vector<std::string> requesterList;
1395 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001396 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001397
1398 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001399 if (requesterList.size() == 0) {
1400 // No requester in Netd, ipfwd should be disabled
1401 // So add one test requester and verify
1402 status = mNetd->ipfwdEnableForwarding("TestRequester");
1403 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001404
Luke Huang728cf4c2019-03-14 19:43:02 +08001405 expectIpfwdEnable(true);
1406 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1407 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1408 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001409
Luke Huang728cf4c2019-03-14 19:43:02 +08001410 // Remove test one, verify again
1411 status = mNetd->ipfwdDisableForwarding("TestRequester");
1412 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1413
1414 expectIpfwdEnable(false);
1415 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1416 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1417 EXPECT_FALSE(ipfwdEnabled);
1418 } else {
1419 // Disable all requesters
1420 for (const auto& requester : requesterList) {
1421 status = mNetd->ipfwdDisableForwarding(requester);
1422 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1423 }
1424
1425 // After disable all requester, ipfwd should be disabled
1426 expectIpfwdEnable(false);
1427 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1428 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1429 EXPECT_FALSE(ipfwdEnabled);
1430
1431 // Enable them back
1432 for (const auto& requester : requesterList) {
1433 status = mNetd->ipfwdEnableForwarding(requester);
1434 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1435 }
1436
1437 // ipfwd should be enabled
1438 expectIpfwdEnable(true);
1439 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1440 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1441 EXPECT_TRUE(ipfwdEnabled);
1442 }
Luke Huang457d4702018-08-16 15:39:15 +08001443}
1444
1445TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001446 // Add test physical network
1447 EXPECT_TRUE(
1448 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1449 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1450 EXPECT_TRUE(
1451 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1452 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001453
Luke Huangd1827b82019-02-15 15:03:27 +08001454 binder::Status status =
1455 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1456 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1457 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001458
Luke Huangd1827b82019-02-15 15:03:27 +08001459 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1460 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1461 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001462}
Luke Huang531f5d32018-08-03 15:19:05 +08001463
1464namespace {
1465
1466constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1467constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1468constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1469constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1470constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001471constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001472
Luke Huang19b49c52018-10-22 12:12:05 +09001473// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1474// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001475bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1476 const char* chainName, const std::string& expectedTargetA,
1477 const std::string& expectedTargetB) {
1478 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1479 int matchCount = 0;
1480
1481 for (const auto& rule : rules) {
1482 if (rule.find(expectedTargetA) != std::string::npos) {
1483 if (rule.find(expectedTargetB) != std::string::npos) {
1484 matchCount++;
1485 }
1486 }
1487 }
1488 return matchCount == expectedCount;
1489}
1490
1491void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1492 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1493 std::string result = "";
1494
1495 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001496 // Quota value might be decreased while matching packets
1497 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001498}
1499
1500void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1501 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1502 std::string quotaRule = StringPrintf("quota %s", ifname);
1503
1504 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1505 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1506 BANDWIDTH_COSTLY_IF));
1507 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1508 BANDWIDTH_COSTLY_IF));
1509 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1510 BANDWIDTH_COSTLY_IF));
1511 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1512 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1513 }
1514 expectXtQuotaValueEqual(ifname, quotaBytes);
1515}
1516
1517void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1518 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1519 std::string quotaRule = StringPrintf("quota %s", ifname);
1520
1521 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1522 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1523 BANDWIDTH_COSTLY_IF));
1524 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1525 BANDWIDTH_COSTLY_IF));
1526 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1527 BANDWIDTH_COSTLY_IF));
1528 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1529 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1530 }
1531}
1532
1533void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1534 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1535 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1536 std::string alertName = StringPrintf("%sAlert", ifname);
1537
1538 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1539 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1540 }
1541 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1542}
1543
1544void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1545 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1546 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1547
1548 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1549 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1550 }
1551}
1552
1553void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1554 static const char globalAlertRule[] = "quota globalAlert";
1555 static const char globalAlertName[] = "globalAlert";
1556
1557 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001558 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001559 }
1560 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1561}
1562
1563void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1564 std::string uidRule = StringPrintf("owner UID match %u", uid);
1565
1566 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1567 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1568 }
1569}
1570
1571void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1572 std::string uidRule = StringPrintf("owner UID match %u", uid);
1573
1574 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1575 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1576 }
1577}
1578
1579} // namespace
1580
1581TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1582 long testQuotaBytes = 5550;
1583
1584 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001585 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001586 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1587
1588 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1589 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1590 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1591
1592 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1593 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1594 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1595
1596 // Remove test physical network
1597 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1598}
1599
1600TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1601 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001602 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001603 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001604 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001605 // Need to have a prior interface quota set to set an alert
1606 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1607 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1608 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1609 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1610
1611 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1612 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1613 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1614
1615 // Remove interface quota
1616 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1617 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1618 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1619
1620 // Remove test physical network
1621 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1622}
1623
1624TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001625 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001626
1627 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1628 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1629 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1630
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001631 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001632 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1633 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1634 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1635}
1636
1637TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1638 SKIP_IF_BPF_SUPPORTED;
1639
1640 int32_t uid = randomUid();
1641 static const char targetReject[] = "REJECT";
1642 static const char targetReturn[] = "RETURN";
1643
1644 // add NaughtyApp
1645 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1646 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1647 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1648
1649 // remove NaughtyApp
1650 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1651 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1652 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1653
1654 // add NiceApp
1655 status = mNetd->bandwidthAddNiceApp(uid);
1656 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1657 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1658
1659 // remove NiceApp
1660 status = mNetd->bandwidthRemoveNiceApp(uid);
1661 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1662 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1663}
Luke Huangb5733d72018-08-21 17:17:19 +08001664
1665namespace {
1666
Luke Huangb670d162018-08-23 20:01:13 +08001667std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1668 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1669 return runCommand(command);
1670}
1671
Luke Huangc3252cc2018-10-16 15:43:23 +08001672bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001673 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1674 for (const auto& route : routes) {
1675 if (route.find(ipRoute) != std::string::npos) {
1676 return true;
1677 }
1678 }
1679 return false;
1680}
1681
Luke Huangc3252cc2018-10-16 15:43:23 +08001682std::string ipRouteString(const std::string& ifName, const std::string& dst,
1683 const std::string& nextHop) {
1684 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1685
1686 if (!nextHop.empty()) {
1687 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001688 }
1689
Luke Huangc3252cc2018-10-16 15:43:23 +08001690 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001691}
1692
Luke Huangc3252cc2018-10-16 15:43:23 +08001693void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1694 const std::string& dst, const std::string& nextHop,
1695 const char* table) {
1696 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1697}
1698
1699void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001700 const std::string& dst, const std::string& nextHop,
1701 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001702 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001703}
1704
1705bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1706 std::vector<std::string> rules = listIpRules(ipVersion);
1707 for (const auto& rule : rules) {
1708 if (rule.find(ipRule) != std::string::npos) {
1709 return true;
1710 }
1711 }
1712 return false;
1713}
1714
1715void expectNetworkDefaultIpRuleExists(const char* ifName) {
1716 std::string networkDefaultRule =
1717 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1718
1719 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1720 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1721 }
1722}
1723
1724void expectNetworkDefaultIpRuleDoesNotExist() {
1725 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1726
1727 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1728 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1729 }
1730}
1731
1732void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1733 std::string networkPermissionRule = "";
1734 switch (permission) {
1735 case INetd::PERMISSION_NONE:
1736 networkPermissionRule = StringPrintf(
1737 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1738 break;
1739 case INetd::PERMISSION_NETWORK:
1740 networkPermissionRule = StringPrintf(
1741 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1742 break;
1743 case INetd::PERMISSION_SYSTEM:
1744 networkPermissionRule = StringPrintf(
1745 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1746 break;
1747 }
1748
1749 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1750 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1751 }
1752}
1753
1754// TODO: It is a duplicate function, need to remove it
1755bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1756 const std::string& expectedInterface,
1757 const std::string& expectedRule,
1758 const char* table) {
1759 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1760 for (const auto& rule : rules) {
1761 if (rule.find(expectedInterface) != std::string::npos) {
1762 if (rule.find(expectedRule) != std::string::npos) {
1763 return true;
1764 }
1765 }
1766 }
1767 return false;
1768}
1769
1770void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1771 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1772 std::string networkIncomingPacketMarkRule = "";
1773 switch (permission) {
1774 case INetd::PERMISSION_NONE:
1775 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1776 break;
1777 case INetd::PERMISSION_NETWORK:
1778 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1779 break;
1780 case INetd::PERMISSION_SYSTEM:
1781 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1782 break;
1783 }
1784
1785 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1786 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1787 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1788 }
1789}
1790
1791} // namespace
1792
1793TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001794 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001795 const char* ipVersion;
1796 const char* testDest;
1797 const char* testNextHop;
1798 const bool expectSuccess;
1799 } kTestData[] = {
1800 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001801 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1802 {IP_RULE_V4, "10.251.0.0/16", "", true},
1803 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1804 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001805 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001806 {IP_RULE_V6, "::/0", "2001:db8::", true},
1807 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001808 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1809 };
1810
Luke Huangc3252cc2018-10-16 15:43:23 +08001811 static const struct {
1812 const char* ipVersion;
1813 const char* testDest;
1814 const char* testNextHop;
1815 } kTestDataWithNextHop[] = {
1816 {IP_RULE_V4, "10.251.10.0/30", ""},
1817 {IP_RULE_V6, "2001:db8::/32", ""},
1818 };
1819
Luke Huangb670d162018-08-23 20:01:13 +08001820 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001821 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001822 const int testUid = randomUid();
1823 const std::vector<int32_t> testUids = {testUid};
1824
1825 // Add test physical network
1826 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1827 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1828
Luke Huangc3252cc2018-10-16 15:43:23 +08001829 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001830 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001831 const auto& td = kTestDataWithNextHop[i];
1832
1833 // All route for test tun will disappear once the tun interface is deleted.
1834 binder::Status status =
1835 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1836 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1837 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1838 sTun.name().c_str());
1839
1840 // Add system permission for test uid, setup route in legacy system table.
1841 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1842
1843 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1844 testUid);
1845 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1846 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1847 testTableLegacySystem);
1848
1849 // Remove system permission for test uid, setup route in legacy network table.
1850 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1851
1852 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1853 testUid);
1854 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1855 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1856 testTableLegacyNetwork);
1857 }
1858
Sehee Park8659b8d2018-11-16 10:53:16 +09001859 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001860 const auto& td = kTestData[i];
1861
1862 binder::Status status =
1863 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1864 if (td.expectSuccess) {
1865 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001866 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001867 sTun.name().c_str());
1868 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001869 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1870 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001871 }
1872
1873 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1874 if (td.expectSuccess) {
1875 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001876 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1877 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001878 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001879 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1880 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001881 }
1882
Luke Huangc3252cc2018-10-16 15:43:23 +08001883 // Add system permission for test uid, route will be added into legacy system table.
1884 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001885
1886 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1887 testUid);
1888 if (td.expectSuccess) {
1889 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001890 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001891 testTableLegacySystem);
1892 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001893 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1894 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001895 }
1896
1897 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1898 td.testNextHop, testUid);
1899 if (td.expectSuccess) {
1900 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001901 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1902 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001903 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001904 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1905 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001906 }
1907
Luke Huangc3252cc2018-10-16 15:43:23 +08001908 // Remove system permission for test uid, route will be added into legacy network table.
1909 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1910
1911 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1912 testUid);
1913 if (td.expectSuccess) {
1914 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1915 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1916 testTableLegacyNetwork);
1917 } else {
1918 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1919 EXPECT_NE(0, status.serviceSpecificErrorCode());
1920 }
1921
1922 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1923 td.testNextHop, testUid);
1924 if (td.expectSuccess) {
1925 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1926 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1927 testTableLegacyNetwork);
1928 } else {
1929 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1930 EXPECT_NE(0, status.serviceSpecificErrorCode());
1931 }
Luke Huangb670d162018-08-23 20:01:13 +08001932 }
1933
1934 // Remove test physical network
1935 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1936}
1937
Luke Huang33a92792019-05-28 16:59:25 +08001938namespace {
1939
1940constexpr char CUTTLEFISH_PRODUCT_DEVICE[] = "vsoc_x86";
1941constexpr char CUTTLEFISH_SYSTEM_NAME[] = "cf_x86_phone";
1942
1943bool isCuttleFish() {
1944 static const std::string sProductDevice = android::base::GetProperty("ro.product.device", "");
1945 static const std::string sSystemName = android::base::GetProperty("ro.product.system.name", "");
1946 return (sProductDevice.find(CUTTLEFISH_PRODUCT_DEVICE) != std::string::npos) &&
1947 (sSystemName.find(CUTTLEFISH_SYSTEM_NAME) != std::string::npos);
1948}
1949
1950} // namespace
1951
Luke Huangb670d162018-08-23 20:01:13 +08001952TEST_F(BinderTest, NetworkPermissionDefault) {
Luke Huang33a92792019-05-28 16:59:25 +08001953 SKIP_IF_CUTTLEFISH;
1954
Luke Huangb670d162018-08-23 20:01:13 +08001955 // Add test physical network
1956 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1957 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1958
Luke Huangc3252cc2018-10-16 15:43:23 +08001959 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001960 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1961 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001962
1963 // Test SetDefault
1964 status = mNetd->networkSetDefault(TEST_NETID1);
1965 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1966 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1967
1968 status = mNetd->networkClearDefault();
1969 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1970 expectNetworkDefaultIpRuleDoesNotExist();
1971
Luke Huangd2861982019-05-17 19:47:28 +08001972 // Set default network back
1973 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001974 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1975
1976 // Test SetPermission
1977 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1978 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1979 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1980 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1981
1982 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1983 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1985 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1986
1987 // Remove test physical network
1988 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1989}
1990
1991TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001992 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001993 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1994 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001995 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001996 EXPECT_TRUE(ret);
1997
Luke Huang854e2992019-05-29 16:42:48 +08001998 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001999 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08002000
2001 // Clear uid permission before calling networkCanProtect to ensure
2002 // the call won't be affected by uid permission.
2003 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2004
2005 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002006 EXPECT_FALSE(ret);
2007}
2008
2009namespace {
2010
Luke Huangb5733d72018-08-21 17:17:19 +08002011int readIntFromPath(const std::string& path) {
2012 std::string result = "";
2013 EXPECT_TRUE(ReadFileToString(path, &result));
2014 return std::stoi(result);
2015}
2016
2017int getTetherAcceptIPv6Ra(const std::string& ifName) {
2018 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2019 return readIntFromPath(path);
2020}
2021
2022bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2023 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2024 return readIntFromPath(path);
2025}
2026
2027int getTetherIPv6DadTransmits(const std::string& ifName) {
2028 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2029 return readIntFromPath(path);
2030}
2031
2032bool getTetherEnableIPv6(const std::string& ifName) {
2033 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2034 int disableIPv6 = readIntFromPath(path);
2035 return !disableIPv6;
2036}
2037
2038bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2039 for (const auto& iface : ifList) {
2040 if (iface == ifName) {
2041 return true;
2042 }
2043 }
2044 return false;
2045}
2046
2047void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2048 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2049 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2050 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2051 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2052}
2053
2054void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2055 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2056 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2057 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2058 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2059}
2060
2061void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2062 const std::string& ifName) {
2063 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2064}
2065
2066void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2067 const std::string& ifName) {
2068 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2069}
2070
2071void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2072 const std::vector<std::string>& testDnsAddrs) {
2073 EXPECT_TRUE(dnsList == testDnsAddrs);
2074}
2075
2076} // namespace
2077
2078TEST_F(BinderTest, TetherStartStopStatus) {
2079 std::vector<std::string> noDhcpRange = {};
2080 static const char dnsdName[] = "dnsmasq";
2081
2082 binder::Status status = mNetd->tetherStart(noDhcpRange);
2083 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002084 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002085
2086 bool tetherEnabled;
2087 status = mNetd->tetherIsEnabled(&tetherEnabled);
2088 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2089 EXPECT_TRUE(tetherEnabled);
2090
2091 status = mNetd->tetherStop();
2092 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002093 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002094
2095 status = mNetd->tetherIsEnabled(&tetherEnabled);
2096 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2097 EXPECT_FALSE(tetherEnabled);
2098}
2099
2100TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2101 // TODO: verify if dnsmasq update interface successfully
2102
2103 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2104 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2105 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2106
2107 std::vector<std::string> ifList;
2108 status = mNetd->tetherInterfaceList(&ifList);
2109 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2110 expectTetherInterfaceExists(ifList, sTun.name());
2111
2112 status = mNetd->tetherInterfaceRemove(sTun.name());
2113 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2114 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2115
2116 status = mNetd->tetherInterfaceList(&ifList);
2117 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2118 expectTetherInterfaceNotExists(ifList, sTun.name());
2119}
2120
2121TEST_F(BinderTest, TetherDnsSetList) {
2122 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002123 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2124 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002125
2126 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2127 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2128
2129 std::vector<std::string> dnsList;
2130 status = mNetd->tetherDnsList(&dnsList);
2131 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2132 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002133}
2134
2135namespace {
2136
2137constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2138constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2139constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2140constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2141constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2142constexpr char FIREWALL_STANDBY[] = "fw_standby";
2143constexpr char targetReturn[] = "RETURN";
2144constexpr char targetDrop[] = "DROP";
2145
2146void expectFirewallWhitelistMode() {
2147 static const char dropRule[] = "DROP all";
2148 static const char rejectRule[] = "REJECT all";
2149 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2150 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2151 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2152 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2153 }
2154}
2155
2156void expectFirewallBlacklistMode() {
2157 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2158 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2159 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2160 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2161 }
2162}
2163
2164bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2165 const std::string& expectedInterface,
2166 const std::string& expectedRule) {
2167 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2168 // Expected rule:
2169 // Chain fw_INPUT (1 references)
2170 // pkts bytes target prot opt in out source destination
2171 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2172 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2173 int firstRuleIndex = 2;
2174 if (rules.size() < 4) return false;
2175 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2176 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2177 return true;
2178 }
2179 }
2180 return false;
2181}
2182
2183// TODO: It is a duplicate function, need to remove it
2184bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2185 const std::string& expectedInterface,
2186 const std::string& expectedRule) {
2187 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2188 for (const auto& rule : rules) {
2189 if (rule.find(expectedInterface) != std::string::npos) {
2190 if (rule.find(expectedRule) != std::string::npos) {
2191 return true;
2192 }
2193 }
2194 }
2195 return false;
2196}
2197
2198void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2199 static const char returnRule[] = "RETURN all";
2200 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2201 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2202 returnRule));
2203 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2204 returnRule));
2205 }
2206}
2207
2208void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2209 static const char returnRule[] = "RETURN all";
2210 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2211 EXPECT_FALSE(
2212 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2213 EXPECT_FALSE(
2214 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2215 }
2216}
2217
2218bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2219 const std::string& expectedTarget,
2220 const std::string& expectedRule) {
2221 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2222 int firstRuleIndex = 2;
2223 if (rules.size() < 4) return false;
2224 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2225 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2226 return true;
2227 }
2228 }
2229 return false;
2230}
2231
2232bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2233 const std::string& expectedTarget,
2234 const std::string& expectedRule) {
2235 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2236 int lastRuleIndex = rules.size() - 1;
2237 if (lastRuleIndex < 0) return false;
2238 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2239 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2240 return true;
2241 }
2242 }
2243 return false;
2244}
2245
2246void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2247 std::string uidRule = StringPrintf("owner UID match %u", uid);
2248 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2249 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2250}
2251
2252void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2253 std::string uidRule = StringPrintf("owner UID match %u", uid);
2254 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2255 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2256}
2257
2258void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2259 std::string uidRule = StringPrintf("owner UID match %u", uid);
2260 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2261 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2262}
2263
2264void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2265 std::string uidRule = StringPrintf("owner UID match %u", uid);
2266 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2267 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2268}
2269
2270bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2271 std::vector<std::string> inputRules =
2272 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2273 std::vector<std::string> outputRules =
2274 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2275 int inputLastRuleIndex = inputRules.size() - 1;
2276 int outputLastRuleIndex = outputRules.size() - 1;
2277
2278 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2279 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2280 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2281 return true;
2282 }
2283 }
2284 return false;
2285}
2286
2287void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2288 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2289 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2290}
2291
2292void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2293 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2294 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2295 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2296 }
2297}
2298
2299} // namespace
2300
2301TEST_F(BinderTest, FirewallSetFirewallType) {
2302 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2303 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2304 expectFirewallWhitelistMode();
2305
2306 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2307 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2308 expectFirewallBlacklistMode();
2309
2310 // set firewall type blacklist twice
2311 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2312 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2313 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2314 expectFirewallBlacklistMode();
2315
2316 // set firewall type whitelist twice
2317 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2318 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2319 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2320 expectFirewallWhitelistMode();
2321
2322 // reset firewall type to default
2323 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFirewallBlacklistMode();
2326}
2327
2328TEST_F(BinderTest, FirewallSetInterfaceRule) {
2329 // setinterfaceRule is not supported in BLACKLIST MODE
2330 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2331 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2332
2333 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2334 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2335
2336 // set WHITELIST mode first
2337 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2338 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2339
2340 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2341 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2342 expectFirewallInterfaceRuleAllowExists(sTun.name());
2343
2344 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2345 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2346 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2347
2348 // reset firewall mode to default
2349 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectFirewallBlacklistMode();
2352}
2353
2354TEST_F(BinderTest, FirewallSetUidRule) {
2355 SKIP_IF_BPF_SUPPORTED;
2356
2357 int32_t uid = randomUid();
2358
2359 // Doze allow
2360 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2361 INetd::FIREWALL_RULE_ALLOW);
2362 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2363 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2364
2365 // Doze deny
2366 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2367 INetd::FIREWALL_RULE_DENY);
2368 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2369 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2370
2371 // Powersave allow
2372 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2373 INetd::FIREWALL_RULE_ALLOW);
2374 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2375 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2376
2377 // Powersave deny
2378 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2379 INetd::FIREWALL_RULE_DENY);
2380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2381 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2382
2383 // Standby deny
2384 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2385 INetd::FIREWALL_RULE_DENY);
2386 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2387 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2388
2389 // Standby allow
2390 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2391 INetd::FIREWALL_RULE_ALLOW);
2392 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2393 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2394
2395 // None deny in BLACKLIST
2396 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2397 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2398 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2399 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2400
2401 // None allow in BLACKLIST
2402 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2403 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2404 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2405 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2406
2407 // set firewall type whitelist twice
2408 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2409 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2410 expectFirewallWhitelistMode();
2411
2412 // None allow in WHITELIST
2413 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2414 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2415 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2416 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2417
2418 // None deny in WHITELIST
2419 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2420 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2421 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2422 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2423
2424 // reset firewall mode to default
2425 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2426 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2427 expectFirewallBlacklistMode();
2428}
2429
2430TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2431 SKIP_IF_BPF_SUPPORTED;
2432
2433 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2434 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2435 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2436
2437 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2438 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2439 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2440
2441 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2442 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2443 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2444
2445 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2446 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2447 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2448
2449 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2450 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2451 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2452
2453 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2454 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2455 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2456}
Luke Huangf7782042018-08-08 13:13:04 +08002457
2458namespace {
2459
2460std::string hwAddrToStr(unsigned char* hwaddr) {
2461 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2462 hwaddr[4], hwaddr[5]);
2463}
2464
2465int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2466 int prefixLength = 0;
2467 uint32_t m = ntohl(mask);
2468 while (m & (1 << 31)) {
2469 prefixLength++;
2470 m = m << 1;
2471 }
2472 return prefixLength;
2473}
2474
2475std::string toStdString(const String16& s) {
2476 return std::string(String8(s.string()));
2477}
2478
2479android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2480 const auto& sys = sSyscalls.get();
2481 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2482 EXPECT_TRUE(isOk(fd.status()));
2483
2484 struct ifreq ifr = {};
2485 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2486
2487 return sys.ioctl(fd.value(), flag, &ifr);
2488}
2489
2490std::string getInterfaceHwAddr(const std::string& ifName) {
2491 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2492
2493 unsigned char hwaddr[ETH_ALEN] = {};
2494 if (isOk(res.status())) {
2495 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2496 }
2497
2498 return hwAddrToStr(hwaddr);
2499}
2500
2501int getInterfaceIPv4Prefix(const std::string& ifName) {
2502 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2503
2504 int prefixLength = 0;
2505 if (isOk(res.status())) {
2506 prefixLength = ipv4NetmaskToPrefixLength(
2507 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2508 }
2509
2510 return prefixLength;
2511}
2512
2513std::string getInterfaceIPv4Addr(const std::string& ifName) {
2514 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2515
2516 struct in_addr addr = {};
2517 if (isOk(res.status())) {
2518 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2519 }
2520
2521 return std::string(inet_ntoa(addr));
2522}
2523
2524std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2525 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2526
2527 unsigned flags = 0;
2528 if (isOk(res.status())) {
2529 flags = res.value().ifr_flags;
2530 }
2531
2532 std::vector<std::string> ifFlags;
2533 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2534 : toStdString(INetd::IF_STATE_DOWN()));
2535
2536 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2537 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2538 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2539 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2540 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2541
2542 return ifFlags;
2543}
2544
2545bool compareListInterface(const std::vector<std::string>& interfaceList) {
2546 const auto& res = InterfaceController::getIfaceNames();
2547 EXPECT_TRUE(isOk(res));
2548
2549 std::vector<std::string> resIfList;
2550 resIfList.reserve(res.value().size());
2551 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2552
2553 return resIfList == interfaceList;
2554}
2555
2556int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2557 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2558 return readIntFromPath(path);
2559}
2560
2561bool getInterfaceEnableIPv6(const std::string& ifName) {
2562 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2563
2564 int disableIPv6 = readIntFromPath(path);
2565 return !disableIPv6;
2566}
2567
2568int getInterfaceMtu(const std::string& ifName) {
2569 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2570 return readIntFromPath(path);
2571}
2572
2573void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2574 EXPECT_TRUE(compareListInterface(interfaceList));
2575}
2576
2577void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2578 const InterfaceConfigurationParcel& interfaceCfg) {
2579 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2580 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2581 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2582 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2583}
2584
2585void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2586 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2587 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2588
2589 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2590 for (const auto& flag : setCfg.flags) {
2591 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2592 }
2593}
2594
2595void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2596 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2597 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2598}
2599
2600void expectInterfaceNoAddr(const std::string& ifName) {
2601 // noAddr
2602 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2603 // noPrefix
2604 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2605}
2606
2607void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2608 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2609 EXPECT_EQ(enableIPv6, enable);
2610}
2611
2612void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2613 int mtuSize = getInterfaceMtu(ifName);
2614 EXPECT_EQ(mtu, mtuSize);
2615}
2616
2617InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2618 const std::string& addr, int prefixLength,
2619 const std::vector<std::string>& flags) {
2620 InterfaceConfigurationParcel cfg;
2621 cfg.ifName = ifName;
2622 cfg.hwAddr = "";
2623 cfg.ipv4Addr = addr;
2624 cfg.prefixLength = prefixLength;
2625 cfg.flags = flags;
2626 return cfg;
2627}
2628
2629void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2630 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2631 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2632
2633 for (const auto& flag : expectedFlags) {
2634 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2635 interfaceCfg.flags.end());
2636 }
2637
2638 for (const auto& flag : unexpectedFlags) {
2639 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2640 interfaceCfg.flags.end());
2641 }
2642}
2643
2644} // namespace
2645
2646TEST_F(BinderTest, InterfaceList) {
2647 std::vector<std::string> interfaceListResult;
2648
2649 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2650 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2651 expectInterfaceList(interfaceListResult);
2652}
2653
2654TEST_F(BinderTest, InterfaceGetCfg) {
2655 InterfaceConfigurationParcel interfaceCfgResult;
2656
2657 // Add test physical network
2658 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2659 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2660
2661 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2662 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2663 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2664 expectTunFlags(interfaceCfgResult);
2665
2666 // Remove test physical network
2667 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2668}
2669
2670TEST_F(BinderTest, InterfaceSetCfg) {
2671 const std::string testAddr = "192.0.2.3";
2672 const int testPrefixLength = 24;
2673 std::vector<std::string> upFlags = {"up"};
2674 std::vector<std::string> downFlags = {"down"};
2675
2676 // Add test physical network
2677 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2678 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2679
2680 // Set tun interface down.
2681 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2682 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2683 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2684 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2685
2686 // Set tun interface up again.
2687 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2688 status = mNetd->interfaceSetCfg(interfaceCfg);
2689 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2690 status = mNetd->interfaceClearAddrs(sTun.name());
2691 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2692
2693 // Remove test physical network
2694 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2695}
2696
2697TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2698 // enable
2699 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2700 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2701 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2702
2703 // disable
2704 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2705 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2706 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2707}
2708
2709TEST_F(BinderTest, InterfaceClearAddr) {
2710 const std::string testAddr = "192.0.2.3";
2711 const int testPrefixLength = 24;
2712 std::vector<std::string> noFlags{};
2713
2714 // Add test physical network
2715 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2716 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2717
2718 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2719 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2720 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2721 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2722
2723 status = mNetd->interfaceClearAddrs(sTun.name());
2724 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2725 expectInterfaceNoAddr(sTun.name());
2726
2727 // Remove test physical network
2728 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2729}
2730
2731TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2732 // Add test physical network
2733 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2734 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2735
2736 // disable
2737 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2738 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2739 expectInterfaceEnableIPv6(sTun.name(), false);
2740
2741 // enable
2742 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2743 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2744 expectInterfaceEnableIPv6(sTun.name(), true);
2745
2746 // Remove test physical network
2747 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2748}
2749
2750TEST_F(BinderTest, InterfaceSetMtu) {
2751 const int testMtu = 1200;
2752
2753 // Add test physical network
2754 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2755 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2756
2757 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2758 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2759 expectInterfaceMtu(sTun.name(), testMtu);
2760
2761 // Remove test physical network
2762 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2763}
Luke Huang19b49c52018-10-22 12:12:05 +09002764
2765namespace {
2766
2767constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2768constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002769constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002770constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2771
Luke Huangae038f82018-11-05 11:17:31 +09002772int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002773 return listIptablesRuleByTable(binary, table, chainName).size();
2774}
2775
2776bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2777 const std::vector<std::string>& targetVec) {
2778 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2779 if (targetVec.size() != rules.size() - 2) {
2780 return false;
2781 }
2782
2783 /*
Luke Huangae038f82018-11-05 11:17:31 +09002784 * Check that the rules match. Note that this function matches substrings, not entire rules,
2785 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002786 * Skip first two lines since rules start from third line.
2787 * Chain chainName (x references)
2788 * pkts bytes target prot opt in out source destination
2789 * ...
2790 */
2791 int rIndex = 2;
2792 for (const auto& target : targetVec) {
2793 if (rules[rIndex].find(target) == std::string::npos) {
2794 return false;
2795 }
2796 rIndex++;
2797 }
2798 return true;
2799}
2800
2801void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2802 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2803 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2804 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002805 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002806 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2807 "DROP"};
2808
2809 // V4
2810 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2811 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002812 EXPECT_TRUE(
2813 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002814 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2815
Luke Huangae038f82018-11-05 11:17:31 +09002816 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002817 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2818
2819 // V6
2820 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002821 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2822 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002823
2824 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2825 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2826 extIf));
2827 }
2828}
2829
2830void expectNatDisable() {
2831 // It is the default DROP rule with tethering disable.
2832 // Chain tetherctrl_FORWARD (1 references)
2833 // pkts bytes target prot opt in out source destination
2834 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2835 std::vector<std::string> forwardV4Match = {"DROP"};
2836 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2837
2838 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002839 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2840 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002841
Luke Huangae038f82018-11-05 11:17:31 +09002842 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2843 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002844
2845 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2846}
2847
2848} // namespace
2849
2850TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002851 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2852 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2853 expectNatEnable(sTun.name(), sTun2.name());
2854
2855 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2856 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2857 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002858}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002859
2860namespace {
2861
2862using TripleInt = std::array<int, 3>;
2863
2864TripleInt readProcFileToTripleInt(const std::string& path) {
2865 std::string valueString;
2866 int min, def, max;
2867 EXPECT_TRUE(ReadFileToString(path, &valueString));
2868 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2869 return {min, def, max};
2870}
2871
2872void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2873 std::string testRmemValues =
2874 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2875 std::string testWmemValues =
2876 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2877 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2878
2879 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2880 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2881
2882 for (int i = 0; i < 3; i++) {
2883 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2884 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2885 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2886 }
2887}
2888
2889} // namespace
2890
2891TEST_F(BinderTest, TcpBufferSet) {
2892 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2893 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2894 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2895 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2896
2897 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2898 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2899}
Luke Huang528af602018-08-29 19:06:05 +08002900
Chenbo Feng48eaed32018-12-26 17:40:21 -08002901namespace {
2902
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002903void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002904 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2905 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2906 for (int32_t uid : uids) {
2907 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2908 if (exist) {
2909 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002910 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002911 } else {
2912 EXPECT_FALSE(isOk(permission));
2913 EXPECT_EQ(ENOENT, permission.status().code());
2914 }
2915 }
2916}
2917
2918} // namespace
2919
2920TEST_F(BinderTest, TestInternetPermission) {
2921 SKIP_IF_BPF_NOT_SUPPORTED;
2922
2923 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2924
2925 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002926 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002927 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002928 checkUidsInPermissionMap(appUids, true);
2929 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2930 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002931}
2932
Luke Huang528af602018-08-29 19:06:05 +08002933TEST_F(BinderTest, UnsolEvents) {
2934 auto testUnsolService = android::net::TestUnsolService::start();
2935 std::string oldTunName = sTun.name();
2936 std::string newTunName = "unsolTest";
2937 testUnsolService->tarVec.push_back(oldTunName);
2938 testUnsolService->tarVec.push_back(newTunName);
2939 auto& cv = testUnsolService->getCv();
2940 auto& cvMutex = testUnsolService->getCvMutex();
2941 binder::Status status = mNetd->registerUnsolicitedEventListener(
2942 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2943 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2944
2945 // TODO: Add test for below events
2946 // StrictCleartextDetected / InterfaceDnsServersAdded
2947 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2948
2949 {
2950 std::unique_lock lock(cvMutex);
2951
2952 // Re-init test Tun, and we expect that we will get some unsol events.
2953 // Use the test Tun device name to verify if we receive its unsol events.
2954 sTun.destroy();
2955 // Use predefined name
2956 sTun.init(newTunName);
2957
2958 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2959 }
2960
2961 // bit mask 1101101000
2962 // Test only covers below events currently
2963 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2964 InterfaceLinkStatusChanged | RouteChanged;
2965 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002966
2967 // Re-init sTun to clear predefined name
2968 sTun.destroy();
2969 sTun.init();
2970}
2971
2972TEST_F(BinderTest, NDC) {
2973 struct Command {
2974 const std::string cmdString;
2975 const std::string expectedResult;
2976 };
2977
2978 // clang-format off
2979 // Do not change the commands order
2980 const Command networkCmds[] = {
2981 {StringPrintf("ndc network create %d", TEST_NETID1),
2982 "200 0 success"},
2983 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2984 "200 0 success"},
2985 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2986 "200 0 success"},
2987 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2988 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2989 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2990 "200 0 success"},
2991 };
2992
2993 const std::vector<Command> ipfwdCmds = {
2994 {"ndc ipfwd enable " + sTun.name(),
2995 "200 0 ipfwd operation succeeded"},
2996 {"ndc ipfwd disable " + sTun.name(),
2997 "200 0 ipfwd operation succeeded"},
2998 {"ndc ipfwd add lo2 lo3",
2999 "400 0 ipfwd operation failed (No such process)"},
3000 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3001 "200 0 ipfwd operation succeeded"},
3002 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3003 "200 0 ipfwd operation succeeded"},
3004 };
3005
3006 static const struct {
3007 const char* ipVersion;
3008 const char* testDest;
3009 const char* testNextHop;
3010 const bool expectSuccess;
3011 const std::string expectedResult;
3012 } kTestData[] = {
3013 {IP_RULE_V4, "0.0.0.0/0", "", true,
3014 "200 0 success"},
3015 {IP_RULE_V4, "10.251.0.0/16", "", true,
3016 "200 0 success"},
3017 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3018 "400 0 addRoute() failed (Invalid argument)",},
3019 {IP_RULE_V6, "::/0", "", true,
3020 "200 0 success"},
3021 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3022 "200 0 success"},
3023 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3024 "400 0 addRoute() failed (Invalid argument)"},
3025 };
3026 // clang-format on
3027
3028 for (const auto& cmd : networkCmds) {
3029 const std::vector<std::string> result = runCommand(cmd.cmdString);
3030 SCOPED_TRACE(cmd.cmdString);
3031 EXPECT_EQ(result.size(), 1U);
3032 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3033 }
3034
3035 for (const auto& cmd : ipfwdCmds) {
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 // Add test physical network
3043 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3044 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3045
3046 for (const auto& td : kTestData) {
3047 const std::string routeAddCmd =
3048 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3049 td.testDest, td.testNextHop);
3050 const std::string routeRemoveCmd =
3051 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3052 sTun.name().c_str(), td.testDest, td.testNextHop);
3053 std::vector<std::string> result = runCommand(routeAddCmd);
3054 SCOPED_TRACE(routeAddCmd);
3055 EXPECT_EQ(result.size(), 1U);
3056 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3057 if (td.expectSuccess) {
3058 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3059 sTun.name().c_str());
3060 result = runCommand(routeRemoveCmd);
3061 EXPECT_EQ(result.size(), 1U);
3062 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3063 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3064 sTun.name().c_str());
3065 }
3066 }
3067 // Remove test physical network
3068 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003069}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003070
Luke Huang2ff8b342019-04-30 15:33:33 +08003071TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003072 sp<IBinder> binder;
3073 binder::Status status = mNetd->getOemNetd(&binder);
3074 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3075 sp<com::android::internal::net::IOemNetd> oemNetd;
3076 if (binder != nullptr) {
3077 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3078 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003079 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003080
3081 TimedOperation t("OemNetd isAlive RPC");
3082 bool isAlive = false;
3083 oemNetd->isAlive(&isAlive);
3084 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003085
3086 class TestOemUnsolListener
3087 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3088 public:
3089 android::binder::Status onRegistered() override {
3090 std::lock_guard lock(mCvMutex);
3091 mCv.notify_one();
3092 return android::binder::Status::ok();
3093 }
3094 std::condition_variable& getCv() { return mCv; }
3095 std::mutex& getCvMutex() { return mCvMutex; }
3096
3097 private:
3098 std::mutex mCvMutex;
3099 std::condition_variable mCv;
3100 };
3101
3102 // Start the Binder thread pool.
3103 android::ProcessState::self()->startThreadPool();
3104
3105 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3106
3107 auto& cv = testListener->getCv();
3108 auto& cvMutex = testListener->getCvMutex();
3109
3110 {
3111 std::unique_lock lock(cvMutex);
3112
3113 status = oemNetd->registerOemUnsolicitedEventListener(
3114 ::android::interface_cast<
3115 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3116 testListener));
3117 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3118
3119 // Wait for receiving expected events.
3120 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3121 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003122}
Luke Huangd2861982019-05-17 19:47:28 +08003123
3124void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3125 int fallthroughNetId) {
3126 // Re-init sTun* to ensure route rule exists.
3127 sTun.destroy();
3128 sTun.init();
3129 sTun2.destroy();
3130 sTun2.init();
3131
3132 // Create physical network with fallthroughNetId but not set it as default network
3133 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3134 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3135
3136 // Create VPN with vpnNetId
3137 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3138
3139 // Add uid to VPN
3140 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3141 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3142
3143 // Add default route to fallthroughNetwork
3144 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3145 // Add limited route
3146 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3147}
3148
3149namespace {
3150
3151class ScopedUidChange {
3152 public:
3153 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3154 mStoredUid = getuid();
3155 if (mInputUid == mStoredUid) return;
3156 EXPECT_TRUE(seteuid(uid) == 0);
3157 }
3158 ~ScopedUidChange() {
3159 if (mInputUid == mStoredUid) return;
3160 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3161 }
3162
3163 private:
3164 uid_t mInputUid;
3165 uid_t mStoredUid;
3166};
3167
3168constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3169
3170void clearQueue(int tunFd) {
3171 char buf[4096];
3172 int ret;
3173 do {
3174 ret = read(tunFd, buf, sizeof(buf));
3175 } while (ret > 0);
3176}
3177
3178void checkDataReceived(int udpSocket, int tunFd) {
3179 char buf[4096] = {};
3180 // Clear tunFd's queue before write something because there might be some
3181 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3182 clearQueue(tunFd);
3183 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3184 // TODO: extract header and verify data
3185 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3186}
3187
3188bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3189 ScopedUidChange scopedUidChange(uid);
3190 android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3191 if (testSocket < 0) return false;
3192
3193 const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
3194 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3195 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3196 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3197 if (res == -1) return false;
3198
3199 char addr[INET6_ADDRSTRLEN];
3200 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3201 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3202 checkDataReceived(testSocket, tunFd);
3203 return true;
3204}
3205
3206void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3207 std::string vpnFallthroughRule =
3208 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3209 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3210 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3211 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3212 }
3213}
3214
3215void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3216 const TunInterface& fallthroughNetwork,
3217 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3218 int fallthroughNetId = TEST_NETID1) {
3219 // Set default network to NETID_UNSET
3220 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3221
3222 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3223 in6_addr insideVpnAddr = {
3224 {// 2001:db8:cafe::1
3225 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3226 // outsideVpnAddr will hit the route in the fallthrough network route table
3227 // because we added default route in createVpnNetworkWithUid
3228 in6_addr outsideVpnAddr = {
3229 {// 2607:f0d0:1002::4
3230 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3231
3232 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3233 int vpnFd = vpnNetwork.getFdForTesting();
3234 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3235 // default network.
3236 Fwmark fwmark;
3237 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3238 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3239
3240 // Set default network
3241 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3242
3243 // Connections go on the default network because UID 0 is not subject to the VPN.
3244 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3245 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3246 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3247 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3248
3249 // Check if fallthrough rule exists
3250 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3251
3252 // Expect fallthrough to default network
3253 // The fwmark differs depending on whether the VPN is bypassable or not.
3254 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3255 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3256
3257 // Expect connect success, packet will be sent to vpnFd.
3258 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3259 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3260
3261 // Explicitly select vpn network
3262 setNetworkForProcess(vpnNetId);
3263
3264 // Expect fallthrough to default network
3265 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3266 // Expect the mark contains all the bit because we've selected network.
3267 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3268
3269 // Expect connect success, packet will be sent to vpnFd.
3270 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3271 // Expect the mark contains all the bit because we've selected network.
3272 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3273
3274 // Explicitly select fallthrough network
3275 setNetworkForProcess(fallthroughNetId);
3276
3277 // The mark is set to fallthrough network because we've selected it.
3278 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3279 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3280
3281 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3282 if (bypassable) {
3283 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3284 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3285 } else {
3286 // If not, no permission to bypass vpn.
3287 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3288 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3289 }
3290}
3291
3292} // namespace
3293
3294TEST_F(BinderTest, SecureVPNFallthrough) {
3295 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3296 // Get current default network NetId
3297 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3298 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3299}
3300
3301TEST_F(BinderTest, BypassableVPNFallthrough) {
3302 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3303 // Get current default network NetId
3304 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3305 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
3306}