blob: a7b36469eee6b2cc702f5d56547f5666720ff029 [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>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090045#include <android-base/strings.h>
Chiachang Wang00fc62f2019-12-04 20:38:26 +080046#include <android/multinetwork.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080047#include <binder/IPCThreadState.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080048#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070049#include <bpf/BpfUtils.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080050#include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
51#include <com/android/internal/net/IOemNetd.h>
Robin Leeb8087362016-03-30 18:43:08 +010052#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090053#include <gtest/gtest.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080054#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090055#include <netutils/ifc.h>
Luke Huangd2861982019-05-17 19:47:28 +080056#include "Fwmark.h"
Nathan Harold21299f72018-03-16 20:13:03 -070057#include "InterfaceController.h"
Luke Huangd2861982019-05-17 19:47:28 +080058#include "NetdClient.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090059#include "NetdConstants.h"
Chiachang Wang00fc62f2019-12-04 20:38:26 +080060#include "NetworkController.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"
Luke Huang25599322019-06-14 00:34:05 +080065#include "netdutils/InternetAddresses.h"
Mike Yue7e332f2019-03-13 17:15:48 +080066#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070067#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080068#include "netid_client.h" // NETID_UNSET
Lorenzo Colitti758bccc2019-06-26 22:12:35 +090069#include "test_utils.h"
Mike Yu5ae61542018-10-19 22:11:43 +080070#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090071
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090072#define IP6TABLES_PATH "/system/bin/ip6tables"
73#define IPTABLES_PATH "/system/bin/iptables"
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;
Bernie Innocentid26a04a2019-10-30 17:15:15 +090091using android::base::unique_fd;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090092using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080093using android::net::InterfaceConfigurationParcel;
94using android::net::InterfaceController;
Chiachang Wang00fc62f2019-12-04 20:38:26 +080095using android::net::MarkMaskParcel;
Luke Huangcaebcbb2018-09-27 20:37:14 +080096using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090097using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090098using android::net::UidRangeParcel;
Luke Huang25599322019-06-14 00:34:05 +080099using android::netdutils::ScopedAddrinfo;
Luke Huangf7782042018-08-08 13:13:04 +0800100using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +0800101using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +0100102
103static const char* IP_RULE_V4 = "-4";
104static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900105static const int TEST_NETID1 = 65501;
106static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800107
108// Use maximum reserved appId for applications to avoid conflict with existing
109// uids.
110static const int TEST_UID1 = 99999;
111static const int TEST_UID2 = 99998;
112
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900113constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900114
Benedict Wongb2daefb2017-12-06 22:05:46 -0800115static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
116static const std::string ESP_ALLOW_RULE("esp");
117
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900118class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900119 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900120 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900121 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900122 sp<IBinder> binder = sm->getService(String16("netd"));
123 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900124 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900125 }
126 }
127
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900128 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900129 ASSERT_NE(nullptr, mNetd.get());
130 }
131
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900132 void TearDown() override {
133 mNetd->networkDestroy(TEST_NETID1);
134 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800135 setNetworkForProcess(NETID_UNSET);
136 // Restore default network
137 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900138 }
139
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900140 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700141
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900142 // Static because setting up the tun interface takes about 40ms.
143 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900144 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900145 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900146 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900147 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900148 }
149
150 static void TearDownTestCase() {
151 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900152 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900153 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900154 }
155
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900156 static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
157 unique_fd* acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900158
Luke Huangd2861982019-05-17 19:47:28 +0800159 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
160 int fallthroughNetId = TEST_NETID1);
161
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900162 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800163 // Use -1 to represent that default network was not modified because
164 // real netId must be an unsigned value.
165 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900166 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900167 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900168 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900169};
170
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900171TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900172TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900173
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900174class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900175 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700176 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900177 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900178 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179 }
180
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900181 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900182 std::string mName;
183};
184
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900185TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900186 TimedOperation t("isAlive RPC");
187 bool isAlive = false;
188 mNetd->isAlive(&isAlive);
189 ASSERT_TRUE(isAlive);
190}
191
Benedict Wongb2daefb2017-12-06 22:05:46 -0800192static bool iptablesNoSocketAllowRuleExists(const char *chainName){
193 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
194 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
195}
196
197static bool iptablesEspAllowRuleExists(const char *chainName){
198 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
199 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
200}
201
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900202TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700203 SKIP_IF_BPF_SUPPORTED;
204
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900205 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
206 const int kNumUids = 500;
207 std::vector<int32_t> noUids(0);
208 std::vector<int32_t> uids(kNumUids);
209 for (int i = 0; i < kNumUids; i++) {
210 uids[i] = randomUid();
211 }
212
213 bool ret;
214 {
215 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900216 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900217 }
218 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800219 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
220 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
221 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
222 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900223 {
224 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900225 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900226 }
227 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900228 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
229 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900230
231 {
232 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900233 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900234 }
235 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900236 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
237 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800238 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
239 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900240
241 {
242 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900243 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900244 }
245 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900246 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
247 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900248
249 // Check that the call fails if iptables returns an error.
250 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900251 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900252 EXPECT_EQ(false, ret);
253}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900254
Benedict Wong319f17e2018-05-15 17:06:44 -0700255TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700256 const struct TestData {
257 const std::string family;
258 const std::string deviceName;
259 const std::string localAddress;
260 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800261 int32_t iKey;
262 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700263 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800264 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700265 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
266 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
267 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800268 };
269
Sehee Park8659b8d2018-11-16 10:53:16 +0900270 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700271 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800272
273 binder::Status status;
274
Benedict Wong319f17e2018-05-15 17:06:44 -0700275 // Create Tunnel Interface.
276 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700277 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800278 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
279
Benedict Wonga450e722018-05-07 10:29:02 -0700280 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900281 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700282
Benedict Wong319f17e2018-05-15 17:06:44 -0700283 // Update Tunnel Interface.
284 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700285 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800286 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
287
Benedict Wong319f17e2018-05-15 17:06:44 -0700288 // Remove Tunnel Interface.
289 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800290 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700291
292 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900293 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800294 }
295}
296
Benedict Wong1cb73df2018-12-03 00:54:14 -0800297TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900298 unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Benedict Wong1cb73df2018-12-03 00:54:14 -0800299 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
300
301 int sockOptVal = UDP_ENCAP_ESPINUDP;
302 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
303
304 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
305 EXPECT_TRUE(res.isOk());
306
307 struct stat info;
308 EXPECT_EQ(0, fstat(sockFd.get(), &info));
309 EXPECT_EQ(1001, (int) info.st_uid);
310}
311
Nathan Harold2deff322018-05-10 14:03:48 -0700312// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
313// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
314#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900315
316using android::net::XfrmController;
317
Benedict Wonga04ffa72018-05-09 21:42:42 -0700318static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
319 static_cast<int>(android::net::XfrmDirection::OUT)};
320static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
321
Nathan Harold21299f72018-03-16 20:13:03 -0700322#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
323 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900324bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900325 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700326 SCOPED_TRACE(status);
327 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
328
329 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700330 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700331 SCOPED_TRACE(status);
332 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
333
334 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700335 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
336 0xD00D, 0xE00D, false)
337 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700338}
339
Benedict Wonga04ffa72018-05-09 21:42:42 -0700340TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900341 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700342
343 // Repeat to ensure cleanup and recreation works correctly
344 for (int i = 0; i < 2; i++) {
345 for (int direction : XFRM_DIRECTIONS) {
346 for (int addrFamily : ADDRESS_FAMILIES) {
347 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700348 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700349 EXPECT_TRUE(status.isOk())
350 << " family: " << addrFamily << " direction: " << direction;
351 }
352 }
353
354 // Cleanup
355 for (int direction : XFRM_DIRECTIONS) {
356 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700357 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700358 EXPECT_TRUE(status.isOk());
359 }
360 }
361 }
362}
363
364TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
365 binder::Status status;
366
367 // Repeat to ensure cleanup and recreation works correctly
368 for (int i = 0; i < 2; i++) {
369 for (int direction : XFRM_DIRECTIONS) {
370 for (int addrFamily : ADDRESS_FAMILIES) {
371 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700372 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700373 EXPECT_TRUE(status.isOk())
374 << " family: " << addrFamily << " direction: " << direction;
375 }
376 }
377
378 // Cleanup
379 for (int direction : XFRM_DIRECTIONS) {
380 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700381 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700382 EXPECT_TRUE(status.isOk());
383 }
384 }
385 }
386}
387
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900388TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900389 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700390 status = XfrmController::Init();
391 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700392
393 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
394 // feature.
395 if (status.code() == EOPNOTSUPP) return;
396
Nathan Harold21299f72018-03-16 20:13:03 -0700397 ASSERT_TRUE(status.ok());
398
399 int32_t spi = 0;
400
401 ASSERT_TRUE(allocateIpSecResources(true, &spi));
402 ASSERT_TRUE(allocateIpSecResources(false, &spi));
403
404 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700405 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700406 ASSERT_TRUE(allocateIpSecResources(true, &spi));
407
408 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700409 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700410 SCOPED_TRACE(status);
411 ASSERT_TRUE(status.ok());
412
Benedict Wonga450e722018-05-07 10:29:02 -0700413 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700414 SCOPED_TRACE(status);
415 ASSERT_TRUE(status.ok());
416
417 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700418 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700419}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900420
421#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700422
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900423static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900424 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900425
426 // Output looks like this:
427 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900428 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900429 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900430 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900431 //
432 // or:
433 //
434 // Chain bw_data_saver (1 references)
435 // target prot opt source destination
436 // ... possibly connectivity critical packet rules here ...
437 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900438
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900439 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900440
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900441 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
442 // Data saver disabled.
443 return 0;
444 }
445
446 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
447
448 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
449 // Data saver enabled.
450 return 1;
451 }
452
453 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900454}
455
456bool enableDataSaver(sp<INetd>& netd, bool enable) {
457 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
458 bool ret;
459 netd->bandwidthEnableDataSaver(enable, &ret);
460 return ret;
461}
462
463int getDataSaverState() {
464 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
465 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
466 EXPECT_EQ(enabled4, enabled6);
467 EXPECT_NE(-1, enabled4);
468 EXPECT_NE(-1, enabled6);
469 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
470 return -1;
471 }
472 return enabled6;
473}
474
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900475TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900476 const int wasEnabled = getDataSaverState();
477 ASSERT_NE(-1, wasEnabled);
478
479 if (wasEnabled) {
480 ASSERT_TRUE(enableDataSaver(mNetd, false));
481 EXPECT_EQ(0, getDataSaverState());
482 }
483
484 ASSERT_TRUE(enableDataSaver(mNetd, false));
485 EXPECT_EQ(0, getDataSaverState());
486
487 ASSERT_TRUE(enableDataSaver(mNetd, true));
488 EXPECT_EQ(1, getDataSaverState());
489
490 ASSERT_TRUE(enableDataSaver(mNetd, true));
491 EXPECT_EQ(1, getDataSaverState());
492
493 if (!wasEnabled) {
494 ASSERT_TRUE(enableDataSaver(mNetd, false));
495 EXPECT_EQ(0, getDataSaverState());
496 }
497}
Robin Leeb8087362016-03-30 18:43:08 +0100498
Luke Huang94658ac2018-10-18 19:35:12 +0900499static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
500 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100501 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100502 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100503 std::vector<std::string> rules = listIpRules(ipVersion);
504
505 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900506 std::string suffix =
507 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900508 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800509 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100510 return true;
511 }
512 }
513 return false;
514}
515
Luke Huang94658ac2018-10-18 19:35:12 +0900516static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
517 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100518 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
519 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
520 EXPECT_EQ(existsIp4, existsIp6);
521 return existsIp4;
522}
523
Luke Huang94658ac2018-10-18 19:35:12 +0900524namespace {
525
526UidRangeParcel makeUidRangeParcel(int start, int stop) {
527 UidRangeParcel res;
528 res.start = start;
529 res.stop = stop;
530
531 return res;
532}
533
534} // namespace
535
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900536TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800537 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
538 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
539 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900540 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
541 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900542
543 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
544 EXPECT_EQ(EBUSY,
545 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
546
547 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
548 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
549 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800550 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900551}
552
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900553TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900554 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
555
cken67cd14c2018-12-05 17:26:59 +0900556 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
557 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900558 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
559
Luke Huang94658ac2018-10-18 19:35:12 +0900560 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
561 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
562 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900563 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
564
565 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
566
567 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
568 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
569 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
570 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
571
572 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
573 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
574 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
575 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
576
577 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
578}
579
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900580TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100581 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100582
Luke Huang94658ac2018-10-18 19:35:12 +0900583 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
584 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800585 // Make sure no rules existed before calling commands.
586 for (auto const& range : uidRanges) {
587 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
588 }
Robin Leeb8087362016-03-30 18:43:08 +0100589 // Create two valid rules.
590 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100591 for (auto const& range : uidRanges) {
592 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
593 }
594
595 // Remove the rules.
596 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100597 for (auto const& range : uidRanges) {
598 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
599 }
600
601 // Fail to remove the rules a second time after they are already deleted.
602 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
603 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
604 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100605}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900606
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900607// Create a socket pair that isLoopbackSocket won't think is local.
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900608void BinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
609 unique_fd* acceptedSocket) {
610 serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900611 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900612 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
613
614 socklen_t addrlen = sizeof(server6);
615 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
616 ASSERT_EQ(0, listen(*serverSocket, 10));
617
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900618 clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900619 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900620 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900621 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
622 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
623
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900624 acceptedSocket->reset(
625 accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900626 ASSERT_NE(-1, *acceptedSocket);
627
628 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
629}
630
631void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
632 char buf[4096];
633 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
634 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
635 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
636}
637
638void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
639 // Check that the client socket was closed with ECONNABORTED.
640 int ret = write(clientSocket, "foo", sizeof("foo"));
641 int err = errno;
642 EXPECT_EQ(-1, ret);
643 EXPECT_EQ(ECONNABORTED, err);
644
645 // Check that it sent a RST to the server.
646 ret = write(acceptedSocket, "foo", sizeof("foo"));
647 err = errno;
648 EXPECT_EQ(-1, ret);
649 EXPECT_EQ(ECONNRESET, err);
650}
651
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900652TEST_F(BinderTest, SocketDestroy) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900653 unique_fd clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900654 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900655
656 // Pick a random UID in the system UID range.
657 constexpr int baseUid = AID_APP - 2000;
658 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
659 int uid = baseUid + 500 + arc4random_uniform(1000);
660 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
661
662 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900663 std::vector<UidRangeParcel> uidRanges = {
664 makeUidRangeParcel(baseUid + 42, baseUid + 449),
665 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
666 makeUidRangeParcel(baseUid + 498, uid - 1),
667 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900668 };
669 // A skip list that doesn't contain UID.
670 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
671
672 // Close sockets. Our test socket should be intact.
673 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
674 checkSocketpairOpen(clientSocket, acceptedSocket);
675
676 // UID ranges that do contain uid.
677 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900678 makeUidRangeParcel(baseUid + 42, baseUid + 449),
679 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
680 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900681 };
682 // Add uid to the skip list.
683 skipUids.push_back(uid);
684
685 // Close sockets. Our test socket should still be intact because it's in the skip list.
686 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
687 checkSocketpairOpen(clientSocket, acceptedSocket);
688
689 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
690 skipUids.resize(skipUids.size() - 1);
691 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
692 checkSocketpairClosed(clientSocket, acceptedSocket);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900693}
Erik Klinecc4f2732016-08-03 11:24:27 +0900694
695namespace {
696
697int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
698 if (buf == nullptr) return -1;
699
700 int prefixLength = 0;
701 bool endOfContiguousBits = false;
702 for (unsigned int i = 0; i < buflen; i++) {
703 const uint8_t value = buf[i];
704
705 // Bad bit sequence: check for a contiguous set of bits from the high
706 // end by verifying that the inverted value + 1 is a power of 2
707 // (power of 2 iff. (v & (v - 1)) == 0).
708 const uint8_t inverse = ~value + 1;
709 if ((inverse & (inverse - 1)) != 0) return -1;
710
711 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
712
713 // Bogus netmask.
714 if (endOfContiguousBits && value != 0) return -1;
715
716 if (value != 0xff) endOfContiguousBits = true;
717 }
718
719 return prefixLength;
720}
721
722template<typename T>
723int netmaskToPrefixLength(const T *p) {
724 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
725}
726
727
728static bool interfaceHasAddress(
729 const std::string &ifname, const char *addrString, int prefixLength) {
730 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900731
732 const struct addrinfo hints = {
733 .ai_flags = AI_NUMERICHOST,
734 .ai_family = AF_UNSPEC,
735 .ai_socktype = SOCK_DGRAM,
736 };
737 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
738 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
739 return false;
740 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900741 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900742
743 struct ifaddrs *ifaddrsList = nullptr;
744 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
745
746 if (getifaddrs(&ifaddrsList) != 0) {
747 return false;
748 }
749
750 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
751 if (std::string(addr->ifa_name) != ifname ||
752 addr->ifa_addr == nullptr ||
753 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
754 continue;
755 }
756
757 switch (addr->ifa_addr->sa_family) {
758 case AF_INET: {
759 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
760 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
761 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
762 continue;
763 }
764
765 if (prefixLength < 0) return true; // not checking prefix lengths
766
767 if (addr->ifa_netmask == nullptr) return false;
768 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
769 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
770 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
771 }
772 case AF_INET6: {
773 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
774 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
775 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
776 continue;
777 }
778
779 if (prefixLength < 0) return true; // not checking prefix lengths
780
781 if (addr->ifa_netmask == nullptr) return false;
782 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
783 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
784 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
785 }
786 default:
787 // Cannot happen because we have already screened for matching
788 // address families at the top of each iteration.
789 continue;
790 }
791 }
792
793 return false;
794}
795
796} // namespace
797
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900798TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900799 static const struct TestData {
800 const char *addrString;
801 const int prefixLength;
Lorenzo Colitti01118982019-12-02 13:19:44 +0900802 const int expectAddResult;
803 const int expectRemoveResult;
Erik Klinecc4f2732016-08-03 11:24:27 +0900804 } kTestData[] = {
Lorenzo Colitti01118982019-12-02 13:19:44 +0900805 {"192.0.2.1", 24, 0, 0},
806 {"192.0.2.2", 25, 0, 0},
807 {"192.0.2.3", 32, 0, 0},
808 {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL},
809 {"192.not.an.ip", 24, EINVAL, EINVAL},
810 {"2001:db8::1", 64, 0, 0},
811 {"2001:db8::2", 65, 0, 0},
812 {"2001:db8::3", 128, 0, 0},
813 {"2001:db8::4", 129, EINVAL, EINVAL},
814 {"foo:bar::bad", 64, EINVAL, EINVAL},
815 {"2001:db8::1/64", 64, EINVAL, EINVAL},
Erik Klinecc4f2732016-08-03 11:24:27 +0900816 };
817
Sehee Park8659b8d2018-11-16 10:53:16 +0900818 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900819 const auto &td = kTestData[i];
820
Lorenzo Colitti01118982019-12-02 13:19:44 +0900821 SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength));
822
Erik Klinecc4f2732016-08-03 11:24:27 +0900823 // [1.a] Add the address.
824 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900825 sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900826 if (td.expectAddResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900827 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
828 } else {
829 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900830 ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900831 }
832
833 // [1.b] Verify the addition meets the expectation.
Lorenzo Colitti01118982019-12-02 13:19:44 +0900834 if (td.expectAddResult == 0) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900835 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900836 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900837 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900838 }
839
840 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900841 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900842 if (td.expectRemoveResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900843 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
844 } else {
845 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900846 ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900847 }
848
849 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900850 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900851 }
Lorenzo Colitti9ae17712019-12-02 17:28:49 +0900852
853 // Check that netlink errors are returned correctly.
854 // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled,
855 // which returns EACCES.
856 TunInterface tun;
857 ASSERT_EQ(0, tun.init());
858 binder::Status status =
859 mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1");
860 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
861 status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64);
862 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
863 EXPECT_EQ(EACCES, status.serviceSpecificErrorCode());
864 tun.destroy();
Erik Klinecc4f2732016-08-03 11:24:27 +0900865}
Erik Kline55b06f82016-07-04 09:57:18 +0900866
Erik Kline38e51f12018-09-06 20:14:44 +0900867TEST_F(BinderTest, GetProcSysNet) {
868 const char LOOPBACK[] = "lo";
869 static const struct {
870 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900871 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900872 const char* ifname;
873 const char* parameter;
874 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900875 const int expectedReturnCode;
876 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900877 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
878 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
879 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
880 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
881 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
882 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
883 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900884 };
885
Sehee Park8659b8d2018-11-16 10:53:16 +0900886 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900887 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900888
Erik Kline38e51f12018-09-06 20:14:44 +0900889 std::string value;
890 const binder::Status status =
891 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
892
893 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900894 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900895 EXPECT_EQ(0, status.exceptionCode());
896 EXPECT_EQ(0, status.serviceSpecificErrorCode());
897 EXPECT_EQ(td.expectedValue, value);
898 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900899 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900900 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
901 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
902 }
903 }
904}
905
906TEST_F(BinderTest, SetProcSysNet) {
907 static const struct {
908 const int ipversion;
909 const int which;
910 const char* ifname;
911 const char* parameter;
912 const char* value;
913 const int expectedReturnCode;
914 } kTestData[] = {
915 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
916 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
917 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
918 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
919 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
920 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
921 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
922 };
923
Sehee Park8659b8d2018-11-16 10:53:16 +0900924 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900925 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900926 const binder::Status status =
927 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900928
929 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900930 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900931 EXPECT_EQ(0, status.exceptionCode());
932 EXPECT_EQ(0, status.serviceSpecificErrorCode());
933 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900934 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900935 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
936 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
937 }
938 }
939}
Ben Schwartze7601812017-04-28 16:38:29 -0400940
Erik Kline38e51f12018-09-06 20:14:44 +0900941TEST_F(BinderTest, GetSetProcSysNet) {
942 const int ipversion = INetd::IPV6;
943 const int category = INetd::NEIGH;
944 const std::string& tun = sTun.name();
945 const std::string parameter("ucast_solicit");
946
947 std::string value{};
948 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700949 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900950 const int ival = std::stoi(value);
951 EXPECT_GT(ival, 0);
952 // Try doubling the parameter value (always best!).
953 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
954 .isOk());
955 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
956 EXPECT_EQ(2 * ival, std::stoi(value));
957 // Try resetting the parameter.
958 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
959 .isOk());
960 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
961 EXPECT_EQ(ival, std::stoi(value));
962}
963
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900964namespace {
965
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900966void expectNoTestCounterRules() {
967 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
968 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
969 std::string allRules = Join(runCommand(command), "\n");
970 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
971 }
972}
973
Bernie Innocentif6918262018-06-11 17:37:35 +0900974void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
975 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900976 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
977 path, if1.c_str(), if2.c_str(), pkt, byte));
978}
979
Bernie Innocentif6918262018-06-11 17:37:35 +0900980void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900981 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
982 path, if1.c_str(), if2.c_str()));
983 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
984 path, if2.c_str(), if1.c_str()));
985}
986
Luke Huangcaebcbb2018-09-27 20:37:14 +0800987std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
988 const std::string& iface) {
989 for (auto& stats : statsVec) {
990 if (stats.iface == iface) {
991 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
992 }
993 }
994 return {};
995}
996
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900997} // namespace
998
999TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001000 expectNoTestCounterRules();
1001
1002 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1003 // disabling tethering. We don't check the return value because these commands will fail if
1004 // tethering is already enabled.
1005 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1006 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1007
1008 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1009 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1010 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001011
1012 // Ensure we won't use the same interface name, otherwise the test will fail.
1013 u_int32_t rNumber = arc4random_uniform(10000);
1014 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1015 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001016
1017 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1018 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1019 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1020 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1021 // RX is from external to internal, and TX is from internal to external.
1022 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1023 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1024
1025 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1026 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1027
1028 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1029 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1030
1031 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1032 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1033 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1034
Luke Huangcaebcbb2018-09-27 20:37:14 +08001035 std::vector<TetherStatsParcel> statsVec;
1036 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001037 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1038
Luke Huangcaebcbb2018-09-27 20:37:14 +08001039 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001040
Luke Huangcaebcbb2018-09-27 20:37:14 +08001041 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001042
1043 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1044 delTetherCounterValues(path, intIface1, extIface1);
1045 delTetherCounterValues(path, intIface2, extIface2);
1046 if (path == IP6TABLES_PATH) {
1047 delTetherCounterValues(path, intIface3, extIface2);
1048 }
1049 }
1050
1051 expectNoTestCounterRules();
1052}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001053
Luke Huang0051a622018-07-23 20:30:16 +08001054namespace {
1055
Luke Huanga5211072018-08-01 23:36:29 +08001056constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1057constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001058
1059static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1060 const char* chainName) {
1061 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1062 return runCommand(command);
1063}
1064
Luke Huang19b49c52018-10-22 12:12:05 +09001065// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001066bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001067 const std::string& expectedInterface,
1068 const std::string& expectedRule, const char* table) {
1069 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1070 for (const auto& rule : rules) {
1071 if (rule.find(expectedInterface) != std::string::npos) {
1072 if (rule.find(expectedRule) != std::string::npos) {
1073 return true;
1074 }
1075 }
1076 }
1077 return false;
1078}
1079
1080void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001081 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001082 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001083 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001084 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001085 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1086 IdletimerRule, RAW_TABLE));
1087 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001088 ifname, IdletimerRule, MANGLE_TABLE));
1089 }
1090}
1091
1092void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001093 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001094 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001095 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001096 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001097 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1098 IdletimerRule, RAW_TABLE));
1099 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001100 ifname, IdletimerRule, MANGLE_TABLE));
1101 }
1102}
1103
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001104} // namespace
1105
1106TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001107 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1108 // rule in the table. Because we only check the result after calling remove function. We might
1109 // check the actual rule which is removed by our function (maybe compare the results between
1110 // calling function before and after)
1111 binder::Status status;
1112 const struct TestData {
1113 const std::string ifname;
1114 int32_t timeout;
1115 const std::string classLabel;
1116 } idleTestData[] = {
1117 {"wlan0", 1234, "happyday"},
1118 {"rmnet_data0", 4567, "friday"},
1119 };
1120 for (const auto& td : idleTestData) {
1121 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1122 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1123 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1124
1125 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1126 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1127 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1128 }
1129}
1130
Luke Huanga67dd562018-07-17 19:58:25 +08001131namespace {
1132
1133constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1134constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1135
1136void expectStrictSetUidAccept(const int uid) {
1137 std::string uidRule = StringPrintf("owner UID match %u", uid);
1138 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1139 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001140 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1141 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001142 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1143 }
1144}
1145
1146void expectStrictSetUidLog(const int uid) {
1147 static const char logRule[] = "st_penalty_log all";
1148 std::string uidRule = StringPrintf("owner UID match %u", uid);
1149 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1150 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001151 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1152 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001153 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1154 }
1155}
1156
1157void expectStrictSetUidReject(const int uid) {
1158 static const char rejectRule[] = "st_penalty_reject all";
1159 std::string uidRule = StringPrintf("owner UID match %u", uid);
1160 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1161 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001162 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1163 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001164 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1165 }
1166}
1167
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001168} // namespace
1169
1170TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001171 binder::Status status;
1172 int32_t uid = randomUid();
1173
1174 // setUidCleartextPenalty Policy:Log with randomUid
1175 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1176 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1177 expectStrictSetUidLog(uid);
1178
1179 // setUidCleartextPenalty Policy:Accept with randomUid
1180 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1181 expectStrictSetUidAccept(uid);
1182
1183 // setUidCleartextPenalty Policy:Reject with randomUid
1184 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1185 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1186 expectStrictSetUidReject(uid);
1187
1188 // setUidCleartextPenalty Policy:Accept with randomUid
1189 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1190 expectStrictSetUidAccept(uid);
1191
1192 // test wrong policy
1193 int32_t wrongPolicy = -123;
1194 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1195 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1196}
1197
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001198namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001199
Luke Huangd1675922019-03-11 17:29:27 +08001200std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001201 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001202 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001203 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1204 // ...
1205 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1206
Luke Huangd1675922019-03-11 17:29:27 +08001207 // (dnsmasq)
1208 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1209
1210 if (maxTries == 0) return {};
1211
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001212 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001213 std::vector<std::string> result;
1214 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001215 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001216 if (result.size() || ++run > maxTries) {
1217 break;
1218 }
1219
Luke Huang728cf4c2019-03-14 19:43:02 +08001220 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001221 }
1222 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001223}
1224
Luke Huangd1675922019-03-11 17:29:27 +08001225void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001226 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001227}
1228
Luke Huang728cf4c2019-03-14 19:43:02 +08001229void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001230 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001231}
1232
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001233} // namespace
1234
1235TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001236 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001237
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001238 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1239 std::string clatAddress;
1240 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001241
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001242 // Can't start clatd on an interface that's not part of any network...
1243 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1244 EXPECT_FALSE(status.isOk());
1245 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1246
1247 // ... so create a test physical network and add our tun to it.
1248 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1249 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1250
1251 // Prefix must be 96 bits long.
1252 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1253 EXPECT_FALSE(status.isOk());
1254 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1255
1256 // Can't start clatd unless there's a default route...
1257 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1258 EXPECT_FALSE(status.isOk());
1259 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1260
1261 // so add a default route.
1262 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1263
1264 // Can't start clatd unless there's a global address...
1265 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1266 EXPECT_FALSE(status.isOk());
1267 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1268
1269 // ... so add a global address.
1270 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001271 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001272
1273 // Now expect clatd to start successfully.
1274 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1275 EXPECT_TRUE(status.isOk());
1276 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1277
1278 // Starting it again returns EBUSY.
1279 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1280 EXPECT_FALSE(status.isOk());
1281 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1282
Luke Huangd1675922019-03-11 17:29:27 +08001283 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001284
1285 // Expect clatd to stop successfully.
1286 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001287 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001288 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001289
1290 // Stopping a clatd that doesn't exist returns ENODEV.
1291 status = mNetd->clatdStop(sTun.name());
1292 EXPECT_FALSE(status.isOk());
1293 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001294 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001295
1296 // Clean up.
1297 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1298 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1299 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001300}
Luke Huang457d4702018-08-16 15:39:15 +08001301
1302namespace {
1303
1304bool getIpfwdV4Enable() {
1305 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1306 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1307 EXPECT_TRUE(!result.empty());
1308 int v4Enable = std::stoi(result[0]);
1309 return v4Enable;
1310}
1311
1312bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001313 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001314 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1315 EXPECT_TRUE(!result.empty());
1316 int v6Enable = std::stoi(result[0]);
1317 return v6Enable;
1318}
1319
1320void expectIpfwdEnable(bool enable) {
1321 int enableIPv4 = getIpfwdV4Enable();
1322 int enableIPv6 = getIpfwdV6Enable();
1323 EXPECT_EQ(enable, enableIPv4);
1324 EXPECT_EQ(enable, enableIPv6);
1325}
1326
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001327bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001328 std::vector<std::string> rules = listIpRules(ipVersion);
1329 for (const auto& rule : rules) {
1330 if (rule.find(ipfwdRule) != std::string::npos) {
1331 return true;
1332 }
1333 }
1334 return false;
1335}
1336
1337void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1338 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1339
1340 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1341 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1342 }
1343}
1344
1345void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1346 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1347
1348 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1349 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1350 }
1351}
1352
1353} // namespace
1354
1355TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001356 // Get ipfwd requester list from Netd
1357 std::vector<std::string> requesterList;
1358 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001360
1361 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001362 if (requesterList.size() == 0) {
1363 // No requester in Netd, ipfwd should be disabled
1364 // So add one test requester and verify
1365 status = mNetd->ipfwdEnableForwarding("TestRequester");
1366 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001367
Luke Huang728cf4c2019-03-14 19:43:02 +08001368 expectIpfwdEnable(true);
1369 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1370 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1371 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001372
Luke Huang728cf4c2019-03-14 19:43:02 +08001373 // Remove test one, verify again
1374 status = mNetd->ipfwdDisableForwarding("TestRequester");
1375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1376
1377 expectIpfwdEnable(false);
1378 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1379 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1380 EXPECT_FALSE(ipfwdEnabled);
1381 } else {
1382 // Disable all requesters
1383 for (const auto& requester : requesterList) {
1384 status = mNetd->ipfwdDisableForwarding(requester);
1385 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1386 }
1387
1388 // After disable all requester, ipfwd should be disabled
1389 expectIpfwdEnable(false);
1390 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1391 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1392 EXPECT_FALSE(ipfwdEnabled);
1393
1394 // Enable them back
1395 for (const auto& requester : requesterList) {
1396 status = mNetd->ipfwdEnableForwarding(requester);
1397 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1398 }
1399
1400 // ipfwd should be enabled
1401 expectIpfwdEnable(true);
1402 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1403 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1404 EXPECT_TRUE(ipfwdEnabled);
1405 }
Luke Huang457d4702018-08-16 15:39:15 +08001406}
1407
1408TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001409 // Add test physical network
1410 EXPECT_TRUE(
1411 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1412 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1413 EXPECT_TRUE(
1414 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1415 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001416
Luke Huangd1827b82019-02-15 15:03:27 +08001417 binder::Status status =
1418 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1419 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1420 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001421
Luke Huangd1827b82019-02-15 15:03:27 +08001422 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1423 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1424 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001425}
Luke Huang531f5d32018-08-03 15:19:05 +08001426
1427namespace {
1428
1429constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1430constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1431constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1432constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1433constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001434constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001435
Luke Huang19b49c52018-10-22 12:12:05 +09001436// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1437// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001438bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1439 const char* chainName, const std::string& expectedTargetA,
1440 const std::string& expectedTargetB) {
1441 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1442 int matchCount = 0;
1443
1444 for (const auto& rule : rules) {
1445 if (rule.find(expectedTargetA) != std::string::npos) {
1446 if (rule.find(expectedTargetB) != std::string::npos) {
1447 matchCount++;
1448 }
1449 }
1450 }
1451 return matchCount == expectedCount;
1452}
1453
1454void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1455 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1456 std::string result = "";
1457
1458 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001459 // Quota value might be decreased while matching packets
1460 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001461}
1462
1463void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1464 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1465 std::string quotaRule = StringPrintf("quota %s", ifname);
1466
1467 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1468 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1469 BANDWIDTH_COSTLY_IF));
1470 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1471 BANDWIDTH_COSTLY_IF));
1472 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1473 BANDWIDTH_COSTLY_IF));
1474 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1475 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1476 }
1477 expectXtQuotaValueEqual(ifname, quotaBytes);
1478}
1479
1480void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1481 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1482 std::string quotaRule = StringPrintf("quota %s", ifname);
1483
1484 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1485 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1486 BANDWIDTH_COSTLY_IF));
1487 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1488 BANDWIDTH_COSTLY_IF));
1489 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1490 BANDWIDTH_COSTLY_IF));
1491 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1492 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1493 }
1494}
1495
1496void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1497 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1498 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1499 std::string alertName = StringPrintf("%sAlert", ifname);
1500
1501 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1502 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1503 }
1504 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1505}
1506
1507void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1508 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1509 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1510
1511 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1512 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1513 }
1514}
1515
1516void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1517 static const char globalAlertRule[] = "quota globalAlert";
1518 static const char globalAlertName[] = "globalAlert";
1519
1520 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001521 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001522 }
1523 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1524}
1525
1526void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1527 std::string uidRule = StringPrintf("owner UID match %u", uid);
1528
1529 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1530 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1531 }
1532}
1533
1534void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1535 std::string uidRule = StringPrintf("owner UID match %u", uid);
1536
1537 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1538 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1539 }
1540}
1541
1542} // namespace
1543
1544TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1545 long testQuotaBytes = 5550;
1546
1547 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001548 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001549 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1550
1551 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1552 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1553 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1554
1555 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1556 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1557 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1558
1559 // Remove test physical network
1560 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1561}
1562
1563TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1564 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001565 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001566 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001567 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001568 // Need to have a prior interface quota set to set an alert
1569 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1570 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1571 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1572 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1573
1574 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1575 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1576 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1577
1578 // Remove interface quota
1579 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1580 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1581 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1582
1583 // Remove test physical network
1584 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1585}
1586
1587TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001588 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001589
1590 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1591 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1592 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1593
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001594 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001595 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1596 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1597 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1598}
1599
1600TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1601 SKIP_IF_BPF_SUPPORTED;
1602
1603 int32_t uid = randomUid();
1604 static const char targetReject[] = "REJECT";
1605 static const char targetReturn[] = "RETURN";
1606
1607 // add NaughtyApp
1608 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1609 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1610 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1611
1612 // remove NaughtyApp
1613 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1614 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1615 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1616
1617 // add NiceApp
1618 status = mNetd->bandwidthAddNiceApp(uid);
1619 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1620 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1621
1622 // remove NiceApp
1623 status = mNetd->bandwidthRemoveNiceApp(uid);
1624 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1625 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1626}
Luke Huangb5733d72018-08-21 17:17:19 +08001627
1628namespace {
1629
Luke Huangc3252cc2018-10-16 15:43:23 +08001630std::string ipRouteString(const std::string& ifName, const std::string& dst,
Tyler Wearfa94a272019-12-05 15:01:48 -08001631 const std::string& nextHop, const std::string& mtu) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001632 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1633
1634 if (!nextHop.empty()) {
1635 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001636 }
1637
Tyler Wearfa94a272019-12-05 15:01:48 -08001638 dstString += " dev " + ifName;
1639
1640 if (!mtu.empty()) {
1641 dstString += " proto static";
1642 // IPv6 routes report the metric, IPv4 routes report the scope.
1643 // TODO: move away from specifying the entire string and use a regexp instead.
1644 if (dst.find(':') != std::string::npos) {
1645 dstString += " metric 1024";
1646 } else {
1647 if (nextHop.empty()) {
1648 dstString += " scope link";
1649 }
1650 }
1651 dstString += " mtu " + mtu;
1652 }
1653
1654 return dstString;
1655}
1656
1657void expectNetworkRouteExistsWithMtu(const char* ipVersion, const std::string& ifName,
1658 const std::string& dst, const std::string& nextHop,
1659 const std::string& mtu, const char* table) {
1660 std::string routeString = ipRouteString(ifName, dst, nextHop, mtu);
1661 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, mtu)))
1662 << "Couldn't find route to " << dst << ": '" << routeString << "' in table " << table;
Luke Huangb670d162018-08-23 20:01:13 +08001663}
1664
Luke Huangc3252cc2018-10-16 15:43:23 +08001665void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1666 const std::string& dst, const std::string& nextHop,
1667 const char* table) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001668 expectNetworkRouteExistsWithMtu(ipVersion, ifName, dst, nextHop, "", table);
Luke Huangc3252cc2018-10-16 15:43:23 +08001669}
1670
1671void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001672 const std::string& dst, const std::string& nextHop,
1673 const char* table) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001674 std::string routeString = ipRouteString(ifName, dst, nextHop, "");
1675 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, "")))
1676 << "Found unexpected route " << routeString << " in table " << table;
Luke Huangb670d162018-08-23 20:01:13 +08001677}
1678
1679bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1680 std::vector<std::string> rules = listIpRules(ipVersion);
1681 for (const auto& rule : rules) {
1682 if (rule.find(ipRule) != std::string::npos) {
1683 return true;
1684 }
1685 }
1686 return false;
1687}
1688
1689void expectNetworkDefaultIpRuleExists(const char* ifName) {
1690 std::string networkDefaultRule =
1691 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1692
1693 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1694 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1695 }
1696}
1697
1698void expectNetworkDefaultIpRuleDoesNotExist() {
1699 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1700
1701 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1702 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1703 }
1704}
1705
1706void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1707 std::string networkPermissionRule = "";
1708 switch (permission) {
1709 case INetd::PERMISSION_NONE:
1710 networkPermissionRule = StringPrintf(
1711 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1712 break;
1713 case INetd::PERMISSION_NETWORK:
1714 networkPermissionRule = StringPrintf(
1715 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1716 break;
1717 case INetd::PERMISSION_SYSTEM:
1718 networkPermissionRule = StringPrintf(
1719 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1720 break;
1721 }
1722
1723 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1724 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1725 }
1726}
1727
1728// TODO: It is a duplicate function, need to remove it
1729bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1730 const std::string& expectedInterface,
1731 const std::string& expectedRule,
1732 const char* table) {
1733 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1734 for (const auto& rule : rules) {
1735 if (rule.find(expectedInterface) != std::string::npos) {
1736 if (rule.find(expectedRule) != std::string::npos) {
1737 return true;
1738 }
1739 }
1740 }
1741 return false;
1742}
1743
1744void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1745 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1746 std::string networkIncomingPacketMarkRule = "";
1747 switch (permission) {
1748 case INetd::PERMISSION_NONE:
1749 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1750 break;
1751 case INetd::PERMISSION_NETWORK:
1752 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1753 break;
1754 case INetd::PERMISSION_SYSTEM:
1755 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1756 break;
1757 }
1758
1759 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1760 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1761 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1762 }
1763}
1764
1765} // namespace
1766
1767TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001768 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001769 const char* ipVersion;
1770 const char* testDest;
1771 const char* testNextHop;
1772 const bool expectSuccess;
1773 } kTestData[] = {
1774 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001775 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1776 {IP_RULE_V4, "10.251.0.0/16", "", true},
1777 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1778 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001779 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001780 {IP_RULE_V6, "::/0", "2001:db8::", true},
1781 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001782 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1783 };
1784
Luke Huangc3252cc2018-10-16 15:43:23 +08001785 static const struct {
1786 const char* ipVersion;
1787 const char* testDest;
1788 const char* testNextHop;
1789 } kTestDataWithNextHop[] = {
1790 {IP_RULE_V4, "10.251.10.0/30", ""},
1791 {IP_RULE_V6, "2001:db8::/32", ""},
1792 };
1793
Luke Huangb670d162018-08-23 20:01:13 +08001794 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001795 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001796 const int testUid = randomUid();
1797 const std::vector<int32_t> testUids = {testUid};
1798
1799 // Add test physical network
1800 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1801 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1802
Luke Huangc3252cc2018-10-16 15:43:23 +08001803 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001804 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001805 const auto& td = kTestDataWithNextHop[i];
1806
1807 // All route for test tun will disappear once the tun interface is deleted.
1808 binder::Status status =
1809 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1810 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1811 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1812 sTun.name().c_str());
1813
1814 // Add system permission for test uid, setup route in legacy system table.
1815 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1816
1817 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1818 testUid);
1819 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1820 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1821 testTableLegacySystem);
1822
1823 // Remove system permission for test uid, setup route in legacy network table.
1824 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1825
1826 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1827 testUid);
1828 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1829 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1830 testTableLegacyNetwork);
1831 }
1832
Sehee Park8659b8d2018-11-16 10:53:16 +09001833 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001834 const auto& td = kTestData[i];
1835
1836 binder::Status status =
1837 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1838 if (td.expectSuccess) {
1839 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001840 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001841 sTun.name().c_str());
1842 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001843 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1844 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001845 }
1846
1847 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1848 if (td.expectSuccess) {
1849 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001850 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1851 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001852 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001853 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1854 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001855 }
1856
Luke Huangc3252cc2018-10-16 15:43:23 +08001857 // Add system permission for test uid, route will be added into legacy system table.
1858 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001859
1860 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1861 testUid);
1862 if (td.expectSuccess) {
1863 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001864 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001865 testTableLegacySystem);
1866 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001867 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1868 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001869 }
1870
1871 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1872 td.testNextHop, testUid);
1873 if (td.expectSuccess) {
1874 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001875 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1876 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001877 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001878 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1879 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001880 }
1881
Luke Huangc3252cc2018-10-16 15:43:23 +08001882 // Remove system permission for test uid, route will be added into legacy network table.
1883 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1884
1885 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1886 testUid);
1887 if (td.expectSuccess) {
1888 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1889 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1890 testTableLegacyNetwork);
1891 } else {
1892 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1893 EXPECT_NE(0, status.serviceSpecificErrorCode());
1894 }
1895
1896 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1897 td.testNextHop, testUid);
1898 if (td.expectSuccess) {
1899 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1900 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1901 testTableLegacyNetwork);
1902 } else {
1903 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1904 EXPECT_NE(0, status.serviceSpecificErrorCode());
1905 }
Luke Huangb670d162018-08-23 20:01:13 +08001906 }
1907
Tyler Wearfa94a272019-12-05 15:01:48 -08001908 for (size_t i = 0; i < std::size(kTestData); i++) {
1909 const auto& td = kTestData[i];
1910 int mtu = (i % 2) ? 1480 : 1280;
1911
1912 android::net::RouteInfoParcel parcel;
1913 parcel.ifName = sTun.name();
1914 parcel.destination = td.testDest;
1915 parcel.nextHop = td.testNextHop;
1916 parcel.mtu = mtu;
1917 binder::Status status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel);
1918 if (td.expectSuccess) {
1919 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1920 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1921 std::to_string(parcel.mtu), sTun.name().c_str());
1922 } else {
1923 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1924 EXPECT_NE(0, status.serviceSpecificErrorCode());
1925 }
1926
1927 parcel.mtu = 1337;
1928 status = mNetd->networkUpdateRouteParcel(TEST_NETID1, parcel);
1929 if (td.expectSuccess) {
1930 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1931 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1932 std::to_string(parcel.mtu), sTun.name().c_str());
1933 } else {
1934 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1935 EXPECT_NE(0, status.serviceSpecificErrorCode());
1936 }
1937
1938 status = mNetd->networkRemoveRouteParcel(TEST_NETID1, parcel);
1939 if (td.expectSuccess) {
1940 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1941 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1942 sTun.name().c_str());
1943 } else {
1944 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1945 EXPECT_NE(0, status.serviceSpecificErrorCode());
1946 }
1947 }
Luke Huangb670d162018-08-23 20:01:13 +08001948 // Remove test physical network
1949 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1950}
1951
1952TEST_F(BinderTest, NetworkPermissionDefault) {
1953 // Add test physical network
1954 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1955 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1956
Luke Huangc3252cc2018-10-16 15:43:23 +08001957 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001958 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1959 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001960
1961 // Test SetDefault
1962 status = mNetd->networkSetDefault(TEST_NETID1);
1963 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1964 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1965
1966 status = mNetd->networkClearDefault();
1967 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1968 expectNetworkDefaultIpRuleDoesNotExist();
1969
Luke Huangd2861982019-05-17 19:47:28 +08001970 // Set default network back
1971 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001972 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1973
1974 // Test SetPermission
1975 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1976 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1977 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1978 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1979
1980 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1981 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1982 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1983 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1984
1985 // Remove test physical network
1986 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1987}
1988
1989TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001990 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001991 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1992 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001993 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001994 EXPECT_TRUE(ret);
1995
Luke Huang854e2992019-05-29 16:42:48 +08001996 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001997 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08001998
1999 // Clear uid permission before calling networkCanProtect to ensure
2000 // the call won't be affected by uid permission.
2001 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2002
2003 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002004 EXPECT_FALSE(ret);
2005}
2006
2007namespace {
2008
Luke Huangb5733d72018-08-21 17:17:19 +08002009int readIntFromPath(const std::string& path) {
2010 std::string result = "";
2011 EXPECT_TRUE(ReadFileToString(path, &result));
2012 return std::stoi(result);
2013}
2014
2015int getTetherAcceptIPv6Ra(const std::string& ifName) {
2016 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2017 return readIntFromPath(path);
2018}
2019
2020bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2021 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2022 return readIntFromPath(path);
2023}
2024
2025int getTetherIPv6DadTransmits(const std::string& ifName) {
2026 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2027 return readIntFromPath(path);
2028}
2029
2030bool getTetherEnableIPv6(const std::string& ifName) {
2031 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2032 int disableIPv6 = readIntFromPath(path);
2033 return !disableIPv6;
2034}
2035
2036bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2037 for (const auto& iface : ifList) {
2038 if (iface == ifName) {
2039 return true;
2040 }
2041 }
2042 return false;
2043}
2044
2045void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2046 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2047 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2048 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2049 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2050}
2051
2052void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2053 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2054 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2055 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2056 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2057}
2058
2059void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2060 const std::string& ifName) {
2061 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2062}
2063
2064void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2065 const std::string& ifName) {
2066 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2067}
2068
2069void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2070 const std::vector<std::string>& testDnsAddrs) {
2071 EXPECT_TRUE(dnsList == testDnsAddrs);
2072}
2073
2074} // namespace
2075
2076TEST_F(BinderTest, TetherStartStopStatus) {
2077 std::vector<std::string> noDhcpRange = {};
2078 static const char dnsdName[] = "dnsmasq";
2079
Luke Huang91bd3e12019-08-20 11:33:52 +08002080 for (bool usingLegacyDnsProxy : {true, false}) {
Chiachang Wang08cb2112019-12-10 09:53:24 +08002081 android::net::TetherConfigParcel config;
2082 config.usingLegacyDnsProxy = usingLegacyDnsProxy;
2083 config.dhcpRanges = noDhcpRange;
2084 binder::Status status = mNetd->tetherStartWithConfiguration(config);
Luke Huang91bd3e12019-08-20 11:33:52 +08002085 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2086 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2087 if (usingLegacyDnsProxy == true) {
2088 expectProcessExists(dnsdName);
2089 } else {
2090 expectProcessDoesNotExist(dnsdName);
2091 }
Luke Huangb5733d72018-08-21 17:17:19 +08002092
Luke Huang91bd3e12019-08-20 11:33:52 +08002093 bool tetherEnabled;
2094 status = mNetd->tetherIsEnabled(&tetherEnabled);
2095 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2096 EXPECT_TRUE(tetherEnabled);
Luke Huangb5733d72018-08-21 17:17:19 +08002097
Luke Huang91bd3e12019-08-20 11:33:52 +08002098 status = mNetd->tetherStop();
2099 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2100 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002101
Luke Huang91bd3e12019-08-20 11:33:52 +08002102 status = mNetd->tetherIsEnabled(&tetherEnabled);
2103 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2104 EXPECT_FALSE(tetherEnabled);
2105 }
Luke Huangb5733d72018-08-21 17:17:19 +08002106}
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) {
Maciej Żenczykowskif879a7f2020-01-20 03:18:06 -08002912 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(UID_PERMISSION_MAP_PATH);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002913 for (int32_t uid : uids) {
Steven Morelanda3074542020-01-13 14:13:44 -08002914 android::base::Result<uint8_t> permission = uidPermissionMap.readValue(uid);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002915 if (exist) {
Bernie Innocentidfd5a432020-02-12 09:21:56 +09002916 ASSERT_RESULT_OK(permission);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002917 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002918 } else {
Bernie Innocentidfd5a432020-02-12 09:21:56 +09002919 ASSERT_FALSE(permission.ok());
Steven Morelanda3074542020-01-13 14:13:44 -08002920 EXPECT_EQ(ENOENT, permission.error().code());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002921 }
2922 }
2923}
2924
2925} // namespace
2926
2927TEST_F(BinderTest, TestInternetPermission) {
2928 SKIP_IF_BPF_NOT_SUPPORTED;
2929
2930 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2931
2932 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002933 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002934 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002935 checkUidsInPermissionMap(appUids, true);
2936 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2937 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002938}
2939
Luke Huang528af602018-08-29 19:06:05 +08002940TEST_F(BinderTest, UnsolEvents) {
2941 auto testUnsolService = android::net::TestUnsolService::start();
2942 std::string oldTunName = sTun.name();
2943 std::string newTunName = "unsolTest";
2944 testUnsolService->tarVec.push_back(oldTunName);
2945 testUnsolService->tarVec.push_back(newTunName);
2946 auto& cv = testUnsolService->getCv();
2947 auto& cvMutex = testUnsolService->getCvMutex();
2948 binder::Status status = mNetd->registerUnsolicitedEventListener(
2949 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2950 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2951
2952 // TODO: Add test for below events
2953 // StrictCleartextDetected / InterfaceDnsServersAdded
2954 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2955
2956 {
2957 std::unique_lock lock(cvMutex);
2958
2959 // Re-init test Tun, and we expect that we will get some unsol events.
2960 // Use the test Tun device name to verify if we receive its unsol events.
2961 sTun.destroy();
2962 // Use predefined name
2963 sTun.init(newTunName);
2964
2965 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2966 }
2967
2968 // bit mask 1101101000
2969 // Test only covers below events currently
2970 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2971 InterfaceLinkStatusChanged | RouteChanged;
2972 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002973
2974 // Re-init sTun to clear predefined name
2975 sTun.destroy();
2976 sTun.init();
2977}
2978
2979TEST_F(BinderTest, NDC) {
2980 struct Command {
2981 const std::string cmdString;
2982 const std::string expectedResult;
2983 };
2984
2985 // clang-format off
2986 // Do not change the commands order
2987 const Command networkCmds[] = {
2988 {StringPrintf("ndc network create %d", TEST_NETID1),
2989 "200 0 success"},
2990 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2991 "200 0 success"},
2992 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2993 "200 0 success"},
2994 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2995 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2996 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2997 "200 0 success"},
2998 };
2999
3000 const std::vector<Command> ipfwdCmds = {
3001 {"ndc ipfwd enable " + sTun.name(),
3002 "200 0 ipfwd operation succeeded"},
3003 {"ndc ipfwd disable " + sTun.name(),
3004 "200 0 ipfwd operation succeeded"},
3005 {"ndc ipfwd add lo2 lo3",
3006 "400 0 ipfwd operation failed (No such process)"},
3007 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3008 "200 0 ipfwd operation succeeded"},
3009 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3010 "200 0 ipfwd operation succeeded"},
3011 };
3012
3013 static const struct {
3014 const char* ipVersion;
3015 const char* testDest;
3016 const char* testNextHop;
3017 const bool expectSuccess;
3018 const std::string expectedResult;
3019 } kTestData[] = {
3020 {IP_RULE_V4, "0.0.0.0/0", "", true,
3021 "200 0 success"},
3022 {IP_RULE_V4, "10.251.0.0/16", "", true,
3023 "200 0 success"},
3024 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3025 "400 0 addRoute() failed (Invalid argument)",},
3026 {IP_RULE_V6, "::/0", "", true,
3027 "200 0 success"},
3028 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3029 "200 0 success"},
3030 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3031 "400 0 addRoute() failed (Invalid argument)"},
3032 };
3033 // clang-format on
3034
3035 for (const auto& cmd : networkCmds) {
3036 const std::vector<std::string> result = runCommand(cmd.cmdString);
3037 SCOPED_TRACE(cmd.cmdString);
3038 EXPECT_EQ(result.size(), 1U);
3039 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3040 }
3041
3042 for (const auto& cmd : ipfwdCmds) {
3043 const std::vector<std::string> result = runCommand(cmd.cmdString);
3044 SCOPED_TRACE(cmd.cmdString);
3045 EXPECT_EQ(result.size(), 1U);
3046 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3047 }
3048
3049 // Add test physical network
3050 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3051 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3052
3053 for (const auto& td : kTestData) {
3054 const std::string routeAddCmd =
3055 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3056 td.testDest, td.testNextHop);
3057 const std::string routeRemoveCmd =
3058 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3059 sTun.name().c_str(), td.testDest, td.testNextHop);
3060 std::vector<std::string> result = runCommand(routeAddCmd);
3061 SCOPED_TRACE(routeAddCmd);
3062 EXPECT_EQ(result.size(), 1U);
3063 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3064 if (td.expectSuccess) {
3065 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3066 sTun.name().c_str());
3067 result = runCommand(routeRemoveCmd);
3068 EXPECT_EQ(result.size(), 1U);
3069 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3070 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3071 sTun.name().c_str());
3072 }
3073 }
3074 // Remove test physical network
3075 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003076}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003077
Luke Huang2ff8b342019-04-30 15:33:33 +08003078TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003079 sp<IBinder> binder;
3080 binder::Status status = mNetd->getOemNetd(&binder);
3081 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3082 sp<com::android::internal::net::IOemNetd> oemNetd;
3083 if (binder != nullptr) {
3084 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3085 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003086 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003087
3088 TimedOperation t("OemNetd isAlive RPC");
3089 bool isAlive = false;
3090 oemNetd->isAlive(&isAlive);
3091 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003092
3093 class TestOemUnsolListener
3094 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3095 public:
3096 android::binder::Status onRegistered() override {
3097 std::lock_guard lock(mCvMutex);
3098 mCv.notify_one();
3099 return android::binder::Status::ok();
3100 }
3101 std::condition_variable& getCv() { return mCv; }
3102 std::mutex& getCvMutex() { return mCvMutex; }
3103
3104 private:
3105 std::mutex mCvMutex;
3106 std::condition_variable mCv;
3107 };
3108
3109 // Start the Binder thread pool.
3110 android::ProcessState::self()->startThreadPool();
3111
3112 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3113
3114 auto& cv = testListener->getCv();
3115 auto& cvMutex = testListener->getCvMutex();
3116
3117 {
3118 std::unique_lock lock(cvMutex);
3119
3120 status = oemNetd->registerOemUnsolicitedEventListener(
3121 ::android::interface_cast<
3122 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3123 testListener));
3124 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3125
3126 // Wait for receiving expected events.
3127 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3128 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003129}
Luke Huangd2861982019-05-17 19:47:28 +08003130
3131void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3132 int fallthroughNetId) {
3133 // Re-init sTun* to ensure route rule exists.
3134 sTun.destroy();
3135 sTun.init();
3136 sTun2.destroy();
3137 sTun2.init();
3138
3139 // Create physical network with fallthroughNetId but not set it as default network
3140 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3141 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3142
3143 // Create VPN with vpnNetId
3144 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3145
3146 // Add uid to VPN
3147 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3148 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3149
3150 // Add default route to fallthroughNetwork
3151 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3152 // Add limited route
3153 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3154}
3155
3156namespace {
3157
3158class ScopedUidChange {
3159 public:
3160 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3161 mStoredUid = getuid();
3162 if (mInputUid == mStoredUid) return;
3163 EXPECT_TRUE(seteuid(uid) == 0);
3164 }
3165 ~ScopedUidChange() {
3166 if (mInputUid == mStoredUid) return;
3167 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3168 }
3169
3170 private:
3171 uid_t mInputUid;
3172 uid_t mStoredUid;
3173};
3174
3175constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3176
3177void clearQueue(int tunFd) {
3178 char buf[4096];
3179 int ret;
3180 do {
3181 ret = read(tunFd, buf, sizeof(buf));
3182 } while (ret > 0);
3183}
3184
3185void checkDataReceived(int udpSocket, int tunFd) {
3186 char buf[4096] = {};
3187 // Clear tunFd's queue before write something because there might be some
3188 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3189 clearQueue(tunFd);
3190 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3191 // TODO: extract header and verify data
3192 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3193}
3194
3195bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3196 ScopedUidChange scopedUidChange(uid);
Bernie Innocentid26a04a2019-10-30 17:15:15 +09003197 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Luke Huangd2861982019-05-17 19:47:28 +08003198 if (testSocket < 0) return false;
3199
Nick Desaulniers6b357502019-10-11 09:26:44 -07003200 const sockaddr_in6 dst6 = {
3201 .sin6_family = AF_INET6,
3202 .sin6_port = 42,
3203 .sin6_addr = dstAddr,
3204 };
Luke Huangd2861982019-05-17 19:47:28 +08003205 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3206 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3207 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3208 if (res == -1) return false;
3209
3210 char addr[INET6_ADDRSTRLEN];
3211 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3212 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3213 checkDataReceived(testSocket, tunFd);
3214 return true;
3215}
3216
3217void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3218 std::string vpnFallthroughRule =
3219 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3220 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3221 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3222 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3223 }
3224}
3225
3226void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3227 const TunInterface& fallthroughNetwork,
3228 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3229 int fallthroughNetId = TEST_NETID1) {
3230 // Set default network to NETID_UNSET
3231 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3232
3233 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3234 in6_addr insideVpnAddr = {
3235 {// 2001:db8:cafe::1
3236 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3237 // outsideVpnAddr will hit the route in the fallthrough network route table
3238 // because we added default route in createVpnNetworkWithUid
3239 in6_addr outsideVpnAddr = {
3240 {// 2607:f0d0:1002::4
3241 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3242
3243 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3244 int vpnFd = vpnNetwork.getFdForTesting();
3245 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3246 // default network.
3247 Fwmark fwmark;
3248 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3249 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3250
3251 // Set default network
3252 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3253
3254 // Connections go on the default network because UID 0 is not subject to the VPN.
3255 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3256 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3257 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3258 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3259
3260 // Check if fallthrough rule exists
3261 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3262
3263 // Expect fallthrough to default network
3264 // The fwmark differs depending on whether the VPN is bypassable or not.
3265 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3266 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3267
3268 // Expect connect success, packet will be sent to vpnFd.
3269 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3270 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3271
3272 // Explicitly select vpn network
3273 setNetworkForProcess(vpnNetId);
3274
3275 // Expect fallthrough to default network
3276 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3277 // Expect the mark contains all the bit because we've selected network.
3278 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3279
3280 // Expect connect success, packet will be sent to vpnFd.
3281 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3282 // Expect the mark contains all the bit because we've selected network.
3283 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3284
3285 // Explicitly select fallthrough network
3286 setNetworkForProcess(fallthroughNetId);
3287
3288 // The mark is set to fallthrough network because we've selected it.
3289 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3290 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3291
3292 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3293 if (bypassable) {
3294 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3295 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3296 } else {
3297 // If not, no permission to bypass vpn.
3298 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3299 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3300 }
3301}
3302
3303} // namespace
3304
3305TEST_F(BinderTest, SecureVPNFallthrough) {
3306 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3307 // Get current default network NetId
3308 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3309 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3310}
3311
3312TEST_F(BinderTest, BypassableVPNFallthrough) {
3313 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3314 // Get current default network NetId
3315 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3316 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003317}
Chiachang Wang00fc62f2019-12-04 20:38:26 +08003318
3319namespace {
3320
3321int32_t createIpv6SocketAndCheckMark(int type, const in6_addr& dstAddr) {
3322 const sockaddr_in6 dst6 = {
3323 .sin6_family = AF_INET6,
3324 .sin6_port = 1234,
3325 .sin6_addr = dstAddr,
3326 };
3327 // create non-blocking socket.
3328 int sockFd = socket(AF_INET6, type | SOCK_NONBLOCK, 0);
3329 EXPECT_NE(-1, sockFd);
3330 EXPECT_EQ((type == SOCK_STREAM) ? -1 : 0, connect(sockFd, (sockaddr*)&dst6, sizeof(dst6)));
3331
3332 // Get socket fwmark.
3333 Fwmark fwmark;
3334 socklen_t fwmarkLen = sizeof(fwmark.intValue);
3335 EXPECT_EQ(0, getsockopt(sockFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen));
3336 EXPECT_EQ(0, close(sockFd));
3337 return fwmark.intValue;
3338}
3339
3340} // namespace
3341
3342TEST_F(BinderTest, GetFwmarkForNetwork) {
3343 in6_addr v6Addr = {
3344 {// 2001:db8:cafe::8888
3345 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}};
3346 // Add test physical network 1 and set as default network.
3347 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3348 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3349 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "2001:db8::/32", "").isOk());
3350 EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk());
3351 // Add test physical network 2
3352 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
3353 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
3354
3355 // Get fwmark for network 1.
3356 MarkMaskParcel maskMarkNet1;
3357 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID1, &maskMarkNet1).isOk());
3358
3359 uint32_t fwmarkTcp = createIpv6SocketAndCheckMark(SOCK_STREAM, v6Addr);
3360 uint32_t fwmarkUdp = createIpv6SocketAndCheckMark(SOCK_DGRAM, v6Addr);
3361 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkTcp & maskMarkNet1.mask));
3362 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkUdp & maskMarkNet1.mask));
3363
3364 // Get fwmark for network 2.
3365 MarkMaskParcel maskMarkNet2;
3366 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID2, &maskMarkNet2).isOk());
3367 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkTcp & maskMarkNet2.mask));
3368 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkUdp & maskMarkNet2.mask));
3369
3370 // Remove test physical network.
3371 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
3372 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3373}