blob: 0050066aa80c3839ef4d5e6311f0b174d768d18a [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>
Alistair Delvaefb7ec32019-12-19 17:47:03 -080041#include <sys/utsname.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090042
Luke Huang531f5d32018-08-03 15:19:05 +080043#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090044#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090045#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090046#include <android-base/strings.h>
Chiachang Wang00fc62f2019-12-04 20:38:26 +080047#include <android/multinetwork.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080048#include <binder/IPCThreadState.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080049#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070050#include <bpf/BpfUtils.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080051#include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
52#include <com/android/internal/net/IOemNetd.h>
Robin Leeb8087362016-03-30 18:43:08 +010053#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090054#include <gtest/gtest.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080055#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090056#include <netutils/ifc.h>
Luke Huangd2861982019-05-17 19:47:28 +080057#include "Fwmark.h"
Nathan Harold21299f72018-03-16 20:13:03 -070058#include "InterfaceController.h"
Luke Huangd2861982019-05-17 19:47:28 +080059#include "NetdClient.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090060#include "NetdConstants.h"
Chiachang Wang00fc62f2019-12-04 20:38:26 +080061#include "NetworkController.h"
Luke Huang528af602018-08-29 19:06:05 +080062#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070063#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090064#include "android/net/INetd.h"
65#include "binder/IServiceManager.h"
Luke Huang25599322019-06-14 00:34:05 +080066#include "netdutils/InternetAddresses.h"
Mike Yue7e332f2019-03-13 17:15:48 +080067#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070068#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080069#include "netid_client.h" // NETID_UNSET
Lorenzo Colitti758bccc2019-06-26 22:12:35 +090070#include "test_utils.h"
Mike Yu5ae61542018-10-19 22:11:43 +080071#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090072
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090073#define IP6TABLES_PATH "/system/bin/ip6tables"
74#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090075#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080076#define RAW_TABLE "raw"
77#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080078#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090079#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090080
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090081namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090082
83using android::IBinder;
84using android::IServiceManager;
85using android::sp;
86using android::String16;
87using android::String8;
88using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080089using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090090using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090091using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080092using android::base::Trim;
Bernie Innocentid26a04a2019-10-30 17:15:15 +090093using android::base::unique_fd;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090094using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080095using android::net::InterfaceConfigurationParcel;
96using android::net::InterfaceController;
Chiachang Wang00fc62f2019-12-04 20:38:26 +080097using android::net::MarkMaskParcel;
Luke Huangcaebcbb2018-09-27 20:37:14 +080098using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090099using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +0900100using android::net::UidRangeParcel;
Luke Huang25599322019-06-14 00:34:05 +0800101using android::netdutils::ScopedAddrinfo;
Luke Huangf7782042018-08-08 13:13:04 +0800102using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +0800103using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +0100104
105static const char* IP_RULE_V4 = "-4";
106static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900107static const int TEST_NETID1 = 65501;
108static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800109
110// Use maximum reserved appId for applications to avoid conflict with existing
111// uids.
112static const int TEST_UID1 = 99999;
113static const int TEST_UID2 = 99998;
114
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900115constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116
Benedict Wongb2daefb2017-12-06 22:05:46 -0800117static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
118static const std::string ESP_ALLOW_RULE("esp");
119
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900120class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900121 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900122 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900123 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900124 sp<IBinder> binder = sm->getService(String16("netd"));
125 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900126 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900127 }
128 }
129
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900130 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900131 ASSERT_NE(nullptr, mNetd.get());
132 }
133
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900134 void TearDown() override {
135 mNetd->networkDestroy(TEST_NETID1);
136 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800137 setNetworkForProcess(NETID_UNSET);
138 // Restore default network
139 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900140 }
141
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900142 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700143
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900144 // Static because setting up the tun interface takes about 40ms.
145 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900146 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900147 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900148 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900149 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900150 }
151
152 static void TearDownTestCase() {
153 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900154 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900155 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900156 }
157
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900158 static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
159 unique_fd* acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900160
Luke Huangd2861982019-05-17 19:47:28 +0800161 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
162 int fallthroughNetId = TEST_NETID1);
163
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900164 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800165 // Use -1 to represent that default network was not modified because
166 // real netId must be an unsigned value.
167 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900168 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900169 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900170 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900171};
172
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900173TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900174TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900175
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900176class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900177 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700178 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900180 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900181 }
182
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900183 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900184 std::string mName;
185};
186
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900187TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900188 TimedOperation t("isAlive RPC");
189 bool isAlive = false;
190 mNetd->isAlive(&isAlive);
191 ASSERT_TRUE(isAlive);
192}
193
Benedict Wongb2daefb2017-12-06 22:05:46 -0800194static bool iptablesNoSocketAllowRuleExists(const char *chainName){
195 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
196 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
197}
198
199static bool iptablesEspAllowRuleExists(const char *chainName){
200 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
201 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
202}
203
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900204TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700205 SKIP_IF_BPF_SUPPORTED;
206
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900207 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
208 const int kNumUids = 500;
209 std::vector<int32_t> noUids(0);
210 std::vector<int32_t> uids(kNumUids);
211 for (int i = 0; i < kNumUids; i++) {
212 uids[i] = randomUid();
213 }
214
215 bool ret;
216 {
217 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900218 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900219 }
220 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800221 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
222 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
223 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
224 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900225 {
226 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900227 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900228 }
229 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900230 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
231 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900232
233 {
234 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900235 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900236 }
237 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900238 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
239 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800240 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
241 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900242
243 {
244 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900245 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900246 }
247 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900248 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
249 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900250
251 // Check that the call fails if iptables returns an error.
252 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900253 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900254 EXPECT_EQ(false, ret);
255}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900256
Benedict Wong319f17e2018-05-15 17:06:44 -0700257TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700258 const struct TestData {
259 const std::string family;
260 const std::string deviceName;
261 const std::string localAddress;
262 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800263 int32_t iKey;
264 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700265 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800266 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700267 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
268 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
269 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800270 };
271
Sehee Park8659b8d2018-11-16 10:53:16 +0900272 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700273 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800274
275 binder::Status status;
276
Benedict Wong319f17e2018-05-15 17:06:44 -0700277 // Create Tunnel Interface.
278 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700279 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800280 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
281
Benedict Wonga450e722018-05-07 10:29:02 -0700282 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900283 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700284
Benedict Wong319f17e2018-05-15 17:06:44 -0700285 // Update Tunnel Interface.
286 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700287 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800288 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
289
Benedict Wong319f17e2018-05-15 17:06:44 -0700290 // Remove Tunnel Interface.
291 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800292 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700293
294 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900295 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800296 }
297}
298
Benedict Wong1cb73df2018-12-03 00:54:14 -0800299TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900300 unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Benedict Wong1cb73df2018-12-03 00:54:14 -0800301 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
302
303 int sockOptVal = UDP_ENCAP_ESPINUDP;
304 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
305
306 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
307 EXPECT_TRUE(res.isOk());
308
309 struct stat info;
310 EXPECT_EQ(0, fstat(sockFd.get(), &info));
311 EXPECT_EQ(1001, (int) info.st_uid);
312}
313
Nathan Harold2deff322018-05-10 14:03:48 -0700314// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
315// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
316#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900317
318using android::net::XfrmController;
319
Benedict Wonga04ffa72018-05-09 21:42:42 -0700320static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
321 static_cast<int>(android::net::XfrmDirection::OUT)};
322static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
323
Nathan Harold21299f72018-03-16 20:13:03 -0700324#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
325 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900326bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900327 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700328 SCOPED_TRACE(status);
329 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
330
331 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700332 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700333 SCOPED_TRACE(status);
334 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
335
336 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700337 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
338 0xD00D, 0xE00D, false)
339 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700340}
341
Benedict Wonga04ffa72018-05-09 21:42:42 -0700342TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900343 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700344
345 // Repeat to ensure cleanup and recreation works correctly
346 for (int i = 0; i < 2; i++) {
347 for (int direction : XFRM_DIRECTIONS) {
348 for (int addrFamily : ADDRESS_FAMILIES) {
349 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700350 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700351 EXPECT_TRUE(status.isOk())
352 << " family: " << addrFamily << " direction: " << direction;
353 }
354 }
355
356 // Cleanup
357 for (int direction : XFRM_DIRECTIONS) {
358 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700359 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700360 EXPECT_TRUE(status.isOk());
361 }
362 }
363 }
364}
365
366TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
367 binder::Status status;
368
369 // Repeat to ensure cleanup and recreation works correctly
370 for (int i = 0; i < 2; i++) {
371 for (int direction : XFRM_DIRECTIONS) {
372 for (int addrFamily : ADDRESS_FAMILIES) {
373 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700374 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700375 EXPECT_TRUE(status.isOk())
376 << " family: " << addrFamily << " direction: " << direction;
377 }
378 }
379
380 // Cleanup
381 for (int direction : XFRM_DIRECTIONS) {
382 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700383 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700384 EXPECT_TRUE(status.isOk());
385 }
386 }
387 }
388}
389
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900390TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900391 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700392 status = XfrmController::Init();
393 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700394
395 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
396 // feature.
397 if (status.code() == EOPNOTSUPP) return;
398
Nathan Harold21299f72018-03-16 20:13:03 -0700399 ASSERT_TRUE(status.ok());
400
401 int32_t spi = 0;
402
403 ASSERT_TRUE(allocateIpSecResources(true, &spi));
404 ASSERT_TRUE(allocateIpSecResources(false, &spi));
405
406 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700407 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700408 ASSERT_TRUE(allocateIpSecResources(true, &spi));
409
410 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700411 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700412 SCOPED_TRACE(status);
413 ASSERT_TRUE(status.ok());
414
Benedict Wonga450e722018-05-07 10:29:02 -0700415 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700416 SCOPED_TRACE(status);
417 ASSERT_TRUE(status.ok());
418
419 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700420 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700421}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900422
423#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700424
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900425static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900426 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900427
428 // Output looks like this:
429 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900430 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900431 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900432 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900433 //
434 // or:
435 //
436 // Chain bw_data_saver (1 references)
437 // target prot opt source destination
438 // ... possibly connectivity critical packet rules here ...
439 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900440
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900441 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900442
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900443 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
444 // Data saver disabled.
445 return 0;
446 }
447
448 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
449
450 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
451 // Data saver enabled.
452 return 1;
453 }
454
455 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900456}
457
458bool enableDataSaver(sp<INetd>& netd, bool enable) {
459 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
460 bool ret;
461 netd->bandwidthEnableDataSaver(enable, &ret);
462 return ret;
463}
464
465int getDataSaverState() {
466 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
467 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
468 EXPECT_EQ(enabled4, enabled6);
469 EXPECT_NE(-1, enabled4);
470 EXPECT_NE(-1, enabled6);
471 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
472 return -1;
473 }
474 return enabled6;
475}
476
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900477TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900478 const int wasEnabled = getDataSaverState();
479 ASSERT_NE(-1, wasEnabled);
480
481 if (wasEnabled) {
482 ASSERT_TRUE(enableDataSaver(mNetd, false));
483 EXPECT_EQ(0, getDataSaverState());
484 }
485
486 ASSERT_TRUE(enableDataSaver(mNetd, false));
487 EXPECT_EQ(0, getDataSaverState());
488
489 ASSERT_TRUE(enableDataSaver(mNetd, true));
490 EXPECT_EQ(1, getDataSaverState());
491
492 ASSERT_TRUE(enableDataSaver(mNetd, true));
493 EXPECT_EQ(1, getDataSaverState());
494
495 if (!wasEnabled) {
496 ASSERT_TRUE(enableDataSaver(mNetd, false));
497 EXPECT_EQ(0, getDataSaverState());
498 }
499}
Robin Leeb8087362016-03-30 18:43:08 +0100500
Luke Huang94658ac2018-10-18 19:35:12 +0900501static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
502 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100503 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100504 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100505 std::vector<std::string> rules = listIpRules(ipVersion);
506
507 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900508 std::string suffix =
509 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900510 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800511 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100512 return true;
513 }
514 }
515 return false;
516}
517
Luke Huang94658ac2018-10-18 19:35:12 +0900518static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
519 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100520 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
521 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
522 EXPECT_EQ(existsIp4, existsIp6);
523 return existsIp4;
524}
525
Luke Huang94658ac2018-10-18 19:35:12 +0900526namespace {
527
528UidRangeParcel makeUidRangeParcel(int start, int stop) {
529 UidRangeParcel res;
530 res.start = start;
531 res.stop = stop;
532
533 return res;
534}
535
536} // namespace
537
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900538TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800539 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
540 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
541 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900542 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
543 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900544
545 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
546 EXPECT_EQ(EBUSY,
547 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
548
549 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
550 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
551 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800552 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900553}
554
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900555TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900556 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
557
cken67cd14c2018-12-05 17:26:59 +0900558 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
559 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900560 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
561
Luke Huang94658ac2018-10-18 19:35:12 +0900562 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
563 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
564 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900565 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
566
567 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
568
569 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
570 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
571 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
572 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
573
574 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
575 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
576 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
577 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
578
579 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
580}
581
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900582TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100583 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100584
Luke Huang94658ac2018-10-18 19:35:12 +0900585 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
586 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800587 // Make sure no rules existed before calling commands.
588 for (auto const& range : uidRanges) {
589 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
590 }
Robin Leeb8087362016-03-30 18:43:08 +0100591 // Create two valid rules.
592 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100593 for (auto const& range : uidRanges) {
594 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
595 }
596
597 // Remove the rules.
598 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100599 for (auto const& range : uidRanges) {
600 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
601 }
602
603 // Fail to remove the rules a second time after they are already deleted.
604 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
605 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
606 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100607}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900608
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900609// Create a socket pair that isLoopbackSocket won't think is local.
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900610void BinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
611 unique_fd* acceptedSocket) {
612 serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900613 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900614 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
615
616 socklen_t addrlen = sizeof(server6);
617 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
618 ASSERT_EQ(0, listen(*serverSocket, 10));
619
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900620 clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900621 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900622 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900623 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
624 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
625
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900626 acceptedSocket->reset(
627 accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900628 ASSERT_NE(-1, *acceptedSocket);
629
630 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
631}
632
633void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
634 char buf[4096];
635 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
636 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
637 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
638}
639
640void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
641 // Check that the client socket was closed with ECONNABORTED.
642 int ret = write(clientSocket, "foo", sizeof("foo"));
643 int err = errno;
644 EXPECT_EQ(-1, ret);
645 EXPECT_EQ(ECONNABORTED, err);
646
647 // Check that it sent a RST to the server.
648 ret = write(acceptedSocket, "foo", sizeof("foo"));
649 err = errno;
650 EXPECT_EQ(-1, ret);
651 EXPECT_EQ(ECONNRESET, err);
652}
653
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900654TEST_F(BinderTest, SocketDestroy) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900655 unique_fd clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900656 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900657
658 // Pick a random UID in the system UID range.
659 constexpr int baseUid = AID_APP - 2000;
660 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
661 int uid = baseUid + 500 + arc4random_uniform(1000);
662 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
663
664 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900665 std::vector<UidRangeParcel> uidRanges = {
666 makeUidRangeParcel(baseUid + 42, baseUid + 449),
667 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
668 makeUidRangeParcel(baseUid + 498, uid - 1),
669 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900670 };
671 // A skip list that doesn't contain UID.
672 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
673
674 // Close sockets. Our test socket should be intact.
675 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
676 checkSocketpairOpen(clientSocket, acceptedSocket);
677
678 // UID ranges that do contain uid.
679 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900680 makeUidRangeParcel(baseUid + 42, baseUid + 449),
681 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
682 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900683 };
684 // Add uid to the skip list.
685 skipUids.push_back(uid);
686
687 // Close sockets. Our test socket should still be intact because it's in the skip list.
688 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
689 checkSocketpairOpen(clientSocket, acceptedSocket);
690
691 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
692 skipUids.resize(skipUids.size() - 1);
693 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
694 checkSocketpairClosed(clientSocket, acceptedSocket);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900695}
Erik Klinecc4f2732016-08-03 11:24:27 +0900696
697namespace {
698
699int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
700 if (buf == nullptr) return -1;
701
702 int prefixLength = 0;
703 bool endOfContiguousBits = false;
704 for (unsigned int i = 0; i < buflen; i++) {
705 const uint8_t value = buf[i];
706
707 // Bad bit sequence: check for a contiguous set of bits from the high
708 // end by verifying that the inverted value + 1 is a power of 2
709 // (power of 2 iff. (v & (v - 1)) == 0).
710 const uint8_t inverse = ~value + 1;
711 if ((inverse & (inverse - 1)) != 0) return -1;
712
713 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
714
715 // Bogus netmask.
716 if (endOfContiguousBits && value != 0) return -1;
717
718 if (value != 0xff) endOfContiguousBits = true;
719 }
720
721 return prefixLength;
722}
723
724template<typename T>
725int netmaskToPrefixLength(const T *p) {
726 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
727}
728
729
730static bool interfaceHasAddress(
731 const std::string &ifname, const char *addrString, int prefixLength) {
732 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900733
734 const struct addrinfo hints = {
735 .ai_flags = AI_NUMERICHOST,
736 .ai_family = AF_UNSPEC,
737 .ai_socktype = SOCK_DGRAM,
738 };
739 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
740 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
741 return false;
742 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900743 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900744
745 struct ifaddrs *ifaddrsList = nullptr;
746 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
747
748 if (getifaddrs(&ifaddrsList) != 0) {
749 return false;
750 }
751
752 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
753 if (std::string(addr->ifa_name) != ifname ||
754 addr->ifa_addr == nullptr ||
755 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
756 continue;
757 }
758
759 switch (addr->ifa_addr->sa_family) {
760 case AF_INET: {
761 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
762 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
763 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
764 continue;
765 }
766
767 if (prefixLength < 0) return true; // not checking prefix lengths
768
769 if (addr->ifa_netmask == nullptr) return false;
770 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
771 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
772 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
773 }
774 case AF_INET6: {
775 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
776 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
777 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
778 continue;
779 }
780
781 if (prefixLength < 0) return true; // not checking prefix lengths
782
783 if (addr->ifa_netmask == nullptr) return false;
784 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
785 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
786 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
787 }
788 default:
789 // Cannot happen because we have already screened for matching
790 // address families at the top of each iteration.
791 continue;
792 }
793 }
794
795 return false;
796}
797
798} // namespace
799
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900800TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900801 static const struct TestData {
802 const char *addrString;
803 const int prefixLength;
Lorenzo Colitti01118982019-12-02 13:19:44 +0900804 const int expectAddResult;
805 const int expectRemoveResult;
Erik Klinecc4f2732016-08-03 11:24:27 +0900806 } kTestData[] = {
Lorenzo Colitti01118982019-12-02 13:19:44 +0900807 {"192.0.2.1", 24, 0, 0},
808 {"192.0.2.2", 25, 0, 0},
809 {"192.0.2.3", 32, 0, 0},
810 {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL},
811 {"192.not.an.ip", 24, EINVAL, EINVAL},
812 {"2001:db8::1", 64, 0, 0},
813 {"2001:db8::2", 65, 0, 0},
814 {"2001:db8::3", 128, 0, 0},
815 {"2001:db8::4", 129, EINVAL, EINVAL},
816 {"foo:bar::bad", 64, EINVAL, EINVAL},
817 {"2001:db8::1/64", 64, EINVAL, EINVAL},
Erik Klinecc4f2732016-08-03 11:24:27 +0900818 };
819
Sehee Park8659b8d2018-11-16 10:53:16 +0900820 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900821 const auto &td = kTestData[i];
822
Lorenzo Colitti01118982019-12-02 13:19:44 +0900823 SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength));
824
Erik Klinecc4f2732016-08-03 11:24:27 +0900825 // [1.a] Add the address.
826 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900827 sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900828 if (td.expectAddResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900829 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
830 } else {
831 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900832 ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900833 }
834
835 // [1.b] Verify the addition meets the expectation.
Lorenzo Colitti01118982019-12-02 13:19:44 +0900836 if (td.expectAddResult == 0) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900837 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900838 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900839 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900840 }
841
842 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900843 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900844 if (td.expectRemoveResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900845 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
846 } else {
847 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900848 ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900849 }
850
851 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900852 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900853 }
Lorenzo Colitti9ae17712019-12-02 17:28:49 +0900854
855 // Check that netlink errors are returned correctly.
856 // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled,
857 // which returns EACCES.
858 TunInterface tun;
859 ASSERT_EQ(0, tun.init());
860 binder::Status status =
861 mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1");
862 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
863 status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64);
864 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
865 EXPECT_EQ(EACCES, status.serviceSpecificErrorCode());
866 tun.destroy();
Erik Klinecc4f2732016-08-03 11:24:27 +0900867}
Erik Kline55b06f82016-07-04 09:57:18 +0900868
Erik Kline38e51f12018-09-06 20:14:44 +0900869TEST_F(BinderTest, GetProcSysNet) {
870 const char LOOPBACK[] = "lo";
871 static const struct {
872 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900873 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900874 const char* ifname;
875 const char* parameter;
876 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900877 const int expectedReturnCode;
878 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900879 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
880 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
881 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
882 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
883 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
884 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
885 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900886 };
887
Sehee Park8659b8d2018-11-16 10:53:16 +0900888 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900889 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900890
Erik Kline38e51f12018-09-06 20:14:44 +0900891 std::string value;
892 const binder::Status status =
893 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
894
895 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900896 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900897 EXPECT_EQ(0, status.exceptionCode());
898 EXPECT_EQ(0, status.serviceSpecificErrorCode());
899 EXPECT_EQ(td.expectedValue, value);
900 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900901 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900902 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
903 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
904 }
905 }
906}
907
908TEST_F(BinderTest, SetProcSysNet) {
909 static const struct {
910 const int ipversion;
911 const int which;
912 const char* ifname;
913 const char* parameter;
914 const char* value;
915 const int expectedReturnCode;
916 } kTestData[] = {
917 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
918 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
919 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
920 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
921 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
922 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
923 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
924 };
925
Sehee Park8659b8d2018-11-16 10:53:16 +0900926 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900927 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900928 const binder::Status status =
929 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900930
931 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900932 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900933 EXPECT_EQ(0, status.exceptionCode());
934 EXPECT_EQ(0, status.serviceSpecificErrorCode());
935 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900936 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900937 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
938 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
939 }
940 }
941}
Ben Schwartze7601812017-04-28 16:38:29 -0400942
Erik Kline38e51f12018-09-06 20:14:44 +0900943TEST_F(BinderTest, GetSetProcSysNet) {
944 const int ipversion = INetd::IPV6;
945 const int category = INetd::NEIGH;
946 const std::string& tun = sTun.name();
947 const std::string parameter("ucast_solicit");
948
949 std::string value{};
950 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700951 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900952 const int ival = std::stoi(value);
953 EXPECT_GT(ival, 0);
954 // Try doubling the parameter value (always best!).
955 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
956 .isOk());
957 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
958 EXPECT_EQ(2 * ival, std::stoi(value));
959 // Try resetting the parameter.
960 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
961 .isOk());
962 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
963 EXPECT_EQ(ival, std::stoi(value));
964}
965
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900966namespace {
967
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900968void expectNoTestCounterRules() {
969 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
970 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
971 std::string allRules = Join(runCommand(command), "\n");
972 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
973 }
974}
975
Bernie Innocentif6918262018-06-11 17:37:35 +0900976void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
977 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900978 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
979 path, if1.c_str(), if2.c_str(), pkt, byte));
980}
981
Bernie Innocentif6918262018-06-11 17:37:35 +0900982void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900983 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
984 path, if1.c_str(), if2.c_str()));
985 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
986 path, if2.c_str(), if1.c_str()));
987}
988
Luke Huangcaebcbb2018-09-27 20:37:14 +0800989std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
990 const std::string& iface) {
991 for (auto& stats : statsVec) {
992 if (stats.iface == iface) {
993 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
994 }
995 }
996 return {};
997}
998
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900999} // namespace
1000
1001TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001002 expectNoTestCounterRules();
1003
1004 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1005 // disabling tethering. We don't check the return value because these commands will fail if
1006 // tethering is already enabled.
1007 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1008 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1009
1010 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1011 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1012 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001013
1014 // Ensure we won't use the same interface name, otherwise the test will fail.
1015 u_int32_t rNumber = arc4random_uniform(10000);
1016 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1017 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001018
1019 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1020 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1021 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1022 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1023 // RX is from external to internal, and TX is from internal to external.
1024 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1025 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1026
1027 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1028 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1029
1030 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1031 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1032
1033 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1034 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1035 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1036
Luke Huangcaebcbb2018-09-27 20:37:14 +08001037 std::vector<TetherStatsParcel> statsVec;
1038 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001039 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1040
Luke Huangcaebcbb2018-09-27 20:37:14 +08001041 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001042
Luke Huangcaebcbb2018-09-27 20:37:14 +08001043 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001044
1045 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1046 delTetherCounterValues(path, intIface1, extIface1);
1047 delTetherCounterValues(path, intIface2, extIface2);
1048 if (path == IP6TABLES_PATH) {
1049 delTetherCounterValues(path, intIface3, extIface2);
1050 }
1051 }
1052
1053 expectNoTestCounterRules();
1054}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001055
Luke Huang0051a622018-07-23 20:30:16 +08001056namespace {
1057
Luke Huanga5211072018-08-01 23:36:29 +08001058constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1059constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001060
1061static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1062 const char* chainName) {
1063 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1064 return runCommand(command);
1065}
1066
Luke Huang19b49c52018-10-22 12:12:05 +09001067// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001068bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001069 const std::string& expectedInterface,
1070 const std::string& expectedRule, const char* table) {
1071 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1072 for (const auto& rule : rules) {
1073 if (rule.find(expectedInterface) != std::string::npos) {
1074 if (rule.find(expectedRule) != std::string::npos) {
1075 return true;
1076 }
1077 }
1078 }
1079 return false;
1080}
1081
1082void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001083 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001084 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001085 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001086 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001087 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1088 IdletimerRule, RAW_TABLE));
1089 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001090 ifname, IdletimerRule, MANGLE_TABLE));
1091 }
1092}
1093
1094void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001095 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001096 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001097 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001098 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001099 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1100 IdletimerRule, RAW_TABLE));
1101 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001102 ifname, IdletimerRule, MANGLE_TABLE));
1103 }
1104}
1105
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001106} // namespace
1107
1108TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001109 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1110 // rule in the table. Because we only check the result after calling remove function. We might
1111 // check the actual rule which is removed by our function (maybe compare the results between
1112 // calling function before and after)
1113 binder::Status status;
1114 const struct TestData {
1115 const std::string ifname;
1116 int32_t timeout;
1117 const std::string classLabel;
1118 } idleTestData[] = {
1119 {"wlan0", 1234, "happyday"},
1120 {"rmnet_data0", 4567, "friday"},
1121 };
1122 for (const auto& td : idleTestData) {
1123 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1124 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1125 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1126
1127 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1128 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1129 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1130 }
1131}
1132
Luke Huanga67dd562018-07-17 19:58:25 +08001133namespace {
1134
1135constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1136constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1137
1138void expectStrictSetUidAccept(const int uid) {
1139 std::string uidRule = StringPrintf("owner UID match %u", uid);
1140 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1141 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001142 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1143 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001144 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1145 }
1146}
1147
1148void expectStrictSetUidLog(const int uid) {
1149 static const char logRule[] = "st_penalty_log all";
1150 std::string uidRule = StringPrintf("owner UID match %u", uid);
1151 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1152 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001153 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1154 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001155 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1156 }
1157}
1158
1159void expectStrictSetUidReject(const int uid) {
1160 static const char rejectRule[] = "st_penalty_reject all";
1161 std::string uidRule = StringPrintf("owner UID match %u", uid);
1162 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1163 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001164 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1165 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001166 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1167 }
1168}
1169
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001170} // namespace
1171
1172TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001173 binder::Status status;
1174 int32_t uid = randomUid();
1175
1176 // setUidCleartextPenalty Policy:Log with randomUid
1177 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1178 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1179 expectStrictSetUidLog(uid);
1180
1181 // setUidCleartextPenalty Policy:Accept with randomUid
1182 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1183 expectStrictSetUidAccept(uid);
1184
1185 // setUidCleartextPenalty Policy:Reject with randomUid
1186 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1187 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1188 expectStrictSetUidReject(uid);
1189
1190 // setUidCleartextPenalty Policy:Accept with randomUid
1191 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1192 expectStrictSetUidAccept(uid);
1193
1194 // test wrong policy
1195 int32_t wrongPolicy = -123;
1196 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1197 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1198}
1199
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001200namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001201
Luke Huangd1675922019-03-11 17:29:27 +08001202std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001203 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001204 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001205 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1206 // ...
1207 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1208
Luke Huangd1675922019-03-11 17:29:27 +08001209 // (dnsmasq)
1210 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1211
1212 if (maxTries == 0) return {};
1213
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001214 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001215 std::vector<std::string> result;
1216 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001217 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001218 if (result.size() || ++run > maxTries) {
1219 break;
1220 }
1221
Luke Huang728cf4c2019-03-14 19:43:02 +08001222 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001223 }
1224 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001225}
1226
Luke Huangd1675922019-03-11 17:29:27 +08001227void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001228 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001229}
1230
Luke Huang728cf4c2019-03-14 19:43:02 +08001231void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001232 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001233}
1234
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001235} // namespace
1236
1237TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001238 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001239
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001240 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1241 std::string clatAddress;
1242 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001243
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001244 // Can't start clatd on an interface that's not part of any network...
1245 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1246 EXPECT_FALSE(status.isOk());
1247 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1248
1249 // ... so create a test physical network and add our tun to it.
1250 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1251 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1252
1253 // Prefix must be 96 bits long.
1254 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1255 EXPECT_FALSE(status.isOk());
1256 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1257
1258 // Can't start clatd unless there's a default route...
1259 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1260 EXPECT_FALSE(status.isOk());
1261 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1262
1263 // so add a default route.
1264 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1265
1266 // Can't start clatd unless there's a global address...
1267 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1268 EXPECT_FALSE(status.isOk());
1269 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1270
1271 // ... so add a global address.
1272 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001273 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001274
1275 // Now expect clatd to start successfully.
1276 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1277 EXPECT_TRUE(status.isOk());
1278 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1279
1280 // Starting it again returns EBUSY.
1281 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1282 EXPECT_FALSE(status.isOk());
1283 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1284
Luke Huangd1675922019-03-11 17:29:27 +08001285 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001286
1287 // Expect clatd to stop successfully.
1288 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001289 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001290 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001291
1292 // Stopping a clatd that doesn't exist returns ENODEV.
1293 status = mNetd->clatdStop(sTun.name());
1294 EXPECT_FALSE(status.isOk());
1295 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001296 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001297
1298 // Clean up.
1299 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1300 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1301 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001302}
Luke Huang457d4702018-08-16 15:39:15 +08001303
1304namespace {
1305
1306bool getIpfwdV4Enable() {
1307 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1308 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1309 EXPECT_TRUE(!result.empty());
1310 int v4Enable = std::stoi(result[0]);
1311 return v4Enable;
1312}
1313
1314bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001315 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001316 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1317 EXPECT_TRUE(!result.empty());
1318 int v6Enable = std::stoi(result[0]);
1319 return v6Enable;
1320}
1321
1322void expectIpfwdEnable(bool enable) {
1323 int enableIPv4 = getIpfwdV4Enable();
1324 int enableIPv6 = getIpfwdV6Enable();
1325 EXPECT_EQ(enable, enableIPv4);
1326 EXPECT_EQ(enable, enableIPv6);
1327}
1328
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001329bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001330 std::vector<std::string> rules = listIpRules(ipVersion);
1331 for (const auto& rule : rules) {
1332 if (rule.find(ipfwdRule) != std::string::npos) {
1333 return true;
1334 }
1335 }
1336 return false;
1337}
1338
1339void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1340 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1341
1342 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1343 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1344 }
1345}
1346
1347void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1348 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1349
1350 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1351 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1352 }
1353}
1354
1355} // namespace
1356
1357TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Alistair Delvaefb7ec32019-12-19 17:47:03 -08001358 // Disable test on 5.x kernels.
1359 utsname u;
1360 uname(&u);
1361 if (u.release[0] == '5') return;
1362
Luke Huang728cf4c2019-03-14 19:43:02 +08001363 // Get ipfwd requester list from Netd
1364 std::vector<std::string> requesterList;
1365 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001366 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001367
1368 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001369 if (requesterList.size() == 0) {
1370 // No requester in Netd, ipfwd should be disabled
1371 // So add one test requester and verify
1372 status = mNetd->ipfwdEnableForwarding("TestRequester");
1373 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001374
Luke Huang728cf4c2019-03-14 19:43:02 +08001375 expectIpfwdEnable(true);
1376 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1377 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1378 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001379
Luke Huang728cf4c2019-03-14 19:43:02 +08001380 // Remove test one, verify again
1381 status = mNetd->ipfwdDisableForwarding("TestRequester");
1382 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1383
1384 expectIpfwdEnable(false);
1385 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1386 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1387 EXPECT_FALSE(ipfwdEnabled);
1388 } else {
1389 // Disable all requesters
1390 for (const auto& requester : requesterList) {
1391 status = mNetd->ipfwdDisableForwarding(requester);
1392 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1393 }
1394
1395 // After disable all requester, ipfwd should be disabled
1396 expectIpfwdEnable(false);
1397 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1398 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1399 EXPECT_FALSE(ipfwdEnabled);
1400
1401 // Enable them back
1402 for (const auto& requester : requesterList) {
1403 status = mNetd->ipfwdEnableForwarding(requester);
1404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1405 }
1406
1407 // ipfwd should be enabled
1408 expectIpfwdEnable(true);
1409 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1410 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1411 EXPECT_TRUE(ipfwdEnabled);
1412 }
Luke Huang457d4702018-08-16 15:39:15 +08001413}
1414
1415TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001416 // Add test physical network
1417 EXPECT_TRUE(
1418 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1419 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1420 EXPECT_TRUE(
1421 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1422 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001423
Luke Huangd1827b82019-02-15 15:03:27 +08001424 binder::Status status =
1425 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1426 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1427 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001428
Luke Huangd1827b82019-02-15 15:03:27 +08001429 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1430 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1431 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001432}
Luke Huang531f5d32018-08-03 15:19:05 +08001433
1434namespace {
1435
1436constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1437constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1438constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1439constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1440constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001441constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001442
Luke Huang19b49c52018-10-22 12:12:05 +09001443// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1444// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001445bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1446 const char* chainName, const std::string& expectedTargetA,
1447 const std::string& expectedTargetB) {
1448 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1449 int matchCount = 0;
1450
1451 for (const auto& rule : rules) {
1452 if (rule.find(expectedTargetA) != std::string::npos) {
1453 if (rule.find(expectedTargetB) != std::string::npos) {
1454 matchCount++;
1455 }
1456 }
1457 }
1458 return matchCount == expectedCount;
1459}
1460
1461void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1462 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1463 std::string result = "";
1464
1465 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001466 // Quota value might be decreased while matching packets
1467 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001468}
1469
1470void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1471 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1472 std::string quotaRule = StringPrintf("quota %s", ifname);
1473
1474 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1475 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1476 BANDWIDTH_COSTLY_IF));
1477 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1478 BANDWIDTH_COSTLY_IF));
1479 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1480 BANDWIDTH_COSTLY_IF));
1481 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1482 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1483 }
1484 expectXtQuotaValueEqual(ifname, quotaBytes);
1485}
1486
1487void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1488 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1489 std::string quotaRule = StringPrintf("quota %s", ifname);
1490
1491 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1492 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1493 BANDWIDTH_COSTLY_IF));
1494 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1495 BANDWIDTH_COSTLY_IF));
1496 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1497 BANDWIDTH_COSTLY_IF));
1498 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1499 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1500 }
1501}
1502
1503void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1504 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1505 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1506 std::string alertName = StringPrintf("%sAlert", ifname);
1507
1508 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1509 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1510 }
1511 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1512}
1513
1514void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1515 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1516 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1517
1518 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1519 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1520 }
1521}
1522
1523void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1524 static const char globalAlertRule[] = "quota globalAlert";
1525 static const char globalAlertName[] = "globalAlert";
1526
1527 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001528 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001529 }
1530 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1531}
1532
1533void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1534 std::string uidRule = StringPrintf("owner UID match %u", uid);
1535
1536 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1537 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1538 }
1539}
1540
1541void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1542 std::string uidRule = StringPrintf("owner UID match %u", uid);
1543
1544 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1545 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1546 }
1547}
1548
1549} // namespace
1550
1551TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1552 long testQuotaBytes = 5550;
1553
1554 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001555 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001556 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1557
1558 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1559 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1560 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1561
1562 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1563 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1564 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1565
1566 // Remove test physical network
1567 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1568}
1569
1570TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1571 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001572 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001573 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001574 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001575 // Need to have a prior interface quota set to set an alert
1576 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1577 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1578 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1579 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1580
1581 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1582 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1583 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1584
1585 // Remove interface quota
1586 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1587 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1588 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1589
1590 // Remove test physical network
1591 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1592}
1593
1594TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001595 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001596
1597 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1598 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1599 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1600
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001601 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001602 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1603 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1604 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1605}
1606
1607TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1608 SKIP_IF_BPF_SUPPORTED;
1609
1610 int32_t uid = randomUid();
1611 static const char targetReject[] = "REJECT";
1612 static const char targetReturn[] = "RETURN";
1613
1614 // add NaughtyApp
1615 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1616 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1617 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1618
1619 // remove NaughtyApp
1620 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1621 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1622 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1623
1624 // add NiceApp
1625 status = mNetd->bandwidthAddNiceApp(uid);
1626 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1627 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1628
1629 // remove NiceApp
1630 status = mNetd->bandwidthRemoveNiceApp(uid);
1631 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1632 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1633}
Luke Huangb5733d72018-08-21 17:17:19 +08001634
1635namespace {
1636
Luke Huangc3252cc2018-10-16 15:43:23 +08001637std::string ipRouteString(const std::string& ifName, const std::string& dst,
1638 const std::string& nextHop) {
1639 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1640
1641 if (!nextHop.empty()) {
1642 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001643 }
1644
Luke Huangc3252cc2018-10-16 15:43:23 +08001645 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001646}
1647
Luke Huangc3252cc2018-10-16 15:43:23 +08001648void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1649 const std::string& dst, const std::string& nextHop,
1650 const char* table) {
1651 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1652}
1653
1654void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001655 const std::string& dst, const std::string& nextHop,
1656 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001657 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001658}
1659
1660bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1661 std::vector<std::string> rules = listIpRules(ipVersion);
1662 for (const auto& rule : rules) {
1663 if (rule.find(ipRule) != std::string::npos) {
1664 return true;
1665 }
1666 }
1667 return false;
1668}
1669
1670void expectNetworkDefaultIpRuleExists(const char* ifName) {
1671 std::string networkDefaultRule =
1672 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1673
1674 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1675 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1676 }
1677}
1678
1679void expectNetworkDefaultIpRuleDoesNotExist() {
1680 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1681
1682 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1683 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1684 }
1685}
1686
1687void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1688 std::string networkPermissionRule = "";
1689 switch (permission) {
1690 case INetd::PERMISSION_NONE:
1691 networkPermissionRule = StringPrintf(
1692 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1693 break;
1694 case INetd::PERMISSION_NETWORK:
1695 networkPermissionRule = StringPrintf(
1696 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1697 break;
1698 case INetd::PERMISSION_SYSTEM:
1699 networkPermissionRule = StringPrintf(
1700 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1701 break;
1702 }
1703
1704 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1705 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1706 }
1707}
1708
1709// TODO: It is a duplicate function, need to remove it
1710bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1711 const std::string& expectedInterface,
1712 const std::string& expectedRule,
1713 const char* table) {
1714 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1715 for (const auto& rule : rules) {
1716 if (rule.find(expectedInterface) != std::string::npos) {
1717 if (rule.find(expectedRule) != std::string::npos) {
1718 return true;
1719 }
1720 }
1721 }
1722 return false;
1723}
1724
1725void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1726 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1727 std::string networkIncomingPacketMarkRule = "";
1728 switch (permission) {
1729 case INetd::PERMISSION_NONE:
1730 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1731 break;
1732 case INetd::PERMISSION_NETWORK:
1733 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1734 break;
1735 case INetd::PERMISSION_SYSTEM:
1736 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1737 break;
1738 }
1739
1740 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1741 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1742 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1743 }
1744}
1745
1746} // namespace
1747
1748TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001749 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001750 const char* ipVersion;
1751 const char* testDest;
1752 const char* testNextHop;
1753 const bool expectSuccess;
1754 } kTestData[] = {
1755 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001756 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1757 {IP_RULE_V4, "10.251.0.0/16", "", true},
1758 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1759 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001760 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001761 {IP_RULE_V6, "::/0", "2001:db8::", true},
1762 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001763 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1764 };
1765
Luke Huangc3252cc2018-10-16 15:43:23 +08001766 static const struct {
1767 const char* ipVersion;
1768 const char* testDest;
1769 const char* testNextHop;
1770 } kTestDataWithNextHop[] = {
1771 {IP_RULE_V4, "10.251.10.0/30", ""},
1772 {IP_RULE_V6, "2001:db8::/32", ""},
1773 };
1774
Luke Huangb670d162018-08-23 20:01:13 +08001775 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001776 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001777 const int testUid = randomUid();
1778 const std::vector<int32_t> testUids = {testUid};
1779
1780 // Add test physical network
1781 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1782 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1783
Luke Huangc3252cc2018-10-16 15:43:23 +08001784 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001785 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001786 const auto& td = kTestDataWithNextHop[i];
1787
1788 // All route for test tun will disappear once the tun interface is deleted.
1789 binder::Status status =
1790 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1791 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1792 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1793 sTun.name().c_str());
1794
1795 // Add system permission for test uid, setup route in legacy system table.
1796 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1797
1798 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1799 testUid);
1800 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1801 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1802 testTableLegacySystem);
1803
1804 // Remove system permission for test uid, setup route in legacy network table.
1805 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1806
1807 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1808 testUid);
1809 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1810 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1811 testTableLegacyNetwork);
1812 }
1813
Sehee Park8659b8d2018-11-16 10:53:16 +09001814 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001815 const auto& td = kTestData[i];
1816
1817 binder::Status status =
1818 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1819 if (td.expectSuccess) {
1820 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001821 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001822 sTun.name().c_str());
1823 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001824 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1825 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001826 }
1827
1828 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1829 if (td.expectSuccess) {
1830 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001831 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1832 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001833 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001834 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1835 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001836 }
1837
Luke Huangc3252cc2018-10-16 15:43:23 +08001838 // Add system permission for test uid, route will be added into legacy system table.
1839 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001840
1841 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1842 testUid);
1843 if (td.expectSuccess) {
1844 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001845 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001846 testTableLegacySystem);
1847 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001848 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1849 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001850 }
1851
1852 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1853 td.testNextHop, testUid);
1854 if (td.expectSuccess) {
1855 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001856 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1857 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001858 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001859 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1860 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001861 }
1862
Luke Huangc3252cc2018-10-16 15:43:23 +08001863 // Remove system permission for test uid, route will be added into legacy network table.
1864 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1865
1866 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1867 testUid);
1868 if (td.expectSuccess) {
1869 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1870 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1871 testTableLegacyNetwork);
1872 } else {
1873 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1874 EXPECT_NE(0, status.serviceSpecificErrorCode());
1875 }
1876
1877 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1878 td.testNextHop, testUid);
1879 if (td.expectSuccess) {
1880 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1881 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1882 testTableLegacyNetwork);
1883 } else {
1884 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1885 EXPECT_NE(0, status.serviceSpecificErrorCode());
1886 }
Luke Huangb670d162018-08-23 20:01:13 +08001887 }
1888
1889 // Remove test physical network
1890 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1891}
1892
1893TEST_F(BinderTest, NetworkPermissionDefault) {
1894 // Add test physical network
1895 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1896 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1897
Luke Huangc3252cc2018-10-16 15:43:23 +08001898 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001899 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1900 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001901
1902 // Test SetDefault
1903 status = mNetd->networkSetDefault(TEST_NETID1);
1904 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1905 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1906
1907 status = mNetd->networkClearDefault();
1908 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1909 expectNetworkDefaultIpRuleDoesNotExist();
1910
Luke Huangd2861982019-05-17 19:47:28 +08001911 // Set default network back
1912 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001913 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1914
1915 // Test SetPermission
1916 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1917 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1918 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1919 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1920
1921 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1922 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1923 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1924 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1925
1926 // Remove test physical network
1927 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1928}
1929
1930TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001931 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001932 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1933 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001934 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001935 EXPECT_TRUE(ret);
1936
Luke Huang854e2992019-05-29 16:42:48 +08001937 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001938 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08001939
1940 // Clear uid permission before calling networkCanProtect to ensure
1941 // the call won't be affected by uid permission.
1942 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
1943
1944 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001945 EXPECT_FALSE(ret);
1946}
1947
1948namespace {
1949
Luke Huangb5733d72018-08-21 17:17:19 +08001950int readIntFromPath(const std::string& path) {
1951 std::string result = "";
1952 EXPECT_TRUE(ReadFileToString(path, &result));
1953 return std::stoi(result);
1954}
1955
1956int getTetherAcceptIPv6Ra(const std::string& ifName) {
1957 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1958 return readIntFromPath(path);
1959}
1960
1961bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1962 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1963 return readIntFromPath(path);
1964}
1965
1966int getTetherIPv6DadTransmits(const std::string& ifName) {
1967 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1968 return readIntFromPath(path);
1969}
1970
1971bool getTetherEnableIPv6(const std::string& ifName) {
1972 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1973 int disableIPv6 = readIntFromPath(path);
1974 return !disableIPv6;
1975}
1976
1977bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1978 for (const auto& iface : ifList) {
1979 if (iface == ifName) {
1980 return true;
1981 }
1982 }
1983 return false;
1984}
1985
1986void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1987 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1988 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1989 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1990 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1991}
1992
1993void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1994 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1995 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1996 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1997 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1998}
1999
2000void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2001 const std::string& ifName) {
2002 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2003}
2004
2005void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2006 const std::string& ifName) {
2007 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2008}
2009
2010void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2011 const std::vector<std::string>& testDnsAddrs) {
2012 EXPECT_TRUE(dnsList == testDnsAddrs);
2013}
2014
2015} // namespace
2016
2017TEST_F(BinderTest, TetherStartStopStatus) {
2018 std::vector<std::string> noDhcpRange = {};
2019 static const char dnsdName[] = "dnsmasq";
2020
Luke Huang91bd3e12019-08-20 11:33:52 +08002021 for (bool usingLegacyDnsProxy : {true, false}) {
Chiachang Wang08cb2112019-12-10 09:53:24 +08002022 android::net::TetherConfigParcel config;
2023 config.usingLegacyDnsProxy = usingLegacyDnsProxy;
2024 config.dhcpRanges = noDhcpRange;
2025 binder::Status status = mNetd->tetherStartWithConfiguration(config);
Luke Huang91bd3e12019-08-20 11:33:52 +08002026 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2027 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2028 if (usingLegacyDnsProxy == true) {
2029 expectProcessExists(dnsdName);
2030 } else {
2031 expectProcessDoesNotExist(dnsdName);
2032 }
Luke Huangb5733d72018-08-21 17:17:19 +08002033
Luke Huang91bd3e12019-08-20 11:33:52 +08002034 bool tetherEnabled;
2035 status = mNetd->tetherIsEnabled(&tetherEnabled);
2036 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2037 EXPECT_TRUE(tetherEnabled);
Luke Huangb5733d72018-08-21 17:17:19 +08002038
Luke Huang91bd3e12019-08-20 11:33:52 +08002039 status = mNetd->tetherStop();
2040 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2041 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002042
Luke Huang91bd3e12019-08-20 11:33:52 +08002043 status = mNetd->tetherIsEnabled(&tetherEnabled);
2044 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2045 EXPECT_FALSE(tetherEnabled);
2046 }
Luke Huangb5733d72018-08-21 17:17:19 +08002047}
2048
2049TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2050 // TODO: verify if dnsmasq update interface successfully
2051
2052 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2053 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2054 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2055
2056 std::vector<std::string> ifList;
2057 status = mNetd->tetherInterfaceList(&ifList);
2058 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2059 expectTetherInterfaceExists(ifList, sTun.name());
2060
2061 status = mNetd->tetherInterfaceRemove(sTun.name());
2062 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2063 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2064
2065 status = mNetd->tetherInterfaceList(&ifList);
2066 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2067 expectTetherInterfaceNotExists(ifList, sTun.name());
2068}
2069
2070TEST_F(BinderTest, TetherDnsSetList) {
2071 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002072 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2073 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002074
2075 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2076 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2077
2078 std::vector<std::string> dnsList;
2079 status = mNetd->tetherDnsList(&dnsList);
2080 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2081 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002082}
2083
2084namespace {
2085
2086constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2087constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2088constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2089constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2090constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2091constexpr char FIREWALL_STANDBY[] = "fw_standby";
2092constexpr char targetReturn[] = "RETURN";
2093constexpr char targetDrop[] = "DROP";
2094
2095void expectFirewallWhitelistMode() {
2096 static const char dropRule[] = "DROP all";
2097 static const char rejectRule[] = "REJECT all";
2098 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2099 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2100 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2101 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2102 }
2103}
2104
2105void expectFirewallBlacklistMode() {
2106 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2107 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2108 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2109 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2110 }
2111}
2112
2113bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2114 const std::string& expectedInterface,
2115 const std::string& expectedRule) {
2116 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2117 // Expected rule:
2118 // Chain fw_INPUT (1 references)
2119 // pkts bytes target prot opt in out source destination
2120 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2121 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2122 int firstRuleIndex = 2;
2123 if (rules.size() < 4) return false;
2124 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2125 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2126 return true;
2127 }
2128 }
2129 return false;
2130}
2131
2132// TODO: It is a duplicate function, need to remove it
2133bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2134 const std::string& expectedInterface,
2135 const std::string& expectedRule) {
2136 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2137 for (const auto& rule : rules) {
2138 if (rule.find(expectedInterface) != std::string::npos) {
2139 if (rule.find(expectedRule) != std::string::npos) {
2140 return true;
2141 }
2142 }
2143 }
2144 return false;
2145}
2146
2147void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2148 static const char returnRule[] = "RETURN all";
2149 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2150 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2151 returnRule));
2152 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2153 returnRule));
2154 }
2155}
2156
2157void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2158 static const char returnRule[] = "RETURN all";
2159 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2160 EXPECT_FALSE(
2161 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2162 EXPECT_FALSE(
2163 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2164 }
2165}
2166
2167bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2168 const std::string& expectedTarget,
2169 const std::string& expectedRule) {
2170 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2171 int firstRuleIndex = 2;
2172 if (rules.size() < 4) return false;
2173 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2174 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2175 return true;
2176 }
2177 }
2178 return false;
2179}
2180
2181bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2182 const std::string& expectedTarget,
2183 const std::string& expectedRule) {
2184 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2185 int lastRuleIndex = rules.size() - 1;
2186 if (lastRuleIndex < 0) return false;
2187 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2188 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2189 return true;
2190 }
2191 }
2192 return false;
2193}
2194
2195void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2196 std::string uidRule = StringPrintf("owner UID match %u", uid);
2197 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2198 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2199}
2200
2201void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2202 std::string uidRule = StringPrintf("owner UID match %u", uid);
2203 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2204 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2205}
2206
2207void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2208 std::string uidRule = StringPrintf("owner UID match %u", uid);
2209 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2210 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2211}
2212
2213void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2214 std::string uidRule = StringPrintf("owner UID match %u", uid);
2215 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2216 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2217}
2218
2219bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2220 std::vector<std::string> inputRules =
2221 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2222 std::vector<std::string> outputRules =
2223 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2224 int inputLastRuleIndex = inputRules.size() - 1;
2225 int outputLastRuleIndex = outputRules.size() - 1;
2226
2227 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2228 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2229 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2230 return true;
2231 }
2232 }
2233 return false;
2234}
2235
2236void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2237 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2238 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2239}
2240
2241void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2242 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2243 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2244 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2245 }
2246}
2247
2248} // namespace
2249
2250TEST_F(BinderTest, FirewallSetFirewallType) {
2251 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2252 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2253 expectFirewallWhitelistMode();
2254
2255 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2256 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2257 expectFirewallBlacklistMode();
2258
2259 // set firewall type blacklist twice
2260 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2261 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2262 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2263 expectFirewallBlacklistMode();
2264
2265 // set firewall type whitelist twice
2266 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2267 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2268 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2269 expectFirewallWhitelistMode();
2270
2271 // reset firewall type to default
2272 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2273 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2274 expectFirewallBlacklistMode();
2275}
2276
2277TEST_F(BinderTest, FirewallSetInterfaceRule) {
2278 // setinterfaceRule is not supported in BLACKLIST MODE
2279 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2280 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2281
2282 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2283 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2284
2285 // set WHITELIST mode first
2286 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2287 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2288
2289 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2290 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2291 expectFirewallInterfaceRuleAllowExists(sTun.name());
2292
2293 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2294 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2295 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2296
2297 // reset firewall mode to default
2298 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2299 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2300 expectFirewallBlacklistMode();
2301}
2302
2303TEST_F(BinderTest, FirewallSetUidRule) {
2304 SKIP_IF_BPF_SUPPORTED;
2305
2306 int32_t uid = randomUid();
2307
2308 // Doze allow
2309 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2310 INetd::FIREWALL_RULE_ALLOW);
2311 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2312 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2313
2314 // Doze deny
2315 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2316 INetd::FIREWALL_RULE_DENY);
2317 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2318 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2319
2320 // Powersave allow
2321 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2322 INetd::FIREWALL_RULE_ALLOW);
2323 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2324 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2325
2326 // Powersave deny
2327 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2328 INetd::FIREWALL_RULE_DENY);
2329 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2330 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2331
2332 // Standby deny
2333 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2334 INetd::FIREWALL_RULE_DENY);
2335 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2336 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2337
2338 // Standby allow
2339 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2340 INetd::FIREWALL_RULE_ALLOW);
2341 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2342 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2343
2344 // None deny in BLACKLIST
2345 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2347 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2348 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2349
2350 // None allow in BLACKLIST
2351 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2352 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2353 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2354 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2355
2356 // set firewall type whitelist twice
2357 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2358 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2359 expectFirewallWhitelistMode();
2360
2361 // None allow in WHITELIST
2362 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2363 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2364 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2365 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2366
2367 // None deny in WHITELIST
2368 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2369 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2370 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2371 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2372
2373 // reset firewall mode to default
2374 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2376 expectFirewallBlacklistMode();
2377}
2378
2379TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2380 SKIP_IF_BPF_SUPPORTED;
2381
2382 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2383 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2384 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2385
2386 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2387 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2388 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2389
2390 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2391 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2392 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2393
2394 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2395 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2396 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2397
2398 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2399 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2400 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2401
2402 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2403 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2404 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2405}
Luke Huangf7782042018-08-08 13:13:04 +08002406
2407namespace {
2408
2409std::string hwAddrToStr(unsigned char* hwaddr) {
2410 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2411 hwaddr[4], hwaddr[5]);
2412}
2413
2414int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2415 int prefixLength = 0;
2416 uint32_t m = ntohl(mask);
2417 while (m & (1 << 31)) {
2418 prefixLength++;
2419 m = m << 1;
2420 }
2421 return prefixLength;
2422}
2423
2424std::string toStdString(const String16& s) {
2425 return std::string(String8(s.string()));
2426}
2427
2428android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2429 const auto& sys = sSyscalls.get();
2430 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2431 EXPECT_TRUE(isOk(fd.status()));
2432
2433 struct ifreq ifr = {};
2434 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2435
2436 return sys.ioctl(fd.value(), flag, &ifr);
2437}
2438
2439std::string getInterfaceHwAddr(const std::string& ifName) {
2440 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2441
2442 unsigned char hwaddr[ETH_ALEN] = {};
2443 if (isOk(res.status())) {
2444 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2445 }
2446
2447 return hwAddrToStr(hwaddr);
2448}
2449
2450int getInterfaceIPv4Prefix(const std::string& ifName) {
2451 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2452
2453 int prefixLength = 0;
2454 if (isOk(res.status())) {
2455 prefixLength = ipv4NetmaskToPrefixLength(
2456 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2457 }
2458
2459 return prefixLength;
2460}
2461
2462std::string getInterfaceIPv4Addr(const std::string& ifName) {
2463 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2464
2465 struct in_addr addr = {};
2466 if (isOk(res.status())) {
2467 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2468 }
2469
2470 return std::string(inet_ntoa(addr));
2471}
2472
2473std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2474 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2475
2476 unsigned flags = 0;
2477 if (isOk(res.status())) {
2478 flags = res.value().ifr_flags;
2479 }
2480
2481 std::vector<std::string> ifFlags;
2482 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2483 : toStdString(INetd::IF_STATE_DOWN()));
2484
2485 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2486 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2487 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2488 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2489 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2490
2491 return ifFlags;
2492}
2493
2494bool compareListInterface(const std::vector<std::string>& interfaceList) {
2495 const auto& res = InterfaceController::getIfaceNames();
2496 EXPECT_TRUE(isOk(res));
2497
2498 std::vector<std::string> resIfList;
2499 resIfList.reserve(res.value().size());
2500 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2501
2502 return resIfList == interfaceList;
2503}
2504
2505int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2506 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2507 return readIntFromPath(path);
2508}
2509
2510bool getInterfaceEnableIPv6(const std::string& ifName) {
2511 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2512
2513 int disableIPv6 = readIntFromPath(path);
2514 return !disableIPv6;
2515}
2516
2517int getInterfaceMtu(const std::string& ifName) {
2518 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2519 return readIntFromPath(path);
2520}
2521
2522void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2523 EXPECT_TRUE(compareListInterface(interfaceList));
2524}
2525
2526void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2527 const InterfaceConfigurationParcel& interfaceCfg) {
2528 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2529 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2530 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2531 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2532}
2533
2534void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2535 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2536 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2537
2538 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2539 for (const auto& flag : setCfg.flags) {
2540 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2541 }
2542}
2543
2544void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2545 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2546 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2547}
2548
2549void expectInterfaceNoAddr(const std::string& ifName) {
2550 // noAddr
2551 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2552 // noPrefix
2553 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2554}
2555
2556void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2557 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2558 EXPECT_EQ(enableIPv6, enable);
2559}
2560
2561void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2562 int mtuSize = getInterfaceMtu(ifName);
2563 EXPECT_EQ(mtu, mtuSize);
2564}
2565
2566InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2567 const std::string& addr, int prefixLength,
2568 const std::vector<std::string>& flags) {
2569 InterfaceConfigurationParcel cfg;
2570 cfg.ifName = ifName;
2571 cfg.hwAddr = "";
2572 cfg.ipv4Addr = addr;
2573 cfg.prefixLength = prefixLength;
2574 cfg.flags = flags;
2575 return cfg;
2576}
2577
2578void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2579 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2580 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2581
2582 for (const auto& flag : expectedFlags) {
2583 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2584 interfaceCfg.flags.end());
2585 }
2586
2587 for (const auto& flag : unexpectedFlags) {
2588 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2589 interfaceCfg.flags.end());
2590 }
2591}
2592
2593} // namespace
2594
2595TEST_F(BinderTest, InterfaceList) {
2596 std::vector<std::string> interfaceListResult;
2597
2598 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2599 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2600 expectInterfaceList(interfaceListResult);
2601}
2602
2603TEST_F(BinderTest, InterfaceGetCfg) {
2604 InterfaceConfigurationParcel interfaceCfgResult;
2605
2606 // Add test physical network
2607 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2608 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2609
2610 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2611 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2612 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2613 expectTunFlags(interfaceCfgResult);
2614
2615 // Remove test physical network
2616 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2617}
2618
2619TEST_F(BinderTest, InterfaceSetCfg) {
2620 const std::string testAddr = "192.0.2.3";
2621 const int testPrefixLength = 24;
2622 std::vector<std::string> upFlags = {"up"};
2623 std::vector<std::string> downFlags = {"down"};
2624
2625 // Add test physical network
2626 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2627 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2628
2629 // Set tun interface down.
2630 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2631 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2632 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2633 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2634
2635 // Set tun interface up again.
2636 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2637 status = mNetd->interfaceSetCfg(interfaceCfg);
2638 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2639 status = mNetd->interfaceClearAddrs(sTun.name());
2640 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2641
2642 // Remove test physical network
2643 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2644}
2645
2646TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2647 // enable
2648 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2649 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2650 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2651
2652 // disable
2653 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2654 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2655 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2656}
2657
2658TEST_F(BinderTest, InterfaceClearAddr) {
2659 const std::string testAddr = "192.0.2.3";
2660 const int testPrefixLength = 24;
2661 std::vector<std::string> noFlags{};
2662
2663 // Add test physical network
2664 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2665 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2666
2667 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2668 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2669 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2670 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2671
2672 status = mNetd->interfaceClearAddrs(sTun.name());
2673 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2674 expectInterfaceNoAddr(sTun.name());
2675
2676 // Remove test physical network
2677 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2678}
2679
2680TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2681 // Add test physical network
2682 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2683 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2684
2685 // disable
2686 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2687 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2688 expectInterfaceEnableIPv6(sTun.name(), false);
2689
2690 // enable
2691 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2692 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2693 expectInterfaceEnableIPv6(sTun.name(), true);
2694
2695 // Remove test physical network
2696 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2697}
2698
2699TEST_F(BinderTest, InterfaceSetMtu) {
2700 const int testMtu = 1200;
2701
2702 // Add test physical network
2703 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2704 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2705
2706 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2707 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2708 expectInterfaceMtu(sTun.name(), testMtu);
2709
2710 // Remove test physical network
2711 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2712}
Luke Huang19b49c52018-10-22 12:12:05 +09002713
2714namespace {
2715
2716constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2717constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002718constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002719constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2720
Luke Huangae038f82018-11-05 11:17:31 +09002721int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002722 return listIptablesRuleByTable(binary, table, chainName).size();
2723}
2724
2725bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2726 const std::vector<std::string>& targetVec) {
2727 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2728 if (targetVec.size() != rules.size() - 2) {
2729 return false;
2730 }
2731
2732 /*
Luke Huangae038f82018-11-05 11:17:31 +09002733 * Check that the rules match. Note that this function matches substrings, not entire rules,
2734 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002735 * Skip first two lines since rules start from third line.
2736 * Chain chainName (x references)
2737 * pkts bytes target prot opt in out source destination
2738 * ...
2739 */
2740 int rIndex = 2;
2741 for (const auto& target : targetVec) {
2742 if (rules[rIndex].find(target) == std::string::npos) {
2743 return false;
2744 }
2745 rIndex++;
2746 }
2747 return true;
2748}
2749
2750void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2751 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2752 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2753 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002754 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002755 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2756 "DROP"};
2757
2758 // V4
2759 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2760 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002761 EXPECT_TRUE(
2762 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002763 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2764
Luke Huangae038f82018-11-05 11:17:31 +09002765 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002766 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2767
2768 // V6
2769 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002770 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2771 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002772
2773 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2774 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2775 extIf));
2776 }
2777}
2778
2779void expectNatDisable() {
2780 // It is the default DROP rule with tethering disable.
2781 // Chain tetherctrl_FORWARD (1 references)
2782 // pkts bytes target prot opt in out source destination
2783 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2784 std::vector<std::string> forwardV4Match = {"DROP"};
2785 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2786
2787 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002788 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2789 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002790
Luke Huangae038f82018-11-05 11:17:31 +09002791 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2792 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002793
2794 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2795}
2796
2797} // namespace
2798
2799TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002800 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2801 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2802 expectNatEnable(sTun.name(), sTun2.name());
2803
2804 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2805 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2806 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002807}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002808
2809namespace {
2810
2811using TripleInt = std::array<int, 3>;
2812
2813TripleInt readProcFileToTripleInt(const std::string& path) {
2814 std::string valueString;
2815 int min, def, max;
2816 EXPECT_TRUE(ReadFileToString(path, &valueString));
2817 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2818 return {min, def, max};
2819}
2820
2821void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2822 std::string testRmemValues =
2823 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2824 std::string testWmemValues =
2825 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2826 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2827
2828 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2829 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2830
2831 for (int i = 0; i < 3; i++) {
2832 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2833 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2834 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2835 }
2836}
2837
2838} // namespace
2839
2840TEST_F(BinderTest, TcpBufferSet) {
2841 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2842 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2843 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2844 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2845
2846 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2847 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2848}
Luke Huang528af602018-08-29 19:06:05 +08002849
Chenbo Feng48eaed32018-12-26 17:40:21 -08002850namespace {
2851
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002852void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002853 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2854 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2855 for (int32_t uid : uids) {
Steven Morelanda3074542020-01-13 14:13:44 -08002856 android::base::Result<uint8_t> permission = uidPermissionMap.readValue(uid);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002857 if (exist) {
Steven Morelanda3074542020-01-13 14:13:44 -08002858 ASSERT_TRUE(permission);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002859 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002860 } else {
Steven Morelanda3074542020-01-13 14:13:44 -08002861 ASSERT_FALSE(permission);
2862 EXPECT_EQ(ENOENT, permission.error().code());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002863 }
2864 }
2865}
2866
2867} // namespace
2868
2869TEST_F(BinderTest, TestInternetPermission) {
2870 SKIP_IF_BPF_NOT_SUPPORTED;
2871
2872 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2873
2874 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002875 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002876 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002877 checkUidsInPermissionMap(appUids, true);
2878 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2879 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002880}
2881
Luke Huang528af602018-08-29 19:06:05 +08002882TEST_F(BinderTest, UnsolEvents) {
2883 auto testUnsolService = android::net::TestUnsolService::start();
2884 std::string oldTunName = sTun.name();
2885 std::string newTunName = "unsolTest";
2886 testUnsolService->tarVec.push_back(oldTunName);
2887 testUnsolService->tarVec.push_back(newTunName);
2888 auto& cv = testUnsolService->getCv();
2889 auto& cvMutex = testUnsolService->getCvMutex();
2890 binder::Status status = mNetd->registerUnsolicitedEventListener(
2891 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2892 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2893
2894 // TODO: Add test for below events
2895 // StrictCleartextDetected / InterfaceDnsServersAdded
2896 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2897
2898 {
2899 std::unique_lock lock(cvMutex);
2900
2901 // Re-init test Tun, and we expect that we will get some unsol events.
2902 // Use the test Tun device name to verify if we receive its unsol events.
2903 sTun.destroy();
2904 // Use predefined name
2905 sTun.init(newTunName);
2906
2907 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2908 }
2909
2910 // bit mask 1101101000
2911 // Test only covers below events currently
2912 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2913 InterfaceLinkStatusChanged | RouteChanged;
2914 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002915
2916 // Re-init sTun to clear predefined name
2917 sTun.destroy();
2918 sTun.init();
2919}
2920
2921TEST_F(BinderTest, NDC) {
Alistair Delvaefb7ec32019-12-19 17:47:03 -08002922 // Disable test on 5.x kernels.
2923 utsname u;
2924 uname(&u);
2925 if (u.release[0] == '5') return;
2926
Luke Huangcfd04b22019-03-18 15:53:21 +08002927 struct Command {
2928 const std::string cmdString;
2929 const std::string expectedResult;
2930 };
2931
2932 // clang-format off
2933 // Do not change the commands order
2934 const Command networkCmds[] = {
2935 {StringPrintf("ndc network create %d", TEST_NETID1),
2936 "200 0 success"},
2937 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2938 "200 0 success"},
2939 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2940 "200 0 success"},
2941 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2942 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2943 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2944 "200 0 success"},
2945 };
2946
2947 const std::vector<Command> ipfwdCmds = {
2948 {"ndc ipfwd enable " + sTun.name(),
2949 "200 0 ipfwd operation succeeded"},
2950 {"ndc ipfwd disable " + sTun.name(),
2951 "200 0 ipfwd operation succeeded"},
2952 {"ndc ipfwd add lo2 lo3",
2953 "400 0 ipfwd operation failed (No such process)"},
2954 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
2955 "200 0 ipfwd operation succeeded"},
2956 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
2957 "200 0 ipfwd operation succeeded"},
2958 };
2959
2960 static const struct {
2961 const char* ipVersion;
2962 const char* testDest;
2963 const char* testNextHop;
2964 const bool expectSuccess;
2965 const std::string expectedResult;
2966 } kTestData[] = {
2967 {IP_RULE_V4, "0.0.0.0/0", "", true,
2968 "200 0 success"},
2969 {IP_RULE_V4, "10.251.0.0/16", "", true,
2970 "200 0 success"},
2971 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
2972 "400 0 addRoute() failed (Invalid argument)",},
2973 {IP_RULE_V6, "::/0", "", true,
2974 "200 0 success"},
2975 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
2976 "200 0 success"},
2977 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
2978 "400 0 addRoute() failed (Invalid argument)"},
2979 };
2980 // clang-format on
2981
2982 for (const auto& cmd : networkCmds) {
2983 const std::vector<std::string> result = runCommand(cmd.cmdString);
2984 SCOPED_TRACE(cmd.cmdString);
2985 EXPECT_EQ(result.size(), 1U);
2986 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
2987 }
2988
2989 for (const auto& cmd : ipfwdCmds) {
2990 const std::vector<std::string> result = runCommand(cmd.cmdString);
2991 SCOPED_TRACE(cmd.cmdString);
2992 EXPECT_EQ(result.size(), 1U);
2993 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
2994 }
2995
2996 // Add test physical network
2997 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2998 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2999
3000 for (const auto& td : kTestData) {
3001 const std::string routeAddCmd =
3002 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3003 td.testDest, td.testNextHop);
3004 const std::string routeRemoveCmd =
3005 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3006 sTun.name().c_str(), td.testDest, td.testNextHop);
3007 std::vector<std::string> result = runCommand(routeAddCmd);
3008 SCOPED_TRACE(routeAddCmd);
3009 EXPECT_EQ(result.size(), 1U);
3010 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3011 if (td.expectSuccess) {
3012 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3013 sTun.name().c_str());
3014 result = runCommand(routeRemoveCmd);
3015 EXPECT_EQ(result.size(), 1U);
3016 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3017 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3018 sTun.name().c_str());
3019 }
3020 }
3021 // Remove test physical network
3022 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003023}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003024
Luke Huang2ff8b342019-04-30 15:33:33 +08003025TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003026 sp<IBinder> binder;
3027 binder::Status status = mNetd->getOemNetd(&binder);
3028 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3029 sp<com::android::internal::net::IOemNetd> oemNetd;
3030 if (binder != nullptr) {
3031 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3032 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003033 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003034
3035 TimedOperation t("OemNetd isAlive RPC");
3036 bool isAlive = false;
3037 oemNetd->isAlive(&isAlive);
3038 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003039
3040 class TestOemUnsolListener
3041 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3042 public:
3043 android::binder::Status onRegistered() override {
3044 std::lock_guard lock(mCvMutex);
3045 mCv.notify_one();
3046 return android::binder::Status::ok();
3047 }
3048 std::condition_variable& getCv() { return mCv; }
3049 std::mutex& getCvMutex() { return mCvMutex; }
3050
3051 private:
3052 std::mutex mCvMutex;
3053 std::condition_variable mCv;
3054 };
3055
3056 // Start the Binder thread pool.
3057 android::ProcessState::self()->startThreadPool();
3058
3059 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3060
3061 auto& cv = testListener->getCv();
3062 auto& cvMutex = testListener->getCvMutex();
3063
3064 {
3065 std::unique_lock lock(cvMutex);
3066
3067 status = oemNetd->registerOemUnsolicitedEventListener(
3068 ::android::interface_cast<
3069 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3070 testListener));
3071 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3072
3073 // Wait for receiving expected events.
3074 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3075 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003076}
Luke Huangd2861982019-05-17 19:47:28 +08003077
3078void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3079 int fallthroughNetId) {
3080 // Re-init sTun* to ensure route rule exists.
3081 sTun.destroy();
3082 sTun.init();
3083 sTun2.destroy();
3084 sTun2.init();
3085
3086 // Create physical network with fallthroughNetId but not set it as default network
3087 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3088 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3089
3090 // Create VPN with vpnNetId
3091 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3092
3093 // Add uid to VPN
3094 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3095 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3096
3097 // Add default route to fallthroughNetwork
3098 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3099 // Add limited route
3100 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3101}
3102
3103namespace {
3104
3105class ScopedUidChange {
3106 public:
3107 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3108 mStoredUid = getuid();
3109 if (mInputUid == mStoredUid) return;
3110 EXPECT_TRUE(seteuid(uid) == 0);
3111 }
3112 ~ScopedUidChange() {
3113 if (mInputUid == mStoredUid) return;
3114 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3115 }
3116
3117 private:
3118 uid_t mInputUid;
3119 uid_t mStoredUid;
3120};
3121
3122constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3123
3124void clearQueue(int tunFd) {
3125 char buf[4096];
3126 int ret;
3127 do {
3128 ret = read(tunFd, buf, sizeof(buf));
3129 } while (ret > 0);
3130}
3131
3132void checkDataReceived(int udpSocket, int tunFd) {
3133 char buf[4096] = {};
3134 // Clear tunFd's queue before write something because there might be some
3135 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3136 clearQueue(tunFd);
3137 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3138 // TODO: extract header and verify data
3139 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3140}
3141
3142bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3143 ScopedUidChange scopedUidChange(uid);
Bernie Innocentid26a04a2019-10-30 17:15:15 +09003144 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Luke Huangd2861982019-05-17 19:47:28 +08003145 if (testSocket < 0) return false;
3146
Nick Desaulniers6b357502019-10-11 09:26:44 -07003147 const sockaddr_in6 dst6 = {
3148 .sin6_family = AF_INET6,
3149 .sin6_port = 42,
3150 .sin6_addr = dstAddr,
3151 };
Luke Huangd2861982019-05-17 19:47:28 +08003152 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3153 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3154 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3155 if (res == -1) return false;
3156
3157 char addr[INET6_ADDRSTRLEN];
3158 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3159 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3160 checkDataReceived(testSocket, tunFd);
3161 return true;
3162}
3163
3164void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3165 std::string vpnFallthroughRule =
3166 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3167 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3168 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3169 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3170 }
3171}
3172
3173void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3174 const TunInterface& fallthroughNetwork,
3175 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3176 int fallthroughNetId = TEST_NETID1) {
3177 // Set default network to NETID_UNSET
3178 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3179
3180 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3181 in6_addr insideVpnAddr = {
3182 {// 2001:db8:cafe::1
3183 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3184 // outsideVpnAddr will hit the route in the fallthrough network route table
3185 // because we added default route in createVpnNetworkWithUid
3186 in6_addr outsideVpnAddr = {
3187 {// 2607:f0d0:1002::4
3188 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3189
3190 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3191 int vpnFd = vpnNetwork.getFdForTesting();
3192 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3193 // default network.
3194 Fwmark fwmark;
3195 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3196 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3197
3198 // Set default network
3199 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3200
3201 // Connections go on the default network because UID 0 is not subject to the VPN.
3202 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3203 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3204 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3205 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3206
3207 // Check if fallthrough rule exists
3208 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3209
3210 // Expect fallthrough to default network
3211 // The fwmark differs depending on whether the VPN is bypassable or not.
3212 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3213 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3214
3215 // Expect connect success, packet will be sent to vpnFd.
3216 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3217 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3218
3219 // Explicitly select vpn network
3220 setNetworkForProcess(vpnNetId);
3221
3222 // Expect fallthrough to default network
3223 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3224 // Expect the mark contains all the bit because we've selected network.
3225 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3226
3227 // Expect connect success, packet will be sent to vpnFd.
3228 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3229 // Expect the mark contains all the bit because we've selected network.
3230 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3231
3232 // Explicitly select fallthrough network
3233 setNetworkForProcess(fallthroughNetId);
3234
3235 // The mark is set to fallthrough network because we've selected it.
3236 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3237 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3238
3239 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3240 if (bypassable) {
3241 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3242 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3243 } else {
3244 // If not, no permission to bypass vpn.
3245 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3246 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3247 }
3248}
3249
3250} // namespace
3251
3252TEST_F(BinderTest, SecureVPNFallthrough) {
3253 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3254 // Get current default network NetId
3255 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3256 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3257}
3258
3259TEST_F(BinderTest, BypassableVPNFallthrough) {
3260 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3261 // Get current default network NetId
3262 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3263 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003264}
Chiachang Wang00fc62f2019-12-04 20:38:26 +08003265
3266namespace {
3267
3268int32_t createIpv6SocketAndCheckMark(int type, const in6_addr& dstAddr) {
3269 const sockaddr_in6 dst6 = {
3270 .sin6_family = AF_INET6,
3271 .sin6_port = 1234,
3272 .sin6_addr = dstAddr,
3273 };
3274 // create non-blocking socket.
3275 int sockFd = socket(AF_INET6, type | SOCK_NONBLOCK, 0);
3276 EXPECT_NE(-1, sockFd);
3277 EXPECT_EQ((type == SOCK_STREAM) ? -1 : 0, connect(sockFd, (sockaddr*)&dst6, sizeof(dst6)));
3278
3279 // Get socket fwmark.
3280 Fwmark fwmark;
3281 socklen_t fwmarkLen = sizeof(fwmark.intValue);
3282 EXPECT_EQ(0, getsockopt(sockFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen));
3283 EXPECT_EQ(0, close(sockFd));
3284 return fwmark.intValue;
3285}
3286
3287} // namespace
3288
3289TEST_F(BinderTest, GetFwmarkForNetwork) {
3290 in6_addr v6Addr = {
3291 {// 2001:db8:cafe::8888
3292 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}};
3293 // Add test physical network 1 and set as default network.
3294 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3295 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3296 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "2001:db8::/32", "").isOk());
3297 EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk());
3298 // Add test physical network 2
3299 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
3300 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
3301
3302 // Get fwmark for network 1.
3303 MarkMaskParcel maskMarkNet1;
3304 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID1, &maskMarkNet1).isOk());
3305
3306 uint32_t fwmarkTcp = createIpv6SocketAndCheckMark(SOCK_STREAM, v6Addr);
3307 uint32_t fwmarkUdp = createIpv6SocketAndCheckMark(SOCK_DGRAM, v6Addr);
3308 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkTcp & maskMarkNet1.mask));
3309 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkUdp & maskMarkNet1.mask));
3310
3311 // Get fwmark for network 2.
3312 MarkMaskParcel maskMarkNet2;
3313 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID2, &maskMarkNet2).isOk());
3314 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkTcp & maskMarkNet2.mask));
3315 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkUdp & maskMarkNet2.mask));
3316
3317 // Remove test physical network.
3318 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
3319 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3320}