blob: 1d11885ad9bc35ea87e61a00d379d084fc73b512 [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));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001056
1057 // Ensure we won't use the same interface name, otherwise the test will fail.
1058 u_int32_t rNumber = arc4random_uniform(10000);
1059 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1060 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001061
1062 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1063 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1064 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1065 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1066 // RX is from external to internal, and TX is from internal to external.
1067 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1068 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1069
1070 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1071 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1072
1073 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1074 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1075
1076 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1077 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1078 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1079
Luke Huangcaebcbb2018-09-27 20:37:14 +08001080 std::vector<TetherStatsParcel> statsVec;
1081 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001082 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1083
Luke Huangcaebcbb2018-09-27 20:37:14 +08001084 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001085
Luke Huangcaebcbb2018-09-27 20:37:14 +08001086 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001087
1088 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1089 delTetherCounterValues(path, intIface1, extIface1);
1090 delTetherCounterValues(path, intIface2, extIface2);
1091 if (path == IP6TABLES_PATH) {
1092 delTetherCounterValues(path, intIface3, extIface2);
1093 }
1094 }
1095
1096 expectNoTestCounterRules();
1097}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001098
Luke Huang0051a622018-07-23 20:30:16 +08001099namespace {
1100
Luke Huanga5211072018-08-01 23:36:29 +08001101constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1102constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001103
1104static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1105 const char* chainName) {
1106 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1107 return runCommand(command);
1108}
1109
Luke Huang19b49c52018-10-22 12:12:05 +09001110// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001111bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001112 const std::string& expectedInterface,
1113 const std::string& expectedRule, const char* table) {
1114 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1115 for (const auto& rule : rules) {
1116 if (rule.find(expectedInterface) != std::string::npos) {
1117 if (rule.find(expectedRule) != std::string::npos) {
1118 return true;
1119 }
1120 }
1121 }
1122 return false;
1123}
1124
1125void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001126 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001127 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001128 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001129 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001130 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1131 IdletimerRule, RAW_TABLE));
1132 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001133 ifname, IdletimerRule, MANGLE_TABLE));
1134 }
1135}
1136
1137void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001138 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001139 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001140 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001141 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001142 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1143 IdletimerRule, RAW_TABLE));
1144 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001145 ifname, IdletimerRule, MANGLE_TABLE));
1146 }
1147}
1148
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001149} // namespace
1150
1151TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001152 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1153 // rule in the table. Because we only check the result after calling remove function. We might
1154 // check the actual rule which is removed by our function (maybe compare the results between
1155 // calling function before and after)
1156 binder::Status status;
1157 const struct TestData {
1158 const std::string ifname;
1159 int32_t timeout;
1160 const std::string classLabel;
1161 } idleTestData[] = {
1162 {"wlan0", 1234, "happyday"},
1163 {"rmnet_data0", 4567, "friday"},
1164 };
1165 for (const auto& td : idleTestData) {
1166 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1167 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1168 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1169
1170 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1171 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1172 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1173 }
1174}
1175
Luke Huanga67dd562018-07-17 19:58:25 +08001176namespace {
1177
1178constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1179constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1180
1181void expectStrictSetUidAccept(const int uid) {
1182 std::string uidRule = StringPrintf("owner UID match %u", uid);
1183 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1184 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001185 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1186 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001187 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1188 }
1189}
1190
1191void expectStrictSetUidLog(const int uid) {
1192 static const char logRule[] = "st_penalty_log all";
1193 std::string uidRule = StringPrintf("owner UID match %u", uid);
1194 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1195 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001196 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1197 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001198 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1199 }
1200}
1201
1202void expectStrictSetUidReject(const int uid) {
1203 static const char rejectRule[] = "st_penalty_reject all";
1204 std::string uidRule = StringPrintf("owner UID match %u", uid);
1205 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1206 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001207 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1208 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001209 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1210 }
1211}
1212
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001213} // namespace
1214
1215TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001216 binder::Status status;
1217 int32_t uid = randomUid();
1218
1219 // setUidCleartextPenalty Policy:Log with randomUid
1220 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1221 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1222 expectStrictSetUidLog(uid);
1223
1224 // setUidCleartextPenalty Policy:Accept with randomUid
1225 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1226 expectStrictSetUidAccept(uid);
1227
1228 // setUidCleartextPenalty Policy:Reject with randomUid
1229 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1230 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1231 expectStrictSetUidReject(uid);
1232
1233 // setUidCleartextPenalty Policy:Accept with randomUid
1234 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1235 expectStrictSetUidAccept(uid);
1236
1237 // test wrong policy
1238 int32_t wrongPolicy = -123;
1239 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1240 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1241}
1242
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001243namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001244
Luke Huangd1675922019-03-11 17:29:27 +08001245std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001246 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001247 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001248 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1249 // ...
1250 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1251
Luke Huangd1675922019-03-11 17:29:27 +08001252 // (dnsmasq)
1253 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1254
1255 if (maxTries == 0) return {};
1256
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001257 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001258 std::vector<std::string> result;
1259 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001260 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001261 if (result.size() || ++run > maxTries) {
1262 break;
1263 }
1264
Luke Huang728cf4c2019-03-14 19:43:02 +08001265 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001266 }
1267 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001268}
1269
Luke Huangd1675922019-03-11 17:29:27 +08001270void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001271 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001272}
1273
Luke Huang728cf4c2019-03-14 19:43:02 +08001274void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001275 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001276}
1277
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001278} // namespace
1279
1280TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001281 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001282
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001283 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1284 std::string clatAddress;
1285 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001286
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001287 // Can't start clatd on an interface that's not part of any network...
1288 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1289 EXPECT_FALSE(status.isOk());
1290 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1291
1292 // ... so create a test physical network and add our tun to it.
1293 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1294 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1295
1296 // Prefix must be 96 bits long.
1297 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1298 EXPECT_FALSE(status.isOk());
1299 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1300
1301 // Can't start clatd unless there's a default route...
1302 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1303 EXPECT_FALSE(status.isOk());
1304 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1305
1306 // so add a default route.
1307 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1308
1309 // Can't start clatd unless there's a global address...
1310 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1311 EXPECT_FALSE(status.isOk());
1312 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1313
1314 // ... so add a global address.
1315 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001316 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001317
1318 // Now expect clatd to start successfully.
1319 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1320 EXPECT_TRUE(status.isOk());
1321 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1322
1323 // Starting it again returns EBUSY.
1324 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1325 EXPECT_FALSE(status.isOk());
1326 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1327
Luke Huangd1675922019-03-11 17:29:27 +08001328 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001329
1330 // Expect clatd to stop successfully.
1331 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001332 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001333 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001334
1335 // Stopping a clatd that doesn't exist returns ENODEV.
1336 status = mNetd->clatdStop(sTun.name());
1337 EXPECT_FALSE(status.isOk());
1338 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001339 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001340
1341 // Clean up.
1342 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1343 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1344 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001345}
Luke Huang457d4702018-08-16 15:39:15 +08001346
1347namespace {
1348
1349bool getIpfwdV4Enable() {
1350 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1351 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1352 EXPECT_TRUE(!result.empty());
1353 int v4Enable = std::stoi(result[0]);
1354 return v4Enable;
1355}
1356
1357bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001358 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001359 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1360 EXPECT_TRUE(!result.empty());
1361 int v6Enable = std::stoi(result[0]);
1362 return v6Enable;
1363}
1364
1365void expectIpfwdEnable(bool enable) {
1366 int enableIPv4 = getIpfwdV4Enable();
1367 int enableIPv6 = getIpfwdV6Enable();
1368 EXPECT_EQ(enable, enableIPv4);
1369 EXPECT_EQ(enable, enableIPv6);
1370}
1371
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001372bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001373 std::vector<std::string> rules = listIpRules(ipVersion);
1374 for (const auto& rule : rules) {
1375 if (rule.find(ipfwdRule) != std::string::npos) {
1376 return true;
1377 }
1378 }
1379 return false;
1380}
1381
1382void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1383 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1384
1385 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1386 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1387 }
1388}
1389
1390void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1391 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1392
1393 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1394 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1395 }
1396}
1397
1398} // namespace
1399
1400TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001401 // Get ipfwd requester list from Netd
1402 std::vector<std::string> requesterList;
1403 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001405
1406 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001407 if (requesterList.size() == 0) {
1408 // No requester in Netd, ipfwd should be disabled
1409 // So add one test requester and verify
1410 status = mNetd->ipfwdEnableForwarding("TestRequester");
1411 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001412
Luke Huang728cf4c2019-03-14 19:43:02 +08001413 expectIpfwdEnable(true);
1414 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1415 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1416 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001417
Luke Huang728cf4c2019-03-14 19:43:02 +08001418 // Remove test one, verify again
1419 status = mNetd->ipfwdDisableForwarding("TestRequester");
1420 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1421
1422 expectIpfwdEnable(false);
1423 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1424 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1425 EXPECT_FALSE(ipfwdEnabled);
1426 } else {
1427 // Disable all requesters
1428 for (const auto& requester : requesterList) {
1429 status = mNetd->ipfwdDisableForwarding(requester);
1430 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1431 }
1432
1433 // After disable all requester, ipfwd should be disabled
1434 expectIpfwdEnable(false);
1435 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1436 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1437 EXPECT_FALSE(ipfwdEnabled);
1438
1439 // Enable them back
1440 for (const auto& requester : requesterList) {
1441 status = mNetd->ipfwdEnableForwarding(requester);
1442 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1443 }
1444
1445 // ipfwd should be enabled
1446 expectIpfwdEnable(true);
1447 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1448 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1449 EXPECT_TRUE(ipfwdEnabled);
1450 }
Luke Huang457d4702018-08-16 15:39:15 +08001451}
1452
1453TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001454 // Add test physical network
1455 EXPECT_TRUE(
1456 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1457 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1458 EXPECT_TRUE(
1459 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1460 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001461
Luke Huangd1827b82019-02-15 15:03:27 +08001462 binder::Status status =
1463 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1464 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1465 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001466
Luke Huangd1827b82019-02-15 15:03:27 +08001467 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1468 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1469 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001470}
Luke Huang531f5d32018-08-03 15:19:05 +08001471
1472namespace {
1473
1474constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1475constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1476constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1477constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1478constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001479constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001480
Luke Huang19b49c52018-10-22 12:12:05 +09001481// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1482// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001483bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1484 const char* chainName, const std::string& expectedTargetA,
1485 const std::string& expectedTargetB) {
1486 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1487 int matchCount = 0;
1488
1489 for (const auto& rule : rules) {
1490 if (rule.find(expectedTargetA) != std::string::npos) {
1491 if (rule.find(expectedTargetB) != std::string::npos) {
1492 matchCount++;
1493 }
1494 }
1495 }
1496 return matchCount == expectedCount;
1497}
1498
1499void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1500 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1501 std::string result = "";
1502
1503 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001504 // Quota value might be decreased while matching packets
1505 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001506}
1507
1508void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1509 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1510 std::string quotaRule = StringPrintf("quota %s", ifname);
1511
1512 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1513 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1514 BANDWIDTH_COSTLY_IF));
1515 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1516 BANDWIDTH_COSTLY_IF));
1517 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1518 BANDWIDTH_COSTLY_IF));
1519 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1520 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1521 }
1522 expectXtQuotaValueEqual(ifname, quotaBytes);
1523}
1524
1525void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1526 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1527 std::string quotaRule = StringPrintf("quota %s", ifname);
1528
1529 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1530 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1531 BANDWIDTH_COSTLY_IF));
1532 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1533 BANDWIDTH_COSTLY_IF));
1534 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1535 BANDWIDTH_COSTLY_IF));
1536 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1537 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1538 }
1539}
1540
1541void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1542 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1543 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1544 std::string alertName = StringPrintf("%sAlert", ifname);
1545
1546 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1547 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1548 }
1549 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1550}
1551
1552void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1553 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1554 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1555
1556 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1557 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1558 }
1559}
1560
1561void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1562 static const char globalAlertRule[] = "quota globalAlert";
1563 static const char globalAlertName[] = "globalAlert";
1564
1565 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001566 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001567 }
1568 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1569}
1570
1571void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1572 std::string uidRule = StringPrintf("owner UID match %u", uid);
1573
1574 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1575 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1576 }
1577}
1578
1579void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1580 std::string uidRule = StringPrintf("owner UID match %u", uid);
1581
1582 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1583 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1584 }
1585}
1586
1587} // namespace
1588
1589TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1590 long testQuotaBytes = 5550;
1591
1592 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001593 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001594 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1595
1596 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1597 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1598 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1599
1600 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1601 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1602 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1603
1604 // Remove test physical network
1605 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1606}
1607
1608TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1609 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001610 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001611 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001612 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001613 // Need to have a prior interface quota set to set an alert
1614 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1615 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1616 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1617 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1618
1619 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1620 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1621 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1622
1623 // Remove interface quota
1624 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1625 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1626 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1627
1628 // Remove test physical network
1629 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1630}
1631
1632TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001633 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001634
1635 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1636 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1637 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1638
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001639 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001640 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1641 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1642 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1643}
1644
1645TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1646 SKIP_IF_BPF_SUPPORTED;
1647
1648 int32_t uid = randomUid();
1649 static const char targetReject[] = "REJECT";
1650 static const char targetReturn[] = "RETURN";
1651
1652 // add NaughtyApp
1653 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1654 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1655 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1656
1657 // remove NaughtyApp
1658 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1659 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1660 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1661
1662 // add NiceApp
1663 status = mNetd->bandwidthAddNiceApp(uid);
1664 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1665 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1666
1667 // remove NiceApp
1668 status = mNetd->bandwidthRemoveNiceApp(uid);
1669 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1670 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1671}
Luke Huangb5733d72018-08-21 17:17:19 +08001672
1673namespace {
1674
Luke Huangb670d162018-08-23 20:01:13 +08001675std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
1676 std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
1677 return runCommand(command);
1678}
1679
Luke Huangc3252cc2018-10-16 15:43:23 +08001680bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
Luke Huangb670d162018-08-23 20:01:13 +08001681 std::vector<std::string> routes = listIpRoutes(ipVersion, table);
1682 for (const auto& route : routes) {
1683 if (route.find(ipRoute) != std::string::npos) {
1684 return true;
1685 }
1686 }
1687 return false;
1688}
1689
Luke Huangc3252cc2018-10-16 15:43:23 +08001690std::string ipRouteString(const std::string& ifName, const std::string& dst,
1691 const std::string& nextHop) {
1692 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1693
1694 if (!nextHop.empty()) {
1695 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001696 }
1697
Luke Huangc3252cc2018-10-16 15:43:23 +08001698 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001699}
1700
Luke Huangc3252cc2018-10-16 15:43:23 +08001701void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1702 const std::string& dst, const std::string& nextHop,
1703 const char* table) {
1704 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1705}
1706
1707void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001708 const std::string& dst, const std::string& nextHop,
1709 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001710 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001711}
1712
1713bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1714 std::vector<std::string> rules = listIpRules(ipVersion);
1715 for (const auto& rule : rules) {
1716 if (rule.find(ipRule) != std::string::npos) {
1717 return true;
1718 }
1719 }
1720 return false;
1721}
1722
1723void expectNetworkDefaultIpRuleExists(const char* ifName) {
1724 std::string networkDefaultRule =
1725 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1726
1727 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1728 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1729 }
1730}
1731
1732void expectNetworkDefaultIpRuleDoesNotExist() {
1733 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1734
1735 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1736 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1737 }
1738}
1739
1740void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1741 std::string networkPermissionRule = "";
1742 switch (permission) {
1743 case INetd::PERMISSION_NONE:
1744 networkPermissionRule = StringPrintf(
1745 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1746 break;
1747 case INetd::PERMISSION_NETWORK:
1748 networkPermissionRule = StringPrintf(
1749 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1750 break;
1751 case INetd::PERMISSION_SYSTEM:
1752 networkPermissionRule = StringPrintf(
1753 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1754 break;
1755 }
1756
1757 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1758 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1759 }
1760}
1761
1762// TODO: It is a duplicate function, need to remove it
1763bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1764 const std::string& expectedInterface,
1765 const std::string& expectedRule,
1766 const char* table) {
1767 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1768 for (const auto& rule : rules) {
1769 if (rule.find(expectedInterface) != std::string::npos) {
1770 if (rule.find(expectedRule) != std::string::npos) {
1771 return true;
1772 }
1773 }
1774 }
1775 return false;
1776}
1777
1778void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1779 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1780 std::string networkIncomingPacketMarkRule = "";
1781 switch (permission) {
1782 case INetd::PERMISSION_NONE:
1783 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1784 break;
1785 case INetd::PERMISSION_NETWORK:
1786 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1787 break;
1788 case INetd::PERMISSION_SYSTEM:
1789 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1790 break;
1791 }
1792
1793 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1794 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1795 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1796 }
1797}
1798
1799} // namespace
1800
1801TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001802 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001803 const char* ipVersion;
1804 const char* testDest;
1805 const char* testNextHop;
1806 const bool expectSuccess;
1807 } kTestData[] = {
1808 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001809 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1810 {IP_RULE_V4, "10.251.0.0/16", "", true},
1811 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1812 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001813 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001814 {IP_RULE_V6, "::/0", "2001:db8::", true},
1815 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001816 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1817 };
1818
Luke Huangc3252cc2018-10-16 15:43:23 +08001819 static const struct {
1820 const char* ipVersion;
1821 const char* testDest;
1822 const char* testNextHop;
1823 } kTestDataWithNextHop[] = {
1824 {IP_RULE_V4, "10.251.10.0/30", ""},
1825 {IP_RULE_V6, "2001:db8::/32", ""},
1826 };
1827
Luke Huangb670d162018-08-23 20:01:13 +08001828 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001829 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001830 const int testUid = randomUid();
1831 const std::vector<int32_t> testUids = {testUid};
1832
1833 // Add test physical network
1834 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1835 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1836
Luke Huangc3252cc2018-10-16 15:43:23 +08001837 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001838 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001839 const auto& td = kTestDataWithNextHop[i];
1840
1841 // All route for test tun will disappear once the tun interface is deleted.
1842 binder::Status status =
1843 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1844 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1845 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1846 sTun.name().c_str());
1847
1848 // Add system permission for test uid, setup route in legacy system table.
1849 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1850
1851 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1852 testUid);
1853 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1854 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1855 testTableLegacySystem);
1856
1857 // Remove system permission for test uid, setup route in legacy network table.
1858 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1859
1860 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1861 testUid);
1862 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1863 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1864 testTableLegacyNetwork);
1865 }
1866
Sehee Park8659b8d2018-11-16 10:53:16 +09001867 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001868 const auto& td = kTestData[i];
1869
1870 binder::Status status =
1871 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1872 if (td.expectSuccess) {
1873 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001874 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001875 sTun.name().c_str());
1876 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001877 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1878 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001879 }
1880
1881 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1882 if (td.expectSuccess) {
1883 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001884 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1885 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001886 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001887 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1888 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001889 }
1890
Luke Huangc3252cc2018-10-16 15:43:23 +08001891 // Add system permission for test uid, route will be added into legacy system table.
1892 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001893
1894 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1895 testUid);
1896 if (td.expectSuccess) {
1897 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001898 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001899 testTableLegacySystem);
1900 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001901 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1902 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001903 }
1904
1905 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1906 td.testNextHop, testUid);
1907 if (td.expectSuccess) {
1908 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001909 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1910 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001911 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001912 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1913 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001914 }
1915
Luke Huangc3252cc2018-10-16 15:43:23 +08001916 // Remove system permission for test uid, route will be added into legacy network table.
1917 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1918
1919 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1920 testUid);
1921 if (td.expectSuccess) {
1922 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1923 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1924 testTableLegacyNetwork);
1925 } else {
1926 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1927 EXPECT_NE(0, status.serviceSpecificErrorCode());
1928 }
1929
1930 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1931 td.testNextHop, testUid);
1932 if (td.expectSuccess) {
1933 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1934 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1935 testTableLegacyNetwork);
1936 } else {
1937 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1938 EXPECT_NE(0, status.serviceSpecificErrorCode());
1939 }
Luke Huangb670d162018-08-23 20:01:13 +08001940 }
1941
1942 // Remove test physical network
1943 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1944}
1945
Luke Huang33a92792019-05-28 16:59:25 +08001946namespace {
1947
1948constexpr char CUTTLEFISH_PRODUCT_DEVICE[] = "vsoc_x86";
1949constexpr char CUTTLEFISH_SYSTEM_NAME[] = "cf_x86_phone";
1950
1951bool isCuttleFish() {
1952 static const std::string sProductDevice = android::base::GetProperty("ro.product.device", "");
1953 static const std::string sSystemName = android::base::GetProperty("ro.product.system.name", "");
1954 return (sProductDevice.find(CUTTLEFISH_PRODUCT_DEVICE) != std::string::npos) &&
1955 (sSystemName.find(CUTTLEFISH_SYSTEM_NAME) != std::string::npos);
1956}
1957
1958} // namespace
1959
Luke Huangb670d162018-08-23 20:01:13 +08001960TEST_F(BinderTest, NetworkPermissionDefault) {
Luke Huang33a92792019-05-28 16:59:25 +08001961 SKIP_IF_CUTTLEFISH;
1962
Luke Huangb670d162018-08-23 20:01:13 +08001963 // Add test physical network
1964 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1965 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1966
Luke Huangc3252cc2018-10-16 15:43:23 +08001967 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001968 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1969 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001970
1971 // Test SetDefault
1972 status = mNetd->networkSetDefault(TEST_NETID1);
1973 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1974 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1975
1976 status = mNetd->networkClearDefault();
1977 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1978 expectNetworkDefaultIpRuleDoesNotExist();
1979
Luke Huangd2861982019-05-17 19:47:28 +08001980 // Set default network back
1981 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001982 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1983
1984 // Test SetPermission
1985 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1986 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1987 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1988 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1989
1990 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1991 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1992 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1993 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1994
1995 // Remove test physical network
1996 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1997}
1998
1999TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08002000 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002001 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2002 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08002003 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002004 EXPECT_TRUE(ret);
2005
Luke Huang854e2992019-05-29 16:42:48 +08002006 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002007 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08002008
2009 // Clear uid permission before calling networkCanProtect to ensure
2010 // the call won't be affected by uid permission.
2011 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2012
2013 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002014 EXPECT_FALSE(ret);
2015}
2016
2017namespace {
2018
Luke Huangb5733d72018-08-21 17:17:19 +08002019int readIntFromPath(const std::string& path) {
2020 std::string result = "";
2021 EXPECT_TRUE(ReadFileToString(path, &result));
2022 return std::stoi(result);
2023}
2024
2025int getTetherAcceptIPv6Ra(const std::string& ifName) {
2026 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2027 return readIntFromPath(path);
2028}
2029
2030bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2031 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2032 return readIntFromPath(path);
2033}
2034
2035int getTetherIPv6DadTransmits(const std::string& ifName) {
2036 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2037 return readIntFromPath(path);
2038}
2039
2040bool getTetherEnableIPv6(const std::string& ifName) {
2041 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2042 int disableIPv6 = readIntFromPath(path);
2043 return !disableIPv6;
2044}
2045
2046bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2047 for (const auto& iface : ifList) {
2048 if (iface == ifName) {
2049 return true;
2050 }
2051 }
2052 return false;
2053}
2054
2055void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2056 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2057 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2058 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2059 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2060}
2061
2062void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2063 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2064 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2065 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2066 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2067}
2068
2069void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2070 const std::string& ifName) {
2071 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2072}
2073
2074void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2075 const std::string& ifName) {
2076 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2077}
2078
2079void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2080 const std::vector<std::string>& testDnsAddrs) {
2081 EXPECT_TRUE(dnsList == testDnsAddrs);
2082}
2083
2084} // namespace
2085
2086TEST_F(BinderTest, TetherStartStopStatus) {
2087 std::vector<std::string> noDhcpRange = {};
2088 static const char dnsdName[] = "dnsmasq";
2089
2090 binder::Status status = mNetd->tetherStart(noDhcpRange);
2091 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangd1675922019-03-11 17:29:27 +08002092 expectProcessExists(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002093
2094 bool tetherEnabled;
2095 status = mNetd->tetherIsEnabled(&tetherEnabled);
2096 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2097 EXPECT_TRUE(tetherEnabled);
2098
2099 status = mNetd->tetherStop();
2100 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08002101 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002102
2103 status = mNetd->tetherIsEnabled(&tetherEnabled);
2104 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2105 EXPECT_FALSE(tetherEnabled);
2106}
2107
2108TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2109 // TODO: verify if dnsmasq update interface successfully
2110
2111 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2112 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2113 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2114
2115 std::vector<std::string> ifList;
2116 status = mNetd->tetherInterfaceList(&ifList);
2117 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2118 expectTetherInterfaceExists(ifList, sTun.name());
2119
2120 status = mNetd->tetherInterfaceRemove(sTun.name());
2121 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2122 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2123
2124 status = mNetd->tetherInterfaceList(&ifList);
2125 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2126 expectTetherInterfaceNotExists(ifList, sTun.name());
2127}
2128
2129TEST_F(BinderTest, TetherDnsSetList) {
2130 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002131 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2132 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002133
2134 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2135 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2136
2137 std::vector<std::string> dnsList;
2138 status = mNetd->tetherDnsList(&dnsList);
2139 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2140 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002141}
2142
2143namespace {
2144
2145constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2146constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2147constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2148constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2149constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2150constexpr char FIREWALL_STANDBY[] = "fw_standby";
2151constexpr char targetReturn[] = "RETURN";
2152constexpr char targetDrop[] = "DROP";
2153
2154void expectFirewallWhitelistMode() {
2155 static const char dropRule[] = "DROP all";
2156 static const char rejectRule[] = "REJECT all";
2157 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2158 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2159 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2160 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2161 }
2162}
2163
2164void expectFirewallBlacklistMode() {
2165 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2166 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2167 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2168 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2169 }
2170}
2171
2172bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2173 const std::string& expectedInterface,
2174 const std::string& expectedRule) {
2175 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2176 // Expected rule:
2177 // Chain fw_INPUT (1 references)
2178 // pkts bytes target prot opt in out source destination
2179 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2180 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2181 int firstRuleIndex = 2;
2182 if (rules.size() < 4) return false;
2183 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2184 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2185 return true;
2186 }
2187 }
2188 return false;
2189}
2190
2191// TODO: It is a duplicate function, need to remove it
2192bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2193 const std::string& expectedInterface,
2194 const std::string& expectedRule) {
2195 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2196 for (const auto& rule : rules) {
2197 if (rule.find(expectedInterface) != std::string::npos) {
2198 if (rule.find(expectedRule) != std::string::npos) {
2199 return true;
2200 }
2201 }
2202 }
2203 return false;
2204}
2205
2206void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2207 static const char returnRule[] = "RETURN all";
2208 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2209 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2210 returnRule));
2211 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2212 returnRule));
2213 }
2214}
2215
2216void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2217 static const char returnRule[] = "RETURN all";
2218 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2219 EXPECT_FALSE(
2220 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2221 EXPECT_FALSE(
2222 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2223 }
2224}
2225
2226bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2227 const std::string& expectedTarget,
2228 const std::string& expectedRule) {
2229 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2230 int firstRuleIndex = 2;
2231 if (rules.size() < 4) return false;
2232 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2233 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2234 return true;
2235 }
2236 }
2237 return false;
2238}
2239
2240bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2241 const std::string& expectedTarget,
2242 const std::string& expectedRule) {
2243 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2244 int lastRuleIndex = rules.size() - 1;
2245 if (lastRuleIndex < 0) return false;
2246 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2247 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2248 return true;
2249 }
2250 }
2251 return false;
2252}
2253
2254void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2255 std::string uidRule = StringPrintf("owner UID match %u", uid);
2256 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2257 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2258}
2259
2260void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2261 std::string uidRule = StringPrintf("owner UID match %u", uid);
2262 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2263 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2264}
2265
2266void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2267 std::string uidRule = StringPrintf("owner UID match %u", uid);
2268 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2269 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2270}
2271
2272void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2273 std::string uidRule = StringPrintf("owner UID match %u", uid);
2274 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2275 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2276}
2277
2278bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2279 std::vector<std::string> inputRules =
2280 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2281 std::vector<std::string> outputRules =
2282 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2283 int inputLastRuleIndex = inputRules.size() - 1;
2284 int outputLastRuleIndex = outputRules.size() - 1;
2285
2286 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2287 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2288 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2289 return true;
2290 }
2291 }
2292 return false;
2293}
2294
2295void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2296 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2297 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2298}
2299
2300void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2301 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2302 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2303 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2304 }
2305}
2306
2307} // namespace
2308
2309TEST_F(BinderTest, FirewallSetFirewallType) {
2310 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2311 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2312 expectFirewallWhitelistMode();
2313
2314 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2315 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2316 expectFirewallBlacklistMode();
2317
2318 // set firewall type blacklist twice
2319 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2320 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2321 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2322 expectFirewallBlacklistMode();
2323
2324 // set firewall type whitelist twice
2325 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2326 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2327 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2328 expectFirewallWhitelistMode();
2329
2330 // reset firewall type to default
2331 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2332 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2333 expectFirewallBlacklistMode();
2334}
2335
2336TEST_F(BinderTest, FirewallSetInterfaceRule) {
2337 // setinterfaceRule is not supported in BLACKLIST MODE
2338 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2339 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2340
2341 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2342 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2343
2344 // set WHITELIST mode first
2345 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2347
2348 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2349 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2350 expectFirewallInterfaceRuleAllowExists(sTun.name());
2351
2352 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2353 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2354 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2355
2356 // reset firewall mode to default
2357 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2358 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2359 expectFirewallBlacklistMode();
2360}
2361
2362TEST_F(BinderTest, FirewallSetUidRule) {
2363 SKIP_IF_BPF_SUPPORTED;
2364
2365 int32_t uid = randomUid();
2366
2367 // Doze allow
2368 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2369 INetd::FIREWALL_RULE_ALLOW);
2370 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2371 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2372
2373 // Doze deny
2374 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2375 INetd::FIREWALL_RULE_DENY);
2376 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2377 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2378
2379 // Powersave allow
2380 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2381 INetd::FIREWALL_RULE_ALLOW);
2382 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2383 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2384
2385 // Powersave deny
2386 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2387 INetd::FIREWALL_RULE_DENY);
2388 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2389 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2390
2391 // Standby deny
2392 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2393 INetd::FIREWALL_RULE_DENY);
2394 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2395 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2396
2397 // Standby allow
2398 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2399 INetd::FIREWALL_RULE_ALLOW);
2400 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2401 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2402
2403 // None deny in BLACKLIST
2404 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2405 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2406 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2407 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2408
2409 // None allow in BLACKLIST
2410 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2411 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2412 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2413 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2414
2415 // set firewall type whitelist twice
2416 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2417 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2418 expectFirewallWhitelistMode();
2419
2420 // None allow in WHITELIST
2421 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2422 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2423 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2424 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2425
2426 // None deny in WHITELIST
2427 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2428 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2429 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2430 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2431
2432 // reset firewall mode to default
2433 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2434 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2435 expectFirewallBlacklistMode();
2436}
2437
2438TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2439 SKIP_IF_BPF_SUPPORTED;
2440
2441 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2442 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2443 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2444
2445 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2446 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2447 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2448
2449 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2450 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2451 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2452
2453 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2454 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2455 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2456
2457 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2458 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2459 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2460
2461 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2462 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2463 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2464}
Luke Huangf7782042018-08-08 13:13:04 +08002465
2466namespace {
2467
2468std::string hwAddrToStr(unsigned char* hwaddr) {
2469 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2470 hwaddr[4], hwaddr[5]);
2471}
2472
2473int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2474 int prefixLength = 0;
2475 uint32_t m = ntohl(mask);
2476 while (m & (1 << 31)) {
2477 prefixLength++;
2478 m = m << 1;
2479 }
2480 return prefixLength;
2481}
2482
2483std::string toStdString(const String16& s) {
2484 return std::string(String8(s.string()));
2485}
2486
2487android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2488 const auto& sys = sSyscalls.get();
2489 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2490 EXPECT_TRUE(isOk(fd.status()));
2491
2492 struct ifreq ifr = {};
2493 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2494
2495 return sys.ioctl(fd.value(), flag, &ifr);
2496}
2497
2498std::string getInterfaceHwAddr(const std::string& ifName) {
2499 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2500
2501 unsigned char hwaddr[ETH_ALEN] = {};
2502 if (isOk(res.status())) {
2503 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2504 }
2505
2506 return hwAddrToStr(hwaddr);
2507}
2508
2509int getInterfaceIPv4Prefix(const std::string& ifName) {
2510 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2511
2512 int prefixLength = 0;
2513 if (isOk(res.status())) {
2514 prefixLength = ipv4NetmaskToPrefixLength(
2515 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2516 }
2517
2518 return prefixLength;
2519}
2520
2521std::string getInterfaceIPv4Addr(const std::string& ifName) {
2522 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2523
2524 struct in_addr addr = {};
2525 if (isOk(res.status())) {
2526 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2527 }
2528
2529 return std::string(inet_ntoa(addr));
2530}
2531
2532std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2533 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2534
2535 unsigned flags = 0;
2536 if (isOk(res.status())) {
2537 flags = res.value().ifr_flags;
2538 }
2539
2540 std::vector<std::string> ifFlags;
2541 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2542 : toStdString(INetd::IF_STATE_DOWN()));
2543
2544 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2545 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2546 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2547 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2548 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2549
2550 return ifFlags;
2551}
2552
2553bool compareListInterface(const std::vector<std::string>& interfaceList) {
2554 const auto& res = InterfaceController::getIfaceNames();
2555 EXPECT_TRUE(isOk(res));
2556
2557 std::vector<std::string> resIfList;
2558 resIfList.reserve(res.value().size());
2559 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2560
2561 return resIfList == interfaceList;
2562}
2563
2564int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2565 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2566 return readIntFromPath(path);
2567}
2568
2569bool getInterfaceEnableIPv6(const std::string& ifName) {
2570 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2571
2572 int disableIPv6 = readIntFromPath(path);
2573 return !disableIPv6;
2574}
2575
2576int getInterfaceMtu(const std::string& ifName) {
2577 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2578 return readIntFromPath(path);
2579}
2580
2581void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2582 EXPECT_TRUE(compareListInterface(interfaceList));
2583}
2584
2585void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2586 const InterfaceConfigurationParcel& interfaceCfg) {
2587 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2588 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2589 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2590 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2591}
2592
2593void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2594 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2595 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2596
2597 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2598 for (const auto& flag : setCfg.flags) {
2599 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2600 }
2601}
2602
2603void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2604 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2605 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2606}
2607
2608void expectInterfaceNoAddr(const std::string& ifName) {
2609 // noAddr
2610 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2611 // noPrefix
2612 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2613}
2614
2615void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2616 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2617 EXPECT_EQ(enableIPv6, enable);
2618}
2619
2620void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2621 int mtuSize = getInterfaceMtu(ifName);
2622 EXPECT_EQ(mtu, mtuSize);
2623}
2624
2625InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2626 const std::string& addr, int prefixLength,
2627 const std::vector<std::string>& flags) {
2628 InterfaceConfigurationParcel cfg;
2629 cfg.ifName = ifName;
2630 cfg.hwAddr = "";
2631 cfg.ipv4Addr = addr;
2632 cfg.prefixLength = prefixLength;
2633 cfg.flags = flags;
2634 return cfg;
2635}
2636
2637void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2638 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2639 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2640
2641 for (const auto& flag : expectedFlags) {
2642 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2643 interfaceCfg.flags.end());
2644 }
2645
2646 for (const auto& flag : unexpectedFlags) {
2647 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2648 interfaceCfg.flags.end());
2649 }
2650}
2651
2652} // namespace
2653
2654TEST_F(BinderTest, InterfaceList) {
2655 std::vector<std::string> interfaceListResult;
2656
2657 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2658 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2659 expectInterfaceList(interfaceListResult);
2660}
2661
2662TEST_F(BinderTest, InterfaceGetCfg) {
2663 InterfaceConfigurationParcel interfaceCfgResult;
2664
2665 // Add test physical network
2666 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2667 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2668
2669 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2670 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2671 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2672 expectTunFlags(interfaceCfgResult);
2673
2674 // Remove test physical network
2675 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2676}
2677
2678TEST_F(BinderTest, InterfaceSetCfg) {
2679 const std::string testAddr = "192.0.2.3";
2680 const int testPrefixLength = 24;
2681 std::vector<std::string> upFlags = {"up"};
2682 std::vector<std::string> downFlags = {"down"};
2683
2684 // Add test physical network
2685 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2686 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2687
2688 // Set tun interface down.
2689 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2690 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2691 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2692 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2693
2694 // Set tun interface up again.
2695 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2696 status = mNetd->interfaceSetCfg(interfaceCfg);
2697 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2698 status = mNetd->interfaceClearAddrs(sTun.name());
2699 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2700
2701 // Remove test physical network
2702 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2703}
2704
2705TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2706 // enable
2707 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2708 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2709 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2710
2711 // disable
2712 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2713 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2714 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2715}
2716
2717TEST_F(BinderTest, InterfaceClearAddr) {
2718 const std::string testAddr = "192.0.2.3";
2719 const int testPrefixLength = 24;
2720 std::vector<std::string> noFlags{};
2721
2722 // Add test physical network
2723 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2724 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2725
2726 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2727 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2728 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2729 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2730
2731 status = mNetd->interfaceClearAddrs(sTun.name());
2732 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2733 expectInterfaceNoAddr(sTun.name());
2734
2735 // Remove test physical network
2736 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2737}
2738
2739TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2740 // Add test physical network
2741 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2742 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2743
2744 // disable
2745 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2746 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2747 expectInterfaceEnableIPv6(sTun.name(), false);
2748
2749 // enable
2750 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2751 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2752 expectInterfaceEnableIPv6(sTun.name(), true);
2753
2754 // Remove test physical network
2755 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2756}
2757
2758TEST_F(BinderTest, InterfaceSetMtu) {
2759 const int testMtu = 1200;
2760
2761 // Add test physical network
2762 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2763 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2764
2765 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2766 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2767 expectInterfaceMtu(sTun.name(), testMtu);
2768
2769 // Remove test physical network
2770 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2771}
Luke Huang19b49c52018-10-22 12:12:05 +09002772
2773namespace {
2774
2775constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2776constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002777constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002778constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2779
Luke Huangae038f82018-11-05 11:17:31 +09002780int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002781 return listIptablesRuleByTable(binary, table, chainName).size();
2782}
2783
2784bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2785 const std::vector<std::string>& targetVec) {
2786 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2787 if (targetVec.size() != rules.size() - 2) {
2788 return false;
2789 }
2790
2791 /*
Luke Huangae038f82018-11-05 11:17:31 +09002792 * Check that the rules match. Note that this function matches substrings, not entire rules,
2793 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002794 * Skip first two lines since rules start from third line.
2795 * Chain chainName (x references)
2796 * pkts bytes target prot opt in out source destination
2797 * ...
2798 */
2799 int rIndex = 2;
2800 for (const auto& target : targetVec) {
2801 if (rules[rIndex].find(target) == std::string::npos) {
2802 return false;
2803 }
2804 rIndex++;
2805 }
2806 return true;
2807}
2808
2809void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2810 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2811 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2812 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002813 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002814 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2815 "DROP"};
2816
2817 // V4
2818 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2819 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002820 EXPECT_TRUE(
2821 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002822 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2823
Luke Huangae038f82018-11-05 11:17:31 +09002824 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002825 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2826
2827 // V6
2828 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002829 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2830 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002831
2832 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2833 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2834 extIf));
2835 }
2836}
2837
2838void expectNatDisable() {
2839 // It is the default DROP rule with tethering disable.
2840 // Chain tetherctrl_FORWARD (1 references)
2841 // pkts bytes target prot opt in out source destination
2842 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2843 std::vector<std::string> forwardV4Match = {"DROP"};
2844 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2845
2846 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002847 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2848 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002849
Luke Huangae038f82018-11-05 11:17:31 +09002850 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2851 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002852
2853 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2854}
2855
2856} // namespace
2857
2858TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002859 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2860 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2861 expectNatEnable(sTun.name(), sTun2.name());
2862
2863 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2864 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2865 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002866}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002867
2868namespace {
2869
2870using TripleInt = std::array<int, 3>;
2871
2872TripleInt readProcFileToTripleInt(const std::string& path) {
2873 std::string valueString;
2874 int min, def, max;
2875 EXPECT_TRUE(ReadFileToString(path, &valueString));
2876 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2877 return {min, def, max};
2878}
2879
2880void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2881 std::string testRmemValues =
2882 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2883 std::string testWmemValues =
2884 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2885 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2886
2887 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2888 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2889
2890 for (int i = 0; i < 3; i++) {
2891 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2892 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2893 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2894 }
2895}
2896
2897} // namespace
2898
2899TEST_F(BinderTest, TcpBufferSet) {
2900 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2901 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2902 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2903 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2904
2905 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2906 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2907}
Luke Huang528af602018-08-29 19:06:05 +08002908
Chenbo Feng48eaed32018-12-26 17:40:21 -08002909namespace {
2910
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002911void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002912 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2913 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2914 for (int32_t uid : uids) {
2915 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2916 if (exist) {
2917 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002918 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002919 } else {
2920 EXPECT_FALSE(isOk(permission));
2921 EXPECT_EQ(ENOENT, permission.status().code());
2922 }
2923 }
2924}
2925
2926} // namespace
2927
2928TEST_F(BinderTest, TestInternetPermission) {
2929 SKIP_IF_BPF_NOT_SUPPORTED;
2930
2931 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2932
2933 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002934 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002935 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002936 checkUidsInPermissionMap(appUids, true);
2937 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2938 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002939}
2940
Luke Huang528af602018-08-29 19:06:05 +08002941TEST_F(BinderTest, UnsolEvents) {
2942 auto testUnsolService = android::net::TestUnsolService::start();
2943 std::string oldTunName = sTun.name();
2944 std::string newTunName = "unsolTest";
2945 testUnsolService->tarVec.push_back(oldTunName);
2946 testUnsolService->tarVec.push_back(newTunName);
2947 auto& cv = testUnsolService->getCv();
2948 auto& cvMutex = testUnsolService->getCvMutex();
2949 binder::Status status = mNetd->registerUnsolicitedEventListener(
2950 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2951 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2952
2953 // TODO: Add test for below events
2954 // StrictCleartextDetected / InterfaceDnsServersAdded
2955 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2956
2957 {
2958 std::unique_lock lock(cvMutex);
2959
2960 // Re-init test Tun, and we expect that we will get some unsol events.
2961 // Use the test Tun device name to verify if we receive its unsol events.
2962 sTun.destroy();
2963 // Use predefined name
2964 sTun.init(newTunName);
2965
2966 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2967 }
2968
2969 // bit mask 1101101000
2970 // Test only covers below events currently
2971 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2972 InterfaceLinkStatusChanged | RouteChanged;
2973 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002974
2975 // Re-init sTun to clear predefined name
2976 sTun.destroy();
2977 sTun.init();
2978}
2979
2980TEST_F(BinderTest, NDC) {
2981 struct Command {
2982 const std::string cmdString;
2983 const std::string expectedResult;
2984 };
2985
2986 // clang-format off
2987 // Do not change the commands order
2988 const Command networkCmds[] = {
2989 {StringPrintf("ndc network create %d", TEST_NETID1),
2990 "200 0 success"},
2991 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2992 "200 0 success"},
2993 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2994 "200 0 success"},
2995 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2996 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2997 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2998 "200 0 success"},
2999 };
3000
3001 const std::vector<Command> ipfwdCmds = {
3002 {"ndc ipfwd enable " + sTun.name(),
3003 "200 0 ipfwd operation succeeded"},
3004 {"ndc ipfwd disable " + sTun.name(),
3005 "200 0 ipfwd operation succeeded"},
3006 {"ndc ipfwd add lo2 lo3",
3007 "400 0 ipfwd operation failed (No such process)"},
3008 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3009 "200 0 ipfwd operation succeeded"},
3010 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3011 "200 0 ipfwd operation succeeded"},
3012 };
3013
3014 static const struct {
3015 const char* ipVersion;
3016 const char* testDest;
3017 const char* testNextHop;
3018 const bool expectSuccess;
3019 const std::string expectedResult;
3020 } kTestData[] = {
3021 {IP_RULE_V4, "0.0.0.0/0", "", true,
3022 "200 0 success"},
3023 {IP_RULE_V4, "10.251.0.0/16", "", true,
3024 "200 0 success"},
3025 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3026 "400 0 addRoute() failed (Invalid argument)",},
3027 {IP_RULE_V6, "::/0", "", true,
3028 "200 0 success"},
3029 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3030 "200 0 success"},
3031 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3032 "400 0 addRoute() failed (Invalid argument)"},
3033 };
3034 // clang-format on
3035
3036 for (const auto& cmd : networkCmds) {
3037 const std::vector<std::string> result = runCommand(cmd.cmdString);
3038 SCOPED_TRACE(cmd.cmdString);
3039 EXPECT_EQ(result.size(), 1U);
3040 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3041 }
3042
3043 for (const auto& cmd : ipfwdCmds) {
3044 const std::vector<std::string> result = runCommand(cmd.cmdString);
3045 SCOPED_TRACE(cmd.cmdString);
3046 EXPECT_EQ(result.size(), 1U);
3047 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3048 }
3049
3050 // Add test physical network
3051 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3052 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3053
3054 for (const auto& td : kTestData) {
3055 const std::string routeAddCmd =
3056 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3057 td.testDest, td.testNextHop);
3058 const std::string routeRemoveCmd =
3059 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3060 sTun.name().c_str(), td.testDest, td.testNextHop);
3061 std::vector<std::string> result = runCommand(routeAddCmd);
3062 SCOPED_TRACE(routeAddCmd);
3063 EXPECT_EQ(result.size(), 1U);
3064 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3065 if (td.expectSuccess) {
3066 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3067 sTun.name().c_str());
3068 result = runCommand(routeRemoveCmd);
3069 EXPECT_EQ(result.size(), 1U);
3070 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3071 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3072 sTun.name().c_str());
3073 }
3074 }
3075 // Remove test physical network
3076 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003077}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003078
Luke Huang2ff8b342019-04-30 15:33:33 +08003079TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003080 sp<IBinder> binder;
3081 binder::Status status = mNetd->getOemNetd(&binder);
3082 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3083 sp<com::android::internal::net::IOemNetd> oemNetd;
3084 if (binder != nullptr) {
3085 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3086 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003087 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003088
3089 TimedOperation t("OemNetd isAlive RPC");
3090 bool isAlive = false;
3091 oemNetd->isAlive(&isAlive);
3092 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003093
3094 class TestOemUnsolListener
3095 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3096 public:
3097 android::binder::Status onRegistered() override {
3098 std::lock_guard lock(mCvMutex);
3099 mCv.notify_one();
3100 return android::binder::Status::ok();
3101 }
3102 std::condition_variable& getCv() { return mCv; }
3103 std::mutex& getCvMutex() { return mCvMutex; }
3104
3105 private:
3106 std::mutex mCvMutex;
3107 std::condition_variable mCv;
3108 };
3109
3110 // Start the Binder thread pool.
3111 android::ProcessState::self()->startThreadPool();
3112
3113 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3114
3115 auto& cv = testListener->getCv();
3116 auto& cvMutex = testListener->getCvMutex();
3117
3118 {
3119 std::unique_lock lock(cvMutex);
3120
3121 status = oemNetd->registerOemUnsolicitedEventListener(
3122 ::android::interface_cast<
3123 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3124 testListener));
3125 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3126
3127 // Wait for receiving expected events.
3128 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3129 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003130}
Luke Huangd2861982019-05-17 19:47:28 +08003131
3132void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3133 int fallthroughNetId) {
3134 // Re-init sTun* to ensure route rule exists.
3135 sTun.destroy();
3136 sTun.init();
3137 sTun2.destroy();
3138 sTun2.init();
3139
3140 // Create physical network with fallthroughNetId but not set it as default network
3141 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3142 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3143
3144 // Create VPN with vpnNetId
3145 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3146
3147 // Add uid to VPN
3148 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3149 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3150
3151 // Add default route to fallthroughNetwork
3152 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3153 // Add limited route
3154 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3155}
3156
3157namespace {
3158
3159class ScopedUidChange {
3160 public:
3161 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3162 mStoredUid = getuid();
3163 if (mInputUid == mStoredUid) return;
3164 EXPECT_TRUE(seteuid(uid) == 0);
3165 }
3166 ~ScopedUidChange() {
3167 if (mInputUid == mStoredUid) return;
3168 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3169 }
3170
3171 private:
3172 uid_t mInputUid;
3173 uid_t mStoredUid;
3174};
3175
3176constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3177
3178void clearQueue(int tunFd) {
3179 char buf[4096];
3180 int ret;
3181 do {
3182 ret = read(tunFd, buf, sizeof(buf));
3183 } while (ret > 0);
3184}
3185
3186void checkDataReceived(int udpSocket, int tunFd) {
3187 char buf[4096] = {};
3188 // Clear tunFd's queue before write something because there might be some
3189 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3190 clearQueue(tunFd);
3191 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3192 // TODO: extract header and verify data
3193 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3194}
3195
3196bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3197 ScopedUidChange scopedUidChange(uid);
3198 android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
3199 if (testSocket < 0) return false;
3200
3201 const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
3202 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3203 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3204 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3205 if (res == -1) return false;
3206
3207 char addr[INET6_ADDRSTRLEN];
3208 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3209 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3210 checkDataReceived(testSocket, tunFd);
3211 return true;
3212}
3213
3214void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3215 std::string vpnFallthroughRule =
3216 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3217 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3218 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3219 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3220 }
3221}
3222
3223void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3224 const TunInterface& fallthroughNetwork,
3225 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3226 int fallthroughNetId = TEST_NETID1) {
3227 // Set default network to NETID_UNSET
3228 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3229
3230 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3231 in6_addr insideVpnAddr = {
3232 {// 2001:db8:cafe::1
3233 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3234 // outsideVpnAddr will hit the route in the fallthrough network route table
3235 // because we added default route in createVpnNetworkWithUid
3236 in6_addr outsideVpnAddr = {
3237 {// 2607:f0d0:1002::4
3238 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3239
3240 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3241 int vpnFd = vpnNetwork.getFdForTesting();
3242 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3243 // default network.
3244 Fwmark fwmark;
3245 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3246 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3247
3248 // Set default network
3249 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3250
3251 // Connections go on the default network because UID 0 is not subject to the VPN.
3252 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3253 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3254 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3255 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3256
3257 // Check if fallthrough rule exists
3258 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3259
3260 // Expect fallthrough to default network
3261 // The fwmark differs depending on whether the VPN is bypassable or not.
3262 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3263 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3264
3265 // Expect connect success, packet will be sent to vpnFd.
3266 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3267 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3268
3269 // Explicitly select vpn network
3270 setNetworkForProcess(vpnNetId);
3271
3272 // Expect fallthrough to default network
3273 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3274 // Expect the mark contains all the bit because we've selected network.
3275 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3276
3277 // Expect connect success, packet will be sent to vpnFd.
3278 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3279 // Expect the mark contains all the bit because we've selected network.
3280 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3281
3282 // Explicitly select fallthrough network
3283 setNetworkForProcess(fallthroughNetId);
3284
3285 // The mark is set to fallthrough network because we've selected it.
3286 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3287 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3288
3289 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3290 if (bypassable) {
3291 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3292 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3293 } else {
3294 // If not, no permission to bypass vpn.
3295 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3296 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3297 }
3298}
3299
3300} // namespace
3301
3302TEST_F(BinderTest, SecureVPNFallthrough) {
3303 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3304 // Get current default network NetId
3305 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3306 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3307}
3308
3309TEST_F(BinderTest, BypassableVPNFallthrough) {
3310 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3311 // Get current default network NetId
3312 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3313 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
3314}