blob: 66baacea32c80f46a9d58cb8e69779779841b895 [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,
Tyler Wearfa94a272019-12-05 15:01:48 -08001638 const std::string& nextHop, const std::string& mtu) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001639 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
Tyler Wearfa94a272019-12-05 15:01:48 -08001645 dstString += " dev " + ifName;
1646
1647 if (!mtu.empty()) {
1648 dstString += " proto static";
1649 // IPv6 routes report the metric, IPv4 routes report the scope.
1650 // TODO: move away from specifying the entire string and use a regexp instead.
1651 if (dst.find(':') != std::string::npos) {
1652 dstString += " metric 1024";
1653 } else {
1654 if (nextHop.empty()) {
1655 dstString += " scope link";
1656 }
1657 }
1658 dstString += " mtu " + mtu;
1659 }
1660
1661 return dstString;
1662}
1663
1664void expectNetworkRouteExistsWithMtu(const char* ipVersion, const std::string& ifName,
1665 const std::string& dst, const std::string& nextHop,
1666 const std::string& mtu, const char* table) {
1667 std::string routeString = ipRouteString(ifName, dst, nextHop, mtu);
1668 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, mtu)))
1669 << "Couldn't find route to " << dst << ": '" << routeString << "' in table " << table;
Luke Huangb670d162018-08-23 20:01:13 +08001670}
1671
Luke Huangc3252cc2018-10-16 15:43:23 +08001672void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1673 const std::string& dst, const std::string& nextHop,
1674 const char* table) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001675 expectNetworkRouteExistsWithMtu(ipVersion, ifName, dst, nextHop, "", table);
Luke Huangc3252cc2018-10-16 15:43:23 +08001676}
1677
1678void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001679 const std::string& dst, const std::string& nextHop,
1680 const char* table) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001681 std::string routeString = ipRouteString(ifName, dst, nextHop, "");
1682 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, "")))
1683 << "Found unexpected route " << routeString << " in table " << table;
Luke Huangb670d162018-08-23 20:01:13 +08001684}
1685
1686bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1687 std::vector<std::string> rules = listIpRules(ipVersion);
1688 for (const auto& rule : rules) {
1689 if (rule.find(ipRule) != std::string::npos) {
1690 return true;
1691 }
1692 }
1693 return false;
1694}
1695
1696void expectNetworkDefaultIpRuleExists(const char* ifName) {
1697 std::string networkDefaultRule =
1698 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1699
1700 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1701 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1702 }
1703}
1704
1705void expectNetworkDefaultIpRuleDoesNotExist() {
1706 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1707
1708 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1709 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1710 }
1711}
1712
1713void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1714 std::string networkPermissionRule = "";
1715 switch (permission) {
1716 case INetd::PERMISSION_NONE:
1717 networkPermissionRule = StringPrintf(
1718 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1719 break;
1720 case INetd::PERMISSION_NETWORK:
1721 networkPermissionRule = StringPrintf(
1722 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1723 break;
1724 case INetd::PERMISSION_SYSTEM:
1725 networkPermissionRule = StringPrintf(
1726 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1727 break;
1728 }
1729
1730 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1731 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1732 }
1733}
1734
1735// TODO: It is a duplicate function, need to remove it
1736bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1737 const std::string& expectedInterface,
1738 const std::string& expectedRule,
1739 const char* table) {
1740 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1741 for (const auto& rule : rules) {
1742 if (rule.find(expectedInterface) != std::string::npos) {
1743 if (rule.find(expectedRule) != std::string::npos) {
1744 return true;
1745 }
1746 }
1747 }
1748 return false;
1749}
1750
1751void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1752 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1753 std::string networkIncomingPacketMarkRule = "";
1754 switch (permission) {
1755 case INetd::PERMISSION_NONE:
1756 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1757 break;
1758 case INetd::PERMISSION_NETWORK:
1759 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1760 break;
1761 case INetd::PERMISSION_SYSTEM:
1762 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1763 break;
1764 }
1765
1766 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1767 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1768 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1769 }
1770}
1771
1772} // namespace
1773
1774TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001775 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001776 const char* ipVersion;
1777 const char* testDest;
1778 const char* testNextHop;
1779 const bool expectSuccess;
1780 } kTestData[] = {
1781 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001782 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1783 {IP_RULE_V4, "10.251.0.0/16", "", true},
1784 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1785 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001786 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001787 {IP_RULE_V6, "::/0", "2001:db8::", true},
1788 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001789 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1790 };
1791
Luke Huangc3252cc2018-10-16 15:43:23 +08001792 static const struct {
1793 const char* ipVersion;
1794 const char* testDest;
1795 const char* testNextHop;
1796 } kTestDataWithNextHop[] = {
1797 {IP_RULE_V4, "10.251.10.0/30", ""},
1798 {IP_RULE_V6, "2001:db8::/32", ""},
1799 };
1800
Luke Huangb670d162018-08-23 20:01:13 +08001801 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001802 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001803 const int testUid = randomUid();
1804 const std::vector<int32_t> testUids = {testUid};
1805
1806 // Add test physical network
1807 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1808 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1809
Luke Huangc3252cc2018-10-16 15:43:23 +08001810 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001811 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001812 const auto& td = kTestDataWithNextHop[i];
1813
1814 // All route for test tun will disappear once the tun interface is deleted.
1815 binder::Status status =
1816 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1817 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1818 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1819 sTun.name().c_str());
1820
1821 // Add system permission for test uid, setup route in legacy system table.
1822 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1823
1824 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1825 testUid);
1826 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1827 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1828 testTableLegacySystem);
1829
1830 // Remove system permission for test uid, setup route in legacy network table.
1831 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1832
1833 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1834 testUid);
1835 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1836 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1837 testTableLegacyNetwork);
1838 }
1839
Sehee Park8659b8d2018-11-16 10:53:16 +09001840 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001841 const auto& td = kTestData[i];
1842
1843 binder::Status status =
1844 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1845 if (td.expectSuccess) {
1846 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001847 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001848 sTun.name().c_str());
1849 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001850 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1851 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001852 }
1853
1854 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1855 if (td.expectSuccess) {
1856 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001857 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1858 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001859 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001860 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1861 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001862 }
1863
Luke Huangc3252cc2018-10-16 15:43:23 +08001864 // Add system permission for test uid, route will be added into legacy system table.
1865 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001866
1867 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1868 testUid);
1869 if (td.expectSuccess) {
1870 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001871 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001872 testTableLegacySystem);
1873 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001874 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1875 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001876 }
1877
1878 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1879 td.testNextHop, testUid);
1880 if (td.expectSuccess) {
1881 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001882 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1883 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001884 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001885 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1886 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001887 }
1888
Luke Huangc3252cc2018-10-16 15:43:23 +08001889 // Remove system permission for test uid, route will be added into legacy network table.
1890 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1891
1892 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1893 testUid);
1894 if (td.expectSuccess) {
1895 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1896 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1897 testTableLegacyNetwork);
1898 } else {
1899 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1900 EXPECT_NE(0, status.serviceSpecificErrorCode());
1901 }
1902
1903 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1904 td.testNextHop, testUid);
1905 if (td.expectSuccess) {
1906 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1907 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1908 testTableLegacyNetwork);
1909 } else {
1910 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1911 EXPECT_NE(0, status.serviceSpecificErrorCode());
1912 }
Luke Huangb670d162018-08-23 20:01:13 +08001913 }
1914
Tyler Wearfa94a272019-12-05 15:01:48 -08001915 for (size_t i = 0; i < std::size(kTestData); i++) {
1916 const auto& td = kTestData[i];
1917 int mtu = (i % 2) ? 1480 : 1280;
1918
1919 android::net::RouteInfoParcel parcel;
1920 parcel.ifName = sTun.name();
1921 parcel.destination = td.testDest;
1922 parcel.nextHop = td.testNextHop;
1923 parcel.mtu = mtu;
1924 binder::Status status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel);
1925 if (td.expectSuccess) {
1926 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1927 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1928 std::to_string(parcel.mtu), sTun.name().c_str());
1929 } else {
1930 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1931 EXPECT_NE(0, status.serviceSpecificErrorCode());
1932 }
1933
1934 parcel.mtu = 1337;
1935 status = mNetd->networkUpdateRouteParcel(TEST_NETID1, parcel);
1936 if (td.expectSuccess) {
1937 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1938 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1939 std::to_string(parcel.mtu), sTun.name().c_str());
1940 } else {
1941 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1942 EXPECT_NE(0, status.serviceSpecificErrorCode());
1943 }
1944
1945 status = mNetd->networkRemoveRouteParcel(TEST_NETID1, parcel);
1946 if (td.expectSuccess) {
1947 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1948 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1949 sTun.name().c_str());
1950 } else {
1951 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1952 EXPECT_NE(0, status.serviceSpecificErrorCode());
1953 }
1954 }
Luke Huangb670d162018-08-23 20:01:13 +08001955 // Remove test physical network
1956 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1957}
1958
1959TEST_F(BinderTest, NetworkPermissionDefault) {
1960 // Add test physical network
1961 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1962 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1963
Luke Huangc3252cc2018-10-16 15:43:23 +08001964 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001965 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1966 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001967
1968 // Test SetDefault
1969 status = mNetd->networkSetDefault(TEST_NETID1);
1970 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1971 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1972
1973 status = mNetd->networkClearDefault();
1974 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1975 expectNetworkDefaultIpRuleDoesNotExist();
1976
Luke Huangd2861982019-05-17 19:47:28 +08001977 // Set default network back
1978 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001979 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1980
1981 // Test SetPermission
1982 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1983 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1984 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1985 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1986
1987 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1988 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1989 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1990 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1991
1992 // Remove test physical network
1993 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1994}
1995
1996TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001997 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001998 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1999 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08002000 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002001 EXPECT_TRUE(ret);
2002
Luke Huang854e2992019-05-29 16:42:48 +08002003 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002004 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08002005
2006 // Clear uid permission before calling networkCanProtect to ensure
2007 // the call won't be affected by uid permission.
2008 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2009
2010 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002011 EXPECT_FALSE(ret);
2012}
2013
2014namespace {
2015
Luke Huangb5733d72018-08-21 17:17:19 +08002016int readIntFromPath(const std::string& path) {
2017 std::string result = "";
2018 EXPECT_TRUE(ReadFileToString(path, &result));
2019 return std::stoi(result);
2020}
2021
2022int getTetherAcceptIPv6Ra(const std::string& ifName) {
2023 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2024 return readIntFromPath(path);
2025}
2026
2027bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2028 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2029 return readIntFromPath(path);
2030}
2031
2032int getTetherIPv6DadTransmits(const std::string& ifName) {
2033 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2034 return readIntFromPath(path);
2035}
2036
2037bool getTetherEnableIPv6(const std::string& ifName) {
2038 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2039 int disableIPv6 = readIntFromPath(path);
2040 return !disableIPv6;
2041}
2042
2043bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2044 for (const auto& iface : ifList) {
2045 if (iface == ifName) {
2046 return true;
2047 }
2048 }
2049 return false;
2050}
2051
2052void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2053 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2054 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2055 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2056 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2057}
2058
2059void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2060 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2061 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2062 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2063 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2064}
2065
2066void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2067 const std::string& ifName) {
2068 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2069}
2070
2071void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2072 const std::string& ifName) {
2073 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2074}
2075
2076void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2077 const std::vector<std::string>& testDnsAddrs) {
2078 EXPECT_TRUE(dnsList == testDnsAddrs);
2079}
2080
2081} // namespace
2082
2083TEST_F(BinderTest, TetherStartStopStatus) {
2084 std::vector<std::string> noDhcpRange = {};
2085 static const char dnsdName[] = "dnsmasq";
2086
Luke Huang91bd3e12019-08-20 11:33:52 +08002087 for (bool usingLegacyDnsProxy : {true, false}) {
Chiachang Wang08cb2112019-12-10 09:53:24 +08002088 android::net::TetherConfigParcel config;
2089 config.usingLegacyDnsProxy = usingLegacyDnsProxy;
2090 config.dhcpRanges = noDhcpRange;
2091 binder::Status status = mNetd->tetherStartWithConfiguration(config);
Luke Huang91bd3e12019-08-20 11:33:52 +08002092 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2093 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2094 if (usingLegacyDnsProxy == true) {
2095 expectProcessExists(dnsdName);
2096 } else {
2097 expectProcessDoesNotExist(dnsdName);
2098 }
Luke Huangb5733d72018-08-21 17:17:19 +08002099
Luke Huang91bd3e12019-08-20 11:33:52 +08002100 bool tetherEnabled;
2101 status = mNetd->tetherIsEnabled(&tetherEnabled);
2102 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2103 EXPECT_TRUE(tetherEnabled);
Luke Huangb5733d72018-08-21 17:17:19 +08002104
Luke Huang91bd3e12019-08-20 11:33:52 +08002105 status = mNetd->tetherStop();
2106 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2107 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002108
Luke Huang91bd3e12019-08-20 11:33:52 +08002109 status = mNetd->tetherIsEnabled(&tetherEnabled);
2110 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2111 EXPECT_FALSE(tetherEnabled);
2112 }
Luke Huangb5733d72018-08-21 17:17:19 +08002113}
2114
2115TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2116 // TODO: verify if dnsmasq update interface successfully
2117
2118 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2119 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2120 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2121
2122 std::vector<std::string> ifList;
2123 status = mNetd->tetherInterfaceList(&ifList);
2124 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2125 expectTetherInterfaceExists(ifList, sTun.name());
2126
2127 status = mNetd->tetherInterfaceRemove(sTun.name());
2128 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2129 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2130
2131 status = mNetd->tetherInterfaceList(&ifList);
2132 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2133 expectTetherInterfaceNotExists(ifList, sTun.name());
2134}
2135
2136TEST_F(BinderTest, TetherDnsSetList) {
2137 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002138 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2139 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002140
2141 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2142 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2143
2144 std::vector<std::string> dnsList;
2145 status = mNetd->tetherDnsList(&dnsList);
2146 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2147 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002148}
2149
2150namespace {
2151
2152constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2153constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2154constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2155constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2156constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2157constexpr char FIREWALL_STANDBY[] = "fw_standby";
2158constexpr char targetReturn[] = "RETURN";
2159constexpr char targetDrop[] = "DROP";
2160
2161void expectFirewallWhitelistMode() {
2162 static const char dropRule[] = "DROP all";
2163 static const char rejectRule[] = "REJECT all";
2164 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2165 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2166 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2167 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2168 }
2169}
2170
2171void expectFirewallBlacklistMode() {
2172 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2173 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2174 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2175 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2176 }
2177}
2178
2179bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2180 const std::string& expectedInterface,
2181 const std::string& expectedRule) {
2182 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2183 // Expected rule:
2184 // Chain fw_INPUT (1 references)
2185 // pkts bytes target prot opt in out source destination
2186 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2187 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2188 int firstRuleIndex = 2;
2189 if (rules.size() < 4) return false;
2190 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2191 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2192 return true;
2193 }
2194 }
2195 return false;
2196}
2197
2198// TODO: It is a duplicate function, need to remove it
2199bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2200 const std::string& expectedInterface,
2201 const std::string& expectedRule) {
2202 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2203 for (const auto& rule : rules) {
2204 if (rule.find(expectedInterface) != std::string::npos) {
2205 if (rule.find(expectedRule) != std::string::npos) {
2206 return true;
2207 }
2208 }
2209 }
2210 return false;
2211}
2212
2213void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2214 static const char returnRule[] = "RETURN all";
2215 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2216 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2217 returnRule));
2218 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2219 returnRule));
2220 }
2221}
2222
2223void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2224 static const char returnRule[] = "RETURN all";
2225 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2226 EXPECT_FALSE(
2227 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2228 EXPECT_FALSE(
2229 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2230 }
2231}
2232
2233bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2234 const std::string& expectedTarget,
2235 const std::string& expectedRule) {
2236 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2237 int firstRuleIndex = 2;
2238 if (rules.size() < 4) return false;
2239 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2240 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2241 return true;
2242 }
2243 }
2244 return false;
2245}
2246
2247bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2248 const std::string& expectedTarget,
2249 const std::string& expectedRule) {
2250 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2251 int lastRuleIndex = rules.size() - 1;
2252 if (lastRuleIndex < 0) return false;
2253 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2254 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2255 return true;
2256 }
2257 }
2258 return false;
2259}
2260
2261void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2262 std::string uidRule = StringPrintf("owner UID match %u", uid);
2263 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2264 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2265}
2266
2267void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2268 std::string uidRule = StringPrintf("owner UID match %u", uid);
2269 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2270 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2271}
2272
2273void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2274 std::string uidRule = StringPrintf("owner UID match %u", uid);
2275 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2276 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2277}
2278
2279void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2280 std::string uidRule = StringPrintf("owner UID match %u", uid);
2281 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2282 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2283}
2284
2285bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2286 std::vector<std::string> inputRules =
2287 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2288 std::vector<std::string> outputRules =
2289 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2290 int inputLastRuleIndex = inputRules.size() - 1;
2291 int outputLastRuleIndex = outputRules.size() - 1;
2292
2293 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2294 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2295 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2296 return true;
2297 }
2298 }
2299 return false;
2300}
2301
2302void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2303 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2304 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2305}
2306
2307void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2308 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2309 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2310 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2311 }
2312}
2313
2314} // namespace
2315
2316TEST_F(BinderTest, FirewallSetFirewallType) {
2317 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2318 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2319 expectFirewallWhitelistMode();
2320
2321 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2322 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2323 expectFirewallBlacklistMode();
2324
2325 // set firewall type blacklist twice
2326 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2327 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallBlacklistMode();
2330
2331 // set firewall type whitelist twice
2332 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2333 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2334 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2335 expectFirewallWhitelistMode();
2336
2337 // reset firewall type to default
2338 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2339 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2340 expectFirewallBlacklistMode();
2341}
2342
2343TEST_F(BinderTest, FirewallSetInterfaceRule) {
2344 // setinterfaceRule is not supported in BLACKLIST MODE
2345 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2346 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2347
2348 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2349 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2350
2351 // set WHITELIST mode first
2352 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2353 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2354
2355 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2356 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2357 expectFirewallInterfaceRuleAllowExists(sTun.name());
2358
2359 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2360 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2361 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2362
2363 // reset firewall mode to default
2364 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2365 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2366 expectFirewallBlacklistMode();
2367}
2368
2369TEST_F(BinderTest, FirewallSetUidRule) {
2370 SKIP_IF_BPF_SUPPORTED;
2371
2372 int32_t uid = randomUid();
2373
2374 // Doze allow
2375 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2376 INetd::FIREWALL_RULE_ALLOW);
2377 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2378 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2379
2380 // Doze deny
2381 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2382 INetd::FIREWALL_RULE_DENY);
2383 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2384 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2385
2386 // Powersave allow
2387 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2388 INetd::FIREWALL_RULE_ALLOW);
2389 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2390 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2391
2392 // Powersave deny
2393 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2394 INetd::FIREWALL_RULE_DENY);
2395 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2396 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2397
2398 // Standby deny
2399 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2400 INetd::FIREWALL_RULE_DENY);
2401 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2402 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2403
2404 // Standby allow
2405 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2406 INetd::FIREWALL_RULE_ALLOW);
2407 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2408 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2409
2410 // None deny in BLACKLIST
2411 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2412 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2413 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2414 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2415
2416 // None allow in BLACKLIST
2417 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2418 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2419 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2420 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2421
2422 // set firewall type whitelist twice
2423 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2424 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2425 expectFirewallWhitelistMode();
2426
2427 // None allow in WHITELIST
2428 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2429 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2430 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2431 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2432
2433 // None deny in WHITELIST
2434 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2435 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2436 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2437 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2438
2439 // reset firewall mode to default
2440 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2441 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2442 expectFirewallBlacklistMode();
2443}
2444
2445TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2446 SKIP_IF_BPF_SUPPORTED;
2447
2448 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2449 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2450 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2451
2452 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2453 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2454 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2455
2456 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2457 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2458 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2459
2460 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2461 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2462 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2463
2464 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2465 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2466 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2467
2468 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2469 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2470 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2471}
Luke Huangf7782042018-08-08 13:13:04 +08002472
2473namespace {
2474
2475std::string hwAddrToStr(unsigned char* hwaddr) {
2476 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2477 hwaddr[4], hwaddr[5]);
2478}
2479
2480int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2481 int prefixLength = 0;
2482 uint32_t m = ntohl(mask);
2483 while (m & (1 << 31)) {
2484 prefixLength++;
2485 m = m << 1;
2486 }
2487 return prefixLength;
2488}
2489
2490std::string toStdString(const String16& s) {
2491 return std::string(String8(s.string()));
2492}
2493
2494android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2495 const auto& sys = sSyscalls.get();
2496 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2497 EXPECT_TRUE(isOk(fd.status()));
2498
2499 struct ifreq ifr = {};
2500 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2501
2502 return sys.ioctl(fd.value(), flag, &ifr);
2503}
2504
2505std::string getInterfaceHwAddr(const std::string& ifName) {
2506 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2507
2508 unsigned char hwaddr[ETH_ALEN] = {};
2509 if (isOk(res.status())) {
2510 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2511 }
2512
2513 return hwAddrToStr(hwaddr);
2514}
2515
2516int getInterfaceIPv4Prefix(const std::string& ifName) {
2517 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2518
2519 int prefixLength = 0;
2520 if (isOk(res.status())) {
2521 prefixLength = ipv4NetmaskToPrefixLength(
2522 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2523 }
2524
2525 return prefixLength;
2526}
2527
2528std::string getInterfaceIPv4Addr(const std::string& ifName) {
2529 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2530
2531 struct in_addr addr = {};
2532 if (isOk(res.status())) {
2533 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2534 }
2535
2536 return std::string(inet_ntoa(addr));
2537}
2538
2539std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2540 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2541
2542 unsigned flags = 0;
2543 if (isOk(res.status())) {
2544 flags = res.value().ifr_flags;
2545 }
2546
2547 std::vector<std::string> ifFlags;
2548 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2549 : toStdString(INetd::IF_STATE_DOWN()));
2550
2551 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2552 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2553 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2554 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2555 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2556
2557 return ifFlags;
2558}
2559
2560bool compareListInterface(const std::vector<std::string>& interfaceList) {
2561 const auto& res = InterfaceController::getIfaceNames();
2562 EXPECT_TRUE(isOk(res));
2563
2564 std::vector<std::string> resIfList;
2565 resIfList.reserve(res.value().size());
2566 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2567
2568 return resIfList == interfaceList;
2569}
2570
2571int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2572 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2573 return readIntFromPath(path);
2574}
2575
2576bool getInterfaceEnableIPv6(const std::string& ifName) {
2577 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2578
2579 int disableIPv6 = readIntFromPath(path);
2580 return !disableIPv6;
2581}
2582
2583int getInterfaceMtu(const std::string& ifName) {
2584 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2585 return readIntFromPath(path);
2586}
2587
2588void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2589 EXPECT_TRUE(compareListInterface(interfaceList));
2590}
2591
2592void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2593 const InterfaceConfigurationParcel& interfaceCfg) {
2594 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2595 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2596 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2597 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2598}
2599
2600void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2601 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2602 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2603
2604 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2605 for (const auto& flag : setCfg.flags) {
2606 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2607 }
2608}
2609
2610void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2611 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2612 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2613}
2614
2615void expectInterfaceNoAddr(const std::string& ifName) {
2616 // noAddr
2617 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2618 // noPrefix
2619 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2620}
2621
2622void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2623 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2624 EXPECT_EQ(enableIPv6, enable);
2625}
2626
2627void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2628 int mtuSize = getInterfaceMtu(ifName);
2629 EXPECT_EQ(mtu, mtuSize);
2630}
2631
2632InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2633 const std::string& addr, int prefixLength,
2634 const std::vector<std::string>& flags) {
2635 InterfaceConfigurationParcel cfg;
2636 cfg.ifName = ifName;
2637 cfg.hwAddr = "";
2638 cfg.ipv4Addr = addr;
2639 cfg.prefixLength = prefixLength;
2640 cfg.flags = flags;
2641 return cfg;
2642}
2643
2644void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2645 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2646 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2647
2648 for (const auto& flag : expectedFlags) {
2649 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2650 interfaceCfg.flags.end());
2651 }
2652
2653 for (const auto& flag : unexpectedFlags) {
2654 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2655 interfaceCfg.flags.end());
2656 }
2657}
2658
2659} // namespace
2660
2661TEST_F(BinderTest, InterfaceList) {
2662 std::vector<std::string> interfaceListResult;
2663
2664 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2665 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2666 expectInterfaceList(interfaceListResult);
2667}
2668
2669TEST_F(BinderTest, InterfaceGetCfg) {
2670 InterfaceConfigurationParcel interfaceCfgResult;
2671
2672 // Add test physical network
2673 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2674 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2675
2676 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2677 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2678 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2679 expectTunFlags(interfaceCfgResult);
2680
2681 // Remove test physical network
2682 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2683}
2684
2685TEST_F(BinderTest, InterfaceSetCfg) {
2686 const std::string testAddr = "192.0.2.3";
2687 const int testPrefixLength = 24;
2688 std::vector<std::string> upFlags = {"up"};
2689 std::vector<std::string> downFlags = {"down"};
2690
2691 // Add test physical network
2692 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2693 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2694
2695 // Set tun interface down.
2696 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2697 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2698 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2699 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2700
2701 // Set tun interface up again.
2702 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2703 status = mNetd->interfaceSetCfg(interfaceCfg);
2704 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2705 status = mNetd->interfaceClearAddrs(sTun.name());
2706 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2707
2708 // Remove test physical network
2709 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2710}
2711
2712TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2713 // enable
2714 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2715 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2716 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2717
2718 // disable
2719 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2720 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2721 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2722}
2723
2724TEST_F(BinderTest, InterfaceClearAddr) {
2725 const std::string testAddr = "192.0.2.3";
2726 const int testPrefixLength = 24;
2727 std::vector<std::string> noFlags{};
2728
2729 // Add test physical network
2730 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2731 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2732
2733 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2734 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2735 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2736 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2737
2738 status = mNetd->interfaceClearAddrs(sTun.name());
2739 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2740 expectInterfaceNoAddr(sTun.name());
2741
2742 // Remove test physical network
2743 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2744}
2745
2746TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2747 // Add test physical network
2748 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2749 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2750
2751 // disable
2752 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2753 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2754 expectInterfaceEnableIPv6(sTun.name(), false);
2755
2756 // enable
2757 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2758 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2759 expectInterfaceEnableIPv6(sTun.name(), true);
2760
2761 // Remove test physical network
2762 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2763}
2764
2765TEST_F(BinderTest, InterfaceSetMtu) {
2766 const int testMtu = 1200;
2767
2768 // Add test physical network
2769 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2770 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2771
2772 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2773 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2774 expectInterfaceMtu(sTun.name(), testMtu);
2775
2776 // Remove test physical network
2777 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2778}
Luke Huang19b49c52018-10-22 12:12:05 +09002779
2780namespace {
2781
2782constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2783constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002784constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002785constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2786
Luke Huangae038f82018-11-05 11:17:31 +09002787int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002788 return listIptablesRuleByTable(binary, table, chainName).size();
2789}
2790
2791bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2792 const std::vector<std::string>& targetVec) {
2793 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2794 if (targetVec.size() != rules.size() - 2) {
2795 return false;
2796 }
2797
2798 /*
Luke Huangae038f82018-11-05 11:17:31 +09002799 * Check that the rules match. Note that this function matches substrings, not entire rules,
2800 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002801 * Skip first two lines since rules start from third line.
2802 * Chain chainName (x references)
2803 * pkts bytes target prot opt in out source destination
2804 * ...
2805 */
2806 int rIndex = 2;
2807 for (const auto& target : targetVec) {
2808 if (rules[rIndex].find(target) == std::string::npos) {
2809 return false;
2810 }
2811 rIndex++;
2812 }
2813 return true;
2814}
2815
2816void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2817 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2818 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2819 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002820 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002821 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2822 "DROP"};
2823
2824 // V4
2825 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2826 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002827 EXPECT_TRUE(
2828 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002829 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2830
Luke Huangae038f82018-11-05 11:17:31 +09002831 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002832 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2833
2834 // V6
2835 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002836 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2837 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002838
2839 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2840 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2841 extIf));
2842 }
2843}
2844
2845void expectNatDisable() {
2846 // It is the default DROP rule with tethering disable.
2847 // Chain tetherctrl_FORWARD (1 references)
2848 // pkts bytes target prot opt in out source destination
2849 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2850 std::vector<std::string> forwardV4Match = {"DROP"};
2851 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2852
2853 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002854 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2855 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002856
Luke Huangae038f82018-11-05 11:17:31 +09002857 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2858 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002859
2860 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2861}
2862
2863} // namespace
2864
2865TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002866 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2867 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2868 expectNatEnable(sTun.name(), sTun2.name());
2869
2870 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2871 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2872 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002873}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002874
2875namespace {
2876
2877using TripleInt = std::array<int, 3>;
2878
2879TripleInt readProcFileToTripleInt(const std::string& path) {
2880 std::string valueString;
2881 int min, def, max;
2882 EXPECT_TRUE(ReadFileToString(path, &valueString));
2883 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2884 return {min, def, max};
2885}
2886
2887void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2888 std::string testRmemValues =
2889 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2890 std::string testWmemValues =
2891 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2892 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2893
2894 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2895 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2896
2897 for (int i = 0; i < 3; i++) {
2898 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2899 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2900 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2901 }
2902}
2903
2904} // namespace
2905
2906TEST_F(BinderTest, TcpBufferSet) {
2907 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2908 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2909 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2910 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2911
2912 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2913 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2914}
Luke Huang528af602018-08-29 19:06:05 +08002915
Chenbo Feng48eaed32018-12-26 17:40:21 -08002916namespace {
2917
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002918void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002919 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2920 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2921 for (int32_t uid : uids) {
2922 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2923 if (exist) {
2924 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002925 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002926 } else {
2927 EXPECT_FALSE(isOk(permission));
2928 EXPECT_EQ(ENOENT, permission.status().code());
2929 }
2930 }
2931}
2932
2933} // namespace
2934
2935TEST_F(BinderTest, TestInternetPermission) {
2936 SKIP_IF_BPF_NOT_SUPPORTED;
2937
2938 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2939
2940 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002941 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002942 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002943 checkUidsInPermissionMap(appUids, true);
2944 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2945 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002946}
2947
Luke Huang528af602018-08-29 19:06:05 +08002948TEST_F(BinderTest, UnsolEvents) {
2949 auto testUnsolService = android::net::TestUnsolService::start();
2950 std::string oldTunName = sTun.name();
2951 std::string newTunName = "unsolTest";
2952 testUnsolService->tarVec.push_back(oldTunName);
2953 testUnsolService->tarVec.push_back(newTunName);
2954 auto& cv = testUnsolService->getCv();
2955 auto& cvMutex = testUnsolService->getCvMutex();
2956 binder::Status status = mNetd->registerUnsolicitedEventListener(
2957 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2958 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2959
2960 // TODO: Add test for below events
2961 // StrictCleartextDetected / InterfaceDnsServersAdded
2962 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2963
2964 {
2965 std::unique_lock lock(cvMutex);
2966
2967 // Re-init test Tun, and we expect that we will get some unsol events.
2968 // Use the test Tun device name to verify if we receive its unsol events.
2969 sTun.destroy();
2970 // Use predefined name
2971 sTun.init(newTunName);
2972
2973 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2974 }
2975
2976 // bit mask 1101101000
2977 // Test only covers below events currently
2978 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2979 InterfaceLinkStatusChanged | RouteChanged;
2980 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002981
2982 // Re-init sTun to clear predefined name
2983 sTun.destroy();
2984 sTun.init();
2985}
2986
2987TEST_F(BinderTest, NDC) {
Alistair Delvaefb7ec32019-12-19 17:47:03 -08002988 // Disable test on 5.x kernels.
2989 utsname u;
2990 uname(&u);
2991 if (u.release[0] == '5') return;
2992
Luke Huangcfd04b22019-03-18 15:53:21 +08002993 struct Command {
2994 const std::string cmdString;
2995 const std::string expectedResult;
2996 };
2997
2998 // clang-format off
2999 // Do not change the commands order
3000 const Command networkCmds[] = {
3001 {StringPrintf("ndc network create %d", TEST_NETID1),
3002 "200 0 success"},
3003 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
3004 "200 0 success"},
3005 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
3006 "200 0 success"},
3007 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
3008 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
3009 {StringPrintf("ndc network destroy %d", TEST_NETID1),
3010 "200 0 success"},
3011 };
3012
3013 const std::vector<Command> ipfwdCmds = {
3014 {"ndc ipfwd enable " + sTun.name(),
3015 "200 0 ipfwd operation succeeded"},
3016 {"ndc ipfwd disable " + sTun.name(),
3017 "200 0 ipfwd operation succeeded"},
3018 {"ndc ipfwd add lo2 lo3",
3019 "400 0 ipfwd operation failed (No such process)"},
3020 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3021 "200 0 ipfwd operation succeeded"},
3022 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3023 "200 0 ipfwd operation succeeded"},
3024 };
3025
3026 static const struct {
3027 const char* ipVersion;
3028 const char* testDest;
3029 const char* testNextHop;
3030 const bool expectSuccess;
3031 const std::string expectedResult;
3032 } kTestData[] = {
3033 {IP_RULE_V4, "0.0.0.0/0", "", true,
3034 "200 0 success"},
3035 {IP_RULE_V4, "10.251.0.0/16", "", true,
3036 "200 0 success"},
3037 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3038 "400 0 addRoute() failed (Invalid argument)",},
3039 {IP_RULE_V6, "::/0", "", true,
3040 "200 0 success"},
3041 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3042 "200 0 success"},
3043 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3044 "400 0 addRoute() failed (Invalid argument)"},
3045 };
3046 // clang-format on
3047
3048 for (const auto& cmd : networkCmds) {
3049 const std::vector<std::string> result = runCommand(cmd.cmdString);
3050 SCOPED_TRACE(cmd.cmdString);
3051 EXPECT_EQ(result.size(), 1U);
3052 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3053 }
3054
3055 for (const auto& cmd : ipfwdCmds) {
3056 const std::vector<std::string> result = runCommand(cmd.cmdString);
3057 SCOPED_TRACE(cmd.cmdString);
3058 EXPECT_EQ(result.size(), 1U);
3059 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3060 }
3061
3062 // Add test physical network
3063 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3064 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3065
3066 for (const auto& td : kTestData) {
3067 const std::string routeAddCmd =
3068 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3069 td.testDest, td.testNextHop);
3070 const std::string routeRemoveCmd =
3071 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3072 sTun.name().c_str(), td.testDest, td.testNextHop);
3073 std::vector<std::string> result = runCommand(routeAddCmd);
3074 SCOPED_TRACE(routeAddCmd);
3075 EXPECT_EQ(result.size(), 1U);
3076 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3077 if (td.expectSuccess) {
3078 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3079 sTun.name().c_str());
3080 result = runCommand(routeRemoveCmd);
3081 EXPECT_EQ(result.size(), 1U);
3082 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3083 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3084 sTun.name().c_str());
3085 }
3086 }
3087 // Remove test physical network
3088 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003089}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003090
Luke Huang2ff8b342019-04-30 15:33:33 +08003091TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003092 sp<IBinder> binder;
3093 binder::Status status = mNetd->getOemNetd(&binder);
3094 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3095 sp<com::android::internal::net::IOemNetd> oemNetd;
3096 if (binder != nullptr) {
3097 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3098 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003099 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003100
3101 TimedOperation t("OemNetd isAlive RPC");
3102 bool isAlive = false;
3103 oemNetd->isAlive(&isAlive);
3104 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003105
3106 class TestOemUnsolListener
3107 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3108 public:
3109 android::binder::Status onRegistered() override {
3110 std::lock_guard lock(mCvMutex);
3111 mCv.notify_one();
3112 return android::binder::Status::ok();
3113 }
3114 std::condition_variable& getCv() { return mCv; }
3115 std::mutex& getCvMutex() { return mCvMutex; }
3116
3117 private:
3118 std::mutex mCvMutex;
3119 std::condition_variable mCv;
3120 };
3121
3122 // Start the Binder thread pool.
3123 android::ProcessState::self()->startThreadPool();
3124
3125 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3126
3127 auto& cv = testListener->getCv();
3128 auto& cvMutex = testListener->getCvMutex();
3129
3130 {
3131 std::unique_lock lock(cvMutex);
3132
3133 status = oemNetd->registerOemUnsolicitedEventListener(
3134 ::android::interface_cast<
3135 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3136 testListener));
3137 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3138
3139 // Wait for receiving expected events.
3140 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3141 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003142}
Luke Huangd2861982019-05-17 19:47:28 +08003143
3144void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3145 int fallthroughNetId) {
3146 // Re-init sTun* to ensure route rule exists.
3147 sTun.destroy();
3148 sTun.init();
3149 sTun2.destroy();
3150 sTun2.init();
3151
3152 // Create physical network with fallthroughNetId but not set it as default network
3153 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3154 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3155
3156 // Create VPN with vpnNetId
3157 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3158
3159 // Add uid to VPN
3160 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3161 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3162
3163 // Add default route to fallthroughNetwork
3164 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3165 // Add limited route
3166 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3167}
3168
3169namespace {
3170
3171class ScopedUidChange {
3172 public:
3173 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3174 mStoredUid = getuid();
3175 if (mInputUid == mStoredUid) return;
3176 EXPECT_TRUE(seteuid(uid) == 0);
3177 }
3178 ~ScopedUidChange() {
3179 if (mInputUid == mStoredUid) return;
3180 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3181 }
3182
3183 private:
3184 uid_t mInputUid;
3185 uid_t mStoredUid;
3186};
3187
3188constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3189
3190void clearQueue(int tunFd) {
3191 char buf[4096];
3192 int ret;
3193 do {
3194 ret = read(tunFd, buf, sizeof(buf));
3195 } while (ret > 0);
3196}
3197
3198void checkDataReceived(int udpSocket, int tunFd) {
3199 char buf[4096] = {};
3200 // Clear tunFd's queue before write something because there might be some
3201 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3202 clearQueue(tunFd);
3203 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3204 // TODO: extract header and verify data
3205 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3206}
3207
3208bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3209 ScopedUidChange scopedUidChange(uid);
Bernie Innocentid26a04a2019-10-30 17:15:15 +09003210 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Luke Huangd2861982019-05-17 19:47:28 +08003211 if (testSocket < 0) return false;
3212
Nick Desaulniers6b357502019-10-11 09:26:44 -07003213 const sockaddr_in6 dst6 = {
3214 .sin6_family = AF_INET6,
3215 .sin6_port = 42,
3216 .sin6_addr = dstAddr,
3217 };
Luke Huangd2861982019-05-17 19:47:28 +08003218 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3219 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3220 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3221 if (res == -1) return false;
3222
3223 char addr[INET6_ADDRSTRLEN];
3224 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3225 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3226 checkDataReceived(testSocket, tunFd);
3227 return true;
3228}
3229
3230void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3231 std::string vpnFallthroughRule =
3232 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3233 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3234 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3235 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3236 }
3237}
3238
3239void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3240 const TunInterface& fallthroughNetwork,
3241 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3242 int fallthroughNetId = TEST_NETID1) {
3243 // Set default network to NETID_UNSET
3244 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3245
3246 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3247 in6_addr insideVpnAddr = {
3248 {// 2001:db8:cafe::1
3249 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3250 // outsideVpnAddr will hit the route in the fallthrough network route table
3251 // because we added default route in createVpnNetworkWithUid
3252 in6_addr outsideVpnAddr = {
3253 {// 2607:f0d0:1002::4
3254 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3255
3256 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3257 int vpnFd = vpnNetwork.getFdForTesting();
3258 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3259 // default network.
3260 Fwmark fwmark;
3261 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3262 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3263
3264 // Set default network
3265 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3266
3267 // Connections go on the default network because UID 0 is not subject to the VPN.
3268 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3269 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3270 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3271 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3272
3273 // Check if fallthrough rule exists
3274 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3275
3276 // Expect fallthrough to default network
3277 // The fwmark differs depending on whether the VPN is bypassable or not.
3278 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3279 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3280
3281 // Expect connect success, packet will be sent to vpnFd.
3282 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3283 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3284
3285 // Explicitly select vpn network
3286 setNetworkForProcess(vpnNetId);
3287
3288 // Expect fallthrough to default network
3289 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3290 // Expect the mark contains all the bit because we've selected network.
3291 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3292
3293 // Expect connect success, packet will be sent to vpnFd.
3294 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3295 // Expect the mark contains all the bit because we've selected network.
3296 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3297
3298 // Explicitly select fallthrough network
3299 setNetworkForProcess(fallthroughNetId);
3300
3301 // The mark is set to fallthrough network because we've selected it.
3302 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3303 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3304
3305 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3306 if (bypassable) {
3307 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3308 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3309 } else {
3310 // If not, no permission to bypass vpn.
3311 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3312 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3313 }
3314}
3315
3316} // namespace
3317
3318TEST_F(BinderTest, SecureVPNFallthrough) {
3319 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3320 // Get current default network NetId
3321 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3322 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3323}
3324
3325TEST_F(BinderTest, BypassableVPNFallthrough) {
3326 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3327 // Get current default network NetId
3328 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3329 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003330}
Chiachang Wang00fc62f2019-12-04 20:38:26 +08003331
3332namespace {
3333
3334int32_t createIpv6SocketAndCheckMark(int type, const in6_addr& dstAddr) {
3335 const sockaddr_in6 dst6 = {
3336 .sin6_family = AF_INET6,
3337 .sin6_port = 1234,
3338 .sin6_addr = dstAddr,
3339 };
3340 // create non-blocking socket.
3341 int sockFd = socket(AF_INET6, type | SOCK_NONBLOCK, 0);
3342 EXPECT_NE(-1, sockFd);
3343 EXPECT_EQ((type == SOCK_STREAM) ? -1 : 0, connect(sockFd, (sockaddr*)&dst6, sizeof(dst6)));
3344
3345 // Get socket fwmark.
3346 Fwmark fwmark;
3347 socklen_t fwmarkLen = sizeof(fwmark.intValue);
3348 EXPECT_EQ(0, getsockopt(sockFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen));
3349 EXPECT_EQ(0, close(sockFd));
3350 return fwmark.intValue;
3351}
3352
3353} // namespace
3354
3355TEST_F(BinderTest, GetFwmarkForNetwork) {
3356 in6_addr v6Addr = {
3357 {// 2001:db8:cafe::8888
3358 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}};
3359 // Add test physical network 1 and set as default network.
3360 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3361 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3362 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "2001:db8::/32", "").isOk());
3363 EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk());
3364 // Add test physical network 2
3365 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
3366 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
3367
3368 // Get fwmark for network 1.
3369 MarkMaskParcel maskMarkNet1;
3370 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID1, &maskMarkNet1).isOk());
3371
3372 uint32_t fwmarkTcp = createIpv6SocketAndCheckMark(SOCK_STREAM, v6Addr);
3373 uint32_t fwmarkUdp = createIpv6SocketAndCheckMark(SOCK_DGRAM, v6Addr);
3374 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkTcp & maskMarkNet1.mask));
3375 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkUdp & maskMarkNet1.mask));
3376
3377 // Get fwmark for network 2.
3378 MarkMaskParcel maskMarkNet2;
3379 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID2, &maskMarkNet2).isOk());
3380 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkTcp & maskMarkNet2.mask));
3381 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkUdp & maskMarkNet2.mask));
3382
3383 // Remove test physical network.
3384 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
3385 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3386}