blob: 080e22dbfac0c569a55eff48eef24f1e752514db [file] [log] [blame]
Lorenzo Colitti89faa342016-02-26 11:38:47 +09001/*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * binder_test.cpp - unit tests for netd binder RPCs.
17 */
18
Robin Leeb8087362016-03-30 18:43:08 +010019#include <cerrno>
Luke Huang528af602018-08-29 19:06:05 +080020#include <chrono>
Robin Leeb8087362016-03-30 18:43:08 +010021#include <cinttypes>
Luke Huang528af602018-08-29 19:06:05 +080022#include <condition_variable>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090023#include <cstdint>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090024#include <cstdlib>
Bernie Innocenti196f1b82019-05-20 16:34:16 +090025#include <iostream>
Luke Huang528af602018-08-29 19:06:05 +080026#include <mutex>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090027#include <set>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090028#include <vector>
29
Luke Huangf7782042018-08-08 13:13:04 +080030#include <dirent.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090031#include <fcntl.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090032#include <ifaddrs.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090033#include <linux/if.h>
34#include <linux/if_tun.h>
Benedict Wonga450e722018-05-07 10:29:02 -070035#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080036#include <netdb.h>
37#include <netinet/in.h>
Ben Schwartze7601812017-04-28 16:38:29 -040038#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080039#include <sys/socket.h>
40#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090041
Luke Huang531f5d32018-08-03 15:19:05 +080042#include <android-base/file.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090043#include <android-base/macros.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090044#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090045#include <android-base/strings.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080046#include <binder/IPCThreadState.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080047#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070048#include <bpf/BpfUtils.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080049#include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
50#include <com/android/internal/net/IOemNetd.h>
Robin Leeb8087362016-03-30 18:43:08 +010051#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090052#include <gtest/gtest.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080053#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090054#include <netutils/ifc.h>
Luke Huangd2861982019-05-17 19:47:28 +080055#include "Fwmark.h"
Nathan Harold21299f72018-03-16 20:13:03 -070056#include "InterfaceController.h"
Luke Huangd2861982019-05-17 19:47:28 +080057#include "NetdClient.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090058#include "NetdConstants.h"
Luke Huang528af602018-08-29 19:06:05 +080059#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070060#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090061#include "android/net/INetd.h"
62#include "binder/IServiceManager.h"
Luke Huang25599322019-06-14 00:34:05 +080063#include "netdutils/InternetAddresses.h"
Mike Yue7e332f2019-03-13 17:15:48 +080064#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070065#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080066#include "netid_client.h" // NETID_UNSET
Lorenzo Colitti758bccc2019-06-26 22:12:35 +090067#include "test_utils.h"
Mike Yu5ae61542018-10-19 22:11:43 +080068#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090069
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090070#define IP6TABLES_PATH "/system/bin/ip6tables"
71#define IPTABLES_PATH "/system/bin/iptables"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090072#define TUN_DEV "/dev/tun"
Luke Huang0051a622018-07-23 20:30:16 +080073#define RAW_TABLE "raw"
74#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080075#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090076#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090077
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090078namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090079
80using android::IBinder;
81using android::IServiceManager;
82using android::sp;
83using android::String16;
84using android::String8;
85using android::base::Join;
Luke Huang531f5d32018-08-03 15:19:05 +080086using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090087using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090088using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080089using android::base::Trim;
Bernie Innocentid26a04a2019-10-30 17:15:15 +090090using android::base::unique_fd;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090091using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080092using android::net::InterfaceConfigurationParcel;
93using android::net::InterfaceController;
Luke Huangcaebcbb2018-09-27 20:37:14 +080094using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +090095using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +090096using android::net::UidRangeParcel;
Luke Huang25599322019-06-14 00:34:05 +080097using android::netdutils::ScopedAddrinfo;
Luke Huangf7782042018-08-08 13:13:04 +080098using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +080099using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +0100100
101static const char* IP_RULE_V4 = "-4";
102static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900103static const int TEST_NETID1 = 65501;
104static const int TEST_NETID2 = 65502;
Chenbo Feng48eaed32018-12-26 17:40:21 -0800105
106// Use maximum reserved appId for applications to avoid conflict with existing
107// uids.
108static const int TEST_UID1 = 99999;
109static const int TEST_UID2 = 99998;
110
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900111constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900112
Benedict Wongb2daefb2017-12-06 22:05:46 -0800113static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
114static const std::string ESP_ALLOW_RULE("esp");
115
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900116class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900117 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900118 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900119 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900120 sp<IBinder> binder = sm->getService(String16("netd"));
121 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900122 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900123 }
124 }
125
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900126 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900127 ASSERT_NE(nullptr, mNetd.get());
128 }
129
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900130 void TearDown() override {
131 mNetd->networkDestroy(TEST_NETID1);
132 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800133 setNetworkForProcess(NETID_UNSET);
134 // Restore default network
135 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900136 }
137
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900138 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700139
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900140 // Static because setting up the tun interface takes about 40ms.
141 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900142 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900143 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900144 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900145 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900146 }
147
148 static void TearDownTestCase() {
149 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900150 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900151 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900152 }
153
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900154 static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
155 unique_fd* acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900156
Luke Huangd2861982019-05-17 19:47:28 +0800157 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
158 int fallthroughNetId = TEST_NETID1);
159
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900160 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800161 // Use -1 to represent that default network was not modified because
162 // real netId must be an unsigned value.
163 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900164 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900165 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900166 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900167};
168
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900169TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900170TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900171
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900172class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900173 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700174 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900175 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900176 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900177 }
178
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900179 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900180 std::string mName;
181};
182
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900183TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900184 TimedOperation t("isAlive RPC");
185 bool isAlive = false;
186 mNetd->isAlive(&isAlive);
187 ASSERT_TRUE(isAlive);
188}
189
Benedict Wongb2daefb2017-12-06 22:05:46 -0800190static bool iptablesNoSocketAllowRuleExists(const char *chainName){
191 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
192 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
193}
194
195static bool iptablesEspAllowRuleExists(const char *chainName){
196 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
197 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
198}
199
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900200TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700201 SKIP_IF_BPF_SUPPORTED;
202
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900203 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
204 const int kNumUids = 500;
205 std::vector<int32_t> noUids(0);
206 std::vector<int32_t> uids(kNumUids);
207 for (int i = 0; i < kNumUids; i++) {
208 uids[i] = randomUid();
209 }
210
211 bool ret;
212 {
213 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900214 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900215 }
216 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800217 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
218 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
219 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
220 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900221 {
222 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900223 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900224 }
225 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900226 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
227 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900228
229 {
230 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900231 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900232 }
233 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900234 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
235 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800236 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
237 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900238
239 {
240 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900241 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900242 }
243 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900244 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
245 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900246
247 // Check that the call fails if iptables returns an error.
248 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900249 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900250 EXPECT_EQ(false, ret);
251}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900252
Benedict Wong319f17e2018-05-15 17:06:44 -0700253TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700254 const struct TestData {
255 const std::string family;
256 const std::string deviceName;
257 const std::string localAddress;
258 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800259 int32_t iKey;
260 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700261 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800262 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700263 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
264 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
265 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800266 };
267
Sehee Park8659b8d2018-11-16 10:53:16 +0900268 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700269 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800270
271 binder::Status status;
272
Benedict Wong319f17e2018-05-15 17:06:44 -0700273 // Create Tunnel Interface.
274 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700275 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800276 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
277
Benedict Wonga450e722018-05-07 10:29:02 -0700278 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900279 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700280
Benedict Wong319f17e2018-05-15 17:06:44 -0700281 // Update Tunnel Interface.
282 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700283 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800284 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
285
Benedict Wong319f17e2018-05-15 17:06:44 -0700286 // Remove Tunnel Interface.
287 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800288 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700289
290 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900291 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800292 }
293}
294
Benedict Wong1cb73df2018-12-03 00:54:14 -0800295TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900296 unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Benedict Wong1cb73df2018-12-03 00:54:14 -0800297 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
298
299 int sockOptVal = UDP_ENCAP_ESPINUDP;
300 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
301
302 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
303 EXPECT_TRUE(res.isOk());
304
305 struct stat info;
306 EXPECT_EQ(0, fstat(sockFd.get(), &info));
307 EXPECT_EQ(1001, (int) info.st_uid);
308}
309
Nathan Harold2deff322018-05-10 14:03:48 -0700310// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
311// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
312#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900313
314using android::net::XfrmController;
315
Benedict Wonga04ffa72018-05-09 21:42:42 -0700316static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
317 static_cast<int>(android::net::XfrmDirection::OUT)};
318static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
319
Nathan Harold21299f72018-03-16 20:13:03 -0700320#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
321 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900322bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900323 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700324 SCOPED_TRACE(status);
325 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
326
327 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700328 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700329 SCOPED_TRACE(status);
330 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
331
332 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700333 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
334 0xD00D, 0xE00D, false)
335 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700336}
337
Benedict Wonga04ffa72018-05-09 21:42:42 -0700338TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900339 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700340
341 // Repeat to ensure cleanup and recreation works correctly
342 for (int i = 0; i < 2; i++) {
343 for (int direction : XFRM_DIRECTIONS) {
344 for (int addrFamily : ADDRESS_FAMILIES) {
345 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700346 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700347 EXPECT_TRUE(status.isOk())
348 << " family: " << addrFamily << " direction: " << direction;
349 }
350 }
351
352 // Cleanup
353 for (int direction : XFRM_DIRECTIONS) {
354 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700355 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700356 EXPECT_TRUE(status.isOk());
357 }
358 }
359 }
360}
361
362TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
363 binder::Status status;
364
365 // Repeat to ensure cleanup and recreation works correctly
366 for (int i = 0; i < 2; i++) {
367 for (int direction : XFRM_DIRECTIONS) {
368 for (int addrFamily : ADDRESS_FAMILIES) {
369 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700370 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700371 EXPECT_TRUE(status.isOk())
372 << " family: " << addrFamily << " direction: " << direction;
373 }
374 }
375
376 // Cleanup
377 for (int direction : XFRM_DIRECTIONS) {
378 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700379 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700380 EXPECT_TRUE(status.isOk());
381 }
382 }
383 }
384}
385
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900386TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900387 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700388 status = XfrmController::Init();
389 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700390
391 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
392 // feature.
393 if (status.code() == EOPNOTSUPP) return;
394
Nathan Harold21299f72018-03-16 20:13:03 -0700395 ASSERT_TRUE(status.ok());
396
397 int32_t spi = 0;
398
399 ASSERT_TRUE(allocateIpSecResources(true, &spi));
400 ASSERT_TRUE(allocateIpSecResources(false, &spi));
401
402 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700403 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700404 ASSERT_TRUE(allocateIpSecResources(true, &spi));
405
406 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700407 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700408 SCOPED_TRACE(status);
409 ASSERT_TRUE(status.ok());
410
Benedict Wonga450e722018-05-07 10:29:02 -0700411 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700412 SCOPED_TRACE(status);
413 ASSERT_TRUE(status.ok());
414
415 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700416 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700417}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900418
419#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700420
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900421static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900422 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900423
424 // Output looks like this:
425 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900426 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900427 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900428 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900429 //
430 // or:
431 //
432 // Chain bw_data_saver (1 references)
433 // target prot opt source destination
434 // ... possibly connectivity critical packet rules here ...
435 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900436
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900437 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900438
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900439 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
440 // Data saver disabled.
441 return 0;
442 }
443
444 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
445
446 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
447 // Data saver enabled.
448 return 1;
449 }
450
451 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900452}
453
454bool enableDataSaver(sp<INetd>& netd, bool enable) {
455 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
456 bool ret;
457 netd->bandwidthEnableDataSaver(enable, &ret);
458 return ret;
459}
460
461int getDataSaverState() {
462 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
463 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
464 EXPECT_EQ(enabled4, enabled6);
465 EXPECT_NE(-1, enabled4);
466 EXPECT_NE(-1, enabled6);
467 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
468 return -1;
469 }
470 return enabled6;
471}
472
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900473TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900474 const int wasEnabled = getDataSaverState();
475 ASSERT_NE(-1, wasEnabled);
476
477 if (wasEnabled) {
478 ASSERT_TRUE(enableDataSaver(mNetd, false));
479 EXPECT_EQ(0, getDataSaverState());
480 }
481
482 ASSERT_TRUE(enableDataSaver(mNetd, false));
483 EXPECT_EQ(0, getDataSaverState());
484
485 ASSERT_TRUE(enableDataSaver(mNetd, true));
486 EXPECT_EQ(1, getDataSaverState());
487
488 ASSERT_TRUE(enableDataSaver(mNetd, true));
489 EXPECT_EQ(1, getDataSaverState());
490
491 if (!wasEnabled) {
492 ASSERT_TRUE(enableDataSaver(mNetd, false));
493 EXPECT_EQ(0, getDataSaverState());
494 }
495}
Robin Leeb8087362016-03-30 18:43:08 +0100496
Luke Huang94658ac2018-10-18 19:35:12 +0900497static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
498 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100499 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100500 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100501 std::vector<std::string> rules = listIpRules(ipVersion);
502
503 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900504 std::string suffix =
505 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900506 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800507 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100508 return true;
509 }
510 }
511 return false;
512}
513
Luke Huang94658ac2018-10-18 19:35:12 +0900514static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
515 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100516 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
517 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
518 EXPECT_EQ(existsIp4, existsIp6);
519 return existsIp4;
520}
521
Luke Huang94658ac2018-10-18 19:35:12 +0900522namespace {
523
524UidRangeParcel makeUidRangeParcel(int start, int stop) {
525 UidRangeParcel res;
526 res.start = start;
527 res.stop = stop;
528
529 return res;
530}
531
532} // namespace
533
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900534TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800535 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
536 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
537 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900538 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
539 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900540
541 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
542 EXPECT_EQ(EBUSY,
543 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
544
545 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
546 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
547 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800548 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900549}
550
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900551TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900552 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
553
cken67cd14c2018-12-05 17:26:59 +0900554 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
555 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900556 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
557
Luke Huang94658ac2018-10-18 19:35:12 +0900558 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
559 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
560 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900561 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
562
563 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
564
565 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
566 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
567 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
568 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
569
570 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
571 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
572 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
573 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
574
575 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
576}
577
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900578TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100579 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100580
Luke Huang94658ac2018-10-18 19:35:12 +0900581 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
582 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800583 // Make sure no rules existed before calling commands.
584 for (auto const& range : uidRanges) {
585 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
586 }
Robin Leeb8087362016-03-30 18:43:08 +0100587 // Create two valid rules.
588 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100589 for (auto const& range : uidRanges) {
590 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
591 }
592
593 // Remove the rules.
594 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100595 for (auto const& range : uidRanges) {
596 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
597 }
598
599 // Fail to remove the rules a second time after they are already deleted.
600 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
601 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
602 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100603}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900604
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900605// Create a socket pair that isLoopbackSocket won't think is local.
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900606void BinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
607 unique_fd* acceptedSocket) {
608 serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900609 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900610 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
611
612 socklen_t addrlen = sizeof(server6);
613 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
614 ASSERT_EQ(0, listen(*serverSocket, 10));
615
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900616 clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900617 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900618 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900619 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
620 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
621
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900622 acceptedSocket->reset(
623 accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900624 ASSERT_NE(-1, *acceptedSocket);
625
626 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
627}
628
629void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
630 char buf[4096];
631 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
632 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
633 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
634}
635
636void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
637 // Check that the client socket was closed with ECONNABORTED.
638 int ret = write(clientSocket, "foo", sizeof("foo"));
639 int err = errno;
640 EXPECT_EQ(-1, ret);
641 EXPECT_EQ(ECONNABORTED, err);
642
643 // Check that it sent a RST to the server.
644 ret = write(acceptedSocket, "foo", sizeof("foo"));
645 err = errno;
646 EXPECT_EQ(-1, ret);
647 EXPECT_EQ(ECONNRESET, err);
648}
649
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900650TEST_F(BinderTest, SocketDestroy) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900651 unique_fd clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900652 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900653
654 // Pick a random UID in the system UID range.
655 constexpr int baseUid = AID_APP - 2000;
656 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
657 int uid = baseUid + 500 + arc4random_uniform(1000);
658 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
659
660 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900661 std::vector<UidRangeParcel> uidRanges = {
662 makeUidRangeParcel(baseUid + 42, baseUid + 449),
663 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
664 makeUidRangeParcel(baseUid + 498, uid - 1),
665 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900666 };
667 // A skip list that doesn't contain UID.
668 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
669
670 // Close sockets. Our test socket should be intact.
671 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
672 checkSocketpairOpen(clientSocket, acceptedSocket);
673
674 // UID ranges that do contain uid.
675 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900676 makeUidRangeParcel(baseUid + 42, baseUid + 449),
677 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
678 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900679 };
680 // Add uid to the skip list.
681 skipUids.push_back(uid);
682
683 // Close sockets. Our test socket should still be intact because it's in the skip list.
684 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
685 checkSocketpairOpen(clientSocket, acceptedSocket);
686
687 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
688 skipUids.resize(skipUids.size() - 1);
689 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
690 checkSocketpairClosed(clientSocket, acceptedSocket);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900691}
Erik Klinecc4f2732016-08-03 11:24:27 +0900692
693namespace {
694
695int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
696 if (buf == nullptr) return -1;
697
698 int prefixLength = 0;
699 bool endOfContiguousBits = false;
700 for (unsigned int i = 0; i < buflen; i++) {
701 const uint8_t value = buf[i];
702
703 // Bad bit sequence: check for a contiguous set of bits from the high
704 // end by verifying that the inverted value + 1 is a power of 2
705 // (power of 2 iff. (v & (v - 1)) == 0).
706 const uint8_t inverse = ~value + 1;
707 if ((inverse & (inverse - 1)) != 0) return -1;
708
709 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
710
711 // Bogus netmask.
712 if (endOfContiguousBits && value != 0) return -1;
713
714 if (value != 0xff) endOfContiguousBits = true;
715 }
716
717 return prefixLength;
718}
719
720template<typename T>
721int netmaskToPrefixLength(const T *p) {
722 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
723}
724
725
726static bool interfaceHasAddress(
727 const std::string &ifname, const char *addrString, int prefixLength) {
728 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900729
730 const struct addrinfo hints = {
731 .ai_flags = AI_NUMERICHOST,
732 .ai_family = AF_UNSPEC,
733 .ai_socktype = SOCK_DGRAM,
734 };
735 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
736 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
737 return false;
738 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900739 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900740
741 struct ifaddrs *ifaddrsList = nullptr;
742 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
743
744 if (getifaddrs(&ifaddrsList) != 0) {
745 return false;
746 }
747
748 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
749 if (std::string(addr->ifa_name) != ifname ||
750 addr->ifa_addr == nullptr ||
751 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
752 continue;
753 }
754
755 switch (addr->ifa_addr->sa_family) {
756 case AF_INET: {
757 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
758 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
759 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
760 continue;
761 }
762
763 if (prefixLength < 0) return true; // not checking prefix lengths
764
765 if (addr->ifa_netmask == nullptr) return false;
766 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
767 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
768 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
769 }
770 case AF_INET6: {
771 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
772 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
773 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
774 continue;
775 }
776
777 if (prefixLength < 0) return true; // not checking prefix lengths
778
779 if (addr->ifa_netmask == nullptr) return false;
780 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
781 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
782 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
783 }
784 default:
785 // Cannot happen because we have already screened for matching
786 // address families at the top of each iteration.
787 continue;
788 }
789 }
790
791 return false;
792}
793
794} // namespace
795
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900796TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900797 static const struct TestData {
798 const char *addrString;
799 const int prefixLength;
Lorenzo Colitti01118982019-12-02 13:19:44 +0900800 const int expectAddResult;
801 const int expectRemoveResult;
Erik Klinecc4f2732016-08-03 11:24:27 +0900802 } kTestData[] = {
Lorenzo Colitti01118982019-12-02 13:19:44 +0900803 {"192.0.2.1", 24, 0, 0},
804 {"192.0.2.2", 25, 0, 0},
805 {"192.0.2.3", 32, 0, 0},
806 {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL},
807 {"192.not.an.ip", 24, EINVAL, EINVAL},
808 {"2001:db8::1", 64, 0, 0},
809 {"2001:db8::2", 65, 0, 0},
810 {"2001:db8::3", 128, 0, 0},
811 {"2001:db8::4", 129, EINVAL, EINVAL},
812 {"foo:bar::bad", 64, EINVAL, EINVAL},
813 {"2001:db8::1/64", 64, EINVAL, EINVAL},
Erik Klinecc4f2732016-08-03 11:24:27 +0900814 };
815
Sehee Park8659b8d2018-11-16 10:53:16 +0900816 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900817 const auto &td = kTestData[i];
818
Lorenzo Colitti01118982019-12-02 13:19:44 +0900819 SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength));
820
Erik Klinecc4f2732016-08-03 11:24:27 +0900821 // [1.a] Add the address.
822 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900823 sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900824 if (td.expectAddResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900825 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
826 } else {
827 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900828 ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900829 }
830
831 // [1.b] Verify the addition meets the expectation.
Lorenzo Colitti01118982019-12-02 13:19:44 +0900832 if (td.expectAddResult == 0) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900833 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900834 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900835 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900836 }
837
838 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900839 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900840 if (td.expectRemoveResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900841 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
842 } else {
843 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900844 ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900845 }
846
847 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900848 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900849 }
Lorenzo Colitti9ae17712019-12-02 17:28:49 +0900850
851 // Check that netlink errors are returned correctly.
852 // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled,
853 // which returns EACCES.
854 TunInterface tun;
855 ASSERT_EQ(0, tun.init());
856 binder::Status status =
857 mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1");
858 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
859 status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64);
860 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
861 EXPECT_EQ(EACCES, status.serviceSpecificErrorCode());
862 tun.destroy();
Erik Klinecc4f2732016-08-03 11:24:27 +0900863}
Erik Kline55b06f82016-07-04 09:57:18 +0900864
Erik Kline38e51f12018-09-06 20:14:44 +0900865TEST_F(BinderTest, GetProcSysNet) {
866 const char LOOPBACK[] = "lo";
867 static const struct {
868 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900869 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900870 const char* ifname;
871 const char* parameter;
872 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900873 const int expectedReturnCode;
874 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900875 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
876 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
877 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
878 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
879 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
880 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
881 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900882 };
883
Sehee Park8659b8d2018-11-16 10:53:16 +0900884 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900885 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900886
Erik Kline38e51f12018-09-06 20:14:44 +0900887 std::string value;
888 const binder::Status status =
889 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
890
891 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900892 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900893 EXPECT_EQ(0, status.exceptionCode());
894 EXPECT_EQ(0, status.serviceSpecificErrorCode());
895 EXPECT_EQ(td.expectedValue, value);
896 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900897 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900898 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
899 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
900 }
901 }
902}
903
904TEST_F(BinderTest, SetProcSysNet) {
905 static const struct {
906 const int ipversion;
907 const int which;
908 const char* ifname;
909 const char* parameter;
910 const char* value;
911 const int expectedReturnCode;
912 } kTestData[] = {
913 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
914 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
915 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
916 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
917 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
918 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
919 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
920 };
921
Sehee Park8659b8d2018-11-16 10:53:16 +0900922 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900923 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900924 const binder::Status status =
925 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900926
927 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900928 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900929 EXPECT_EQ(0, status.exceptionCode());
930 EXPECT_EQ(0, status.serviceSpecificErrorCode());
931 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900932 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900933 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
934 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
935 }
936 }
937}
Ben Schwartze7601812017-04-28 16:38:29 -0400938
Erik Kline38e51f12018-09-06 20:14:44 +0900939TEST_F(BinderTest, GetSetProcSysNet) {
940 const int ipversion = INetd::IPV6;
941 const int category = INetd::NEIGH;
942 const std::string& tun = sTun.name();
943 const std::string parameter("ucast_solicit");
944
945 std::string value{};
946 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700947 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900948 const int ival = std::stoi(value);
949 EXPECT_GT(ival, 0);
950 // Try doubling the parameter value (always best!).
951 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
952 .isOk());
953 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
954 EXPECT_EQ(2 * ival, std::stoi(value));
955 // Try resetting the parameter.
956 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
957 .isOk());
958 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
959 EXPECT_EQ(ival, std::stoi(value));
960}
961
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900962namespace {
963
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900964void expectNoTestCounterRules() {
965 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
966 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
967 std::string allRules = Join(runCommand(command), "\n");
968 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
969 }
970}
971
Bernie Innocentif6918262018-06-11 17:37:35 +0900972void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
973 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900974 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
975 path, if1.c_str(), if2.c_str(), pkt, byte));
976}
977
Bernie Innocentif6918262018-06-11 17:37:35 +0900978void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900979 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
980 path, if1.c_str(), if2.c_str()));
981 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
982 path, if2.c_str(), if1.c_str()));
983}
984
Luke Huangcaebcbb2018-09-27 20:37:14 +0800985std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
986 const std::string& iface) {
987 for (auto& stats : statsVec) {
988 if (stats.iface == iface) {
989 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
990 }
991 }
992 return {};
993}
994
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900995} // namespace
996
997TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900998 expectNoTestCounterRules();
999
1000 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1001 // disabling tethering. We don't check the return value because these commands will fail if
1002 // tethering is already enabled.
1003 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1004 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1005
1006 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1007 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1008 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001009
1010 // Ensure we won't use the same interface name, otherwise the test will fail.
1011 u_int32_t rNumber = arc4random_uniform(10000);
1012 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1013 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001014
1015 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1016 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1017 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1018 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1019 // RX is from external to internal, and TX is from internal to external.
1020 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1021 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1022
1023 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1024 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1025
1026 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1027 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1028
1029 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1030 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1031 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1032
Luke Huangcaebcbb2018-09-27 20:37:14 +08001033 std::vector<TetherStatsParcel> statsVec;
1034 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001035 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1036
Luke Huangcaebcbb2018-09-27 20:37:14 +08001037 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001038
Luke Huangcaebcbb2018-09-27 20:37:14 +08001039 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001040
1041 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1042 delTetherCounterValues(path, intIface1, extIface1);
1043 delTetherCounterValues(path, intIface2, extIface2);
1044 if (path == IP6TABLES_PATH) {
1045 delTetherCounterValues(path, intIface3, extIface2);
1046 }
1047 }
1048
1049 expectNoTestCounterRules();
1050}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001051
Luke Huang0051a622018-07-23 20:30:16 +08001052namespace {
1053
Luke Huanga5211072018-08-01 23:36:29 +08001054constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1055constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001056
1057static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1058 const char* chainName) {
1059 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1060 return runCommand(command);
1061}
1062
Luke Huang19b49c52018-10-22 12:12:05 +09001063// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001064bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001065 const std::string& expectedInterface,
1066 const std::string& expectedRule, const char* table) {
1067 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1068 for (const auto& rule : rules) {
1069 if (rule.find(expectedInterface) != std::string::npos) {
1070 if (rule.find(expectedRule) != std::string::npos) {
1071 return true;
1072 }
1073 }
1074 }
1075 return false;
1076}
1077
1078void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001079 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001080 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001081 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001082 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001083 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1084 IdletimerRule, RAW_TABLE));
1085 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001086 ifname, IdletimerRule, MANGLE_TABLE));
1087 }
1088}
1089
1090void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001091 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001092 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001093 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001094 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001095 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1096 IdletimerRule, RAW_TABLE));
1097 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001098 ifname, IdletimerRule, MANGLE_TABLE));
1099 }
1100}
1101
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001102} // namespace
1103
1104TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001105 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1106 // rule in the table. Because we only check the result after calling remove function. We might
1107 // check the actual rule which is removed by our function (maybe compare the results between
1108 // calling function before and after)
1109 binder::Status status;
1110 const struct TestData {
1111 const std::string ifname;
1112 int32_t timeout;
1113 const std::string classLabel;
1114 } idleTestData[] = {
1115 {"wlan0", 1234, "happyday"},
1116 {"rmnet_data0", 4567, "friday"},
1117 };
1118 for (const auto& td : idleTestData) {
1119 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1120 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1121 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1122
1123 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1124 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1125 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1126 }
1127}
1128
Luke Huanga67dd562018-07-17 19:58:25 +08001129namespace {
1130
1131constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1132constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1133
1134void expectStrictSetUidAccept(const int uid) {
1135 std::string uidRule = StringPrintf("owner UID match %u", uid);
1136 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1137 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001138 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1139 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001140 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1141 }
1142}
1143
1144void expectStrictSetUidLog(const int uid) {
1145 static const char logRule[] = "st_penalty_log all";
1146 std::string uidRule = StringPrintf("owner UID match %u", uid);
1147 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1148 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001149 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1150 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001151 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1152 }
1153}
1154
1155void expectStrictSetUidReject(const int uid) {
1156 static const char rejectRule[] = "st_penalty_reject all";
1157 std::string uidRule = StringPrintf("owner UID match %u", uid);
1158 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1159 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001160 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1161 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001162 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1163 }
1164}
1165
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001166} // namespace
1167
1168TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001169 binder::Status status;
1170 int32_t uid = randomUid();
1171
1172 // setUidCleartextPenalty Policy:Log with randomUid
1173 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1174 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1175 expectStrictSetUidLog(uid);
1176
1177 // setUidCleartextPenalty Policy:Accept with randomUid
1178 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1179 expectStrictSetUidAccept(uid);
1180
1181 // setUidCleartextPenalty Policy:Reject with randomUid
1182 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1183 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1184 expectStrictSetUidReject(uid);
1185
1186 // setUidCleartextPenalty Policy:Accept with randomUid
1187 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1188 expectStrictSetUidAccept(uid);
1189
1190 // test wrong policy
1191 int32_t wrongPolicy = -123;
1192 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1193 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1194}
1195
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001196namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001197
Luke Huangd1675922019-03-11 17:29:27 +08001198std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001199 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001200 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001201 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1202 // ...
1203 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1204
Luke Huangd1675922019-03-11 17:29:27 +08001205 // (dnsmasq)
1206 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1207
1208 if (maxTries == 0) return {};
1209
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001210 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001211 std::vector<std::string> result;
1212 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001213 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001214 if (result.size() || ++run > maxTries) {
1215 break;
1216 }
1217
Luke Huang728cf4c2019-03-14 19:43:02 +08001218 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001219 }
1220 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001221}
1222
Luke Huangd1675922019-03-11 17:29:27 +08001223void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001224 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001225}
1226
Luke Huang728cf4c2019-03-14 19:43:02 +08001227void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001228 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001229}
1230
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001231} // namespace
1232
1233TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001234 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001235
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001236 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1237 std::string clatAddress;
1238 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001239
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001240 // Can't start clatd on an interface that's not part of any network...
1241 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1242 EXPECT_FALSE(status.isOk());
1243 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1244
1245 // ... so create a test physical network and add our tun to it.
1246 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1247 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1248
1249 // Prefix must be 96 bits long.
1250 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1251 EXPECT_FALSE(status.isOk());
1252 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1253
1254 // Can't start clatd unless there's a default route...
1255 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1256 EXPECT_FALSE(status.isOk());
1257 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1258
1259 // so add a default route.
1260 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1261
1262 // Can't start clatd unless there's a global address...
1263 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1264 EXPECT_FALSE(status.isOk());
1265 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1266
1267 // ... so add a global address.
1268 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001269 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001270
1271 // Now expect clatd to start successfully.
1272 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1273 EXPECT_TRUE(status.isOk());
1274 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1275
1276 // Starting it again returns EBUSY.
1277 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1278 EXPECT_FALSE(status.isOk());
1279 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1280
Luke Huangd1675922019-03-11 17:29:27 +08001281 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001282
1283 // Expect clatd to stop successfully.
1284 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001285 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001286 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001287
1288 // Stopping a clatd that doesn't exist returns ENODEV.
1289 status = mNetd->clatdStop(sTun.name());
1290 EXPECT_FALSE(status.isOk());
1291 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001292 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001293
1294 // Clean up.
1295 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1296 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1297 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001298}
Luke Huang457d4702018-08-16 15:39:15 +08001299
1300namespace {
1301
1302bool getIpfwdV4Enable() {
1303 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1304 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1305 EXPECT_TRUE(!result.empty());
1306 int v4Enable = std::stoi(result[0]);
1307 return v4Enable;
1308}
1309
1310bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001311 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001312 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1313 EXPECT_TRUE(!result.empty());
1314 int v6Enable = std::stoi(result[0]);
1315 return v6Enable;
1316}
1317
1318void expectIpfwdEnable(bool enable) {
1319 int enableIPv4 = getIpfwdV4Enable();
1320 int enableIPv6 = getIpfwdV6Enable();
1321 EXPECT_EQ(enable, enableIPv4);
1322 EXPECT_EQ(enable, enableIPv6);
1323}
1324
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001325bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001326 std::vector<std::string> rules = listIpRules(ipVersion);
1327 for (const auto& rule : rules) {
1328 if (rule.find(ipfwdRule) != std::string::npos) {
1329 return true;
1330 }
1331 }
1332 return false;
1333}
1334
1335void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1336 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1337
1338 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1339 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1340 }
1341}
1342
1343void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1344 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1345
1346 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1347 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1348 }
1349}
1350
1351} // namespace
1352
1353TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001354 // Get ipfwd requester list from Netd
1355 std::vector<std::string> requesterList;
1356 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001357 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001358
1359 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001360 if (requesterList.size() == 0) {
1361 // No requester in Netd, ipfwd should be disabled
1362 // So add one test requester and verify
1363 status = mNetd->ipfwdEnableForwarding("TestRequester");
1364 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001365
Luke Huang728cf4c2019-03-14 19:43:02 +08001366 expectIpfwdEnable(true);
1367 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1368 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1369 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001370
Luke Huang728cf4c2019-03-14 19:43:02 +08001371 // Remove test one, verify again
1372 status = mNetd->ipfwdDisableForwarding("TestRequester");
1373 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1374
1375 expectIpfwdEnable(false);
1376 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1377 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1378 EXPECT_FALSE(ipfwdEnabled);
1379 } else {
1380 // Disable all requesters
1381 for (const auto& requester : requesterList) {
1382 status = mNetd->ipfwdDisableForwarding(requester);
1383 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1384 }
1385
1386 // After disable all requester, ipfwd should be disabled
1387 expectIpfwdEnable(false);
1388 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1389 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1390 EXPECT_FALSE(ipfwdEnabled);
1391
1392 // Enable them back
1393 for (const auto& requester : requesterList) {
1394 status = mNetd->ipfwdEnableForwarding(requester);
1395 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1396 }
1397
1398 // ipfwd should be enabled
1399 expectIpfwdEnable(true);
1400 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1401 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1402 EXPECT_TRUE(ipfwdEnabled);
1403 }
Luke Huang457d4702018-08-16 15:39:15 +08001404}
1405
1406TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001407 // Add test physical network
1408 EXPECT_TRUE(
1409 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1410 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1411 EXPECT_TRUE(
1412 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1413 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001414
Luke Huangd1827b82019-02-15 15:03:27 +08001415 binder::Status status =
1416 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1417 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1418 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001419
Luke Huangd1827b82019-02-15 15:03:27 +08001420 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1421 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1422 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001423}
Luke Huang531f5d32018-08-03 15:19:05 +08001424
1425namespace {
1426
1427constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1428constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1429constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1430constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1431constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001432constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001433
Luke Huang19b49c52018-10-22 12:12:05 +09001434// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1435// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001436bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1437 const char* chainName, const std::string& expectedTargetA,
1438 const std::string& expectedTargetB) {
1439 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1440 int matchCount = 0;
1441
1442 for (const auto& rule : rules) {
1443 if (rule.find(expectedTargetA) != std::string::npos) {
1444 if (rule.find(expectedTargetB) != std::string::npos) {
1445 matchCount++;
1446 }
1447 }
1448 }
1449 return matchCount == expectedCount;
1450}
1451
1452void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1453 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1454 std::string result = "";
1455
1456 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001457 // Quota value might be decreased while matching packets
1458 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001459}
1460
1461void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1462 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1463 std::string quotaRule = StringPrintf("quota %s", ifname);
1464
1465 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1466 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1467 BANDWIDTH_COSTLY_IF));
1468 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1469 BANDWIDTH_COSTLY_IF));
1470 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1471 BANDWIDTH_COSTLY_IF));
1472 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1473 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1474 }
1475 expectXtQuotaValueEqual(ifname, quotaBytes);
1476}
1477
1478void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1479 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1480 std::string quotaRule = StringPrintf("quota %s", ifname);
1481
1482 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1483 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1484 BANDWIDTH_COSTLY_IF));
1485 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1486 BANDWIDTH_COSTLY_IF));
1487 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1488 BANDWIDTH_COSTLY_IF));
1489 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1490 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1491 }
1492}
1493
1494void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1495 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1496 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1497 std::string alertName = StringPrintf("%sAlert", ifname);
1498
1499 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1500 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1501 }
1502 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1503}
1504
1505void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1506 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1507 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1508
1509 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1510 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1511 }
1512}
1513
1514void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1515 static const char globalAlertRule[] = "quota globalAlert";
1516 static const char globalAlertName[] = "globalAlert";
1517
1518 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001519 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001520 }
1521 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1522}
1523
1524void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1525 std::string uidRule = StringPrintf("owner UID match %u", uid);
1526
1527 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1528 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1529 }
1530}
1531
1532void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1533 std::string uidRule = StringPrintf("owner UID match %u", uid);
1534
1535 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1536 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1537 }
1538}
1539
1540} // namespace
1541
1542TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1543 long testQuotaBytes = 5550;
1544
1545 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001546 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001547 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1548
1549 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1550 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1551 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1552
1553 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1554 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1555 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1556
1557 // Remove test physical network
1558 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1559}
1560
1561TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1562 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001563 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001564 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001565 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001566 // Need to have a prior interface quota set to set an alert
1567 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1568 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1569 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1570 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1571
1572 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1573 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1574 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1575
1576 // Remove interface quota
1577 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1578 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1579 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1580
1581 // Remove test physical network
1582 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1583}
1584
1585TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001586 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001587
1588 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1589 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1590 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1591
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001592 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001593 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1594 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1595 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1596}
1597
1598TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1599 SKIP_IF_BPF_SUPPORTED;
1600
1601 int32_t uid = randomUid();
1602 static const char targetReject[] = "REJECT";
1603 static const char targetReturn[] = "RETURN";
1604
1605 // add NaughtyApp
1606 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1607 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1608 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1609
1610 // remove NaughtyApp
1611 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1612 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1613 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1614
1615 // add NiceApp
1616 status = mNetd->bandwidthAddNiceApp(uid);
1617 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1618 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1619
1620 // remove NiceApp
1621 status = mNetd->bandwidthRemoveNiceApp(uid);
1622 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1623 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1624}
Luke Huangb5733d72018-08-21 17:17:19 +08001625
1626namespace {
1627
Luke Huangc3252cc2018-10-16 15:43:23 +08001628std::string ipRouteString(const std::string& ifName, const std::string& dst,
1629 const std::string& nextHop) {
1630 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1631
1632 if (!nextHop.empty()) {
1633 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001634 }
1635
Luke Huangc3252cc2018-10-16 15:43:23 +08001636 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001637}
1638
Luke Huangc3252cc2018-10-16 15:43:23 +08001639void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1640 const std::string& dst, const std::string& nextHop,
1641 const char* table) {
1642 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1643}
1644
1645void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001646 const std::string& dst, const std::string& nextHop,
1647 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001648 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001649}
1650
1651bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1652 std::vector<std::string> rules = listIpRules(ipVersion);
1653 for (const auto& rule : rules) {
1654 if (rule.find(ipRule) != std::string::npos) {
1655 return true;
1656 }
1657 }
1658 return false;
1659}
1660
1661void expectNetworkDefaultIpRuleExists(const char* ifName) {
1662 std::string networkDefaultRule =
1663 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1664
1665 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1666 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1667 }
1668}
1669
1670void expectNetworkDefaultIpRuleDoesNotExist() {
1671 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1672
1673 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1674 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1675 }
1676}
1677
1678void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1679 std::string networkPermissionRule = "";
1680 switch (permission) {
1681 case INetd::PERMISSION_NONE:
1682 networkPermissionRule = StringPrintf(
1683 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1684 break;
1685 case INetd::PERMISSION_NETWORK:
1686 networkPermissionRule = StringPrintf(
1687 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1688 break;
1689 case INetd::PERMISSION_SYSTEM:
1690 networkPermissionRule = StringPrintf(
1691 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1692 break;
1693 }
1694
1695 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1696 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1697 }
1698}
1699
1700// TODO: It is a duplicate function, need to remove it
1701bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1702 const std::string& expectedInterface,
1703 const std::string& expectedRule,
1704 const char* table) {
1705 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1706 for (const auto& rule : rules) {
1707 if (rule.find(expectedInterface) != std::string::npos) {
1708 if (rule.find(expectedRule) != std::string::npos) {
1709 return true;
1710 }
1711 }
1712 }
1713 return false;
1714}
1715
1716void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1717 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1718 std::string networkIncomingPacketMarkRule = "";
1719 switch (permission) {
1720 case INetd::PERMISSION_NONE:
1721 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1722 break;
1723 case INetd::PERMISSION_NETWORK:
1724 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1725 break;
1726 case INetd::PERMISSION_SYSTEM:
1727 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1728 break;
1729 }
1730
1731 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1732 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1733 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1734 }
1735}
1736
1737} // namespace
1738
1739TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001740 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001741 const char* ipVersion;
1742 const char* testDest;
1743 const char* testNextHop;
1744 const bool expectSuccess;
1745 } kTestData[] = {
1746 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001747 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1748 {IP_RULE_V4, "10.251.0.0/16", "", true},
1749 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1750 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001751 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001752 {IP_RULE_V6, "::/0", "2001:db8::", true},
1753 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001754 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1755 };
1756
Luke Huangc3252cc2018-10-16 15:43:23 +08001757 static const struct {
1758 const char* ipVersion;
1759 const char* testDest;
1760 const char* testNextHop;
1761 } kTestDataWithNextHop[] = {
1762 {IP_RULE_V4, "10.251.10.0/30", ""},
1763 {IP_RULE_V6, "2001:db8::/32", ""},
1764 };
1765
Luke Huangb670d162018-08-23 20:01:13 +08001766 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001767 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001768 const int testUid = randomUid();
1769 const std::vector<int32_t> testUids = {testUid};
1770
1771 // Add test physical network
1772 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1773 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1774
Luke Huangc3252cc2018-10-16 15:43:23 +08001775 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001776 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001777 const auto& td = kTestDataWithNextHop[i];
1778
1779 // All route for test tun will disappear once the tun interface is deleted.
1780 binder::Status status =
1781 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1782 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1783 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1784 sTun.name().c_str());
1785
1786 // Add system permission for test uid, setup route in legacy system table.
1787 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1788
1789 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1790 testUid);
1791 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1792 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1793 testTableLegacySystem);
1794
1795 // Remove system permission for test uid, setup route in legacy network table.
1796 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1797
1798 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1799 testUid);
1800 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1801 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1802 testTableLegacyNetwork);
1803 }
1804
Sehee Park8659b8d2018-11-16 10:53:16 +09001805 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001806 const auto& td = kTestData[i];
1807
1808 binder::Status status =
1809 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1810 if (td.expectSuccess) {
1811 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001812 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001813 sTun.name().c_str());
1814 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001815 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1816 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001817 }
1818
1819 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1820 if (td.expectSuccess) {
1821 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001822 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1823 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001824 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001825 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1826 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001827 }
1828
Luke Huangc3252cc2018-10-16 15:43:23 +08001829 // Add system permission for test uid, route will be added into legacy system table.
1830 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001831
1832 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1833 testUid);
1834 if (td.expectSuccess) {
1835 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001836 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001837 testTableLegacySystem);
1838 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001839 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1840 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001841 }
1842
1843 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1844 td.testNextHop, testUid);
1845 if (td.expectSuccess) {
1846 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001847 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1848 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001849 } 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
Luke Huangc3252cc2018-10-16 15:43:23 +08001854 // Remove system permission for test uid, route will be added into legacy network table.
1855 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1856
1857 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1858 testUid);
1859 if (td.expectSuccess) {
1860 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1861 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1862 testTableLegacyNetwork);
1863 } else {
1864 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1865 EXPECT_NE(0, status.serviceSpecificErrorCode());
1866 }
1867
1868 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1869 td.testNextHop, testUid);
1870 if (td.expectSuccess) {
1871 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1872 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1873 testTableLegacyNetwork);
1874 } else {
1875 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1876 EXPECT_NE(0, status.serviceSpecificErrorCode());
1877 }
Luke Huangb670d162018-08-23 20:01:13 +08001878 }
1879
1880 // Remove test physical network
1881 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1882}
1883
1884TEST_F(BinderTest, NetworkPermissionDefault) {
1885 // Add test physical network
1886 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1887 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1888
Luke Huangc3252cc2018-10-16 15:43:23 +08001889 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001890 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1891 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001892
1893 // Test SetDefault
1894 status = mNetd->networkSetDefault(TEST_NETID1);
1895 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1896 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1897
1898 status = mNetd->networkClearDefault();
1899 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1900 expectNetworkDefaultIpRuleDoesNotExist();
1901
Luke Huangd2861982019-05-17 19:47:28 +08001902 // Set default network back
1903 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001904 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1905
1906 // Test SetPermission
1907 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1908 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1909 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1910 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1911
1912 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1913 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1914 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1915 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1916
1917 // Remove test physical network
1918 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1919}
1920
1921TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001922 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001923 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1924 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001925 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001926 EXPECT_TRUE(ret);
1927
Luke Huang854e2992019-05-29 16:42:48 +08001928 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001929 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08001930
1931 // Clear uid permission before calling networkCanProtect to ensure
1932 // the call won't be affected by uid permission.
1933 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
1934
1935 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001936 EXPECT_FALSE(ret);
1937}
1938
1939namespace {
1940
Luke Huangb5733d72018-08-21 17:17:19 +08001941int readIntFromPath(const std::string& path) {
1942 std::string result = "";
1943 EXPECT_TRUE(ReadFileToString(path, &result));
1944 return std::stoi(result);
1945}
1946
1947int getTetherAcceptIPv6Ra(const std::string& ifName) {
1948 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1949 return readIntFromPath(path);
1950}
1951
1952bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1953 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1954 return readIntFromPath(path);
1955}
1956
1957int getTetherIPv6DadTransmits(const std::string& ifName) {
1958 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1959 return readIntFromPath(path);
1960}
1961
1962bool getTetherEnableIPv6(const std::string& ifName) {
1963 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1964 int disableIPv6 = readIntFromPath(path);
1965 return !disableIPv6;
1966}
1967
1968bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1969 for (const auto& iface : ifList) {
1970 if (iface == ifName) {
1971 return true;
1972 }
1973 }
1974 return false;
1975}
1976
1977void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1978 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1979 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1980 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1981 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1982}
1983
1984void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1985 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1986 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1987 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1988 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1989}
1990
1991void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1992 const std::string& ifName) {
1993 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1994}
1995
1996void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1997 const std::string& ifName) {
1998 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1999}
2000
2001void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2002 const std::vector<std::string>& testDnsAddrs) {
2003 EXPECT_TRUE(dnsList == testDnsAddrs);
2004}
2005
2006} // namespace
2007
2008TEST_F(BinderTest, TetherStartStopStatus) {
2009 std::vector<std::string> noDhcpRange = {};
2010 static const char dnsdName[] = "dnsmasq";
2011
Luke Huang91bd3e12019-08-20 11:33:52 +08002012 for (bool usingLegacyDnsProxy : {true, false}) {
2013 binder::Status status =
2014 mNetd->tetherStartWithConfiguration(usingLegacyDnsProxy, noDhcpRange);
2015 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2016 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2017 if (usingLegacyDnsProxy == true) {
2018 expectProcessExists(dnsdName);
2019 } else {
2020 expectProcessDoesNotExist(dnsdName);
2021 }
Luke Huangb5733d72018-08-21 17:17:19 +08002022
Luke Huang91bd3e12019-08-20 11:33:52 +08002023 bool tetherEnabled;
2024 status = mNetd->tetherIsEnabled(&tetherEnabled);
2025 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2026 EXPECT_TRUE(tetherEnabled);
Luke Huangb5733d72018-08-21 17:17:19 +08002027
Luke Huang91bd3e12019-08-20 11:33:52 +08002028 status = mNetd->tetherStop();
2029 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2030 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002031
Luke Huang91bd3e12019-08-20 11:33:52 +08002032 status = mNetd->tetherIsEnabled(&tetherEnabled);
2033 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2034 EXPECT_FALSE(tetherEnabled);
2035 }
Luke Huangb5733d72018-08-21 17:17:19 +08002036}
2037
2038TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2039 // TODO: verify if dnsmasq update interface successfully
2040
2041 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2042 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2043 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2044
2045 std::vector<std::string> ifList;
2046 status = mNetd->tetherInterfaceList(&ifList);
2047 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2048 expectTetherInterfaceExists(ifList, sTun.name());
2049
2050 status = mNetd->tetherInterfaceRemove(sTun.name());
2051 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2052 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2053
2054 status = mNetd->tetherInterfaceList(&ifList);
2055 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2056 expectTetherInterfaceNotExists(ifList, sTun.name());
2057}
2058
2059TEST_F(BinderTest, TetherDnsSetList) {
2060 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002061 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2062 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002063
2064 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2065 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2066
2067 std::vector<std::string> dnsList;
2068 status = mNetd->tetherDnsList(&dnsList);
2069 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2070 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002071}
2072
2073namespace {
2074
2075constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2076constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2077constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2078constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2079constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2080constexpr char FIREWALL_STANDBY[] = "fw_standby";
2081constexpr char targetReturn[] = "RETURN";
2082constexpr char targetDrop[] = "DROP";
2083
2084void expectFirewallWhitelistMode() {
2085 static const char dropRule[] = "DROP all";
2086 static const char rejectRule[] = "REJECT all";
2087 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2088 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2089 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2090 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2091 }
2092}
2093
2094void expectFirewallBlacklistMode() {
2095 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2096 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2097 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2098 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2099 }
2100}
2101
2102bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2103 const std::string& expectedInterface,
2104 const std::string& expectedRule) {
2105 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2106 // Expected rule:
2107 // Chain fw_INPUT (1 references)
2108 // pkts bytes target prot opt in out source destination
2109 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2110 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2111 int firstRuleIndex = 2;
2112 if (rules.size() < 4) return false;
2113 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2114 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2115 return true;
2116 }
2117 }
2118 return false;
2119}
2120
2121// TODO: It is a duplicate function, need to remove it
2122bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2123 const std::string& expectedInterface,
2124 const std::string& expectedRule) {
2125 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2126 for (const auto& rule : rules) {
2127 if (rule.find(expectedInterface) != std::string::npos) {
2128 if (rule.find(expectedRule) != std::string::npos) {
2129 return true;
2130 }
2131 }
2132 }
2133 return false;
2134}
2135
2136void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2137 static const char returnRule[] = "RETURN all";
2138 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2139 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2140 returnRule));
2141 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2142 returnRule));
2143 }
2144}
2145
2146void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2147 static const char returnRule[] = "RETURN all";
2148 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2149 EXPECT_FALSE(
2150 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2151 EXPECT_FALSE(
2152 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2153 }
2154}
2155
2156bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2157 const std::string& expectedTarget,
2158 const std::string& expectedRule) {
2159 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2160 int firstRuleIndex = 2;
2161 if (rules.size() < 4) return false;
2162 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2163 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2164 return true;
2165 }
2166 }
2167 return false;
2168}
2169
2170bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2171 const std::string& expectedTarget,
2172 const std::string& expectedRule) {
2173 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2174 int lastRuleIndex = rules.size() - 1;
2175 if (lastRuleIndex < 0) return false;
2176 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2177 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2178 return true;
2179 }
2180 }
2181 return false;
2182}
2183
2184void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2185 std::string uidRule = StringPrintf("owner UID match %u", uid);
2186 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2187 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2188}
2189
2190void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2191 std::string uidRule = StringPrintf("owner UID match %u", uid);
2192 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2193 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2194}
2195
2196void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2197 std::string uidRule = StringPrintf("owner UID match %u", uid);
2198 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2199 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2200}
2201
2202void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2203 std::string uidRule = StringPrintf("owner UID match %u", uid);
2204 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2205 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2206}
2207
2208bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2209 std::vector<std::string> inputRules =
2210 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2211 std::vector<std::string> outputRules =
2212 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2213 int inputLastRuleIndex = inputRules.size() - 1;
2214 int outputLastRuleIndex = outputRules.size() - 1;
2215
2216 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2217 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2218 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2219 return true;
2220 }
2221 }
2222 return false;
2223}
2224
2225void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2226 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2227 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2228}
2229
2230void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2231 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2232 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2233 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2234 }
2235}
2236
2237} // namespace
2238
2239TEST_F(BinderTest, FirewallSetFirewallType) {
2240 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2241 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2242 expectFirewallWhitelistMode();
2243
2244 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2245 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2246 expectFirewallBlacklistMode();
2247
2248 // set firewall type blacklist twice
2249 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2250 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2251 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2252 expectFirewallBlacklistMode();
2253
2254 // set firewall type whitelist twice
2255 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2256 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2257 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2258 expectFirewallWhitelistMode();
2259
2260 // reset firewall type to default
2261 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2262 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2263 expectFirewallBlacklistMode();
2264}
2265
2266TEST_F(BinderTest, FirewallSetInterfaceRule) {
2267 // setinterfaceRule is not supported in BLACKLIST MODE
2268 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2269 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2270
2271 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2272 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2273
2274 // set WHITELIST mode first
2275 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2276 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2277
2278 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2279 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2280 expectFirewallInterfaceRuleAllowExists(sTun.name());
2281
2282 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2283 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2284 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2285
2286 // reset firewall mode to default
2287 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2288 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2289 expectFirewallBlacklistMode();
2290}
2291
2292TEST_F(BinderTest, FirewallSetUidRule) {
2293 SKIP_IF_BPF_SUPPORTED;
2294
2295 int32_t uid = randomUid();
2296
2297 // Doze allow
2298 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2299 INetd::FIREWALL_RULE_ALLOW);
2300 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2301 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2302
2303 // Doze deny
2304 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2305 INetd::FIREWALL_RULE_DENY);
2306 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2307 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2308
2309 // Powersave allow
2310 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2311 INetd::FIREWALL_RULE_ALLOW);
2312 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2313 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2314
2315 // Powersave deny
2316 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2317 INetd::FIREWALL_RULE_DENY);
2318 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2319 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2320
2321 // Standby deny
2322 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2323 INetd::FIREWALL_RULE_DENY);
2324 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2325 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2326
2327 // Standby allow
2328 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2329 INetd::FIREWALL_RULE_ALLOW);
2330 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2331 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2332
2333 // None deny in BLACKLIST
2334 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2335 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2336 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2337 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2338
2339 // None allow in BLACKLIST
2340 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2341 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2342 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2343 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2344
2345 // set firewall type whitelist twice
2346 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2347 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2348 expectFirewallWhitelistMode();
2349
2350 // None allow in WHITELIST
2351 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2352 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2353 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2354 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2355
2356 // None deny in WHITELIST
2357 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2358 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2359 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2360 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2361
2362 // reset firewall mode to default
2363 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2364 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2365 expectFirewallBlacklistMode();
2366}
2367
2368TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2369 SKIP_IF_BPF_SUPPORTED;
2370
2371 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2372 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2373 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2374
2375 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2376 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2377 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2378
2379 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2381 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2382
2383 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2384 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2385 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2386
2387 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2388 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2389 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2390
2391 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2392 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2393 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2394}
Luke Huangf7782042018-08-08 13:13:04 +08002395
2396namespace {
2397
2398std::string hwAddrToStr(unsigned char* hwaddr) {
2399 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2400 hwaddr[4], hwaddr[5]);
2401}
2402
2403int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2404 int prefixLength = 0;
2405 uint32_t m = ntohl(mask);
2406 while (m & (1 << 31)) {
2407 prefixLength++;
2408 m = m << 1;
2409 }
2410 return prefixLength;
2411}
2412
2413std::string toStdString(const String16& s) {
2414 return std::string(String8(s.string()));
2415}
2416
2417android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2418 const auto& sys = sSyscalls.get();
2419 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2420 EXPECT_TRUE(isOk(fd.status()));
2421
2422 struct ifreq ifr = {};
2423 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2424
2425 return sys.ioctl(fd.value(), flag, &ifr);
2426}
2427
2428std::string getInterfaceHwAddr(const std::string& ifName) {
2429 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2430
2431 unsigned char hwaddr[ETH_ALEN] = {};
2432 if (isOk(res.status())) {
2433 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2434 }
2435
2436 return hwAddrToStr(hwaddr);
2437}
2438
2439int getInterfaceIPv4Prefix(const std::string& ifName) {
2440 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2441
2442 int prefixLength = 0;
2443 if (isOk(res.status())) {
2444 prefixLength = ipv4NetmaskToPrefixLength(
2445 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2446 }
2447
2448 return prefixLength;
2449}
2450
2451std::string getInterfaceIPv4Addr(const std::string& ifName) {
2452 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2453
2454 struct in_addr addr = {};
2455 if (isOk(res.status())) {
2456 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2457 }
2458
2459 return std::string(inet_ntoa(addr));
2460}
2461
2462std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2463 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2464
2465 unsigned flags = 0;
2466 if (isOk(res.status())) {
2467 flags = res.value().ifr_flags;
2468 }
2469
2470 std::vector<std::string> ifFlags;
2471 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2472 : toStdString(INetd::IF_STATE_DOWN()));
2473
2474 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2475 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2476 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2477 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2478 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2479
2480 return ifFlags;
2481}
2482
2483bool compareListInterface(const std::vector<std::string>& interfaceList) {
2484 const auto& res = InterfaceController::getIfaceNames();
2485 EXPECT_TRUE(isOk(res));
2486
2487 std::vector<std::string> resIfList;
2488 resIfList.reserve(res.value().size());
2489 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2490
2491 return resIfList == interfaceList;
2492}
2493
2494int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2495 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2496 return readIntFromPath(path);
2497}
2498
2499bool getInterfaceEnableIPv6(const std::string& ifName) {
2500 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2501
2502 int disableIPv6 = readIntFromPath(path);
2503 return !disableIPv6;
2504}
2505
2506int getInterfaceMtu(const std::string& ifName) {
2507 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2508 return readIntFromPath(path);
2509}
2510
2511void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2512 EXPECT_TRUE(compareListInterface(interfaceList));
2513}
2514
2515void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2516 const InterfaceConfigurationParcel& interfaceCfg) {
2517 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2518 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2519 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2520 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2521}
2522
2523void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2524 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2525 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2526
2527 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2528 for (const auto& flag : setCfg.flags) {
2529 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2530 }
2531}
2532
2533void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2534 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2535 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2536}
2537
2538void expectInterfaceNoAddr(const std::string& ifName) {
2539 // noAddr
2540 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2541 // noPrefix
2542 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2543}
2544
2545void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2546 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2547 EXPECT_EQ(enableIPv6, enable);
2548}
2549
2550void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2551 int mtuSize = getInterfaceMtu(ifName);
2552 EXPECT_EQ(mtu, mtuSize);
2553}
2554
2555InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2556 const std::string& addr, int prefixLength,
2557 const std::vector<std::string>& flags) {
2558 InterfaceConfigurationParcel cfg;
2559 cfg.ifName = ifName;
2560 cfg.hwAddr = "";
2561 cfg.ipv4Addr = addr;
2562 cfg.prefixLength = prefixLength;
2563 cfg.flags = flags;
2564 return cfg;
2565}
2566
2567void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2568 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2569 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2570
2571 for (const auto& flag : expectedFlags) {
2572 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2573 interfaceCfg.flags.end());
2574 }
2575
2576 for (const auto& flag : unexpectedFlags) {
2577 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2578 interfaceCfg.flags.end());
2579 }
2580}
2581
2582} // namespace
2583
2584TEST_F(BinderTest, InterfaceList) {
2585 std::vector<std::string> interfaceListResult;
2586
2587 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2588 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2589 expectInterfaceList(interfaceListResult);
2590}
2591
2592TEST_F(BinderTest, InterfaceGetCfg) {
2593 InterfaceConfigurationParcel interfaceCfgResult;
2594
2595 // Add test physical network
2596 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2597 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2598
2599 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2600 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2601 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2602 expectTunFlags(interfaceCfgResult);
2603
2604 // Remove test physical network
2605 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2606}
2607
2608TEST_F(BinderTest, InterfaceSetCfg) {
2609 const std::string testAddr = "192.0.2.3";
2610 const int testPrefixLength = 24;
2611 std::vector<std::string> upFlags = {"up"};
2612 std::vector<std::string> downFlags = {"down"};
2613
2614 // Add test physical network
2615 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2616 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2617
2618 // Set tun interface down.
2619 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2620 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2621 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2622 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2623
2624 // Set tun interface up again.
2625 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2626 status = mNetd->interfaceSetCfg(interfaceCfg);
2627 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2628 status = mNetd->interfaceClearAddrs(sTun.name());
2629 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2630
2631 // Remove test physical network
2632 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2633}
2634
2635TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2636 // enable
2637 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2638 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2639 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2640
2641 // disable
2642 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2643 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2644 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2645}
2646
2647TEST_F(BinderTest, InterfaceClearAddr) {
2648 const std::string testAddr = "192.0.2.3";
2649 const int testPrefixLength = 24;
2650 std::vector<std::string> noFlags{};
2651
2652 // Add test physical network
2653 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2654 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2655
2656 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2657 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2658 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2659 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2660
2661 status = mNetd->interfaceClearAddrs(sTun.name());
2662 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2663 expectInterfaceNoAddr(sTun.name());
2664
2665 // Remove test physical network
2666 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2667}
2668
2669TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2670 // Add test physical network
2671 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2672 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2673
2674 // disable
2675 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2676 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2677 expectInterfaceEnableIPv6(sTun.name(), false);
2678
2679 // enable
2680 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2681 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2682 expectInterfaceEnableIPv6(sTun.name(), true);
2683
2684 // Remove test physical network
2685 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2686}
2687
2688TEST_F(BinderTest, InterfaceSetMtu) {
2689 const int testMtu = 1200;
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 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2696 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2697 expectInterfaceMtu(sTun.name(), testMtu);
2698
2699 // Remove test physical network
2700 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2701}
Luke Huang19b49c52018-10-22 12:12:05 +09002702
2703namespace {
2704
2705constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2706constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002707constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002708constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2709
Luke Huangae038f82018-11-05 11:17:31 +09002710int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002711 return listIptablesRuleByTable(binary, table, chainName).size();
2712}
2713
2714bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2715 const std::vector<std::string>& targetVec) {
2716 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2717 if (targetVec.size() != rules.size() - 2) {
2718 return false;
2719 }
2720
2721 /*
Luke Huangae038f82018-11-05 11:17:31 +09002722 * Check that the rules match. Note that this function matches substrings, not entire rules,
2723 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002724 * Skip first two lines since rules start from third line.
2725 * Chain chainName (x references)
2726 * pkts bytes target prot opt in out source destination
2727 * ...
2728 */
2729 int rIndex = 2;
2730 for (const auto& target : targetVec) {
2731 if (rules[rIndex].find(target) == std::string::npos) {
2732 return false;
2733 }
2734 rIndex++;
2735 }
2736 return true;
2737}
2738
2739void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2740 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2741 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2742 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002743 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002744 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2745 "DROP"};
2746
2747 // V4
2748 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2749 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002750 EXPECT_TRUE(
2751 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002752 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2753
Luke Huangae038f82018-11-05 11:17:31 +09002754 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002755 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2756
2757 // V6
2758 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002759 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2760 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002761
2762 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2763 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2764 extIf));
2765 }
2766}
2767
2768void expectNatDisable() {
2769 // It is the default DROP rule with tethering disable.
2770 // Chain tetherctrl_FORWARD (1 references)
2771 // pkts bytes target prot opt in out source destination
2772 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2773 std::vector<std::string> forwardV4Match = {"DROP"};
2774 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2775
2776 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002777 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2778 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002779
Luke Huangae038f82018-11-05 11:17:31 +09002780 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2781 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002782
2783 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2784}
2785
2786} // namespace
2787
2788TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002789 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2790 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2791 expectNatEnable(sTun.name(), sTun2.name());
2792
2793 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2794 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2795 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002796}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002797
2798namespace {
2799
2800using TripleInt = std::array<int, 3>;
2801
2802TripleInt readProcFileToTripleInt(const std::string& path) {
2803 std::string valueString;
2804 int min, def, max;
2805 EXPECT_TRUE(ReadFileToString(path, &valueString));
2806 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2807 return {min, def, max};
2808}
2809
2810void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2811 std::string testRmemValues =
2812 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2813 std::string testWmemValues =
2814 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2815 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2816
2817 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2818 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2819
2820 for (int i = 0; i < 3; i++) {
2821 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2822 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2823 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2824 }
2825}
2826
2827} // namespace
2828
2829TEST_F(BinderTest, TcpBufferSet) {
2830 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2831 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2832 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2833 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2834
2835 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2836 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2837}
Luke Huang528af602018-08-29 19:06:05 +08002838
Chenbo Feng48eaed32018-12-26 17:40:21 -08002839namespace {
2840
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002841void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002842 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2843 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2844 for (int32_t uid : uids) {
2845 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2846 if (exist) {
2847 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002848 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002849 } else {
2850 EXPECT_FALSE(isOk(permission));
2851 EXPECT_EQ(ENOENT, permission.status().code());
2852 }
2853 }
2854}
2855
2856} // namespace
2857
2858TEST_F(BinderTest, TestInternetPermission) {
2859 SKIP_IF_BPF_NOT_SUPPORTED;
2860
2861 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2862
2863 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002864 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002865 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002866 checkUidsInPermissionMap(appUids, true);
2867 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2868 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002869}
2870
Luke Huang528af602018-08-29 19:06:05 +08002871TEST_F(BinderTest, UnsolEvents) {
2872 auto testUnsolService = android::net::TestUnsolService::start();
2873 std::string oldTunName = sTun.name();
2874 std::string newTunName = "unsolTest";
2875 testUnsolService->tarVec.push_back(oldTunName);
2876 testUnsolService->tarVec.push_back(newTunName);
2877 auto& cv = testUnsolService->getCv();
2878 auto& cvMutex = testUnsolService->getCvMutex();
2879 binder::Status status = mNetd->registerUnsolicitedEventListener(
2880 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2881 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2882
2883 // TODO: Add test for below events
2884 // StrictCleartextDetected / InterfaceDnsServersAdded
2885 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2886
2887 {
2888 std::unique_lock lock(cvMutex);
2889
2890 // Re-init test Tun, and we expect that we will get some unsol events.
2891 // Use the test Tun device name to verify if we receive its unsol events.
2892 sTun.destroy();
2893 // Use predefined name
2894 sTun.init(newTunName);
2895
2896 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2897 }
2898
2899 // bit mask 1101101000
2900 // Test only covers below events currently
2901 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2902 InterfaceLinkStatusChanged | RouteChanged;
2903 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002904
2905 // Re-init sTun to clear predefined name
2906 sTun.destroy();
2907 sTun.init();
2908}
2909
2910TEST_F(BinderTest, NDC) {
2911 struct Command {
2912 const std::string cmdString;
2913 const std::string expectedResult;
2914 };
2915
2916 // clang-format off
2917 // Do not change the commands order
2918 const Command networkCmds[] = {
2919 {StringPrintf("ndc network create %d", TEST_NETID1),
2920 "200 0 success"},
2921 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2922 "200 0 success"},
2923 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2924 "200 0 success"},
2925 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2926 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2927 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2928 "200 0 success"},
2929 };
2930
2931 const std::vector<Command> ipfwdCmds = {
2932 {"ndc ipfwd enable " + sTun.name(),
2933 "200 0 ipfwd operation succeeded"},
2934 {"ndc ipfwd disable " + sTun.name(),
2935 "200 0 ipfwd operation succeeded"},
2936 {"ndc ipfwd add lo2 lo3",
2937 "400 0 ipfwd operation failed (No such process)"},
2938 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
2939 "200 0 ipfwd operation succeeded"},
2940 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
2941 "200 0 ipfwd operation succeeded"},
2942 };
2943
2944 static const struct {
2945 const char* ipVersion;
2946 const char* testDest;
2947 const char* testNextHop;
2948 const bool expectSuccess;
2949 const std::string expectedResult;
2950 } kTestData[] = {
2951 {IP_RULE_V4, "0.0.0.0/0", "", true,
2952 "200 0 success"},
2953 {IP_RULE_V4, "10.251.0.0/16", "", true,
2954 "200 0 success"},
2955 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
2956 "400 0 addRoute() failed (Invalid argument)",},
2957 {IP_RULE_V6, "::/0", "", true,
2958 "200 0 success"},
2959 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
2960 "200 0 success"},
2961 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
2962 "400 0 addRoute() failed (Invalid argument)"},
2963 };
2964 // clang-format on
2965
2966 for (const auto& cmd : networkCmds) {
2967 const std::vector<std::string> result = runCommand(cmd.cmdString);
2968 SCOPED_TRACE(cmd.cmdString);
2969 EXPECT_EQ(result.size(), 1U);
2970 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
2971 }
2972
2973 for (const auto& cmd : ipfwdCmds) {
2974 const std::vector<std::string> result = runCommand(cmd.cmdString);
2975 SCOPED_TRACE(cmd.cmdString);
2976 EXPECT_EQ(result.size(), 1U);
2977 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
2978 }
2979
2980 // Add test physical network
2981 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2982 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2983
2984 for (const auto& td : kTestData) {
2985 const std::string routeAddCmd =
2986 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
2987 td.testDest, td.testNextHop);
2988 const std::string routeRemoveCmd =
2989 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
2990 sTun.name().c_str(), td.testDest, td.testNextHop);
2991 std::vector<std::string> result = runCommand(routeAddCmd);
2992 SCOPED_TRACE(routeAddCmd);
2993 EXPECT_EQ(result.size(), 1U);
2994 EXPECT_EQ(td.expectedResult, Trim(result[0]));
2995 if (td.expectSuccess) {
2996 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2997 sTun.name().c_str());
2998 result = runCommand(routeRemoveCmd);
2999 EXPECT_EQ(result.size(), 1U);
3000 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3001 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3002 sTun.name().c_str());
3003 }
3004 }
3005 // Remove test physical network
3006 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003007}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003008
Luke Huang2ff8b342019-04-30 15:33:33 +08003009TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003010 sp<IBinder> binder;
3011 binder::Status status = mNetd->getOemNetd(&binder);
3012 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3013 sp<com::android::internal::net::IOemNetd> oemNetd;
3014 if (binder != nullptr) {
3015 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3016 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003017 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003018
3019 TimedOperation t("OemNetd isAlive RPC");
3020 bool isAlive = false;
3021 oemNetd->isAlive(&isAlive);
3022 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003023
3024 class TestOemUnsolListener
3025 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3026 public:
3027 android::binder::Status onRegistered() override {
3028 std::lock_guard lock(mCvMutex);
3029 mCv.notify_one();
3030 return android::binder::Status::ok();
3031 }
3032 std::condition_variable& getCv() { return mCv; }
3033 std::mutex& getCvMutex() { return mCvMutex; }
3034
3035 private:
3036 std::mutex mCvMutex;
3037 std::condition_variable mCv;
3038 };
3039
3040 // Start the Binder thread pool.
3041 android::ProcessState::self()->startThreadPool();
3042
3043 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3044
3045 auto& cv = testListener->getCv();
3046 auto& cvMutex = testListener->getCvMutex();
3047
3048 {
3049 std::unique_lock lock(cvMutex);
3050
3051 status = oemNetd->registerOemUnsolicitedEventListener(
3052 ::android::interface_cast<
3053 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3054 testListener));
3055 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3056
3057 // Wait for receiving expected events.
3058 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3059 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003060}
Luke Huangd2861982019-05-17 19:47:28 +08003061
3062void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3063 int fallthroughNetId) {
3064 // Re-init sTun* to ensure route rule exists.
3065 sTun.destroy();
3066 sTun.init();
3067 sTun2.destroy();
3068 sTun2.init();
3069
3070 // Create physical network with fallthroughNetId but not set it as default network
3071 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3072 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3073
3074 // Create VPN with vpnNetId
3075 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3076
3077 // Add uid to VPN
3078 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3079 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3080
3081 // Add default route to fallthroughNetwork
3082 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3083 // Add limited route
3084 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3085}
3086
3087namespace {
3088
3089class ScopedUidChange {
3090 public:
3091 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3092 mStoredUid = getuid();
3093 if (mInputUid == mStoredUid) return;
3094 EXPECT_TRUE(seteuid(uid) == 0);
3095 }
3096 ~ScopedUidChange() {
3097 if (mInputUid == mStoredUid) return;
3098 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3099 }
3100
3101 private:
3102 uid_t mInputUid;
3103 uid_t mStoredUid;
3104};
3105
3106constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3107
3108void clearQueue(int tunFd) {
3109 char buf[4096];
3110 int ret;
3111 do {
3112 ret = read(tunFd, buf, sizeof(buf));
3113 } while (ret > 0);
3114}
3115
3116void checkDataReceived(int udpSocket, int tunFd) {
3117 char buf[4096] = {};
3118 // Clear tunFd's queue before write something because there might be some
3119 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3120 clearQueue(tunFd);
3121 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3122 // TODO: extract header and verify data
3123 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3124}
3125
3126bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3127 ScopedUidChange scopedUidChange(uid);
Bernie Innocentid26a04a2019-10-30 17:15:15 +09003128 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Luke Huangd2861982019-05-17 19:47:28 +08003129 if (testSocket < 0) return false;
3130
Nick Desaulniers6b357502019-10-11 09:26:44 -07003131 const sockaddr_in6 dst6 = {
3132 .sin6_family = AF_INET6,
3133 .sin6_port = 42,
3134 .sin6_addr = dstAddr,
3135 };
Luke Huangd2861982019-05-17 19:47:28 +08003136 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3137 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3138 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3139 if (res == -1) return false;
3140
3141 char addr[INET6_ADDRSTRLEN];
3142 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3143 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3144 checkDataReceived(testSocket, tunFd);
3145 return true;
3146}
3147
3148void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3149 std::string vpnFallthroughRule =
3150 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3151 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3152 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3153 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3154 }
3155}
3156
3157void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3158 const TunInterface& fallthroughNetwork,
3159 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3160 int fallthroughNetId = TEST_NETID1) {
3161 // Set default network to NETID_UNSET
3162 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3163
3164 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3165 in6_addr insideVpnAddr = {
3166 {// 2001:db8:cafe::1
3167 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3168 // outsideVpnAddr will hit the route in the fallthrough network route table
3169 // because we added default route in createVpnNetworkWithUid
3170 in6_addr outsideVpnAddr = {
3171 {// 2607:f0d0:1002::4
3172 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3173
3174 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3175 int vpnFd = vpnNetwork.getFdForTesting();
3176 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3177 // default network.
3178 Fwmark fwmark;
3179 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3180 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3181
3182 // Set default network
3183 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3184
3185 // Connections go on the default network because UID 0 is not subject to the VPN.
3186 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3187 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3188 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3189 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3190
3191 // Check if fallthrough rule exists
3192 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3193
3194 // Expect fallthrough to default network
3195 // The fwmark differs depending on whether the VPN is bypassable or not.
3196 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3197 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3198
3199 // Expect connect success, packet will be sent to vpnFd.
3200 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3201 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3202
3203 // Explicitly select vpn network
3204 setNetworkForProcess(vpnNetId);
3205
3206 // Expect fallthrough to default network
3207 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3208 // Expect the mark contains all the bit because we've selected network.
3209 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3210
3211 // Expect connect success, packet will be sent to vpnFd.
3212 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3213 // Expect the mark contains all the bit because we've selected network.
3214 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3215
3216 // Explicitly select fallthrough network
3217 setNetworkForProcess(fallthroughNetId);
3218
3219 // The mark is set to fallthrough network because we've selected it.
3220 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3221 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3222
3223 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3224 if (bypassable) {
3225 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3226 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3227 } else {
3228 // If not, no permission to bypass vpn.
3229 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3230 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3231 }
3232}
3233
3234} // namespace
3235
3236TEST_F(BinderTest, SecureVPNFallthrough) {
3237 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3238 // Get current default network NetId
3239 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3240 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3241}
3242
3243TEST_F(BinderTest, BypassableVPNFallthrough) {
3244 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3245 // Get current default network NetId
3246 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3247 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003248}