blob: 7d3d296b699af7d0cc26a3e98860f62a1ed06f34 [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"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090074#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080075#define RAW_TABLE "raw"
76#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080077#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090078#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090079
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090080namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090081
82using android::IBinder;
83using android::IServiceManager;
84using android::sp;
85using android::String16;
86using android::String8;
87using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080088using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090089using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090090using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080091using android::base::Trim;
Bernie Innocentid26a04a2019-10-30 17:15:15 +090092using android::base::unique_fd;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090093using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080094using android::net::InterfaceConfigurationParcel;
95using android::net::InterfaceController;
Chiachang Wang00fc62f2019-12-04 20:38:26 +080096using android::net::MarkMaskParcel;
Luke Huangcaebcbb2018-09-27 20:37:14 +080097using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090098using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090099using android::net::UidRangeParcel;
Luke Huang25599322019-06-14 00:34:05 +0800100using android::netdutils::ScopedAddrinfo;
Luke Huangf7782042018-08-08 13:13:04 +0800101using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +0800102using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +0100103
104static const char* IP_RULE_V4 = "-4";
105static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900106static const int TEST_NETID1 = 65501;
107static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800108
109// Use maximum reserved appId for applications to avoid conflict with existing
110// uids.
111static const int TEST_UID1 = 99999;
112static const int TEST_UID2 = 99998;
113
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900114constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900115
Benedict Wongb2daefb2017-12-06 22:05:46 -0800116static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
117static const std::string ESP_ALLOW_RULE("esp");
118
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900119class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900120 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900121 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900122 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900123 sp<IBinder> binder = sm->getService(String16("netd"));
124 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900125 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900126 }
127 }
128
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900129 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130 ASSERT_NE(nullptr, mNetd.get());
131 }
132
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900133 void TearDown() override {
134 mNetd->networkDestroy(TEST_NETID1);
135 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800136 setNetworkForProcess(NETID_UNSET);
137 // Restore default network
138 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900139 }
140
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900141 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700142
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900143 // Static because setting up the tun interface takes about 40ms.
144 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900145 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900146 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900147 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900148 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900149 }
150
151 static void TearDownTestCase() {
152 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900153 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900154 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900155 }
156
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900157 static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
158 unique_fd* acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900159
Luke Huangd2861982019-05-17 19:47:28 +0800160 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
161 int fallthroughNetId = TEST_NETID1);
162
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900163 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800164 // Use -1 to represent that default network was not modified because
165 // real netId must be an unsigned value.
166 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900167 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900168 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900169 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900170};
171
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900172TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900173TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900174
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900175class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900176 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700177 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900178 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900179 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900180 }
181
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900182 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900183 std::string mName;
184};
185
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900186TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900187 TimedOperation t("isAlive RPC");
188 bool isAlive = false;
189 mNetd->isAlive(&isAlive);
190 ASSERT_TRUE(isAlive);
191}
192
Benedict Wongb2daefb2017-12-06 22:05:46 -0800193static bool iptablesNoSocketAllowRuleExists(const char *chainName){
194 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
195 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
196}
197
198static bool iptablesEspAllowRuleExists(const char *chainName){
199 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
200 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
201}
202
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900203TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700204 SKIP_IF_BPF_SUPPORTED;
205
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900206 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
207 const int kNumUids = 500;
208 std::vector<int32_t> noUids(0);
209 std::vector<int32_t> uids(kNumUids);
210 for (int i = 0; i < kNumUids; i++) {
211 uids[i] = randomUid();
212 }
213
214 bool ret;
215 {
216 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900217 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900218 }
219 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800220 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
221 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
222 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
223 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900224 {
225 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900226 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900227 }
228 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900229 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
230 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900231
232 {
233 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900234 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900235 }
236 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900237 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
238 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800239 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
240 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900241
242 {
243 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900244 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900245 }
246 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900247 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
248 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900249
250 // Check that the call fails if iptables returns an error.
251 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900252 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900253 EXPECT_EQ(false, ret);
254}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900255
Benedict Wong319f17e2018-05-15 17:06:44 -0700256TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700257 const struct TestData {
258 const std::string family;
259 const std::string deviceName;
260 const std::string localAddress;
261 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800262 int32_t iKey;
263 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700264 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800265 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700266 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
267 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
268 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800269 };
270
Sehee Park8659b8d2018-11-16 10:53:16 +0900271 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700272 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800273
274 binder::Status status;
275
Benedict Wong319f17e2018-05-15 17:06:44 -0700276 // Create Tunnel Interface.
277 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700278 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800279 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
280
Benedict Wonga450e722018-05-07 10:29:02 -0700281 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900282 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700283
Benedict Wong319f17e2018-05-15 17:06:44 -0700284 // Update Tunnel Interface.
285 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700286 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800287 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
288
Benedict Wong319f17e2018-05-15 17:06:44 -0700289 // Remove Tunnel Interface.
290 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800291 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700292
293 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900294 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800295 }
296}
297
Benedict Wong1cb73df2018-12-03 00:54:14 -0800298TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900299 unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Benedict Wong1cb73df2018-12-03 00:54:14 -0800300 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
301
302 int sockOptVal = UDP_ENCAP_ESPINUDP;
303 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
304
305 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
306 EXPECT_TRUE(res.isOk());
307
308 struct stat info;
309 EXPECT_EQ(0, fstat(sockFd.get(), &info));
310 EXPECT_EQ(1001, (int) info.st_uid);
311}
312
Nathan Harold2deff322018-05-10 14:03:48 -0700313// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
314// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
315#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900316
317using android::net::XfrmController;
318
Benedict Wonga04ffa72018-05-09 21:42:42 -0700319static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
320 static_cast<int>(android::net::XfrmDirection::OUT)};
321static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
322
Nathan Harold21299f72018-03-16 20:13:03 -0700323#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
324 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900325bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900326 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700327 SCOPED_TRACE(status);
328 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
329
330 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700331 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700332 SCOPED_TRACE(status);
333 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
334
335 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700336 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
337 0xD00D, 0xE00D, false)
338 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700339}
340
Benedict Wonga04ffa72018-05-09 21:42:42 -0700341TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900342 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700343
344 // Repeat to ensure cleanup and recreation works correctly
345 for (int i = 0; i < 2; i++) {
346 for (int direction : XFRM_DIRECTIONS) {
347 for (int addrFamily : ADDRESS_FAMILIES) {
348 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700349 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700350 EXPECT_TRUE(status.isOk())
351 << " family: " << addrFamily << " direction: " << direction;
352 }
353 }
354
355 // Cleanup
356 for (int direction : XFRM_DIRECTIONS) {
357 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700358 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700359 EXPECT_TRUE(status.isOk());
360 }
361 }
362 }
363}
364
365TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
366 binder::Status status;
367
368 // Repeat to ensure cleanup and recreation works correctly
369 for (int i = 0; i < 2; i++) {
370 for (int direction : XFRM_DIRECTIONS) {
371 for (int addrFamily : ADDRESS_FAMILIES) {
372 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700373 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700374 EXPECT_TRUE(status.isOk())
375 << " family: " << addrFamily << " direction: " << direction;
376 }
377 }
378
379 // Cleanup
380 for (int direction : XFRM_DIRECTIONS) {
381 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700382 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700383 EXPECT_TRUE(status.isOk());
384 }
385 }
386 }
387}
388
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900389TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900390 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700391 status = XfrmController::Init();
392 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700393
394 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
395 // feature.
396 if (status.code() == EOPNOTSUPP) return;
397
Nathan Harold21299f72018-03-16 20:13:03 -0700398 ASSERT_TRUE(status.ok());
399
400 int32_t spi = 0;
401
402 ASSERT_TRUE(allocateIpSecResources(true, &spi));
403 ASSERT_TRUE(allocateIpSecResources(false, &spi));
404
405 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700406 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700407 ASSERT_TRUE(allocateIpSecResources(true, &spi));
408
409 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700410 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700411 SCOPED_TRACE(status);
412 ASSERT_TRUE(status.ok());
413
Benedict Wonga450e722018-05-07 10:29:02 -0700414 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700415 SCOPED_TRACE(status);
416 ASSERT_TRUE(status.ok());
417
418 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700419 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700420}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900421
422#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700423
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900424static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900425 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900426
427 // Output looks like this:
428 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900429 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900430 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900431 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900432 //
433 // or:
434 //
435 // Chain bw_data_saver (1 references)
436 // target prot opt source destination
437 // ... possibly connectivity critical packet rules here ...
438 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900439
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900440 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900441
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900442 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
443 // Data saver disabled.
444 return 0;
445 }
446
447 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
448
449 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
450 // Data saver enabled.
451 return 1;
452 }
453
454 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900455}
456
457bool enableDataSaver(sp<INetd>& netd, bool enable) {
458 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
459 bool ret;
460 netd->bandwidthEnableDataSaver(enable, &ret);
461 return ret;
462}
463
464int getDataSaverState() {
465 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
466 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
467 EXPECT_EQ(enabled4, enabled6);
468 EXPECT_NE(-1, enabled4);
469 EXPECT_NE(-1, enabled6);
470 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
471 return -1;
472 }
473 return enabled6;
474}
475
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900476TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900477 const int wasEnabled = getDataSaverState();
478 ASSERT_NE(-1, wasEnabled);
479
480 if (wasEnabled) {
481 ASSERT_TRUE(enableDataSaver(mNetd, false));
482 EXPECT_EQ(0, getDataSaverState());
483 }
484
485 ASSERT_TRUE(enableDataSaver(mNetd, false));
486 EXPECT_EQ(0, getDataSaverState());
487
488 ASSERT_TRUE(enableDataSaver(mNetd, true));
489 EXPECT_EQ(1, getDataSaverState());
490
491 ASSERT_TRUE(enableDataSaver(mNetd, true));
492 EXPECT_EQ(1, getDataSaverState());
493
494 if (!wasEnabled) {
495 ASSERT_TRUE(enableDataSaver(mNetd, false));
496 EXPECT_EQ(0, getDataSaverState());
497 }
498}
Robin Leeb8087362016-03-30 18:43:08 +0100499
Luke Huang94658ac2018-10-18 19:35:12 +0900500static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
501 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100502 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100503 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100504 std::vector<std::string> rules = listIpRules(ipVersion);
505
506 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900507 std::string suffix =
508 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900509 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800510 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100511 return true;
512 }
513 }
514 return false;
515}
516
Luke Huang94658ac2018-10-18 19:35:12 +0900517static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
518 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100519 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
520 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
521 EXPECT_EQ(existsIp4, existsIp6);
522 return existsIp4;
523}
524
Luke Huang94658ac2018-10-18 19:35:12 +0900525namespace {
526
527UidRangeParcel makeUidRangeParcel(int start, int stop) {
528 UidRangeParcel res;
529 res.start = start;
530 res.stop = stop;
531
532 return res;
533}
534
535} // namespace
536
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900537TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800538 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
539 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
540 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900541 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
542 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900543
544 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
545 EXPECT_EQ(EBUSY,
546 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
547
548 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
549 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
550 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800551 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900552}
553
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900554TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900555 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
556
cken67cd14c2018-12-05 17:26:59 +0900557 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
558 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900559 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
560
Luke Huang94658ac2018-10-18 19:35:12 +0900561 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
562 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
563 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900564 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
565
566 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
567
568 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
569 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
570 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
571 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
572
573 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
574 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
575 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
576 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
577
578 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
579}
580
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900581TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100582 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100583
Luke Huang94658ac2018-10-18 19:35:12 +0900584 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
585 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800586 // Make sure no rules existed before calling commands.
587 for (auto const& range : uidRanges) {
588 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
589 }
Robin Leeb8087362016-03-30 18:43:08 +0100590 // Create two valid rules.
591 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100592 for (auto const& range : uidRanges) {
593 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
594 }
595
596 // Remove the rules.
597 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100598 for (auto const& range : uidRanges) {
599 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
600 }
601
602 // Fail to remove the rules a second time after they are already deleted.
603 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
604 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
605 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100606}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900607
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900608// Create a socket pair that isLoopbackSocket won't think is local.
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900609void BinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
610 unique_fd* acceptedSocket) {
611 serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900612 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900613 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
614
615 socklen_t addrlen = sizeof(server6);
616 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
617 ASSERT_EQ(0, listen(*serverSocket, 10));
618
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900619 clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900620 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900621 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900622 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
623 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
624
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900625 acceptedSocket->reset(
626 accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900627 ASSERT_NE(-1, *acceptedSocket);
628
629 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
630}
631
632void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
633 char buf[4096];
634 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
635 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
636 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
637}
638
639void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
640 // Check that the client socket was closed with ECONNABORTED.
641 int ret = write(clientSocket, "foo", sizeof("foo"));
642 int err = errno;
643 EXPECT_EQ(-1, ret);
644 EXPECT_EQ(ECONNABORTED, err);
645
646 // Check that it sent a RST to the server.
647 ret = write(acceptedSocket, "foo", sizeof("foo"));
648 err = errno;
649 EXPECT_EQ(-1, ret);
650 EXPECT_EQ(ECONNRESET, err);
651}
652
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900653TEST_F(BinderTest, SocketDestroy) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900654 unique_fd clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900655 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900656
657 // Pick a random UID in the system UID range.
658 constexpr int baseUid = AID_APP - 2000;
659 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
660 int uid = baseUid + 500 + arc4random_uniform(1000);
661 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
662
663 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900664 std::vector<UidRangeParcel> uidRanges = {
665 makeUidRangeParcel(baseUid + 42, baseUid + 449),
666 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
667 makeUidRangeParcel(baseUid + 498, uid - 1),
668 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900669 };
670 // A skip list that doesn't contain UID.
671 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
672
673 // Close sockets. Our test socket should be intact.
674 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
675 checkSocketpairOpen(clientSocket, acceptedSocket);
676
677 // UID ranges that do contain uid.
678 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900679 makeUidRangeParcel(baseUid + 42, baseUid + 449),
680 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
681 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900682 };
683 // Add uid to the skip list.
684 skipUids.push_back(uid);
685
686 // Close sockets. Our test socket should still be intact because it's in the skip list.
687 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
688 checkSocketpairOpen(clientSocket, acceptedSocket);
689
690 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
691 skipUids.resize(skipUids.size() - 1);
692 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
693 checkSocketpairClosed(clientSocket, acceptedSocket);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900694}
Erik Klinecc4f2732016-08-03 11:24:27 +0900695
696namespace {
697
698int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
699 if (buf == nullptr) return -1;
700
701 int prefixLength = 0;
702 bool endOfContiguousBits = false;
703 for (unsigned int i = 0; i < buflen; i++) {
704 const uint8_t value = buf[i];
705
706 // Bad bit sequence: check for a contiguous set of bits from the high
707 // end by verifying that the inverted value + 1 is a power of 2
708 // (power of 2 iff. (v & (v - 1)) == 0).
709 const uint8_t inverse = ~value + 1;
710 if ((inverse & (inverse - 1)) != 0) return -1;
711
712 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
713
714 // Bogus netmask.
715 if (endOfContiguousBits && value != 0) return -1;
716
717 if (value != 0xff) endOfContiguousBits = true;
718 }
719
720 return prefixLength;
721}
722
723template<typename T>
724int netmaskToPrefixLength(const T *p) {
725 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
726}
727
728
729static bool interfaceHasAddress(
730 const std::string &ifname, const char *addrString, int prefixLength) {
731 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900732
733 const struct addrinfo hints = {
734 .ai_flags = AI_NUMERICHOST,
735 .ai_family = AF_UNSPEC,
736 .ai_socktype = SOCK_DGRAM,
737 };
738 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
739 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
740 return false;
741 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900742 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900743
744 struct ifaddrs *ifaddrsList = nullptr;
745 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
746
747 if (getifaddrs(&ifaddrsList) != 0) {
748 return false;
749 }
750
751 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
752 if (std::string(addr->ifa_name) != ifname ||
753 addr->ifa_addr == nullptr ||
754 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
755 continue;
756 }
757
758 switch (addr->ifa_addr->sa_family) {
759 case AF_INET: {
760 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
761 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
762 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
763 continue;
764 }
765
766 if (prefixLength < 0) return true; // not checking prefix lengths
767
768 if (addr->ifa_netmask == nullptr) return false;
769 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
770 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
771 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
772 }
773 case AF_INET6: {
774 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
775 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
776 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
777 continue;
778 }
779
780 if (prefixLength < 0) return true; // not checking prefix lengths
781
782 if (addr->ifa_netmask == nullptr) return false;
783 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
784 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
785 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
786 }
787 default:
788 // Cannot happen because we have already screened for matching
789 // address families at the top of each iteration.
790 continue;
791 }
792 }
793
794 return false;
795}
796
797} // namespace
798
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900799TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900800 static const struct TestData {
801 const char *addrString;
802 const int prefixLength;
Lorenzo Colitti01118982019-12-02 13:19:44 +0900803 const int expectAddResult;
804 const int expectRemoveResult;
Erik Klinecc4f2732016-08-03 11:24:27 +0900805 } kTestData[] = {
Lorenzo Colitti01118982019-12-02 13:19:44 +0900806 {"192.0.2.1", 24, 0, 0},
807 {"192.0.2.2", 25, 0, 0},
808 {"192.0.2.3", 32, 0, 0},
809 {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL},
810 {"192.not.an.ip", 24, EINVAL, EINVAL},
811 {"2001:db8::1", 64, 0, 0},
812 {"2001:db8::2", 65, 0, 0},
813 {"2001:db8::3", 128, 0, 0},
814 {"2001:db8::4", 129, EINVAL, EINVAL},
815 {"foo:bar::bad", 64, EINVAL, EINVAL},
816 {"2001:db8::1/64", 64, EINVAL, EINVAL},
Erik Klinecc4f2732016-08-03 11:24:27 +0900817 };
818
Sehee Park8659b8d2018-11-16 10:53:16 +0900819 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900820 const auto &td = kTestData[i];
821
Lorenzo Colitti01118982019-12-02 13:19:44 +0900822 SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength));
823
Erik Klinecc4f2732016-08-03 11:24:27 +0900824 // [1.a] Add the address.
825 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900826 sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900827 if (td.expectAddResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900828 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
829 } else {
830 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900831 ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900832 }
833
834 // [1.b] Verify the addition meets the expectation.
Lorenzo Colitti01118982019-12-02 13:19:44 +0900835 if (td.expectAddResult == 0) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900836 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900837 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900838 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900839 }
840
841 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900842 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900843 if (td.expectRemoveResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900844 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
845 } else {
846 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900847 ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900848 }
849
850 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900851 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900852 }
Lorenzo Colitti9ae17712019-12-02 17:28:49 +0900853
854 // Check that netlink errors are returned correctly.
855 // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled,
856 // which returns EACCES.
857 TunInterface tun;
858 ASSERT_EQ(0, tun.init());
859 binder::Status status =
860 mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1");
861 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
862 status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64);
863 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
864 EXPECT_EQ(EACCES, status.serviceSpecificErrorCode());
865 tun.destroy();
Erik Klinecc4f2732016-08-03 11:24:27 +0900866}
Erik Kline55b06f82016-07-04 09:57:18 +0900867
Erik Kline38e51f12018-09-06 20:14:44 +0900868TEST_F(BinderTest, GetProcSysNet) {
869 const char LOOPBACK[] = "lo";
870 static const struct {
871 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900872 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900873 const char* ifname;
874 const char* parameter;
875 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900876 const int expectedReturnCode;
877 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900878 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
879 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
880 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
881 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
882 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
883 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
884 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900885 };
886
Sehee Park8659b8d2018-11-16 10:53:16 +0900887 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900888 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900889
Erik Kline38e51f12018-09-06 20:14:44 +0900890 std::string value;
891 const binder::Status status =
892 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
893
894 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900895 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900896 EXPECT_EQ(0, status.exceptionCode());
897 EXPECT_EQ(0, status.serviceSpecificErrorCode());
898 EXPECT_EQ(td.expectedValue, value);
899 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900900 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900901 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
902 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
903 }
904 }
905}
906
907TEST_F(BinderTest, SetProcSysNet) {
908 static const struct {
909 const int ipversion;
910 const int which;
911 const char* ifname;
912 const char* parameter;
913 const char* value;
914 const int expectedReturnCode;
915 } kTestData[] = {
916 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
917 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
918 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
919 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
920 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
921 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
922 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
923 };
924
Sehee Park8659b8d2018-11-16 10:53:16 +0900925 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900926 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900927 const binder::Status status =
928 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900929
930 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900931 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900932 EXPECT_EQ(0, status.exceptionCode());
933 EXPECT_EQ(0, status.serviceSpecificErrorCode());
934 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900935 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900936 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
937 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
938 }
939 }
940}
Ben Schwartze7601812017-04-28 16:38:29 -0400941
Erik Kline38e51f12018-09-06 20:14:44 +0900942TEST_F(BinderTest, GetSetProcSysNet) {
943 const int ipversion = INetd::IPV6;
944 const int category = INetd::NEIGH;
945 const std::string& tun = sTun.name();
946 const std::string parameter("ucast_solicit");
947
948 std::string value{};
949 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700950 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900951 const int ival = std::stoi(value);
952 EXPECT_GT(ival, 0);
953 // Try doubling the parameter value (always best!).
954 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
955 .isOk());
956 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
957 EXPECT_EQ(2 * ival, std::stoi(value));
958 // Try resetting the parameter.
959 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
960 .isOk());
961 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
962 EXPECT_EQ(ival, std::stoi(value));
963}
964
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900965namespace {
966
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900967void expectNoTestCounterRules() {
968 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
969 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
970 std::string allRules = Join(runCommand(command), "\n");
971 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
972 }
973}
974
Bernie Innocentif6918262018-06-11 17:37:35 +0900975void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
976 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900977 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
978 path, if1.c_str(), if2.c_str(), pkt, byte));
979}
980
Bernie Innocentif6918262018-06-11 17:37:35 +0900981void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900982 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
983 path, if1.c_str(), if2.c_str()));
984 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
985 path, if2.c_str(), if1.c_str()));
986}
987
Luke Huangcaebcbb2018-09-27 20:37:14 +0800988std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
989 const std::string& iface) {
990 for (auto& stats : statsVec) {
991 if (stats.iface == iface) {
992 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
993 }
994 }
995 return {};
996}
997
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900998} // namespace
999
1000TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001001 expectNoTestCounterRules();
1002
1003 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1004 // disabling tethering. We don't check the return value because these commands will fail if
1005 // tethering is already enabled.
1006 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1007 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1008
1009 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1010 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1011 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001012
1013 // Ensure we won't use the same interface name, otherwise the test will fail.
1014 u_int32_t rNumber = arc4random_uniform(10000);
1015 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1016 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001017
1018 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1019 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1020 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1021 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1022 // RX is from external to internal, and TX is from internal to external.
1023 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1024 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1025
1026 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1027 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1028
1029 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1030 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1031
1032 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1033 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1034 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1035
Luke Huangcaebcbb2018-09-27 20:37:14 +08001036 std::vector<TetherStatsParcel> statsVec;
1037 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001038 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1039
Luke Huangcaebcbb2018-09-27 20:37:14 +08001040 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001041
Luke Huangcaebcbb2018-09-27 20:37:14 +08001042 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001043
1044 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1045 delTetherCounterValues(path, intIface1, extIface1);
1046 delTetherCounterValues(path, intIface2, extIface2);
1047 if (path == IP6TABLES_PATH) {
1048 delTetherCounterValues(path, intIface3, extIface2);
1049 }
1050 }
1051
1052 expectNoTestCounterRules();
1053}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001054
Luke Huang0051a622018-07-23 20:30:16 +08001055namespace {
1056
Luke Huanga5211072018-08-01 23:36:29 +08001057constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1058constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001059
1060static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1061 const char* chainName) {
1062 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1063 return runCommand(command);
1064}
1065
Luke Huang19b49c52018-10-22 12:12:05 +09001066// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001067bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001068 const std::string& expectedInterface,
1069 const std::string& expectedRule, const char* table) {
1070 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1071 for (const auto& rule : rules) {
1072 if (rule.find(expectedInterface) != std::string::npos) {
1073 if (rule.find(expectedRule) != std::string::npos) {
1074 return true;
1075 }
1076 }
1077 }
1078 return false;
1079}
1080
1081void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001082 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001083 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001084 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001085 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001086 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1087 IdletimerRule, RAW_TABLE));
1088 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001089 ifname, IdletimerRule, MANGLE_TABLE));
1090 }
1091}
1092
1093void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001094 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001095 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001096 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001097 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001098 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1099 IdletimerRule, RAW_TABLE));
1100 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001101 ifname, IdletimerRule, MANGLE_TABLE));
1102 }
1103}
1104
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001105} // namespace
1106
1107TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001108 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1109 // rule in the table. Because we only check the result after calling remove function. We might
1110 // check the actual rule which is removed by our function (maybe compare the results between
1111 // calling function before and after)
1112 binder::Status status;
1113 const struct TestData {
1114 const std::string ifname;
1115 int32_t timeout;
1116 const std::string classLabel;
1117 } idleTestData[] = {
1118 {"wlan0", 1234, "happyday"},
1119 {"rmnet_data0", 4567, "friday"},
1120 };
1121 for (const auto& td : idleTestData) {
1122 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1123 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1124 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1125
1126 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1127 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1128 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1129 }
1130}
1131
Luke Huanga67dd562018-07-17 19:58:25 +08001132namespace {
1133
1134constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1135constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1136
1137void expectStrictSetUidAccept(const int uid) {
1138 std::string uidRule = StringPrintf("owner UID match %u", uid);
1139 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1140 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001141 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1142 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001143 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1144 }
1145}
1146
1147void expectStrictSetUidLog(const int uid) {
1148 static const char logRule[] = "st_penalty_log all";
1149 std::string uidRule = StringPrintf("owner UID match %u", uid);
1150 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1151 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001152 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1153 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001154 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1155 }
1156}
1157
1158void expectStrictSetUidReject(const int uid) {
1159 static const char rejectRule[] = "st_penalty_reject all";
1160 std::string uidRule = StringPrintf("owner UID match %u", uid);
1161 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1162 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001163 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1164 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001165 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1166 }
1167}
1168
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001169} // namespace
1170
1171TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001172 binder::Status status;
1173 int32_t uid = randomUid();
1174
1175 // setUidCleartextPenalty Policy:Log with randomUid
1176 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1177 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1178 expectStrictSetUidLog(uid);
1179
1180 // setUidCleartextPenalty Policy:Accept with randomUid
1181 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1182 expectStrictSetUidAccept(uid);
1183
1184 // setUidCleartextPenalty Policy:Reject with randomUid
1185 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1186 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1187 expectStrictSetUidReject(uid);
1188
1189 // setUidCleartextPenalty Policy:Accept with randomUid
1190 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1191 expectStrictSetUidAccept(uid);
1192
1193 // test wrong policy
1194 int32_t wrongPolicy = -123;
1195 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1196 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1197}
1198
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001199namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001200
Luke Huangd1675922019-03-11 17:29:27 +08001201std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001202 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001203 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001204 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1205 // ...
1206 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1207
Luke Huangd1675922019-03-11 17:29:27 +08001208 // (dnsmasq)
1209 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1210
1211 if (maxTries == 0) return {};
1212
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001213 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001214 std::vector<std::string> result;
1215 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001216 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001217 if (result.size() || ++run > maxTries) {
1218 break;
1219 }
1220
Luke Huang728cf4c2019-03-14 19:43:02 +08001221 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001222 }
1223 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001224}
1225
Luke Huangd1675922019-03-11 17:29:27 +08001226void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001227 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001228}
1229
Luke Huang728cf4c2019-03-14 19:43:02 +08001230void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001231 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001232}
1233
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001234} // namespace
1235
1236TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001237 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001238
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001239 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1240 std::string clatAddress;
1241 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001242
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001243 // Can't start clatd on an interface that's not part of any network...
1244 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1245 EXPECT_FALSE(status.isOk());
1246 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1247
1248 // ... so create a test physical network and add our tun to it.
1249 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1250 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1251
1252 // Prefix must be 96 bits long.
1253 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1254 EXPECT_FALSE(status.isOk());
1255 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1256
1257 // Can't start clatd unless there's a default route...
1258 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1259 EXPECT_FALSE(status.isOk());
1260 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1261
1262 // so add a default route.
1263 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1264
1265 // Can't start clatd unless there's a global address...
1266 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1267 EXPECT_FALSE(status.isOk());
1268 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1269
1270 // ... so add a global address.
1271 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001272 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001273
1274 // Now expect clatd to start successfully.
1275 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1276 EXPECT_TRUE(status.isOk());
1277 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1278
1279 // Starting it again returns EBUSY.
1280 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1281 EXPECT_FALSE(status.isOk());
1282 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1283
Luke Huangd1675922019-03-11 17:29:27 +08001284 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001285
1286 // Expect clatd to stop successfully.
1287 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001288 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001289 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001290
1291 // Stopping a clatd that doesn't exist returns ENODEV.
1292 status = mNetd->clatdStop(sTun.name());
1293 EXPECT_FALSE(status.isOk());
1294 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001295 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001296
1297 // Clean up.
1298 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1299 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1300 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001301}
Luke Huang457d4702018-08-16 15:39:15 +08001302
1303namespace {
1304
1305bool getIpfwdV4Enable() {
1306 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1307 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1308 EXPECT_TRUE(!result.empty());
1309 int v4Enable = std::stoi(result[0]);
1310 return v4Enable;
1311}
1312
1313bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001314 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001315 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1316 EXPECT_TRUE(!result.empty());
1317 int v6Enable = std::stoi(result[0]);
1318 return v6Enable;
1319}
1320
1321void expectIpfwdEnable(bool enable) {
1322 int enableIPv4 = getIpfwdV4Enable();
1323 int enableIPv6 = getIpfwdV6Enable();
1324 EXPECT_EQ(enable, enableIPv4);
1325 EXPECT_EQ(enable, enableIPv6);
1326}
1327
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001328bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001329 std::vector<std::string> rules = listIpRules(ipVersion);
1330 for (const auto& rule : rules) {
1331 if (rule.find(ipfwdRule) != std::string::npos) {
1332 return true;
1333 }
1334 }
1335 return false;
1336}
1337
1338void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1339 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1340
1341 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1342 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1343 }
1344}
1345
1346void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1347 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1348
1349 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1350 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1351 }
1352}
1353
1354} // namespace
1355
1356TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001357 // Get ipfwd requester list from Netd
1358 std::vector<std::string> requesterList;
1359 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001360 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001361
1362 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001363 if (requesterList.size() == 0) {
1364 // No requester in Netd, ipfwd should be disabled
1365 // So add one test requester and verify
1366 status = mNetd->ipfwdEnableForwarding("TestRequester");
1367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001368
Luke Huang728cf4c2019-03-14 19:43:02 +08001369 expectIpfwdEnable(true);
1370 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1372 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001373
Luke Huang728cf4c2019-03-14 19:43:02 +08001374 // Remove test one, verify again
1375 status = mNetd->ipfwdDisableForwarding("TestRequester");
1376 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1377
1378 expectIpfwdEnable(false);
1379 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1381 EXPECT_FALSE(ipfwdEnabled);
1382 } else {
1383 // Disable all requesters
1384 for (const auto& requester : requesterList) {
1385 status = mNetd->ipfwdDisableForwarding(requester);
1386 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1387 }
1388
1389 // After disable all requester, ipfwd should be disabled
1390 expectIpfwdEnable(false);
1391 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1392 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1393 EXPECT_FALSE(ipfwdEnabled);
1394
1395 // Enable them back
1396 for (const auto& requester : requesterList) {
1397 status = mNetd->ipfwdEnableForwarding(requester);
1398 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1399 }
1400
1401 // ipfwd should be enabled
1402 expectIpfwdEnable(true);
1403 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1405 EXPECT_TRUE(ipfwdEnabled);
1406 }
Luke Huang457d4702018-08-16 15:39:15 +08001407}
1408
1409TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001410 // Add test physical network
1411 EXPECT_TRUE(
1412 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1413 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1414 EXPECT_TRUE(
1415 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1416 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001417
Luke Huangd1827b82019-02-15 15:03:27 +08001418 binder::Status status =
1419 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1420 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1421 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001422
Luke Huangd1827b82019-02-15 15:03:27 +08001423 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1424 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1425 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001426}
Luke Huang531f5d32018-08-03 15:19:05 +08001427
1428namespace {
1429
1430constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1431constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1432constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1433constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1434constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001435constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001436
Luke Huang19b49c52018-10-22 12:12:05 +09001437// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1438// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001439bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1440 const char* chainName, const std::string& expectedTargetA,
1441 const std::string& expectedTargetB) {
1442 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1443 int matchCount = 0;
1444
1445 for (const auto& rule : rules) {
1446 if (rule.find(expectedTargetA) != std::string::npos) {
1447 if (rule.find(expectedTargetB) != std::string::npos) {
1448 matchCount++;
1449 }
1450 }
1451 }
1452 return matchCount == expectedCount;
1453}
1454
1455void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1456 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1457 std::string result = "";
1458
1459 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001460 // Quota value might be decreased while matching packets
1461 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001462}
1463
1464void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1465 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1466 std::string quotaRule = StringPrintf("quota %s", ifname);
1467
1468 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1469 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1470 BANDWIDTH_COSTLY_IF));
1471 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1472 BANDWIDTH_COSTLY_IF));
1473 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1474 BANDWIDTH_COSTLY_IF));
1475 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1476 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1477 }
1478 expectXtQuotaValueEqual(ifname, quotaBytes);
1479}
1480
1481void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1482 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1483 std::string quotaRule = StringPrintf("quota %s", ifname);
1484
1485 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1486 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1487 BANDWIDTH_COSTLY_IF));
1488 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1489 BANDWIDTH_COSTLY_IF));
1490 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1491 BANDWIDTH_COSTLY_IF));
1492 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1493 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1494 }
1495}
1496
1497void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1498 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1499 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1500 std::string alertName = StringPrintf("%sAlert", ifname);
1501
1502 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1503 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1504 }
1505 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1506}
1507
1508void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1509 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1510 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1511
1512 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1513 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1514 }
1515}
1516
1517void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1518 static const char globalAlertRule[] = "quota globalAlert";
1519 static const char globalAlertName[] = "globalAlert";
1520
1521 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001522 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001523 }
1524 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1525}
1526
1527void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1528 std::string uidRule = StringPrintf("owner UID match %u", uid);
1529
1530 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1531 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1532 }
1533}
1534
1535void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1536 std::string uidRule = StringPrintf("owner UID match %u", uid);
1537
1538 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1539 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1540 }
1541}
1542
1543} // namespace
1544
1545TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1546 long testQuotaBytes = 5550;
1547
1548 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001549 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001550 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1551
1552 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1553 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1554 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1555
1556 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1557 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1558 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1559
1560 // Remove test physical network
1561 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1562}
1563
1564TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1565 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001566 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001567 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001568 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001569 // Need to have a prior interface quota set to set an alert
1570 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1571 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1572 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1573 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1574
1575 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1576 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1577 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1578
1579 // Remove interface quota
1580 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1581 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1582 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1583
1584 // Remove test physical network
1585 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1586}
1587
1588TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001589 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001590
1591 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1592 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1593 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1594
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001595 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001596 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1597 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1598 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1599}
1600
1601TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1602 SKIP_IF_BPF_SUPPORTED;
1603
1604 int32_t uid = randomUid();
1605 static const char targetReject[] = "REJECT";
1606 static const char targetReturn[] = "RETURN";
1607
1608 // add NaughtyApp
1609 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1610 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1611 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1612
1613 // remove NaughtyApp
1614 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1615 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1616 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1617
1618 // add NiceApp
1619 status = mNetd->bandwidthAddNiceApp(uid);
1620 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1621 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1622
1623 // remove NiceApp
1624 status = mNetd->bandwidthRemoveNiceApp(uid);
1625 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1626 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1627}
Luke Huangb5733d72018-08-21 17:17:19 +08001628
1629namespace {
1630
Luke Huangc3252cc2018-10-16 15:43:23 +08001631std::string ipRouteString(const std::string& ifName, const std::string& dst,
1632 const std::string& nextHop) {
1633 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1634
1635 if (!nextHop.empty()) {
1636 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001637 }
1638
Luke Huangc3252cc2018-10-16 15:43:23 +08001639 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001640}
1641
Luke Huangc3252cc2018-10-16 15:43:23 +08001642void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1643 const std::string& dst, const std::string& nextHop,
1644 const char* table) {
1645 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1646}
1647
1648void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001649 const std::string& dst, const std::string& nextHop,
1650 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001651 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001652}
1653
1654bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1655 std::vector<std::string> rules = listIpRules(ipVersion);
1656 for (const auto& rule : rules) {
1657 if (rule.find(ipRule) != std::string::npos) {
1658 return true;
1659 }
1660 }
1661 return false;
1662}
1663
1664void expectNetworkDefaultIpRuleExists(const char* ifName) {
1665 std::string networkDefaultRule =
1666 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1667
1668 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1669 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1670 }
1671}
1672
1673void expectNetworkDefaultIpRuleDoesNotExist() {
1674 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1675
1676 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1677 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1678 }
1679}
1680
1681void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1682 std::string networkPermissionRule = "";
1683 switch (permission) {
1684 case INetd::PERMISSION_NONE:
1685 networkPermissionRule = StringPrintf(
1686 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1687 break;
1688 case INetd::PERMISSION_NETWORK:
1689 networkPermissionRule = StringPrintf(
1690 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1691 break;
1692 case INetd::PERMISSION_SYSTEM:
1693 networkPermissionRule = StringPrintf(
1694 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1695 break;
1696 }
1697
1698 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1699 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1700 }
1701}
1702
1703// TODO: It is a duplicate function, need to remove it
1704bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1705 const std::string& expectedInterface,
1706 const std::string& expectedRule,
1707 const char* table) {
1708 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1709 for (const auto& rule : rules) {
1710 if (rule.find(expectedInterface) != std::string::npos) {
1711 if (rule.find(expectedRule) != std::string::npos) {
1712 return true;
1713 }
1714 }
1715 }
1716 return false;
1717}
1718
1719void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1720 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1721 std::string networkIncomingPacketMarkRule = "";
1722 switch (permission) {
1723 case INetd::PERMISSION_NONE:
1724 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1725 break;
1726 case INetd::PERMISSION_NETWORK:
1727 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1728 break;
1729 case INetd::PERMISSION_SYSTEM:
1730 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1731 break;
1732 }
1733
1734 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1735 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1736 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1737 }
1738}
1739
1740} // namespace
1741
1742TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001743 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001744 const char* ipVersion;
1745 const char* testDest;
1746 const char* testNextHop;
1747 const bool expectSuccess;
1748 } kTestData[] = {
1749 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001750 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1751 {IP_RULE_V4, "10.251.0.0/16", "", true},
1752 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1753 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001754 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001755 {IP_RULE_V6, "::/0", "2001:db8::", true},
1756 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001757 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1758 };
1759
Luke Huangc3252cc2018-10-16 15:43:23 +08001760 static const struct {
1761 const char* ipVersion;
1762 const char* testDest;
1763 const char* testNextHop;
1764 } kTestDataWithNextHop[] = {
1765 {IP_RULE_V4, "10.251.10.0/30", ""},
1766 {IP_RULE_V6, "2001:db8::/32", ""},
1767 };
1768
Luke Huangb670d162018-08-23 20:01:13 +08001769 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001770 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001771 const int testUid = randomUid();
1772 const std::vector<int32_t> testUids = {testUid};
1773
1774 // Add test physical network
1775 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1776 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1777
Luke Huangc3252cc2018-10-16 15:43:23 +08001778 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001779 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001780 const auto& td = kTestDataWithNextHop[i];
1781
1782 // All route for test tun will disappear once the tun interface is deleted.
1783 binder::Status status =
1784 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1785 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1786 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1787 sTun.name().c_str());
1788
1789 // Add system permission for test uid, setup route in legacy system table.
1790 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1791
1792 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1793 testUid);
1794 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1795 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1796 testTableLegacySystem);
1797
1798 // Remove system permission for test uid, setup route in legacy network table.
1799 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1800
1801 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1802 testUid);
1803 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1804 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1805 testTableLegacyNetwork);
1806 }
1807
Sehee Park8659b8d2018-11-16 10:53:16 +09001808 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001809 const auto& td = kTestData[i];
1810
1811 binder::Status status =
1812 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1813 if (td.expectSuccess) {
1814 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001815 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001816 sTun.name().c_str());
1817 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001818 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1819 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001820 }
1821
1822 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1823 if (td.expectSuccess) {
1824 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001825 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1826 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001827 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001828 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1829 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001830 }
1831
Luke Huangc3252cc2018-10-16 15:43:23 +08001832 // Add system permission for test uid, route will be added into legacy system table.
1833 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001834
1835 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1836 testUid);
1837 if (td.expectSuccess) {
1838 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001839 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001840 testTableLegacySystem);
1841 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001842 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1843 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001844 }
1845
1846 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1847 td.testNextHop, testUid);
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 testTableLegacySystem);
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 // Remove system permission for test uid, route will be added into legacy network table.
1858 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1859
1860 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1861 testUid);
1862 if (td.expectSuccess) {
1863 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1864 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1865 testTableLegacyNetwork);
1866 } else {
1867 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1868 EXPECT_NE(0, status.serviceSpecificErrorCode());
1869 }
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();
1875 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1876 testTableLegacyNetwork);
1877 } else {
1878 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1879 EXPECT_NE(0, status.serviceSpecificErrorCode());
1880 }
Luke Huangb670d162018-08-23 20:01:13 +08001881 }
1882
1883 // Remove test physical network
1884 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1885}
1886
1887TEST_F(BinderTest, NetworkPermissionDefault) {
1888 // Add test physical network
1889 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1890 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1891
Luke Huangc3252cc2018-10-16 15:43:23 +08001892 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001893 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1894 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001895
1896 // Test SetDefault
1897 status = mNetd->networkSetDefault(TEST_NETID1);
1898 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1899 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1900
1901 status = mNetd->networkClearDefault();
1902 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1903 expectNetworkDefaultIpRuleDoesNotExist();
1904
Luke Huangd2861982019-05-17 19:47:28 +08001905 // Set default network back
1906 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001907 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1908
1909 // Test SetPermission
1910 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1911 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1912 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1913 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1914
1915 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1916 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1917 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1918 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1919
1920 // Remove test physical network
1921 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1922}
1923
1924TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001925 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001926 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1927 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001928 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001929 EXPECT_TRUE(ret);
1930
Luke Huang854e2992019-05-29 16:42:48 +08001931 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001932 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08001933
1934 // Clear uid permission before calling networkCanProtect to ensure
1935 // the call won't be affected by uid permission.
1936 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
1937
1938 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001939 EXPECT_FALSE(ret);
1940}
1941
1942namespace {
1943
Luke Huangb5733d72018-08-21 17:17:19 +08001944int readIntFromPath(const std::string& path) {
1945 std::string result = "";
1946 EXPECT_TRUE(ReadFileToString(path, &result));
1947 return std::stoi(result);
1948}
1949
1950int getTetherAcceptIPv6Ra(const std::string& ifName) {
1951 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1952 return readIntFromPath(path);
1953}
1954
1955bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1956 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1957 return readIntFromPath(path);
1958}
1959
1960int getTetherIPv6DadTransmits(const std::string& ifName) {
1961 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1962 return readIntFromPath(path);
1963}
1964
1965bool getTetherEnableIPv6(const std::string& ifName) {
1966 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1967 int disableIPv6 = readIntFromPath(path);
1968 return !disableIPv6;
1969}
1970
1971bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1972 for (const auto& iface : ifList) {
1973 if (iface == ifName) {
1974 return true;
1975 }
1976 }
1977 return false;
1978}
1979
1980void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1981 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1982 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1983 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1984 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1985}
1986
1987void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1988 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1989 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1990 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1991 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1992}
1993
1994void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1995 const std::string& ifName) {
1996 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1997}
1998
1999void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2000 const std::string& ifName) {
2001 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2002}
2003
2004void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2005 const std::vector<std::string>& testDnsAddrs) {
2006 EXPECT_TRUE(dnsList == testDnsAddrs);
2007}
2008
2009} // namespace
2010
2011TEST_F(BinderTest, TetherStartStopStatus) {
2012 std::vector<std::string> noDhcpRange = {};
2013 static const char dnsdName[] = "dnsmasq";
2014
Luke Huang91bd3e12019-08-20 11:33:52 +08002015 for (bool usingLegacyDnsProxy : {true, false}) {
2016 binder::Status status =
2017 mNetd->tetherStartWithConfiguration(usingLegacyDnsProxy, noDhcpRange);
2018 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2019 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2020 if (usingLegacyDnsProxy == true) {
2021 expectProcessExists(dnsdName);
2022 } else {
2023 expectProcessDoesNotExist(dnsdName);
2024 }
Luke Huangb5733d72018-08-21 17:17:19 +08002025
Luke Huang91bd3e12019-08-20 11:33:52 +08002026 bool tetherEnabled;
2027 status = mNetd->tetherIsEnabled(&tetherEnabled);
2028 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2029 EXPECT_TRUE(tetherEnabled);
Luke Huangb5733d72018-08-21 17:17:19 +08002030
Luke Huang91bd3e12019-08-20 11:33:52 +08002031 status = mNetd->tetherStop();
2032 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2033 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002034
Luke Huang91bd3e12019-08-20 11:33:52 +08002035 status = mNetd->tetherIsEnabled(&tetherEnabled);
2036 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2037 EXPECT_FALSE(tetherEnabled);
2038 }
Luke Huangb5733d72018-08-21 17:17:19 +08002039}
2040
2041TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2042 // TODO: verify if dnsmasq update interface successfully
2043
2044 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2045 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2046 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2047
2048 std::vector<std::string> ifList;
2049 status = mNetd->tetherInterfaceList(&ifList);
2050 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2051 expectTetherInterfaceExists(ifList, sTun.name());
2052
2053 status = mNetd->tetherInterfaceRemove(sTun.name());
2054 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2055 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2056
2057 status = mNetd->tetherInterfaceList(&ifList);
2058 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2059 expectTetherInterfaceNotExists(ifList, sTun.name());
2060}
2061
2062TEST_F(BinderTest, TetherDnsSetList) {
2063 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002064 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2065 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002066
2067 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2068 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2069
2070 std::vector<std::string> dnsList;
2071 status = mNetd->tetherDnsList(&dnsList);
2072 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2073 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002074}
2075
2076namespace {
2077
2078constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2079constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2080constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2081constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2082constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2083constexpr char FIREWALL_STANDBY[] = "fw_standby";
2084constexpr char targetReturn[] = "RETURN";
2085constexpr char targetDrop[] = "DROP";
2086
2087void expectFirewallWhitelistMode() {
2088 static const char dropRule[] = "DROP all";
2089 static const char rejectRule[] = "REJECT all";
2090 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2091 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2092 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2093 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2094 }
2095}
2096
2097void expectFirewallBlacklistMode() {
2098 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2099 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2100 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2101 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2102 }
2103}
2104
2105bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2106 const std::string& expectedInterface,
2107 const std::string& expectedRule) {
2108 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2109 // Expected rule:
2110 // Chain fw_INPUT (1 references)
2111 // pkts bytes target prot opt in out source destination
2112 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2113 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2114 int firstRuleIndex = 2;
2115 if (rules.size() < 4) return false;
2116 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2117 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2118 return true;
2119 }
2120 }
2121 return false;
2122}
2123
2124// TODO: It is a duplicate function, need to remove it
2125bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2126 const std::string& expectedInterface,
2127 const std::string& expectedRule) {
2128 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2129 for (const auto& rule : rules) {
2130 if (rule.find(expectedInterface) != std::string::npos) {
2131 if (rule.find(expectedRule) != std::string::npos) {
2132 return true;
2133 }
2134 }
2135 }
2136 return false;
2137}
2138
2139void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2140 static const char returnRule[] = "RETURN all";
2141 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2142 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2143 returnRule));
2144 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2145 returnRule));
2146 }
2147}
2148
2149void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2150 static const char returnRule[] = "RETURN all";
2151 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2152 EXPECT_FALSE(
2153 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2154 EXPECT_FALSE(
2155 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2156 }
2157}
2158
2159bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2160 const std::string& expectedTarget,
2161 const std::string& expectedRule) {
2162 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2163 int firstRuleIndex = 2;
2164 if (rules.size() < 4) return false;
2165 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2166 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2167 return true;
2168 }
2169 }
2170 return false;
2171}
2172
2173bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2174 const std::string& expectedTarget,
2175 const std::string& expectedRule) {
2176 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2177 int lastRuleIndex = rules.size() - 1;
2178 if (lastRuleIndex < 0) return false;
2179 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2180 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2181 return true;
2182 }
2183 }
2184 return false;
2185}
2186
2187void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2188 std::string uidRule = StringPrintf("owner UID match %u", uid);
2189 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2190 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2191}
2192
2193void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2194 std::string uidRule = StringPrintf("owner UID match %u", uid);
2195 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2196 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2197}
2198
2199void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2200 std::string uidRule = StringPrintf("owner UID match %u", uid);
2201 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2202 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2203}
2204
2205void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2206 std::string uidRule = StringPrintf("owner UID match %u", uid);
2207 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2208 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2209}
2210
2211bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2212 std::vector<std::string> inputRules =
2213 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2214 std::vector<std::string> outputRules =
2215 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2216 int inputLastRuleIndex = inputRules.size() - 1;
2217 int outputLastRuleIndex = outputRules.size() - 1;
2218
2219 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2220 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2221 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2222 return true;
2223 }
2224 }
2225 return false;
2226}
2227
2228void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2229 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2230 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2231}
2232
2233void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2234 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2235 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2236 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2237 }
2238}
2239
2240} // namespace
2241
2242TEST_F(BinderTest, FirewallSetFirewallType) {
2243 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2244 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2245 expectFirewallWhitelistMode();
2246
2247 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2248 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2249 expectFirewallBlacklistMode();
2250
2251 // set firewall type blacklist twice
2252 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2253 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2254 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2255 expectFirewallBlacklistMode();
2256
2257 // set firewall type whitelist twice
2258 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2259 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2260 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2261 expectFirewallWhitelistMode();
2262
2263 // reset firewall type to default
2264 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2265 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2266 expectFirewallBlacklistMode();
2267}
2268
2269TEST_F(BinderTest, FirewallSetInterfaceRule) {
2270 // setinterfaceRule is not supported in BLACKLIST MODE
2271 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2272 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2273
2274 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2275 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2276
2277 // set WHITELIST mode first
2278 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2279 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2280
2281 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2282 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2283 expectFirewallInterfaceRuleAllowExists(sTun.name());
2284
2285 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2286 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2287 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2288
2289 // reset firewall mode to default
2290 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2291 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2292 expectFirewallBlacklistMode();
2293}
2294
2295TEST_F(BinderTest, FirewallSetUidRule) {
2296 SKIP_IF_BPF_SUPPORTED;
2297
2298 int32_t uid = randomUid();
2299
2300 // Doze allow
2301 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2302 INetd::FIREWALL_RULE_ALLOW);
2303 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2304 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2305
2306 // Doze deny
2307 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2308 INetd::FIREWALL_RULE_DENY);
2309 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2310 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2311
2312 // Powersave allow
2313 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2314 INetd::FIREWALL_RULE_ALLOW);
2315 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2316 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2317
2318 // Powersave deny
2319 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2320 INetd::FIREWALL_RULE_DENY);
2321 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2322 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2323
2324 // Standby deny
2325 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2326 INetd::FIREWALL_RULE_DENY);
2327 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2328 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2329
2330 // Standby allow
2331 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2332 INetd::FIREWALL_RULE_ALLOW);
2333 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2334 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2335
2336 // None deny in BLACKLIST
2337 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2338 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2339 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2340 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2341
2342 // None allow in BLACKLIST
2343 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2344 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2345 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2346 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2347
2348 // set firewall type whitelist twice
2349 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2350 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2351 expectFirewallWhitelistMode();
2352
2353 // None allow in WHITELIST
2354 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2355 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2356 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2357 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2358
2359 // None deny in WHITELIST
2360 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2361 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2362 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2363 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2364
2365 // reset firewall mode to default
2366 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2368 expectFirewallBlacklistMode();
2369}
2370
2371TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2372 SKIP_IF_BPF_SUPPORTED;
2373
2374 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2376 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2377
2378 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2379 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2380 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2381
2382 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2383 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2384 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2385
2386 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2387 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2388 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2389
2390 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2391 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2392 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2393
2394 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2395 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2396 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2397}
Luke Huangf7782042018-08-08 13:13:04 +08002398
2399namespace {
2400
2401std::string hwAddrToStr(unsigned char* hwaddr) {
2402 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2403 hwaddr[4], hwaddr[5]);
2404}
2405
2406int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2407 int prefixLength = 0;
2408 uint32_t m = ntohl(mask);
2409 while (m & (1 << 31)) {
2410 prefixLength++;
2411 m = m << 1;
2412 }
2413 return prefixLength;
2414}
2415
2416std::string toStdString(const String16& s) {
2417 return std::string(String8(s.string()));
2418}
2419
2420android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2421 const auto& sys = sSyscalls.get();
2422 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2423 EXPECT_TRUE(isOk(fd.status()));
2424
2425 struct ifreq ifr = {};
2426 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2427
2428 return sys.ioctl(fd.value(), flag, &ifr);
2429}
2430
2431std::string getInterfaceHwAddr(const std::string& ifName) {
2432 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2433
2434 unsigned char hwaddr[ETH_ALEN] = {};
2435 if (isOk(res.status())) {
2436 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2437 }
2438
2439 return hwAddrToStr(hwaddr);
2440}
2441
2442int getInterfaceIPv4Prefix(const std::string& ifName) {
2443 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2444
2445 int prefixLength = 0;
2446 if (isOk(res.status())) {
2447 prefixLength = ipv4NetmaskToPrefixLength(
2448 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2449 }
2450
2451 return prefixLength;
2452}
2453
2454std::string getInterfaceIPv4Addr(const std::string& ifName) {
2455 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2456
2457 struct in_addr addr = {};
2458 if (isOk(res.status())) {
2459 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2460 }
2461
2462 return std::string(inet_ntoa(addr));
2463}
2464
2465std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2466 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2467
2468 unsigned flags = 0;
2469 if (isOk(res.status())) {
2470 flags = res.value().ifr_flags;
2471 }
2472
2473 std::vector<std::string> ifFlags;
2474 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2475 : toStdString(INetd::IF_STATE_DOWN()));
2476
2477 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2478 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2479 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2480 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2481 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2482
2483 return ifFlags;
2484}
2485
2486bool compareListInterface(const std::vector<std::string>& interfaceList) {
2487 const auto& res = InterfaceController::getIfaceNames();
2488 EXPECT_TRUE(isOk(res));
2489
2490 std::vector<std::string> resIfList;
2491 resIfList.reserve(res.value().size());
2492 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2493
2494 return resIfList == interfaceList;
2495}
2496
2497int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2498 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2499 return readIntFromPath(path);
2500}
2501
2502bool getInterfaceEnableIPv6(const std::string& ifName) {
2503 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2504
2505 int disableIPv6 = readIntFromPath(path);
2506 return !disableIPv6;
2507}
2508
2509int getInterfaceMtu(const std::string& ifName) {
2510 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2511 return readIntFromPath(path);
2512}
2513
2514void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2515 EXPECT_TRUE(compareListInterface(interfaceList));
2516}
2517
2518void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2519 const InterfaceConfigurationParcel& interfaceCfg) {
2520 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2521 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2522 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2523 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2524}
2525
2526void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2527 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2528 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2529
2530 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2531 for (const auto& flag : setCfg.flags) {
2532 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2533 }
2534}
2535
2536void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2537 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2538 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2539}
2540
2541void expectInterfaceNoAddr(const std::string& ifName) {
2542 // noAddr
2543 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2544 // noPrefix
2545 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2546}
2547
2548void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2549 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2550 EXPECT_EQ(enableIPv6, enable);
2551}
2552
2553void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2554 int mtuSize = getInterfaceMtu(ifName);
2555 EXPECT_EQ(mtu, mtuSize);
2556}
2557
2558InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2559 const std::string& addr, int prefixLength,
2560 const std::vector<std::string>& flags) {
2561 InterfaceConfigurationParcel cfg;
2562 cfg.ifName = ifName;
2563 cfg.hwAddr = "";
2564 cfg.ipv4Addr = addr;
2565 cfg.prefixLength = prefixLength;
2566 cfg.flags = flags;
2567 return cfg;
2568}
2569
2570void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2571 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2572 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2573
2574 for (const auto& flag : expectedFlags) {
2575 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2576 interfaceCfg.flags.end());
2577 }
2578
2579 for (const auto& flag : unexpectedFlags) {
2580 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2581 interfaceCfg.flags.end());
2582 }
2583}
2584
2585} // namespace
2586
2587TEST_F(BinderTest, InterfaceList) {
2588 std::vector<std::string> interfaceListResult;
2589
2590 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2591 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2592 expectInterfaceList(interfaceListResult);
2593}
2594
2595TEST_F(BinderTest, InterfaceGetCfg) {
2596 InterfaceConfigurationParcel interfaceCfgResult;
2597
2598 // Add test physical network
2599 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2600 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2601
2602 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2603 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2604 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2605 expectTunFlags(interfaceCfgResult);
2606
2607 // Remove test physical network
2608 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2609}
2610
2611TEST_F(BinderTest, InterfaceSetCfg) {
2612 const std::string testAddr = "192.0.2.3";
2613 const int testPrefixLength = 24;
2614 std::vector<std::string> upFlags = {"up"};
2615 std::vector<std::string> downFlags = {"down"};
2616
2617 // Add test physical network
2618 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2619 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2620
2621 // Set tun interface down.
2622 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2623 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2624 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2625 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2626
2627 // Set tun interface up again.
2628 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2629 status = mNetd->interfaceSetCfg(interfaceCfg);
2630 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2631 status = mNetd->interfaceClearAddrs(sTun.name());
2632 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2633
2634 // Remove test physical network
2635 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2636}
2637
2638TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2639 // enable
2640 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2641 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2642 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2643
2644 // disable
2645 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2646 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2647 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2648}
2649
2650TEST_F(BinderTest, InterfaceClearAddr) {
2651 const std::string testAddr = "192.0.2.3";
2652 const int testPrefixLength = 24;
2653 std::vector<std::string> noFlags{};
2654
2655 // Add test physical network
2656 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2657 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2658
2659 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2660 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2661 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2662 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2663
2664 status = mNetd->interfaceClearAddrs(sTun.name());
2665 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2666 expectInterfaceNoAddr(sTun.name());
2667
2668 // Remove test physical network
2669 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2670}
2671
2672TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2673 // Add test physical network
2674 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2675 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2676
2677 // disable
2678 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2679 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2680 expectInterfaceEnableIPv6(sTun.name(), false);
2681
2682 // enable
2683 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2684 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2685 expectInterfaceEnableIPv6(sTun.name(), true);
2686
2687 // Remove test physical network
2688 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2689}
2690
2691TEST_F(BinderTest, InterfaceSetMtu) {
2692 const int testMtu = 1200;
2693
2694 // Add test physical network
2695 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2696 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2697
2698 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2699 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2700 expectInterfaceMtu(sTun.name(), testMtu);
2701
2702 // Remove test physical network
2703 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2704}
Luke Huang19b49c52018-10-22 12:12:05 +09002705
2706namespace {
2707
2708constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2709constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002710constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002711constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2712
Luke Huangae038f82018-11-05 11:17:31 +09002713int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002714 return listIptablesRuleByTable(binary, table, chainName).size();
2715}
2716
2717bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2718 const std::vector<std::string>& targetVec) {
2719 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2720 if (targetVec.size() != rules.size() - 2) {
2721 return false;
2722 }
2723
2724 /*
Luke Huangae038f82018-11-05 11:17:31 +09002725 * Check that the rules match. Note that this function matches substrings, not entire rules,
2726 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002727 * Skip first two lines since rules start from third line.
2728 * Chain chainName (x references)
2729 * pkts bytes target prot opt in out source destination
2730 * ...
2731 */
2732 int rIndex = 2;
2733 for (const auto& target : targetVec) {
2734 if (rules[rIndex].find(target) == std::string::npos) {
2735 return false;
2736 }
2737 rIndex++;
2738 }
2739 return true;
2740}
2741
2742void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2743 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2744 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2745 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002746 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002747 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2748 "DROP"};
2749
2750 // V4
2751 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2752 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002753 EXPECT_TRUE(
2754 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002755 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2756
Luke Huangae038f82018-11-05 11:17:31 +09002757 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002758 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2759
2760 // V6
2761 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002762 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2763 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002764
2765 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2766 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2767 extIf));
2768 }
2769}
2770
2771void expectNatDisable() {
2772 // It is the default DROP rule with tethering disable.
2773 // Chain tetherctrl_FORWARD (1 references)
2774 // pkts bytes target prot opt in out source destination
2775 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2776 std::vector<std::string> forwardV4Match = {"DROP"};
2777 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2778
2779 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002780 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2781 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002782
Luke Huangae038f82018-11-05 11:17:31 +09002783 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2784 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002785
2786 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2787}
2788
2789} // namespace
2790
2791TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002792 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2793 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2794 expectNatEnable(sTun.name(), sTun2.name());
2795
2796 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2797 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2798 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002799}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002800
2801namespace {
2802
2803using TripleInt = std::array<int, 3>;
2804
2805TripleInt readProcFileToTripleInt(const std::string& path) {
2806 std::string valueString;
2807 int min, def, max;
2808 EXPECT_TRUE(ReadFileToString(path, &valueString));
2809 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2810 return {min, def, max};
2811}
2812
2813void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2814 std::string testRmemValues =
2815 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2816 std::string testWmemValues =
2817 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2818 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2819
2820 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2821 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2822
2823 for (int i = 0; i < 3; i++) {
2824 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2825 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2826 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2827 }
2828}
2829
2830} // namespace
2831
2832TEST_F(BinderTest, TcpBufferSet) {
2833 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2834 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2835 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2836 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2837
2838 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2839 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2840}
Luke Huang528af602018-08-29 19:06:05 +08002841
Chenbo Feng48eaed32018-12-26 17:40:21 -08002842namespace {
2843
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002844void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002845 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2846 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2847 for (int32_t uid : uids) {
2848 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2849 if (exist) {
2850 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002851 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002852 } else {
2853 EXPECT_FALSE(isOk(permission));
2854 EXPECT_EQ(ENOENT, permission.status().code());
2855 }
2856 }
2857}
2858
2859} // namespace
2860
2861TEST_F(BinderTest, TestInternetPermission) {
2862 SKIP_IF_BPF_NOT_SUPPORTED;
2863
2864 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2865
2866 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002867 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002868 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002869 checkUidsInPermissionMap(appUids, true);
2870 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2871 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002872}
2873
Luke Huang528af602018-08-29 19:06:05 +08002874TEST_F(BinderTest, UnsolEvents) {
2875 auto testUnsolService = android::net::TestUnsolService::start();
2876 std::string oldTunName = sTun.name();
2877 std::string newTunName = "unsolTest";
2878 testUnsolService->tarVec.push_back(oldTunName);
2879 testUnsolService->tarVec.push_back(newTunName);
2880 auto& cv = testUnsolService->getCv();
2881 auto& cvMutex = testUnsolService->getCvMutex();
2882 binder::Status status = mNetd->registerUnsolicitedEventListener(
2883 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2884 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2885
2886 // TODO: Add test for below events
2887 // StrictCleartextDetected / InterfaceDnsServersAdded
2888 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2889
2890 {
2891 std::unique_lock lock(cvMutex);
2892
2893 // Re-init test Tun, and we expect that we will get some unsol events.
2894 // Use the test Tun device name to verify if we receive its unsol events.
2895 sTun.destroy();
2896 // Use predefined name
2897 sTun.init(newTunName);
2898
2899 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2900 }
2901
2902 // bit mask 1101101000
2903 // Test only covers below events currently
2904 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2905 InterfaceLinkStatusChanged | RouteChanged;
2906 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002907
2908 // Re-init sTun to clear predefined name
2909 sTun.destroy();
2910 sTun.init();
2911}
2912
2913TEST_F(BinderTest, NDC) {
2914 struct Command {
2915 const std::string cmdString;
2916 const std::string expectedResult;
2917 };
2918
2919 // clang-format off
2920 // Do not change the commands order
2921 const Command networkCmds[] = {
2922 {StringPrintf("ndc network create %d", TEST_NETID1),
2923 "200 0 success"},
2924 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2925 "200 0 success"},
2926 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2927 "200 0 success"},
2928 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2929 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2930 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2931 "200 0 success"},
2932 };
2933
2934 const std::vector<Command> ipfwdCmds = {
2935 {"ndc ipfwd enable " + sTun.name(),
2936 "200 0 ipfwd operation succeeded"},
2937 {"ndc ipfwd disable " + sTun.name(),
2938 "200 0 ipfwd operation succeeded"},
2939 {"ndc ipfwd add lo2 lo3",
2940 "400 0 ipfwd operation failed (No such process)"},
2941 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
2942 "200 0 ipfwd operation succeeded"},
2943 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
2944 "200 0 ipfwd operation succeeded"},
2945 };
2946
2947 static const struct {
2948 const char* ipVersion;
2949 const char* testDest;
2950 const char* testNextHop;
2951 const bool expectSuccess;
2952 const std::string expectedResult;
2953 } kTestData[] = {
2954 {IP_RULE_V4, "0.0.0.0/0", "", true,
2955 "200 0 success"},
2956 {IP_RULE_V4, "10.251.0.0/16", "", true,
2957 "200 0 success"},
2958 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
2959 "400 0 addRoute() failed (Invalid argument)",},
2960 {IP_RULE_V6, "::/0", "", true,
2961 "200 0 success"},
2962 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
2963 "200 0 success"},
2964 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
2965 "400 0 addRoute() failed (Invalid argument)"},
2966 };
2967 // clang-format on
2968
2969 for (const auto& cmd : networkCmds) {
2970 const std::vector<std::string> result = runCommand(cmd.cmdString);
2971 SCOPED_TRACE(cmd.cmdString);
2972 EXPECT_EQ(result.size(), 1U);
2973 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
2974 }
2975
2976 for (const auto& cmd : ipfwdCmds) {
2977 const std::vector<std::string> result = runCommand(cmd.cmdString);
2978 SCOPED_TRACE(cmd.cmdString);
2979 EXPECT_EQ(result.size(), 1U);
2980 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
2981 }
2982
2983 // Add test physical network
2984 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2985 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2986
2987 for (const auto& td : kTestData) {
2988 const std::string routeAddCmd =
2989 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
2990 td.testDest, td.testNextHop);
2991 const std::string routeRemoveCmd =
2992 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
2993 sTun.name().c_str(), td.testDest, td.testNextHop);
2994 std::vector<std::string> result = runCommand(routeAddCmd);
2995 SCOPED_TRACE(routeAddCmd);
2996 EXPECT_EQ(result.size(), 1U);
2997 EXPECT_EQ(td.expectedResult, Trim(result[0]));
2998 if (td.expectSuccess) {
2999 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3000 sTun.name().c_str());
3001 result = runCommand(routeRemoveCmd);
3002 EXPECT_EQ(result.size(), 1U);
3003 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3004 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3005 sTun.name().c_str());
3006 }
3007 }
3008 // Remove test physical network
3009 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003010}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003011
Luke Huang2ff8b342019-04-30 15:33:33 +08003012TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003013 sp<IBinder> binder;
3014 binder::Status status = mNetd->getOemNetd(&binder);
3015 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3016 sp<com::android::internal::net::IOemNetd> oemNetd;
3017 if (binder != nullptr) {
3018 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3019 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003020 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003021
3022 TimedOperation t("OemNetd isAlive RPC");
3023 bool isAlive = false;
3024 oemNetd->isAlive(&isAlive);
3025 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003026
3027 class TestOemUnsolListener
3028 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3029 public:
3030 android::binder::Status onRegistered() override {
3031 std::lock_guard lock(mCvMutex);
3032 mCv.notify_one();
3033 return android::binder::Status::ok();
3034 }
3035 std::condition_variable& getCv() { return mCv; }
3036 std::mutex& getCvMutex() { return mCvMutex; }
3037
3038 private:
3039 std::mutex mCvMutex;
3040 std::condition_variable mCv;
3041 };
3042
3043 // Start the Binder thread pool.
3044 android::ProcessState::self()->startThreadPool();
3045
3046 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3047
3048 auto& cv = testListener->getCv();
3049 auto& cvMutex = testListener->getCvMutex();
3050
3051 {
3052 std::unique_lock lock(cvMutex);
3053
3054 status = oemNetd->registerOemUnsolicitedEventListener(
3055 ::android::interface_cast<
3056 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3057 testListener));
3058 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3059
3060 // Wait for receiving expected events.
3061 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3062 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003063}
Luke Huangd2861982019-05-17 19:47:28 +08003064
3065void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3066 int fallthroughNetId) {
3067 // Re-init sTun* to ensure route rule exists.
3068 sTun.destroy();
3069 sTun.init();
3070 sTun2.destroy();
3071 sTun2.init();
3072
3073 // Create physical network with fallthroughNetId but not set it as default network
3074 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3075 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3076
3077 // Create VPN with vpnNetId
3078 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3079
3080 // Add uid to VPN
3081 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3082 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3083
3084 // Add default route to fallthroughNetwork
3085 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3086 // Add limited route
3087 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3088}
3089
3090namespace {
3091
3092class ScopedUidChange {
3093 public:
3094 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3095 mStoredUid = getuid();
3096 if (mInputUid == mStoredUid) return;
3097 EXPECT_TRUE(seteuid(uid) == 0);
3098 }
3099 ~ScopedUidChange() {
3100 if (mInputUid == mStoredUid) return;
3101 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3102 }
3103
3104 private:
3105 uid_t mInputUid;
3106 uid_t mStoredUid;
3107};
3108
3109constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3110
3111void clearQueue(int tunFd) {
3112 char buf[4096];
3113 int ret;
3114 do {
3115 ret = read(tunFd, buf, sizeof(buf));
3116 } while (ret > 0);
3117}
3118
3119void checkDataReceived(int udpSocket, int tunFd) {
3120 char buf[4096] = {};
3121 // Clear tunFd's queue before write something because there might be some
3122 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3123 clearQueue(tunFd);
3124 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3125 // TODO: extract header and verify data
3126 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3127}
3128
3129bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3130 ScopedUidChange scopedUidChange(uid);
Bernie Innocentid26a04a2019-10-30 17:15:15 +09003131 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Luke Huangd2861982019-05-17 19:47:28 +08003132 if (testSocket < 0) return false;
3133
Nick Desaulniers6b357502019-10-11 09:26:44 -07003134 const sockaddr_in6 dst6 = {
3135 .sin6_family = AF_INET6,
3136 .sin6_port = 42,
3137 .sin6_addr = dstAddr,
3138 };
Luke Huangd2861982019-05-17 19:47:28 +08003139 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3140 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3141 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3142 if (res == -1) return false;
3143
3144 char addr[INET6_ADDRSTRLEN];
3145 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3146 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3147 checkDataReceived(testSocket, tunFd);
3148 return true;
3149}
3150
3151void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3152 std::string vpnFallthroughRule =
3153 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3154 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3155 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3156 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3157 }
3158}
3159
3160void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3161 const TunInterface& fallthroughNetwork,
3162 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3163 int fallthroughNetId = TEST_NETID1) {
3164 // Set default network to NETID_UNSET
3165 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3166
3167 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3168 in6_addr insideVpnAddr = {
3169 {// 2001:db8:cafe::1
3170 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3171 // outsideVpnAddr will hit the route in the fallthrough network route table
3172 // because we added default route in createVpnNetworkWithUid
3173 in6_addr outsideVpnAddr = {
3174 {// 2607:f0d0:1002::4
3175 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3176
3177 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3178 int vpnFd = vpnNetwork.getFdForTesting();
3179 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3180 // default network.
3181 Fwmark fwmark;
3182 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3183 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3184
3185 // Set default network
3186 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3187
3188 // Connections go on the default network because UID 0 is not subject to the VPN.
3189 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3190 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3191 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3192 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3193
3194 // Check if fallthrough rule exists
3195 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3196
3197 // Expect fallthrough to default network
3198 // The fwmark differs depending on whether the VPN is bypassable or not.
3199 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3200 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3201
3202 // Expect connect success, packet will be sent to vpnFd.
3203 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3204 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3205
3206 // Explicitly select vpn network
3207 setNetworkForProcess(vpnNetId);
3208
3209 // Expect fallthrough to default network
3210 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3211 // Expect the mark contains all the bit because we've selected network.
3212 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3213
3214 // Expect connect success, packet will be sent to vpnFd.
3215 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3216 // Expect the mark contains all the bit because we've selected network.
3217 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3218
3219 // Explicitly select fallthrough network
3220 setNetworkForProcess(fallthroughNetId);
3221
3222 // The mark is set to fallthrough network because we've selected it.
3223 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3224 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3225
3226 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3227 if (bypassable) {
3228 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3229 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3230 } else {
3231 // If not, no permission to bypass vpn.
3232 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3233 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3234 }
3235}
3236
3237} // namespace
3238
3239TEST_F(BinderTest, SecureVPNFallthrough) {
3240 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3241 // Get current default network NetId
3242 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3243 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3244}
3245
3246TEST_F(BinderTest, BypassableVPNFallthrough) {
3247 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3248 // Get current default network NetId
3249 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3250 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003251}
Chiachang Wang00fc62f2019-12-04 20:38:26 +08003252
3253namespace {
3254
3255int32_t createIpv6SocketAndCheckMark(int type, const in6_addr& dstAddr) {
3256 const sockaddr_in6 dst6 = {
3257 .sin6_family = AF_INET6,
3258 .sin6_port = 1234,
3259 .sin6_addr = dstAddr,
3260 };
3261 // create non-blocking socket.
3262 int sockFd = socket(AF_INET6, type | SOCK_NONBLOCK, 0);
3263 EXPECT_NE(-1, sockFd);
3264 EXPECT_EQ((type == SOCK_STREAM) ? -1 : 0, connect(sockFd, (sockaddr*)&dst6, sizeof(dst6)));
3265
3266 // Get socket fwmark.
3267 Fwmark fwmark;
3268 socklen_t fwmarkLen = sizeof(fwmark.intValue);
3269 EXPECT_EQ(0, getsockopt(sockFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen));
3270 EXPECT_EQ(0, close(sockFd));
3271 return fwmark.intValue;
3272}
3273
3274} // namespace
3275
3276TEST_F(BinderTest, GetFwmarkForNetwork) {
3277 in6_addr v6Addr = {
3278 {// 2001:db8:cafe::8888
3279 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}};
3280 // Add test physical network 1 and set as default network.
3281 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3282 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3283 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "2001:db8::/32", "").isOk());
3284 EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk());
3285 // Add test physical network 2
3286 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
3287 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
3288
3289 // Get fwmark for network 1.
3290 MarkMaskParcel maskMarkNet1;
3291 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID1, &maskMarkNet1).isOk());
3292
3293 uint32_t fwmarkTcp = createIpv6SocketAndCheckMark(SOCK_STREAM, v6Addr);
3294 uint32_t fwmarkUdp = createIpv6SocketAndCheckMark(SOCK_DGRAM, v6Addr);
3295 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkTcp & maskMarkNet1.mask));
3296 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkUdp & maskMarkNet1.mask));
3297
3298 // Get fwmark for network 2.
3299 MarkMaskParcel maskMarkNet2;
3300 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID2, &maskMarkNet2).isOk());
3301 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkTcp & maskMarkNet2.mask));
3302 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkUdp & maskMarkNet2.mask));
3303
3304 // Remove test physical network.
3305 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
3306 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3307}