blob: 8dc9e2b867496295d56404194d735eab6f254e36 [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)};
Robin Leeb8087362016-03-30 18:43:08 +0100637
638 const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
639 const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
640
641 // Create two valid rules.
642 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
643 EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
644 EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
645 for (auto const& range : uidRanges) {
646 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
647 }
648
649 // Remove the rules.
650 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
651 EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
652 EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
653 for (auto const& range : uidRanges) {
654 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
655 }
656
657 // Fail to remove the rules a second time after they are already deleted.
658 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
659 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
660 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
661
662 // All rules should be the same as before.
663 EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
664 EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
665}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900666
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900667// Create a socket pair that isLoopbackSocket won't think is local.
668void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
Bernie Innocentif6918262018-06-11 17:37:35 +0900669 *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900670 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900671 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
672
673 socklen_t addrlen = sizeof(server6);
674 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
675 ASSERT_EQ(0, listen(*serverSocket, 10));
676
Bernie Innocentif6918262018-06-11 17:37:35 +0900677 *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900678 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900679 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900680 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
681 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
682
Bernie Innocentif6918262018-06-11 17:37:35 +0900683 *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900684 ASSERT_NE(-1, *acceptedSocket);
685
686 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
687}
688
689void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
690 char buf[4096];
691 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
692 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
693 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
694}
695
696void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
697 // Check that the client socket was closed with ECONNABORTED.
698 int ret = write(clientSocket, "foo", sizeof("foo"));
699 int err = errno;
700 EXPECT_EQ(-1, ret);
701 EXPECT_EQ(ECONNABORTED, err);
702
703 // Check that it sent a RST to the server.
704 ret = write(acceptedSocket, "foo", sizeof("foo"));
705 err = errno;
706 EXPECT_EQ(-1, ret);
707 EXPECT_EQ(ECONNRESET, err);
708}
709
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900710TEST_F(BinderTest, SocketDestroy) {
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900711 int clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900712 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900713
714 // Pick a random UID in the system UID range.
715 constexpr int baseUid = AID_APP - 2000;
716 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
717 int uid = baseUid + 500 + arc4random_uniform(1000);
718 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
719
720 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900721 std::vector<UidRangeParcel> uidRanges = {
722 makeUidRangeParcel(baseUid + 42, baseUid + 449),
723 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
724 makeUidRangeParcel(baseUid + 498, uid - 1),
725 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900726 };
727 // A skip list that doesn't contain UID.
728 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
729
730 // Close sockets. Our test socket should be intact.
731 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
732 checkSocketpairOpen(clientSocket, acceptedSocket);
733
734 // UID ranges that do contain uid.
735 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900736 makeUidRangeParcel(baseUid + 42, baseUid + 449),
737 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
738 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900739 };
740 // Add uid to the skip list.
741 skipUids.push_back(uid);
742
743 // Close sockets. Our test socket should still be intact because it's in the skip list.
744 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
745 checkSocketpairOpen(clientSocket, acceptedSocket);
746
747 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
748 skipUids.resize(skipUids.size() - 1);
749 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
750 checkSocketpairClosed(clientSocket, acceptedSocket);
751
752 close(clientSocket);
753 close(serverSocket);
754 close(acceptedSocket);
755}
Erik Klinecc4f2732016-08-03 11:24:27 +0900756
757namespace {
758
759int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
760 if (buf == nullptr) return -1;
761
762 int prefixLength = 0;
763 bool endOfContiguousBits = false;
764 for (unsigned int i = 0; i < buflen; i++) {
765 const uint8_t value = buf[i];
766
767 // Bad bit sequence: check for a contiguous set of bits from the high
768 // end by verifying that the inverted value + 1 is a power of 2
769 // (power of 2 iff. (v & (v - 1)) == 0).
770 const uint8_t inverse = ~value + 1;
771 if ((inverse & (inverse - 1)) != 0) return -1;
772
773 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
774
775 // Bogus netmask.
776 if (endOfContiguousBits && value != 0) return -1;
777
778 if (value != 0xff) endOfContiguousBits = true;
779 }
780
781 return prefixLength;
782}
783
784template<typename T>
785int netmaskToPrefixLength(const T *p) {
786 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
787}
788
789
790static bool interfaceHasAddress(
791 const std::string &ifname, const char *addrString, int prefixLength) {
792 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900793
794 const struct addrinfo hints = {
795 .ai_flags = AI_NUMERICHOST,
796 .ai_family = AF_UNSPEC,
797 .ai_socktype = SOCK_DGRAM,
798 };
799 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
800 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
801 return false;
802 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900803 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900804
805 struct ifaddrs *ifaddrsList = nullptr;
806 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
807
808 if (getifaddrs(&ifaddrsList) != 0) {
809 return false;
810 }
811
812 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
813 if (std::string(addr->ifa_name) != ifname ||
814 addr->ifa_addr == nullptr ||
815 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
816 continue;
817 }
818
819 switch (addr->ifa_addr->sa_family) {
820 case AF_INET: {
821 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
822 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
823 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
824 continue;
825 }
826
827 if (prefixLength < 0) return true; // not checking prefix lengths
828
829 if (addr->ifa_netmask == nullptr) return false;
830 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
831 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
832 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
833 }
834 case AF_INET6: {
835 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
836 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
837 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
838 continue;
839 }
840
841 if (prefixLength < 0) return true; // not checking prefix lengths
842
843 if (addr->ifa_netmask == nullptr) return false;
844 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
845 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
846 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
847 }
848 default:
849 // Cannot happen because we have already screened for matching
850 // address families at the top of each iteration.
851 continue;
852 }
853 }
854
855 return false;
856}
857
858} // namespace
859
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900860TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900861 static const struct TestData {
862 const char *addrString;
863 const int prefixLength;
864 const bool expectSuccess;
865 } kTestData[] = {
866 { "192.0.2.1", 24, true },
867 { "192.0.2.2", 25, true },
868 { "192.0.2.3", 32, true },
869 { "192.0.2.4", 33, false },
870 { "192.not.an.ip", 24, false },
871 { "2001:db8::1", 64, true },
872 { "2001:db8::2", 65, true },
873 { "2001:db8::3", 128, true },
874 { "2001:db8::4", 129, false },
875 { "foo:bar::bad", 64, false },
876 };
877
Sehee Park8659b8d2018-11-16 10:53:16 +0900878 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900879 const auto &td = kTestData[i];
880
881 // [1.a] Add the address.
882 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900883 sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900884 if (td.expectSuccess) {
885 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
886 } else {
887 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
888 ASSERT_NE(0, status.serviceSpecificErrorCode());
889 }
890
891 // [1.b] Verify the addition meets the expectation.
892 if (td.expectSuccess) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900893 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900894 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900895 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900896 }
897
898 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900899 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Erik Klinecc4f2732016-08-03 11:24:27 +0900900 if (td.expectSuccess) {
901 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
902 } else {
903 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
904 ASSERT_NE(0, status.serviceSpecificErrorCode());
905 }
906
907 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900908 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900909 }
910}
Erik Kline55b06f82016-07-04 09:57:18 +0900911
Erik Kline38e51f12018-09-06 20:14:44 +0900912TEST_F(BinderTest, GetProcSysNet) {
913 const char LOOPBACK[] = "lo";
914 static const struct {
915 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900916 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900917 const char* ifname;
918 const char* parameter;
919 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900920 const int expectedReturnCode;
921 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900922 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
923 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
924 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
925 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
926 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
927 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
928 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900929 };
930
Sehee Park8659b8d2018-11-16 10:53:16 +0900931 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900932 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900933
Erik Kline38e51f12018-09-06 20:14:44 +0900934 std::string value;
935 const binder::Status status =
936 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
937
938 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900939 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900940 EXPECT_EQ(0, status.exceptionCode());
941 EXPECT_EQ(0, status.serviceSpecificErrorCode());
942 EXPECT_EQ(td.expectedValue, value);
943 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900944 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900945 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
946 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
947 }
948 }
949}
950
951TEST_F(BinderTest, SetProcSysNet) {
952 static const struct {
953 const int ipversion;
954 const int which;
955 const char* ifname;
956 const char* parameter;
957 const char* value;
958 const int expectedReturnCode;
959 } kTestData[] = {
960 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
961 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
962 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
963 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
964 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
965 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
966 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
967 };
968
Sehee Park8659b8d2018-11-16 10:53:16 +0900969 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900970 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900971 const binder::Status status =
972 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900973
974 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900975 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900976 EXPECT_EQ(0, status.exceptionCode());
977 EXPECT_EQ(0, status.serviceSpecificErrorCode());
978 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900979 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900980 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
981 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
982 }
983 }
984}
Ben Schwartze7601812017-04-28 16:38:29 -0400985
Erik Kline38e51f12018-09-06 20:14:44 +0900986TEST_F(BinderTest, GetSetProcSysNet) {
987 const int ipversion = INetd::IPV6;
988 const int category = INetd::NEIGH;
989 const std::string& tun = sTun.name();
990 const std::string parameter("ucast_solicit");
991
992 std::string value{};
993 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700994 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900995 const int ival = std::stoi(value);
996 EXPECT_GT(ival, 0);
997 // Try doubling the parameter value (always best!).
998 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
999 .isOk());
1000 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
1001 EXPECT_EQ(2 * ival, std::stoi(value));
1002 // Try resetting the parameter.
1003 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
1004 .isOk());
1005 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
1006 EXPECT_EQ(ival, std::stoi(value));
1007}
1008
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001009namespace {
1010
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001011void expectNoTestCounterRules() {
1012 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
1013 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
1014 std::string allRules = Join(runCommand(command), "\n");
1015 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
1016 }
1017}
1018
Bernie Innocentif6918262018-06-11 17:37:35 +09001019void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
1020 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001021 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
1022 path, if1.c_str(), if2.c_str(), pkt, byte));
1023}
1024
Bernie Innocentif6918262018-06-11 17:37:35 +09001025void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001026 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1027 path, if1.c_str(), if2.c_str()));
1028 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
1029 path, if2.c_str(), if1.c_str()));
1030}
1031
Luke Huangcaebcbb2018-09-27 20:37:14 +08001032std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
1033 const std::string& iface) {
1034 for (auto& stats : statsVec) {
1035 if (stats.iface == iface) {
1036 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1037 }
1038 }
1039 return {};
1040}
1041
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001042} // namespace
1043
1044TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001045 expectNoTestCounterRules();
1046
1047 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1048 // disabling tethering. We don't check the return value because these commands will fail if
1049 // tethering is already enabled.
1050 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1051 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1052
1053 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1054 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1055 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1056 std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1057 std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1058
1059 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1060 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1061 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1062 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1063 // RX is from external to internal, and TX is from internal to external.
1064 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1065 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1066
1067 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1068 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1069
1070 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1071 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1072
1073 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1074 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1075 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1076
Luke Huangcaebcbb2018-09-27 20:37:14 +08001077 std::vector<TetherStatsParcel> statsVec;
1078 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001079 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1080
Luke Huangcaebcbb2018-09-27 20:37:14 +08001081 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001082
Luke Huangcaebcbb2018-09-27 20:37:14 +08001083 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001084
1085 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1086 delTetherCounterValues(path, intIface1, extIface1);
1087 delTetherCounterValues(path, intIface2, extIface2);
1088 if (path == IP6TABLES_PATH) {
1089 delTetherCounterValues(path, intIface3, extIface2);
1090 }
1091 }
1092
1093 expectNoTestCounterRules();
1094}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001095
Luke Huang0051a622018-07-23 20:30:16 +08001096namespace {
1097
Luke Huanga5211072018-08-01 23:36:29 +08001098constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1099constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001100
1101static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1102 const char* chainName) {
1103 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1104 return runCommand(command);
1105}
1106
Luke Huang19b49c52018-10-22 12:12:05 +09001107// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001108bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001109 const std::string& expectedInterface,
1110 const std::string& expectedRule, const char* table) {
1111 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1112 for (const auto& rule : rules) {
1113 if (rule.find(expectedInterface) != std::string::npos) {
1114 if (rule.find(expectedRule) != std::string::npos) {
1115 return true;
1116 }
1117 }
1118 }
1119 return false;
1120}
1121
1122void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001123 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001124 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001125 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001126 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001127 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1128 IdletimerRule, RAW_TABLE));
1129 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001130 ifname, IdletimerRule, MANGLE_TABLE));
1131 }
1132}
1133
1134void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001135 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001136 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001137 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001138 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001139 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1140 IdletimerRule, RAW_TABLE));
1141 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001142 ifname, IdletimerRule, MANGLE_TABLE));
1143 }
1144}
1145
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001146} // namespace
1147
1148TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001149 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1150 // rule in the table. Because we only check the result after calling remove function. We might
1151 // check the actual rule which is removed by our function (maybe compare the results between
1152 // calling function before and after)
1153 binder::Status status;
1154 const struct TestData {
1155 const std::string ifname;
1156 int32_t timeout;
1157 const std::string classLabel;
1158 } idleTestData[] = {
1159 {"wlan0", 1234, "happyday"},
1160 {"rmnet_data0", 4567, "friday"},
1161 };
1162 for (const auto& td : idleTestData) {
1163 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1164 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1165 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1166
1167 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1168 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1169 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1170 }
1171}
1172
Luke Huanga67dd562018-07-17 19:58:25 +08001173namespace {
1174
1175constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1176constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1177
1178void expectStrictSetUidAccept(const int uid) {
1179 std::string uidRule = StringPrintf("owner UID match %u", uid);
1180 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1181 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001182 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1183 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001184 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1185 }
1186}
1187
1188void expectStrictSetUidLog(const int uid) {
1189 static const char logRule[] = "st_penalty_log all";
1190 std::string uidRule = StringPrintf("owner UID match %u", uid);
1191 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1192 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001193 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1194 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001195 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1196 }
1197}
1198
1199void expectStrictSetUidReject(const int uid) {
1200 static const char rejectRule[] = "st_penalty_reject all";
1201 std::string uidRule = StringPrintf("owner UID match %u", uid);
1202 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1203 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001204 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1205 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001206 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1207 }
1208}
1209
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001210} // namespace
1211
1212TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001213 binder::Status status;
1214 int32_t uid = randomUid();
1215
1216 // setUidCleartextPenalty Policy:Log with randomUid
1217 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1218 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1219 expectStrictSetUidLog(uid);
1220
1221 // setUidCleartextPenalty Policy:Accept with randomUid
1222 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1223 expectStrictSetUidAccept(uid);
1224
1225 // setUidCleartextPenalty Policy:Reject with randomUid
1226 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1227 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1228 expectStrictSetUidReject(uid);
1229
1230 // setUidCleartextPenalty Policy:Accept with randomUid
1231 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1232 expectStrictSetUidAccept(uid);
1233
1234 // test wrong policy
1235 int32_t wrongPolicy = -123;
1236 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1237 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1238}
1239
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001240namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001241
Luke Huangd1675922019-03-11 17:29:27 +08001242std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001243 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001244 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001245 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1246 // ...
1247 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1248
Luke Huangd1675922019-03-11 17:29:27 +08001249 // (dnsmasq)
1250 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1251
1252 if (maxTries == 0) return {};
1253
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001254 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001255 std::vector<std::string> result;
1256 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001257 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001258 if (result.size() || ++run > maxTries) {
1259 break;
1260 }
1261
Luke Huang728cf4c2019-03-14 19:43:02 +08001262 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001263 }
1264 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001265}
1266
Luke Huangd1675922019-03-11 17:29:27 +08001267void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001268 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001269}
1270
Luke Huang728cf4c2019-03-14 19:43:02 +08001271void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001272 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001273}
1274
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001275} // namespace
1276
1277TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001278 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001279
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001280 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1281 std::string clatAddress;
1282 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001283
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001284 // Can't start clatd on an interface that's not part of any network...
1285 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1286 EXPECT_FALSE(status.isOk());
1287 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1288
1289 // ... so create a test physical network and add our tun to it.
1290 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1291 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1292
1293 // Prefix must be 96 bits long.
1294 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1295 EXPECT_FALSE(status.isOk());
1296 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1297
1298 // Can't start clatd unless there's a default route...
1299 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1300 EXPECT_FALSE(status.isOk());
1301 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1302
1303 // so add a default route.
1304 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1305
1306 // Can't start clatd unless there's a global address...
1307 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1308 EXPECT_FALSE(status.isOk());
1309 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1310
1311 // ... so add a global address.
1312 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001313 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001314
1315 // Now expect clatd to start successfully.
1316 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1317 EXPECT_TRUE(status.isOk());
1318 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1319
1320 // Starting it again returns EBUSY.
1321 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1322 EXPECT_FALSE(status.isOk());
1323 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1324
Luke Huangd1675922019-03-11 17:29:27 +08001325 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001326
1327 // Expect clatd to stop successfully.
1328 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001329 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001330 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001331
1332 // Stopping a clatd that doesn't exist returns ENODEV.
1333 status = mNetd->clatdStop(sTun.name());
1334 EXPECT_FALSE(status.isOk());
1335 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001336 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001337
1338 // Clean up.
1339 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1340 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1341 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001342}
Luke Huang457d4702018-08-16 15:39:15 +08001343
1344namespace {
1345
1346bool getIpfwdV4Enable() {
1347 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1348 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1349 EXPECT_TRUE(!result.empty());
1350 int v4Enable = std::stoi(result[0]);
1351 return v4Enable;
1352}
1353
1354bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001355 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001356 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1357 EXPECT_TRUE(!result.empty());
1358 int v6Enable = std::stoi(result[0]);
1359 return v6Enable;
1360}
1361
1362void expectIpfwdEnable(bool enable) {
1363 int enableIPv4 = getIpfwdV4Enable();
1364 int enableIPv6 = getIpfwdV6Enable();
1365 EXPECT_EQ(enable, enableIPv4);
1366 EXPECT_EQ(enable, enableIPv6);
1367}
1368
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001369bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001370 std::vector<std::string> rules = listIpRules(ipVersion);
1371 for (const auto& rule : rules) {
1372 if (rule.find(ipfwdRule) != std::string::npos) {
1373 return true;
1374 }
1375 }
1376 return false;
1377}
1378
1379void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1380 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1381
1382 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1383 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1384 }
1385}
1386
1387void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1388 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1389
1390 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1391 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1392 }
1393}
1394
1395} // namespace
1396
1397TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001398 // Get ipfwd requester list from Netd
1399 std::vector<std::string> requesterList;
1400 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001401 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001402
1403 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001404 if (requesterList.size() == 0) {
1405 // No requester in Netd, ipfwd should be disabled
1406 // So add one test requester and verify
1407 status = mNetd->ipfwdEnableForwarding("TestRequester");
1408 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001409
Luke Huang728cf4c2019-03-14 19:43:02 +08001410 expectIpfwdEnable(true);
1411 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1412 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1413 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001414
Luke Huang728cf4c2019-03-14 19:43:02 +08001415 // Remove test one, verify again
1416 status = mNetd->ipfwdDisableForwarding("TestRequester");
1417 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1418
1419 expectIpfwdEnable(false);
1420 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1421 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1422 EXPECT_FALSE(ipfwdEnabled);
1423 } else {
1424 // Disable all requesters
1425 for (const auto& requester : requesterList) {
1426 status = mNetd->ipfwdDisableForwarding(requester);
1427 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1428 }
1429
1430 // After disable all requester, ipfwd should be disabled
1431 expectIpfwdEnable(false);
1432 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1433 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1434 EXPECT_FALSE(ipfwdEnabled);
1435
1436 // Enable them back
1437 for (const auto& requester : requesterList) {
1438 status = mNetd->ipfwdEnableForwarding(requester);
1439 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1440 }
1441
1442 // ipfwd should be enabled
1443 expectIpfwdEnable(true);
1444 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1445 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1446 EXPECT_TRUE(ipfwdEnabled);
1447 }
Luke Huang457d4702018-08-16 15:39:15 +08001448}
1449
1450TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001451 // Add test physical network
1452 EXPECT_TRUE(
1453 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1454 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1455 EXPECT_TRUE(
1456 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1457 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001458
Luke Huangd1827b82019-02-15 15:03:27 +08001459 binder::Status status =
1460 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1461 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1462 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001463
Luke Huangd1827b82019-02-15 15:03:27 +08001464 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1465 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1466 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001467}
Luke Huang531f5d32018-08-03 15:19:05 +08001468
1469namespace {
1470
1471constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1472constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1473constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1474constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1475constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001476constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001477
Luke Huang19b49c52018-10-22 12:12:05 +09001478// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1479// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001480bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1481 const char* chainName, const std::string& expectedTargetA,
1482 const std::string& expectedTargetB) {
1483 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1484 int matchCount = 0;
1485
1486 for (const auto& rule : rules) {
1487 if (rule.find(expectedTargetA) != std::string::npos) {
1488 if (rule.find(expectedTargetB) != std::string::npos) {
1489 matchCount++;
1490 }
1491 }
1492 }
1493 return matchCount == expectedCount;
1494}
1495
1496void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1497 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1498 std::string result = "";
1499
1500 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001501 // Quota value might be decreased while matching packets
1502 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001503}
1504
1505void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1506 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1507 std::string quotaRule = StringPrintf("quota %s", ifname);
1508
1509 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1510 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1511 BANDWIDTH_COSTLY_IF));
1512 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1513 BANDWIDTH_COSTLY_IF));
1514 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1515 BANDWIDTH_COSTLY_IF));
1516 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1517 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1518 }
1519 expectXtQuotaValueEqual(ifname, quotaBytes);
1520}
1521
1522void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1523 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1524 std::string quotaRule = StringPrintf("quota %s", ifname);
1525
1526 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1527 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1528 BANDWIDTH_COSTLY_IF));
1529 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1530 BANDWIDTH_COSTLY_IF));
1531 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1532 BANDWIDTH_COSTLY_IF));
1533 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1534 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1535 }
1536}
1537
1538void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1539 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1540 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1541 std::string alertName = StringPrintf("%sAlert", ifname);
1542
1543 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1544 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1545 }
1546 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1547}
1548
1549void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1550 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1551 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1552
1553 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1554 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1555 }
1556}
1557
1558void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1559 static const char globalAlertRule[] = "quota globalAlert";
1560 static const char globalAlertName[] = "globalAlert";
1561
1562 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001563 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001564 }
1565 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1566}
1567
1568void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1569 std::string uidRule = StringPrintf("owner UID match %u", uid);
1570
1571 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1572 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1573 }
1574}
1575
1576void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1577 std::string uidRule = StringPrintf("owner UID match %u", uid);
1578
1579 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1580 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1581 }
1582}
1583
1584} // namespace
1585
1586TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1587 long testQuotaBytes = 5550;
1588
1589 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001590 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001591 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1592
1593 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1594 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1595 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1596
1597 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1598 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1599 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1600
1601 // Remove test physical network
1602 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1603}
1604
1605TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1606 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001607 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001608 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001609 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001610 // Need to have a prior interface quota set to set an alert
1611 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1612 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1613 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1614 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1615
1616 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1617 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1618 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1619
1620 // Remove interface quota
1621 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1622 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1623 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1624
1625 // Remove test physical network
1626 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1627}
1628
1629TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001630 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001631
1632 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1633 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1634 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1635
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001636 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001637 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1638 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1639 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1640}
1641
1642TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1643 SKIP_IF_BPF_SUPPORTED;
1644
1645 int32_t uid = randomUid();
1646 static const char targetReject[] = "REJECT";
1647 static const char targetReturn[] = "RETURN";
1648
1649 // add NaughtyApp
1650 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1651 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1652 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1653
1654 // remove NaughtyApp
1655 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1656 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1657 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1658
1659 // add NiceApp
1660 status = mNetd->bandwidthAddNiceApp(uid);
1661 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1662 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1663
1664 // remove NiceApp
1665 status = mNetd->bandwidthRemoveNiceApp(uid);
1666 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1667 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1668}
Luke Huangb5733d72018-08-21 17:17:19 +08001669
1670namespace {
1671
Luke Huangb670d162018-08-23 20:01:13 +08001672std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1673 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1674 return runCommand(command);
1675}
1676
Luke Huangc3252cc2018-10-16 15:43:23 +08001677bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001678 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1679 for (const auto& route : routes) {
1680 if (route.find(ipRoute) != std::string::npos) {
1681 return true;
1682 }
1683 }
1684 return false;
1685}
1686
Luke Huangc3252cc2018-10-16 15:43:23 +08001687std::string ipRouteString(const std::string& ifName, const std::string& dst,
1688 const std::string& nextHop) {
1689 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1690
1691 if (!nextHop.empty()) {
1692 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001693 }
1694
Luke Huangc3252cc2018-10-16 15:43:23 +08001695 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001696}
1697
Luke Huangc3252cc2018-10-16 15:43:23 +08001698void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1699 const std::string& dst, const std::string& nextHop,
1700 const char* table) {
1701 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1702}
1703
1704void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001705 const std::string& dst, const std::string& nextHop,
1706 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001707 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001708}
1709
1710bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1711 std::vector<std::string> rules = listIpRules(ipVersion);
1712 for (const auto& rule : rules) {
1713 if (rule.find(ipRule) != std::string::npos) {
1714 return true;
1715 }
1716 }
1717 return false;
1718}
1719
1720void expectNetworkDefaultIpRuleExists(const char* ifName) {
1721 std::string networkDefaultRule =
1722 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1723
1724 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1725 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1726 }
1727}
1728
1729void expectNetworkDefaultIpRuleDoesNotExist() {
1730 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1731
1732 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1733 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1734 }
1735}
1736
1737void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1738 std::string networkPermissionRule = "";
1739 switch (permission) {
1740 case INetd::PERMISSION_NONE:
1741 networkPermissionRule = StringPrintf(
1742 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1743 break;
1744 case INetd::PERMISSION_NETWORK:
1745 networkPermissionRule = StringPrintf(
1746 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1747 break;
1748 case INetd::PERMISSION_SYSTEM:
1749 networkPermissionRule = StringPrintf(
1750 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1751 break;
1752 }
1753
1754 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1755 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1756 }
1757}
1758
1759// TODO: It is a duplicate function, need to remove it
1760bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1761 const std::string& expectedInterface,
1762 const std::string& expectedRule,
1763 const char* table) {
1764 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1765 for (const auto& rule : rules) {
1766 if (rule.find(expectedInterface) != std::string::npos) {
1767 if (rule.find(expectedRule) != std::string::npos) {
1768 return true;
1769 }
1770 }
1771 }
1772 return false;
1773}
1774
1775void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1776 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1777 std::string networkIncomingPacketMarkRule = "";
1778 switch (permission) {
1779 case INetd::PERMISSION_NONE:
1780 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1781 break;
1782 case INetd::PERMISSION_NETWORK:
1783 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1784 break;
1785 case INetd::PERMISSION_SYSTEM:
1786 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1787 break;
1788 }
1789
1790 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1791 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1792 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1793 }
1794}
1795
1796} // namespace
1797
1798TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001799 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001800 const char* ipVersion;
1801 const char* testDest;
1802 const char* testNextHop;
1803 const bool expectSuccess;
1804 } kTestData[] = {
1805 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001806 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1807 {IP_RULE_V4, "10.251.0.0/16", "", true},
1808 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1809 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001810 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001811 {IP_RULE_V6, "::/0", "2001:db8::", true},
1812 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001813 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1814 };
1815
Luke Huangc3252cc2018-10-16 15:43:23 +08001816 static const struct {
1817 const char* ipVersion;
1818 const char* testDest;
1819 const char* testNextHop;
1820 } kTestDataWithNextHop[] = {
1821 {IP_RULE_V4, "10.251.10.0/30", ""},
1822 {IP_RULE_V6, "2001:db8::/32", ""},
1823 };
1824
Luke Huangb670d162018-08-23 20:01:13 +08001825 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001826 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001827 const int testUid = randomUid();
1828 const std::vector<int32_t> testUids = {testUid};
1829
1830 // Add test physical network
1831 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1832 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1833
Luke Huangc3252cc2018-10-16 15:43:23 +08001834 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001835 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001836 const auto& td = kTestDataWithNextHop[i];
1837
1838 // All route for test tun will disappear once the tun interface is deleted.
1839 binder::Status status =
1840 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1841 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1842 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1843 sTun.name().c_str());
1844
1845 // Add system permission for test uid, setup route in legacy system table.
1846 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1847
1848 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1849 testUid);
1850 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1851 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1852 testTableLegacySystem);
1853
1854 // Remove system permission for test uid, setup route in legacy network table.
1855 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1856
1857 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1858 testUid);
1859 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1860 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1861 testTableLegacyNetwork);
1862 }
1863
Sehee Park8659b8d2018-11-16 10:53:16 +09001864 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001865 const auto& td = kTestData[i];
1866
1867 binder::Status status =
1868 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1869 if (td.expectSuccess) {
1870 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001871 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001872 sTun.name().c_str());
1873 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001874 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1875 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001876 }
1877
1878 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1879 if (td.expectSuccess) {
1880 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001881 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1882 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001883 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001884 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1885 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001886 }
1887
Luke Huangc3252cc2018-10-16 15:43:23 +08001888 // Add system permission for test uid, route will be added into legacy system table.
1889 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001890
1891 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1892 testUid);
1893 if (td.expectSuccess) {
1894 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001895 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001896 testTableLegacySystem);
1897 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001898 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1899 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001900 }
1901
1902 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1903 td.testNextHop, testUid);
1904 if (td.expectSuccess) {
1905 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001906 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1907 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001908 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001909 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1910 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001911 }
1912
Luke Huangc3252cc2018-10-16 15:43:23 +08001913 // Remove system permission for test uid, route will be added into legacy network table.
1914 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1915
1916 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1917 testUid);
1918 if (td.expectSuccess) {
1919 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1920 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1921 testTableLegacyNetwork);
1922 } else {
1923 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1924 EXPECT_NE(0, status.serviceSpecificErrorCode());
1925 }
1926
1927 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1928 td.testNextHop, testUid);
1929 if (td.expectSuccess) {
1930 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1931 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1932 testTableLegacyNetwork);
1933 } else {
1934 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1935 EXPECT_NE(0, status.serviceSpecificErrorCode());
1936 }
Luke Huangb670d162018-08-23 20:01:13 +08001937 }
1938
1939 // Remove test physical network
1940 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1941}
1942
Luke Huang33a92792019-05-28 16:59:25 +08001943namespace {
1944
1945constexpr char CUTTLEFISH_PRODUCT_DEVICE[] = "vsoc_x86";
1946constexpr char CUTTLEFISH_SYSTEM_NAME[] = "cf_x86_phone";
1947
1948bool isCuttleFish() {
1949 static const std::string sProductDevice = android::base::GetProperty("ro.product.device", "");
1950 static const std::string sSystemName = android::base::GetProperty("ro.product.system.name", "");
1951 return (sProductDevice.find(CUTTLEFISH_PRODUCT_DEVICE) != std::string::npos) &&
1952 (sSystemName.find(CUTTLEFISH_SYSTEM_NAME) != std::string::npos);
1953}
1954
1955} // namespace
1956
Luke Huangb670d162018-08-23 20:01:13 +08001957TEST_F(BinderTest, NetworkPermissionDefault) {
Luke Huang33a92792019-05-28 16:59:25 +08001958 SKIP_IF_CUTTLEFISH;
1959
Luke Huangb670d162018-08-23 20:01:13 +08001960 // Add test physical network
1961 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1962 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1963
Luke Huangc3252cc2018-10-16 15:43:23 +08001964 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001965 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1966 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001967
1968 // Test SetDefault
1969 status = mNetd->networkSetDefault(TEST_NETID1);
1970 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1971 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1972
1973 status = mNetd->networkClearDefault();
1974 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1975 expectNetworkDefaultIpRuleDoesNotExist();
1976
Luke Huangd2861982019-05-17 19:47:28 +08001977 // Set default network back
1978 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001979 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1980
1981 // Test SetPermission
1982 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1983 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1985 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1986
1987 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1988 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1989 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1990 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1991
1992 // Remove test physical network
1993 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1994}
1995
1996TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001997 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001998 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1999 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08002000 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002001 EXPECT_TRUE(ret);
2002
Luke Huang854e2992019-05-29 16:42:48 +08002003 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002004 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08002005
2006 // Clear uid permission before calling networkCanProtect to ensure
2007 // the call won't be affected by uid permission.
2008 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2009
2010 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002011 EXPECT_FALSE(ret);
2012}
2013
2014namespace {
2015
Luke Huangb5733d72018-08-21 17:17:19 +08002016int readIntFromPath(const std::string& path) {
2017 std::string result = "";
2018 EXPECT_TRUE(ReadFileToString(path, &result));
2019 return std::stoi(result);
2020}
2021
2022int getTetherAcceptIPv6Ra(const std::string& ifName) {
2023 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2024 return readIntFromPath(path);
2025}
2026
2027bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2028 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2029 return readIntFromPath(path);
2030}
2031
2032int getTetherIPv6DadTransmits(const std::string& ifName) {
2033 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2034 return readIntFromPath(path);
2035}
2036
2037bool getTetherEnableIPv6(const std::string& ifName) {
2038 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2039 int disableIPv6 = readIntFromPath(path);
2040 return !disableIPv6;
2041}
2042
2043bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2044 for (const auto& iface : ifList) {
2045 if (iface == ifName) {
2046 return true;
2047 }
2048 }
2049 return false;
2050}
2051
2052void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2053 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2054 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2055 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2056 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2057}
2058
2059void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2060 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2061 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2062 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2063 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2064}
2065
2066void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2067 const std::string& ifName) {
2068 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2069}
2070
2071void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2072 const std::string& ifName) {
2073 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2074}
2075
2076void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2077 const std::vector<std::string>& testDnsAddrs) {
2078 EXPECT_TRUE(dnsList == testDnsAddrs);
2079}
2080
2081} // namespace
2082
2083TEST_F(BinderTest, TetherStartStopStatus) {
2084 std::vector<std::string> noDhcpRange = {};
2085 static const char dnsdName[] = "dnsmasq";
2086
2087 binder::Status status = mNetd->tetherStart(noDhcpRange);
2088 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002089 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002090
2091 bool tetherEnabled;
2092 status = mNetd->tetherIsEnabled(&tetherEnabled);
2093 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2094 EXPECT_TRUE(tetherEnabled);
2095
2096 status = mNetd->tetherStop();
2097 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002098 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002099
2100 status = mNetd->tetherIsEnabled(&tetherEnabled);
2101 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2102 EXPECT_FALSE(tetherEnabled);
2103}
2104
2105TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2106 // TODO: verify if dnsmasq update interface successfully
2107
2108 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2109 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2110 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2111
2112 std::vector<std::string> ifList;
2113 status = mNetd->tetherInterfaceList(&ifList);
2114 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2115 expectTetherInterfaceExists(ifList, sTun.name());
2116
2117 status = mNetd->tetherInterfaceRemove(sTun.name());
2118 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2119 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2120
2121 status = mNetd->tetherInterfaceList(&ifList);
2122 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2123 expectTetherInterfaceNotExists(ifList, sTun.name());
2124}
2125
2126TEST_F(BinderTest, TetherDnsSetList) {
2127 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002128 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2129 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002130
2131 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2132 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2133
2134 std::vector<std::string> dnsList;
2135 status = mNetd->tetherDnsList(&dnsList);
2136 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2137 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002138}
2139
2140namespace {
2141
2142constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2143constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2144constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2145constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2146constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2147constexpr char FIREWALL_STANDBY[] = "fw_standby";
2148constexpr char targetReturn[] = "RETURN";
2149constexpr char targetDrop[] = "DROP";
2150
2151void expectFirewallWhitelistMode() {
2152 static const char dropRule[] = "DROP all";
2153 static const char rejectRule[] = "REJECT all";
2154 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2155 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2156 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2157 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2158 }
2159}
2160
2161void expectFirewallBlacklistMode() {
2162 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2163 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2164 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2165 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2166 }
2167}
2168
2169bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2170 const std::string& expectedInterface,
2171 const std::string& expectedRule) {
2172 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2173 // Expected rule:
2174 // Chain fw_INPUT (1 references)
2175 // pkts bytes target prot opt in out source destination
2176 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2177 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2178 int firstRuleIndex = 2;
2179 if (rules.size() < 4) return false;
2180 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2181 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2182 return true;
2183 }
2184 }
2185 return false;
2186}
2187
2188// TODO: It is a duplicate function, need to remove it
2189bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2190 const std::string& expectedInterface,
2191 const std::string& expectedRule) {
2192 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2193 for (const auto& rule : rules) {
2194 if (rule.find(expectedInterface) != std::string::npos) {
2195 if (rule.find(expectedRule) != std::string::npos) {
2196 return true;
2197 }
2198 }
2199 }
2200 return false;
2201}
2202
2203void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2204 static const char returnRule[] = "RETURN all";
2205 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2206 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2207 returnRule));
2208 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2209 returnRule));
2210 }
2211}
2212
2213void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2214 static const char returnRule[] = "RETURN all";
2215 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2216 EXPECT_FALSE(
2217 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2218 EXPECT_FALSE(
2219 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2220 }
2221}
2222
2223bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2224 const std::string& expectedTarget,
2225 const std::string& expectedRule) {
2226 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2227 int firstRuleIndex = 2;
2228 if (rules.size() < 4) return false;
2229 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2230 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2231 return true;
2232 }
2233 }
2234 return false;
2235}
2236
2237bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2238 const std::string& expectedTarget,
2239 const std::string& expectedRule) {
2240 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2241 int lastRuleIndex = rules.size() - 1;
2242 if (lastRuleIndex < 0) return false;
2243 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2244 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2245 return true;
2246 }
2247 }
2248 return false;
2249}
2250
2251void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2252 std::string uidRule = StringPrintf("owner UID match %u", uid);
2253 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2254 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2255}
2256
2257void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2258 std::string uidRule = StringPrintf("owner UID match %u", uid);
2259 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2260 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2261}
2262
2263void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2264 std::string uidRule = StringPrintf("owner UID match %u", uid);
2265 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2266 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2267}
2268
2269void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2270 std::string uidRule = StringPrintf("owner UID match %u", uid);
2271 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2272 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2273}
2274
2275bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2276 std::vector<std::string> inputRules =
2277 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2278 std::vector<std::string> outputRules =
2279 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2280 int inputLastRuleIndex = inputRules.size() - 1;
2281 int outputLastRuleIndex = outputRules.size() - 1;
2282
2283 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2284 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2285 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2286 return true;
2287 }
2288 }
2289 return false;
2290}
2291
2292void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2293 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2294 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2295}
2296
2297void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2298 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2299 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2300 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2301 }
2302}
2303
2304} // namespace
2305
2306TEST_F(BinderTest, FirewallSetFirewallType) {
2307 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2308 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2309 expectFirewallWhitelistMode();
2310
2311 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2312 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2313 expectFirewallBlacklistMode();
2314
2315 // set firewall type blacklist twice
2316 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2317 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2318 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2319 expectFirewallBlacklistMode();
2320
2321 // set firewall type whitelist twice
2322 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2323 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFirewallWhitelistMode();
2326
2327 // reset firewall type to default
2328 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2329 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2330 expectFirewallBlacklistMode();
2331}
2332
2333TEST_F(BinderTest, FirewallSetInterfaceRule) {
2334 // setinterfaceRule is not supported in BLACKLIST MODE
2335 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2336 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2337
2338 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2339 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2340
2341 // set WHITELIST mode first
2342 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2343 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2344
2345 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2347 expectFirewallInterfaceRuleAllowExists(sTun.name());
2348
2349 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2352
2353 // reset firewall mode to default
2354 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2355 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2356 expectFirewallBlacklistMode();
2357}
2358
2359TEST_F(BinderTest, FirewallSetUidRule) {
2360 SKIP_IF_BPF_SUPPORTED;
2361
2362 int32_t uid = randomUid();
2363
2364 // Doze allow
2365 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2366 INetd::FIREWALL_RULE_ALLOW);
2367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2368 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2369
2370 // Doze deny
2371 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2372 INetd::FIREWALL_RULE_DENY);
2373 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2374 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2375
2376 // Powersave allow
2377 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2378 INetd::FIREWALL_RULE_ALLOW);
2379 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2380 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2381
2382 // Powersave deny
2383 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2384 INetd::FIREWALL_RULE_DENY);
2385 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2386 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2387
2388 // Standby deny
2389 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2390 INetd::FIREWALL_RULE_DENY);
2391 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2392 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2393
2394 // Standby allow
2395 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2396 INetd::FIREWALL_RULE_ALLOW);
2397 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2398 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2399
2400 // None deny in BLACKLIST
2401 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2402 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2403 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2404 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2405
2406 // None allow in BLACKLIST
2407 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2408 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2409 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2410 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2411
2412 // set firewall type whitelist twice
2413 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2414 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2415 expectFirewallWhitelistMode();
2416
2417 // None allow in WHITELIST
2418 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2419 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2420 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2421 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2422
2423 // None deny in WHITELIST
2424 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2425 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2426 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2427 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2428
2429 // reset firewall mode to default
2430 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2431 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2432 expectFirewallBlacklistMode();
2433}
2434
2435TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2436 SKIP_IF_BPF_SUPPORTED;
2437
2438 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2439 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2440 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2441
2442 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2443 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2444 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2445
2446 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2447 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2448 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2449
2450 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2451 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2452 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2453
2454 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2455 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2456 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2457
2458 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2459 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2460 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2461}
Luke Huangf7782042018-08-08 13:13:04 +08002462
2463namespace {
2464
2465std::string hwAddrToStr(unsigned char* hwaddr) {
2466 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2467 hwaddr[4], hwaddr[5]);
2468}
2469
2470int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2471 int prefixLength = 0;
2472 uint32_t m = ntohl(mask);
2473 while (m & (1 << 31)) {
2474 prefixLength++;
2475 m = m << 1;
2476 }
2477 return prefixLength;
2478}
2479
2480std::string toStdString(const String16& s) {
2481 return std::string(String8(s.string()));
2482}
2483
2484android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2485 const auto& sys = sSyscalls.get();
2486 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2487 EXPECT_TRUE(isOk(fd.status()));
2488
2489 struct ifreq ifr = {};
2490 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2491
2492 return sys.ioctl(fd.value(), flag, &ifr);
2493}
2494
2495std::string getInterfaceHwAddr(const std::string& ifName) {
2496 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2497
2498 unsigned char hwaddr[ETH_ALEN] = {};
2499 if (isOk(res.status())) {
2500 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2501 }
2502
2503 return hwAddrToStr(hwaddr);
2504}
2505
2506int getInterfaceIPv4Prefix(const std::string& ifName) {
2507 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2508
2509 int prefixLength = 0;
2510 if (isOk(res.status())) {
2511 prefixLength = ipv4NetmaskToPrefixLength(
2512 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2513 }
2514
2515 return prefixLength;
2516}
2517
2518std::string getInterfaceIPv4Addr(const std::string& ifName) {
2519 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2520
2521 struct in_addr addr = {};
2522 if (isOk(res.status())) {
2523 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2524 }
2525
2526 return std::string(inet_ntoa(addr));
2527}
2528
2529std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2530 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2531
2532 unsigned flags = 0;
2533 if (isOk(res.status())) {
2534 flags = res.value().ifr_flags;
2535 }
2536
2537 std::vector<std::string> ifFlags;
2538 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2539 : toStdString(INetd::IF_STATE_DOWN()));
2540
2541 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2542 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2543 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2544 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2545 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2546
2547 return ifFlags;
2548}
2549
2550bool compareListInterface(const std::vector<std::string>& interfaceList) {
2551 const auto& res = InterfaceController::getIfaceNames();
2552 EXPECT_TRUE(isOk(res));
2553
2554 std::vector<std::string> resIfList;
2555 resIfList.reserve(res.value().size());
2556 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2557
2558 return resIfList == interfaceList;
2559}
2560
2561int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2562 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2563 return readIntFromPath(path);
2564}
2565
2566bool getInterfaceEnableIPv6(const std::string& ifName) {
2567 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2568
2569 int disableIPv6 = readIntFromPath(path);
2570 return !disableIPv6;
2571}
2572
2573int getInterfaceMtu(const std::string& ifName) {
2574 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2575 return readIntFromPath(path);
2576}
2577
2578void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2579 EXPECT_TRUE(compareListInterface(interfaceList));
2580}
2581
2582void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2583 const InterfaceConfigurationParcel& interfaceCfg) {
2584 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2585 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2586 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2587 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2588}
2589
2590void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2591 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2592 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2593
2594 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2595 for (const auto& flag : setCfg.flags) {
2596 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2597 }
2598}
2599
2600void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2601 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2602 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2603}
2604
2605void expectInterfaceNoAddr(const std::string& ifName) {
2606 // noAddr
2607 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2608 // noPrefix
2609 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2610}
2611
2612void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2613 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2614 EXPECT_EQ(enableIPv6, enable);
2615}
2616
2617void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2618 int mtuSize = getInterfaceMtu(ifName);
2619 EXPECT_EQ(mtu, mtuSize);
2620}
2621
2622InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2623 const std::string& addr, int prefixLength,
2624 const std::vector<std::string>& flags) {
2625 InterfaceConfigurationParcel cfg;
2626 cfg.ifName = ifName;
2627 cfg.hwAddr = "";
2628 cfg.ipv4Addr = addr;
2629 cfg.prefixLength = prefixLength;
2630 cfg.flags = flags;
2631 return cfg;
2632}
2633
2634void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2635 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2636 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2637
2638 for (const auto& flag : expectedFlags) {
2639 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2640 interfaceCfg.flags.end());
2641 }
2642
2643 for (const auto& flag : unexpectedFlags) {
2644 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2645 interfaceCfg.flags.end());
2646 }
2647}
2648
2649} // namespace
2650
2651TEST_F(BinderTest, InterfaceList) {
2652 std::vector<std::string> interfaceListResult;
2653
2654 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2655 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2656 expectInterfaceList(interfaceListResult);
2657}
2658
2659TEST_F(BinderTest, InterfaceGetCfg) {
2660 InterfaceConfigurationParcel interfaceCfgResult;
2661
2662 // Add test physical network
2663 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2664 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2665
2666 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2667 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2668 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2669 expectTunFlags(interfaceCfgResult);
2670
2671 // Remove test physical network
2672 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2673}
2674
2675TEST_F(BinderTest, InterfaceSetCfg) {
2676 const std::string testAddr = "192.0.2.3";
2677 const int testPrefixLength = 24;
2678 std::vector<std::string> upFlags = {"up"};
2679 std::vector<std::string> downFlags = {"down"};
2680
2681 // Add test physical network
2682 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2683 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2684
2685 // Set tun interface down.
2686 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2687 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2688 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2689 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2690
2691 // Set tun interface up again.
2692 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2693 status = mNetd->interfaceSetCfg(interfaceCfg);
2694 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2695 status = mNetd->interfaceClearAddrs(sTun.name());
2696 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2697
2698 // Remove test physical network
2699 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2700}
2701
2702TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2703 // enable
2704 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2705 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2706 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2707
2708 // disable
2709 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2710 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2711 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2712}
2713
2714TEST_F(BinderTest, InterfaceClearAddr) {
2715 const std::string testAddr = "192.0.2.3";
2716 const int testPrefixLength = 24;
2717 std::vector<std::string> noFlags{};
2718
2719 // Add test physical network
2720 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2721 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2722
2723 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2724 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2725 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2726 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2727
2728 status = mNetd->interfaceClearAddrs(sTun.name());
2729 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2730 expectInterfaceNoAddr(sTun.name());
2731
2732 // Remove test physical network
2733 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2734}
2735
2736TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2737 // Add test physical network
2738 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2739 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2740
2741 // disable
2742 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2743 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2744 expectInterfaceEnableIPv6(sTun.name(), false);
2745
2746 // enable
2747 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2748 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2749 expectInterfaceEnableIPv6(sTun.name(), true);
2750
2751 // Remove test physical network
2752 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2753}
2754
2755TEST_F(BinderTest, InterfaceSetMtu) {
2756 const int testMtu = 1200;
2757
2758 // Add test physical network
2759 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2760 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2761
2762 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2763 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2764 expectInterfaceMtu(sTun.name(), testMtu);
2765
2766 // Remove test physical network
2767 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2768}
Luke Huang19b49c52018-10-22 12:12:05 +09002769
2770namespace {
2771
2772constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2773constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002774constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002775constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2776
Luke Huangae038f82018-11-05 11:17:31 +09002777int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002778 return listIptablesRuleByTable(binary, table, chainName).size();
2779}
2780
2781bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2782 const std::vector<std::string>& targetVec) {
2783 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2784 if (targetVec.size() != rules.size() - 2) {
2785 return false;
2786 }
2787
2788 /*
Luke Huangae038f82018-11-05 11:17:31 +09002789 * Check that the rules match. Note that this function matches substrings, not entire rules,
2790 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002791 * Skip first two lines since rules start from third line.
2792 * Chain chainName (x references)
2793 * pkts bytes target prot opt in out source destination
2794 * ...
2795 */
2796 int rIndex = 2;
2797 for (const auto& target : targetVec) {
2798 if (rules[rIndex].find(target) == std::string::npos) {
2799 return false;
2800 }
2801 rIndex++;
2802 }
2803 return true;
2804}
2805
2806void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2807 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2808 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2809 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002810 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002811 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2812 "DROP"};
2813
2814 // V4
2815 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2816 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002817 EXPECT_TRUE(
2818 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002819 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2820
Luke Huangae038f82018-11-05 11:17:31 +09002821 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002822 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2823
2824 // V6
2825 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002826 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2827 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002828
2829 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2830 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2831 extIf));
2832 }
2833}
2834
2835void expectNatDisable() {
2836 // It is the default DROP rule with tethering disable.
2837 // Chain tetherctrl_FORWARD (1 references)
2838 // pkts bytes target prot opt in out source destination
2839 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2840 std::vector<std::string> forwardV4Match = {"DROP"};
2841 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2842
2843 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002844 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2845 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002846
Luke Huangae038f82018-11-05 11:17:31 +09002847 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2848 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002849
2850 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2851}
2852
2853} // namespace
2854
2855TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002856 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2857 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2858 expectNatEnable(sTun.name(), sTun2.name());
2859
2860 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2861 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2862 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002863}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002864
2865namespace {
2866
2867using TripleInt = std::array<int, 3>;
2868
2869TripleInt readProcFileToTripleInt(const std::string& path) {
2870 std::string valueString;
2871 int min, def, max;
2872 EXPECT_TRUE(ReadFileToString(path, &valueString));
2873 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2874 return {min, def, max};
2875}
2876
2877void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2878 std::string testRmemValues =
2879 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2880 std::string testWmemValues =
2881 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2882 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2883
2884 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2885 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2886
2887 for (int i = 0; i < 3; i++) {
2888 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2889 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2890 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2891 }
2892}
2893
2894} // namespace
2895
2896TEST_F(BinderTest, TcpBufferSet) {
2897 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2898 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2899 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2900 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2901
2902 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2903 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2904}
Luke Huang528af602018-08-29 19:06:05 +08002905
Chenbo Feng48eaed32018-12-26 17:40:21 -08002906namespace {
2907
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002908void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002909 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2910 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2911 for (int32_t uid : uids) {
2912 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2913 if (exist) {
2914 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002915 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002916 } else {
2917 EXPECT_FALSE(isOk(permission));
2918 EXPECT_EQ(ENOENT, permission.status().code());
2919 }
2920 }
2921}
2922
2923} // namespace
2924
2925TEST_F(BinderTest, TestInternetPermission) {
2926 SKIP_IF_BPF_NOT_SUPPORTED;
2927
2928 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2929
2930 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002931 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002932 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002933 checkUidsInPermissionMap(appUids, true);
2934 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2935 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002936}
2937
Luke Huang528af602018-08-29 19:06:05 +08002938TEST_F(BinderTest, UnsolEvents) {
2939 auto testUnsolService = android::net::TestUnsolService::start();
2940 std::string oldTunName = sTun.name();
2941 std::string newTunName = "unsolTest";
2942 testUnsolService->tarVec.push_back(oldTunName);
2943 testUnsolService->tarVec.push_back(newTunName);
2944 auto& cv = testUnsolService->getCv();
2945 auto& cvMutex = testUnsolService->getCvMutex();
2946 binder::Status status = mNetd->registerUnsolicitedEventListener(
2947 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2948 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2949
2950 // TODO: Add test for below events
2951 // StrictCleartextDetected / InterfaceDnsServersAdded
2952 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2953
2954 {
2955 std::unique_lock lock(cvMutex);
2956
2957 // Re-init test Tun, and we expect that we will get some unsol events.
2958 // Use the test Tun device name to verify if we receive its unsol events.
2959 sTun.destroy();
2960 // Use predefined name
2961 sTun.init(newTunName);
2962
2963 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2964 }
2965
2966 // bit mask 1101101000
2967 // Test only covers below events currently
2968 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2969 InterfaceLinkStatusChanged | RouteChanged;
2970 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002971
2972 // Re-init sTun to clear predefined name
2973 sTun.destroy();
2974 sTun.init();
2975}
2976
2977TEST_F(BinderTest, NDC) {
2978 struct Command {
2979 const std::string cmdString;
2980 const std::string expectedResult;
2981 };
2982
2983 // clang-format off
2984 // Do not change the commands order
2985 const Command networkCmds[] = {
2986 {StringPrintf("ndc network create %d", TEST_NETID1),
2987 "200 0 success"},
2988 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2989 "200 0 success"},
2990 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2991 "200 0 success"},
2992 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2993 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2994 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2995 "200 0 success"},
2996 };
2997
2998 const std::vector<Command> ipfwdCmds = {
2999 {"ndc ipfwd enable " + sTun.name(),
3000 "200 0 ipfwd operation succeeded"},
3001 {"ndc ipfwd disable " + sTun.name(),
3002 "200 0 ipfwd operation succeeded"},
3003 {"ndc ipfwd add lo2 lo3",
3004 "400 0 ipfwd operation failed (No such process)"},
3005 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3006 "200 0 ipfwd operation succeeded"},
3007 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3008 "200 0 ipfwd operation succeeded"},
3009 };
3010
3011 static const struct {
3012 const char* ipVersion;
3013 const char* testDest;
3014 const char* testNextHop;
3015 const bool expectSuccess;
3016 const std::string expectedResult;
3017 } kTestData[] = {
3018 {IP_RULE_V4, "0.0.0.0/0", "", true,
3019 "200 0 success"},
3020 {IP_RULE_V4, "10.251.0.0/16", "", true,
3021 "200 0 success"},
3022 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3023 "400 0 addRoute() failed (Invalid argument)",},
3024 {IP_RULE_V6, "::/0", "", true,
3025 "200 0 success"},
3026 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3027 "200 0 success"},
3028 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3029 "400 0 addRoute() failed (Invalid argument)"},
3030 };
3031 // clang-format on
3032
3033 for (const auto& cmd : networkCmds) {
3034 const std::vector<std::string> result = runCommand(cmd.cmdString);
3035 SCOPED_TRACE(cmd.cmdString);
3036 EXPECT_EQ(result.size(), 1U);
3037 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3038 }
3039
3040 for (const auto& cmd : ipfwdCmds) {
3041 const std::vector<std::string> result = runCommand(cmd.cmdString);
3042 SCOPED_TRACE(cmd.cmdString);
3043 EXPECT_EQ(result.size(), 1U);
3044 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3045 }
3046
3047 // Add test physical network
3048 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3049 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3050
3051 for (const auto& td : kTestData) {
3052 const std::string routeAddCmd =
3053 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3054 td.testDest, td.testNextHop);
3055 const std::string routeRemoveCmd =
3056 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3057 sTun.name().c_str(), td.testDest, td.testNextHop);
3058 std::vector<std::string> result = runCommand(routeAddCmd);
3059 SCOPED_TRACE(routeAddCmd);
3060 EXPECT_EQ(result.size(), 1U);
3061 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3062 if (td.expectSuccess) {
3063 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3064 sTun.name().c_str());
3065 result = runCommand(routeRemoveCmd);
3066 EXPECT_EQ(result.size(), 1U);
3067 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3068 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3069 sTun.name().c_str());
3070 }
3071 }
3072 // Remove test physical network
3073 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003074}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003075
Luke Huang2ff8b342019-04-30 15:33:33 +08003076TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003077 sp<IBinder> binder;
3078 binder::Status status = mNetd->getOemNetd(&binder);
3079 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3080 sp<com::android::internal::net::IOemNetd> oemNetd;
3081 if (binder != nullptr) {
3082 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3083 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003084 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003085
3086 TimedOperation t("OemNetd isAlive RPC");
3087 bool isAlive = false;
3088 oemNetd->isAlive(&isAlive);
3089 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003090
3091 class TestOemUnsolListener
3092 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3093 public:
3094 android::binder::Status onRegistered() override {
3095 std::lock_guard lock(mCvMutex);
3096 mCv.notify_one();
3097 return android::binder::Status::ok();
3098 }
3099 std::condition_variable& getCv() { return mCv; }
3100 std::mutex& getCvMutex() { return mCvMutex; }
3101
3102 private:
3103 std::mutex mCvMutex;
3104 std::condition_variable mCv;
3105 };
3106
3107 // Start the Binder thread pool.
3108 android::ProcessState::self()->startThreadPool();
3109
3110 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3111
3112 auto& cv = testListener->getCv();
3113 auto& cvMutex = testListener->getCvMutex();
3114
3115 {
3116 std::unique_lock lock(cvMutex);
3117
3118 status = oemNetd->registerOemUnsolicitedEventListener(
3119 ::android::interface_cast<
3120 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3121 testListener));
3122 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3123
3124 // Wait for receiving expected events.
3125 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3126 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003127}
Luke Huangd2861982019-05-17 19:47:28 +08003128
3129void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3130 int fallthroughNetId) {
3131 // Re-init sTun* to ensure route rule exists.
3132 sTun.destroy();
3133 sTun.init();
3134 sTun2.destroy();
3135 sTun2.init();
3136
3137 // Create physical network with fallthroughNetId but not set it as default network
3138 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3139 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3140
3141 // Create VPN with vpnNetId
3142 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3143
3144 // Add uid to VPN
3145 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3146 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3147
3148 // Add default route to fallthroughNetwork
3149 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3150 // Add limited route
3151 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3152}
3153
3154namespace {
3155
3156class ScopedUidChange {
3157 public:
3158 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3159 mStoredUid = getuid();
3160 if (mInputUid == mStoredUid) return;
3161 EXPECT_TRUE(seteuid(uid) == 0);
3162 }
3163 ~ScopedUidChange() {
3164 if (mInputUid == mStoredUid) return;
3165 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3166 }
3167
3168 private:
3169 uid_t mInputUid;
3170 uid_t mStoredUid;
3171};
3172
3173constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3174
3175void clearQueue(int tunFd) {
3176 char buf[4096];
3177 int ret;
3178 do {
3179 ret = read(tunFd, buf, sizeof(buf));
3180 } while (ret > 0);
3181}
3182
3183void checkDataReceived(int udpSocket, int tunFd) {
3184 char buf[4096] = {};
3185 // Clear tunFd's queue before write something because there might be some
3186 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3187 clearQueue(tunFd);
3188 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3189 // TODO: extract header and verify data
3190 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3191}
3192
3193bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3194 ScopedUidChange scopedUidChange(uid);
3195 android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3196 if (testSocket < 0) return false;
3197
3198 const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
3199 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3200 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3201 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3202 if (res == -1) return false;
3203
3204 char addr[INET6_ADDRSTRLEN];
3205 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3206 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3207 checkDataReceived(testSocket, tunFd);
3208 return true;
3209}
3210
3211void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3212 std::string vpnFallthroughRule =
3213 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3214 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3215 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3216 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3217 }
3218}
3219
3220void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3221 const TunInterface& fallthroughNetwork,
3222 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3223 int fallthroughNetId = TEST_NETID1) {
3224 // Set default network to NETID_UNSET
3225 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3226
3227 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3228 in6_addr insideVpnAddr = {
3229 {// 2001:db8:cafe::1
3230 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3231 // outsideVpnAddr will hit the route in the fallthrough network route table
3232 // because we added default route in createVpnNetworkWithUid
3233 in6_addr outsideVpnAddr = {
3234 {// 2607:f0d0:1002::4
3235 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3236
3237 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3238 int vpnFd = vpnNetwork.getFdForTesting();
3239 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3240 // default network.
3241 Fwmark fwmark;
3242 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3243 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3244
3245 // Set default network
3246 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3247
3248 // Connections go on the default network because UID 0 is not subject to the VPN.
3249 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3250 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3251 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3252 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3253
3254 // Check if fallthrough rule exists
3255 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3256
3257 // Expect fallthrough to default network
3258 // The fwmark differs depending on whether the VPN is bypassable or not.
3259 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3260 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3261
3262 // Expect connect success, packet will be sent to vpnFd.
3263 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3264 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3265
3266 // Explicitly select vpn network
3267 setNetworkForProcess(vpnNetId);
3268
3269 // Expect fallthrough to default network
3270 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
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 // Expect connect success, packet will be sent to vpnFd.
3275 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3276 // Expect the mark contains all the bit because we've selected network.
3277 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3278
3279 // Explicitly select fallthrough network
3280 setNetworkForProcess(fallthroughNetId);
3281
3282 // The mark is set to fallthrough network because we've selected it.
3283 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3284 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3285
3286 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3287 if (bypassable) {
3288 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3289 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3290 } else {
3291 // If not, no permission to bypass vpn.
3292 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3293 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3294 }
3295}
3296
3297} // namespace
3298
3299TEST_F(BinderTest, SecureVPNFallthrough) {
3300 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3301 // Get current default network NetId
3302 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3303 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3304}
3305
3306TEST_F(BinderTest, BypassableVPNFallthrough) {
3307 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3308 // Get current default network NetId
3309 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3310 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
3311}