blob: 54746546360e1e9e0f22096e6f35d99f39109b03 [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 }
850}
Erik Kline55b06f82016-07-04 09:57:18 +0900851
Erik Kline38e51f12018-09-06 20:14:44 +0900852TEST_F(BinderTest, GetProcSysNet) {
853 const char LOOPBACK[] = "lo";
854 static const struct {
855 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900856 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900857 const char* ifname;
858 const char* parameter;
859 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900860 const int expectedReturnCode;
861 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900862 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
863 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
864 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
865 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
866 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
867 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
868 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900869 };
870
Sehee Park8659b8d2018-11-16 10:53:16 +0900871 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900872 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900873
Erik Kline38e51f12018-09-06 20:14:44 +0900874 std::string value;
875 const binder::Status status =
876 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
877
878 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900879 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900880 EXPECT_EQ(0, status.exceptionCode());
881 EXPECT_EQ(0, status.serviceSpecificErrorCode());
882 EXPECT_EQ(td.expectedValue, value);
883 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900884 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900885 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
886 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
887 }
888 }
889}
890
891TEST_F(BinderTest, SetProcSysNet) {
892 static const struct {
893 const int ipversion;
894 const int which;
895 const char* ifname;
896 const char* parameter;
897 const char* value;
898 const int expectedReturnCode;
899 } kTestData[] = {
900 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
901 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
902 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
903 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
904 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
905 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
906 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
907 };
908
Sehee Park8659b8d2018-11-16 10:53:16 +0900909 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900910 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900911 const binder::Status status =
912 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900913
914 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900915 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900916 EXPECT_EQ(0, status.exceptionCode());
917 EXPECT_EQ(0, status.serviceSpecificErrorCode());
918 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900919 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900920 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
921 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
922 }
923 }
924}
Ben Schwartze7601812017-04-28 16:38:29 -0400925
Erik Kline38e51f12018-09-06 20:14:44 +0900926TEST_F(BinderTest, GetSetProcSysNet) {
927 const int ipversion = INetd::IPV6;
928 const int category = INetd::NEIGH;
929 const std::string& tun = sTun.name();
930 const std::string parameter("ucast_solicit");
931
932 std::string value{};
933 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700934 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900935 const int ival = std::stoi(value);
936 EXPECT_GT(ival, 0);
937 // Try doubling the parameter value (always best!).
938 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
939 .isOk());
940 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
941 EXPECT_EQ(2 * ival, std::stoi(value));
942 // Try resetting the parameter.
943 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
944 .isOk());
945 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
946 EXPECT_EQ(ival, std::stoi(value));
947}
948
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900949namespace {
950
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900951void expectNoTestCounterRules() {
952 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
953 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
954 std::string allRules = Join(runCommand(command), "\n");
955 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
956 }
957}
958
Bernie Innocentif6918262018-06-11 17:37:35 +0900959void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
960 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900961 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
962 path, if1.c_str(), if2.c_str(), pkt, byte));
963}
964
Bernie Innocentif6918262018-06-11 17:37:35 +0900965void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900966 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
967 path, if1.c_str(), if2.c_str()));
968 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
969 path, if2.c_str(), if1.c_str()));
970}
971
Luke Huangcaebcbb2018-09-27 20:37:14 +0800972std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
973 const std::string& iface) {
974 for (auto& stats : statsVec) {
975 if (stats.iface == iface) {
976 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
977 }
978 }
979 return {};
980}
981
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900982} // namespace
983
984TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900985 expectNoTestCounterRules();
986
987 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
988 // disabling tethering. We don't check the return value because these commands will fail if
989 // tethering is already enabled.
990 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
991 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
992
993 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
994 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
995 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +0800996
997 // Ensure we won't use the same interface name, otherwise the test will fail.
998 u_int32_t rNumber = arc4random_uniform(10000);
999 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1000 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001001
1002 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1003 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1004 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1005 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1006 // RX is from external to internal, and TX is from internal to external.
1007 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1008 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1009
1010 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1011 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1012
1013 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1014 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1015
1016 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1017 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1018 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1019
Luke Huangcaebcbb2018-09-27 20:37:14 +08001020 std::vector<TetherStatsParcel> statsVec;
1021 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001022 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1023
Luke Huangcaebcbb2018-09-27 20:37:14 +08001024 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001025
Luke Huangcaebcbb2018-09-27 20:37:14 +08001026 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001027
1028 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1029 delTetherCounterValues(path, intIface1, extIface1);
1030 delTetherCounterValues(path, intIface2, extIface2);
1031 if (path == IP6TABLES_PATH) {
1032 delTetherCounterValues(path, intIface3, extIface2);
1033 }
1034 }
1035
1036 expectNoTestCounterRules();
1037}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001038
Luke Huang0051a622018-07-23 20:30:16 +08001039namespace {
1040
Luke Huanga5211072018-08-01 23:36:29 +08001041constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1042constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001043
1044static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1045 const char* chainName) {
1046 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1047 return runCommand(command);
1048}
1049
Luke Huang19b49c52018-10-22 12:12:05 +09001050// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001051bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001052 const std::string& expectedInterface,
1053 const std::string& expectedRule, const char* table) {
1054 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1055 for (const auto& rule : rules) {
1056 if (rule.find(expectedInterface) != std::string::npos) {
1057 if (rule.find(expectedRule) != std::string::npos) {
1058 return true;
1059 }
1060 }
1061 }
1062 return false;
1063}
1064
1065void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001066 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001067 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001068 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001069 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001070 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1071 IdletimerRule, RAW_TABLE));
1072 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001073 ifname, IdletimerRule, MANGLE_TABLE));
1074 }
1075}
1076
1077void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001078 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001079 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001080 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001081 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001082 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1083 IdletimerRule, RAW_TABLE));
1084 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001085 ifname, IdletimerRule, MANGLE_TABLE));
1086 }
1087}
1088
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001089} // namespace
1090
1091TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001092 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1093 // rule in the table. Because we only check the result after calling remove function. We might
1094 // check the actual rule which is removed by our function (maybe compare the results between
1095 // calling function before and after)
1096 binder::Status status;
1097 const struct TestData {
1098 const std::string ifname;
1099 int32_t timeout;
1100 const std::string classLabel;
1101 } idleTestData[] = {
1102 {"wlan0", 1234, "happyday"},
1103 {"rmnet_data0", 4567, "friday"},
1104 };
1105 for (const auto& td : idleTestData) {
1106 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1107 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1108 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1109
1110 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1111 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1112 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1113 }
1114}
1115
Luke Huanga67dd562018-07-17 19:58:25 +08001116namespace {
1117
1118constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1119constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1120
1121void expectStrictSetUidAccept(const int uid) {
1122 std::string uidRule = StringPrintf("owner UID match %u", uid);
1123 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1124 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001125 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1126 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001127 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1128 }
1129}
1130
1131void expectStrictSetUidLog(const int uid) {
1132 static const char logRule[] = "st_penalty_log all";
1133 std::string uidRule = StringPrintf("owner UID match %u", uid);
1134 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1135 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001136 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1137 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001138 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1139 }
1140}
1141
1142void expectStrictSetUidReject(const int uid) {
1143 static const char rejectRule[] = "st_penalty_reject all";
1144 std::string uidRule = StringPrintf("owner UID match %u", uid);
1145 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1146 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001147 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1148 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001149 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1150 }
1151}
1152
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001153} // namespace
1154
1155TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001156 binder::Status status;
1157 int32_t uid = randomUid();
1158
1159 // setUidCleartextPenalty Policy:Log with randomUid
1160 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1161 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1162 expectStrictSetUidLog(uid);
1163
1164 // setUidCleartextPenalty Policy:Accept with randomUid
1165 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1166 expectStrictSetUidAccept(uid);
1167
1168 // setUidCleartextPenalty Policy:Reject with randomUid
1169 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1170 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1171 expectStrictSetUidReject(uid);
1172
1173 // setUidCleartextPenalty Policy:Accept with randomUid
1174 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1175 expectStrictSetUidAccept(uid);
1176
1177 // test wrong policy
1178 int32_t wrongPolicy = -123;
1179 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1180 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1181}
1182
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001183namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001184
Luke Huangd1675922019-03-11 17:29:27 +08001185std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001186 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001187 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001188 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1189 // ...
1190 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1191
Luke Huangd1675922019-03-11 17:29:27 +08001192 // (dnsmasq)
1193 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1194
1195 if (maxTries == 0) return {};
1196
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001197 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001198 std::vector<std::string> result;
1199 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001200 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001201 if (result.size() || ++run > maxTries) {
1202 break;
1203 }
1204
Luke Huang728cf4c2019-03-14 19:43:02 +08001205 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001206 }
1207 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001208}
1209
Luke Huangd1675922019-03-11 17:29:27 +08001210void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001211 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001212}
1213
Luke Huang728cf4c2019-03-14 19:43:02 +08001214void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001215 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001216}
1217
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001218} // namespace
1219
1220TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001221 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001222
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001223 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1224 std::string clatAddress;
1225 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001226
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001227 // Can't start clatd on an interface that's not part of any network...
1228 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1229 EXPECT_FALSE(status.isOk());
1230 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1231
1232 // ... so create a test physical network and add our tun to it.
1233 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1234 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1235
1236 // Prefix must be 96 bits long.
1237 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1238 EXPECT_FALSE(status.isOk());
1239 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1240
1241 // Can't start clatd unless there's a default route...
1242 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1243 EXPECT_FALSE(status.isOk());
1244 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1245
1246 // so add a default route.
1247 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1248
1249 // Can't start clatd unless there's a global address...
1250 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1251 EXPECT_FALSE(status.isOk());
1252 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1253
1254 // ... so add a global address.
1255 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001256 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001257
1258 // Now expect clatd to start successfully.
1259 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1260 EXPECT_TRUE(status.isOk());
1261 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1262
1263 // Starting it again returns EBUSY.
1264 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1265 EXPECT_FALSE(status.isOk());
1266 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1267
Luke Huangd1675922019-03-11 17:29:27 +08001268 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001269
1270 // Expect clatd to stop successfully.
1271 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001272 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001273 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001274
1275 // Stopping a clatd that doesn't exist returns ENODEV.
1276 status = mNetd->clatdStop(sTun.name());
1277 EXPECT_FALSE(status.isOk());
1278 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001279 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001280
1281 // Clean up.
1282 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1283 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1284 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001285}
Luke Huang457d4702018-08-16 15:39:15 +08001286
1287namespace {
1288
1289bool getIpfwdV4Enable() {
1290 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1291 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1292 EXPECT_TRUE(!result.empty());
1293 int v4Enable = std::stoi(result[0]);
1294 return v4Enable;
1295}
1296
1297bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001298 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001299 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1300 EXPECT_TRUE(!result.empty());
1301 int v6Enable = std::stoi(result[0]);
1302 return v6Enable;
1303}
1304
1305void expectIpfwdEnable(bool enable) {
1306 int enableIPv4 = getIpfwdV4Enable();
1307 int enableIPv6 = getIpfwdV6Enable();
1308 EXPECT_EQ(enable, enableIPv4);
1309 EXPECT_EQ(enable, enableIPv6);
1310}
1311
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001312bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001313 std::vector<std::string> rules = listIpRules(ipVersion);
1314 for (const auto& rule : rules) {
1315 if (rule.find(ipfwdRule) != std::string::npos) {
1316 return true;
1317 }
1318 }
1319 return false;
1320}
1321
1322void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1323 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1324
1325 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1326 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1327 }
1328}
1329
1330void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1331 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1332
1333 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1334 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1335 }
1336}
1337
1338} // namespace
1339
1340TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001341 // Get ipfwd requester list from Netd
1342 std::vector<std::string> requesterList;
1343 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001344 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001345
1346 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001347 if (requesterList.size() == 0) {
1348 // No requester in Netd, ipfwd should be disabled
1349 // So add one test requester and verify
1350 status = mNetd->ipfwdEnableForwarding("TestRequester");
1351 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001352
Luke Huang728cf4c2019-03-14 19:43:02 +08001353 expectIpfwdEnable(true);
1354 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1355 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1356 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001357
Luke Huang728cf4c2019-03-14 19:43:02 +08001358 // Remove test one, verify again
1359 status = mNetd->ipfwdDisableForwarding("TestRequester");
1360 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1361
1362 expectIpfwdEnable(false);
1363 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1364 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1365 EXPECT_FALSE(ipfwdEnabled);
1366 } else {
1367 // Disable all requesters
1368 for (const auto& requester : requesterList) {
1369 status = mNetd->ipfwdDisableForwarding(requester);
1370 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1371 }
1372
1373 // After disable all requester, ipfwd should be disabled
1374 expectIpfwdEnable(false);
1375 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1376 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1377 EXPECT_FALSE(ipfwdEnabled);
1378
1379 // Enable them back
1380 for (const auto& requester : requesterList) {
1381 status = mNetd->ipfwdEnableForwarding(requester);
1382 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1383 }
1384
1385 // ipfwd should be enabled
1386 expectIpfwdEnable(true);
1387 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1388 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1389 EXPECT_TRUE(ipfwdEnabled);
1390 }
Luke Huang457d4702018-08-16 15:39:15 +08001391}
1392
1393TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001394 // Add test physical network
1395 EXPECT_TRUE(
1396 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1397 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1398 EXPECT_TRUE(
1399 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1400 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001401
Luke Huangd1827b82019-02-15 15:03:27 +08001402 binder::Status status =
1403 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1404 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1405 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001406
Luke Huangd1827b82019-02-15 15:03:27 +08001407 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1408 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1409 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001410}
Luke Huang531f5d32018-08-03 15:19:05 +08001411
1412namespace {
1413
1414constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1415constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1416constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1417constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1418constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001419constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001420
Luke Huang19b49c52018-10-22 12:12:05 +09001421// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1422// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001423bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1424 const char* chainName, const std::string& expectedTargetA,
1425 const std::string& expectedTargetB) {
1426 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1427 int matchCount = 0;
1428
1429 for (const auto& rule : rules) {
1430 if (rule.find(expectedTargetA) != std::string::npos) {
1431 if (rule.find(expectedTargetB) != std::string::npos) {
1432 matchCount++;
1433 }
1434 }
1435 }
1436 return matchCount == expectedCount;
1437}
1438
1439void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1440 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1441 std::string result = "";
1442
1443 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001444 // Quota value might be decreased while matching packets
1445 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001446}
1447
1448void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1449 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1450 std::string quotaRule = StringPrintf("quota %s", ifname);
1451
1452 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1453 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1454 BANDWIDTH_COSTLY_IF));
1455 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1456 BANDWIDTH_COSTLY_IF));
1457 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1458 BANDWIDTH_COSTLY_IF));
1459 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1460 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1461 }
1462 expectXtQuotaValueEqual(ifname, quotaBytes);
1463}
1464
1465void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1466 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1467 std::string quotaRule = StringPrintf("quota %s", ifname);
1468
1469 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1470 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1471 BANDWIDTH_COSTLY_IF));
1472 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1473 BANDWIDTH_COSTLY_IF));
1474 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1475 BANDWIDTH_COSTLY_IF));
1476 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1477 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1478 }
1479}
1480
1481void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1482 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1483 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1484 std::string alertName = StringPrintf("%sAlert", ifname);
1485
1486 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1487 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1488 }
1489 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1490}
1491
1492void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1493 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1494 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1495
1496 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1497 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1498 }
1499}
1500
1501void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1502 static const char globalAlertRule[] = "quota globalAlert";
1503 static const char globalAlertName[] = "globalAlert";
1504
1505 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001506 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001507 }
1508 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1509}
1510
1511void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1512 std::string uidRule = StringPrintf("owner UID match %u", uid);
1513
1514 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1515 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1516 }
1517}
1518
1519void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1520 std::string uidRule = StringPrintf("owner UID match %u", uid);
1521
1522 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1523 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1524 }
1525}
1526
1527} // namespace
1528
1529TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1530 long testQuotaBytes = 5550;
1531
1532 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001533 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001534 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1535
1536 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1537 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1538 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1539
1540 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1541 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1542 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1543
1544 // Remove test physical network
1545 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1546}
1547
1548TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1549 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001550 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001551 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001552 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001553 // Need to have a prior interface quota set to set an alert
1554 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1555 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1556 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1557 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1558
1559 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1560 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1561 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1562
1563 // Remove interface quota
1564 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1565 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1566 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1567
1568 // Remove test physical network
1569 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1570}
1571
1572TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001573 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001574
1575 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1576 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1577 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1578
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001579 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001580 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1581 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1582 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1583}
1584
1585TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1586 SKIP_IF_BPF_SUPPORTED;
1587
1588 int32_t uid = randomUid();
1589 static const char targetReject[] = "REJECT";
1590 static const char targetReturn[] = "RETURN";
1591
1592 // add NaughtyApp
1593 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1594 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1595 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1596
1597 // remove NaughtyApp
1598 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1599 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1600 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1601
1602 // add NiceApp
1603 status = mNetd->bandwidthAddNiceApp(uid);
1604 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1605 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1606
1607 // remove NiceApp
1608 status = mNetd->bandwidthRemoveNiceApp(uid);
1609 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1610 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1611}
Luke Huangb5733d72018-08-21 17:17:19 +08001612
1613namespace {
1614
Luke Huangc3252cc2018-10-16 15:43:23 +08001615std::string ipRouteString(const std::string& ifName, const std::string& dst,
1616 const std::string& nextHop) {
1617 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1618
1619 if (!nextHop.empty()) {
1620 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001621 }
1622
Luke Huangc3252cc2018-10-16 15:43:23 +08001623 return dstString + " dev " + ifName;
Luke Huangb670d162018-08-23 20:01:13 +08001624}
1625
Luke Huangc3252cc2018-10-16 15:43:23 +08001626void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1627 const std::string& dst, const std::string& nextHop,
1628 const char* table) {
1629 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
1630}
1631
1632void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001633 const std::string& dst, const std::string& nextHop,
1634 const char* table) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001635 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
Luke Huangb670d162018-08-23 20:01:13 +08001636}
1637
1638bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1639 std::vector<std::string> rules = listIpRules(ipVersion);
1640 for (const auto& rule : rules) {
1641 if (rule.find(ipRule) != std::string::npos) {
1642 return true;
1643 }
1644 }
1645 return false;
1646}
1647
1648void expectNetworkDefaultIpRuleExists(const char* ifName) {
1649 std::string networkDefaultRule =
1650 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1651
1652 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1653 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1654 }
1655}
1656
1657void expectNetworkDefaultIpRuleDoesNotExist() {
1658 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1659
1660 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1661 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1662 }
1663}
1664
1665void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1666 std::string networkPermissionRule = "";
1667 switch (permission) {
1668 case INetd::PERMISSION_NONE:
1669 networkPermissionRule = StringPrintf(
1670 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1671 break;
1672 case INetd::PERMISSION_NETWORK:
1673 networkPermissionRule = StringPrintf(
1674 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1675 break;
1676 case INetd::PERMISSION_SYSTEM:
1677 networkPermissionRule = StringPrintf(
1678 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1679 break;
1680 }
1681
1682 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1683 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1684 }
1685}
1686
1687// TODO: It is a duplicate function, need to remove it
1688bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1689 const std::string& expectedInterface,
1690 const std::string& expectedRule,
1691 const char* table) {
1692 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1693 for (const auto& rule : rules) {
1694 if (rule.find(expectedInterface) != std::string::npos) {
1695 if (rule.find(expectedRule) != std::string::npos) {
1696 return true;
1697 }
1698 }
1699 }
1700 return false;
1701}
1702
1703void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1704 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1705 std::string networkIncomingPacketMarkRule = "";
1706 switch (permission) {
1707 case INetd::PERMISSION_NONE:
1708 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1709 break;
1710 case INetd::PERMISSION_NETWORK:
1711 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1712 break;
1713 case INetd::PERMISSION_SYSTEM:
1714 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1715 break;
1716 }
1717
1718 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1719 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1720 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1721 }
1722}
1723
1724} // namespace
1725
1726TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001727 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001728 const char* ipVersion;
1729 const char* testDest;
1730 const char* testNextHop;
1731 const bool expectSuccess;
1732 } kTestData[] = {
1733 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001734 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1735 {IP_RULE_V4, "10.251.0.0/16", "", true},
1736 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1737 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001738 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001739 {IP_RULE_V6, "::/0", "2001:db8::", true},
1740 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001741 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1742 };
1743
Luke Huangc3252cc2018-10-16 15:43:23 +08001744 static const struct {
1745 const char* ipVersion;
1746 const char* testDest;
1747 const char* testNextHop;
1748 } kTestDataWithNextHop[] = {
1749 {IP_RULE_V4, "10.251.10.0/30", ""},
1750 {IP_RULE_V6, "2001:db8::/32", ""},
1751 };
1752
Luke Huangb670d162018-08-23 20:01:13 +08001753 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001754 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001755 const int testUid = randomUid();
1756 const std::vector<int32_t> testUids = {testUid};
1757
1758 // Add test physical network
1759 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1760 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1761
Luke Huangc3252cc2018-10-16 15:43:23 +08001762 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001763 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001764 const auto& td = kTestDataWithNextHop[i];
1765
1766 // All route for test tun will disappear once the tun interface is deleted.
1767 binder::Status status =
1768 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1769 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1770 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1771 sTun.name().c_str());
1772
1773 // Add system permission for test uid, setup route in legacy system table.
1774 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1775
1776 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1777 testUid);
1778 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1779 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1780 testTableLegacySystem);
1781
1782 // Remove system permission for test uid, setup route in legacy network table.
1783 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1784
1785 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1786 testUid);
1787 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1788 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1789 testTableLegacyNetwork);
1790 }
1791
Sehee Park8659b8d2018-11-16 10:53:16 +09001792 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001793 const auto& td = kTestData[i];
1794
1795 binder::Status status =
1796 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1797 if (td.expectSuccess) {
1798 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001799 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001800 sTun.name().c_str());
1801 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001802 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1803 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001804 }
1805
1806 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1807 if (td.expectSuccess) {
1808 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001809 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1810 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001811 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001812 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1813 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001814 }
1815
Luke Huangc3252cc2018-10-16 15:43:23 +08001816 // Add system permission for test uid, route will be added into legacy system table.
1817 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001818
1819 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1820 testUid);
1821 if (td.expectSuccess) {
1822 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001823 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001824 testTableLegacySystem);
1825 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001826 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1827 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001828 }
1829
1830 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1831 td.testNextHop, testUid);
1832 if (td.expectSuccess) {
1833 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001834 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1835 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001836 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001837 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1838 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001839 }
1840
Luke Huangc3252cc2018-10-16 15:43:23 +08001841 // Remove system permission for test uid, route will be added into legacy network table.
1842 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1843
1844 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1845 testUid);
1846 if (td.expectSuccess) {
1847 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1848 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1849 testTableLegacyNetwork);
1850 } else {
1851 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1852 EXPECT_NE(0, status.serviceSpecificErrorCode());
1853 }
1854
1855 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1856 td.testNextHop, testUid);
1857 if (td.expectSuccess) {
1858 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1859 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1860 testTableLegacyNetwork);
1861 } else {
1862 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1863 EXPECT_NE(0, status.serviceSpecificErrorCode());
1864 }
Luke Huangb670d162018-08-23 20:01:13 +08001865 }
1866
1867 // Remove test physical network
1868 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1869}
1870
1871TEST_F(BinderTest, NetworkPermissionDefault) {
1872 // Add test physical network
1873 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1874 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1875
Luke Huangc3252cc2018-10-16 15:43:23 +08001876 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001877 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1878 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001879
1880 // Test SetDefault
1881 status = mNetd->networkSetDefault(TEST_NETID1);
1882 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1883 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1884
1885 status = mNetd->networkClearDefault();
1886 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1887 expectNetworkDefaultIpRuleDoesNotExist();
1888
Luke Huangd2861982019-05-17 19:47:28 +08001889 // Set default network back
1890 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001891 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1892
1893 // Test SetPermission
1894 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1895 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1896 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1897 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1898
1899 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1900 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1901 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1902 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1903
1904 // Remove test physical network
1905 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1906}
1907
1908TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08001909 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001910 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1911 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08001912 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001913 EXPECT_TRUE(ret);
1914
Luke Huang854e2992019-05-29 16:42:48 +08001915 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08001916 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08001917
1918 // Clear uid permission before calling networkCanProtect to ensure
1919 // the call won't be affected by uid permission.
1920 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
1921
1922 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08001923 EXPECT_FALSE(ret);
1924}
1925
1926namespace {
1927
Luke Huangb5733d72018-08-21 17:17:19 +08001928int readIntFromPath(const std::string& path) {
1929 std::string result = "";
1930 EXPECT_TRUE(ReadFileToString(path, &result));
1931 return std::stoi(result);
1932}
1933
1934int getTetherAcceptIPv6Ra(const std::string& ifName) {
1935 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
1936 return readIntFromPath(path);
1937}
1938
1939bool getTetherAcceptIPv6Dad(const std::string& ifName) {
1940 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
1941 return readIntFromPath(path);
1942}
1943
1944int getTetherIPv6DadTransmits(const std::string& ifName) {
1945 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
1946 return readIntFromPath(path);
1947}
1948
1949bool getTetherEnableIPv6(const std::string& ifName) {
1950 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
1951 int disableIPv6 = readIntFromPath(path);
1952 return !disableIPv6;
1953}
1954
1955bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
1956 for (const auto& iface : ifList) {
1957 if (iface == ifName) {
1958 return true;
1959 }
1960 }
1961 return false;
1962}
1963
1964void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
1965 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
1966 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
1967 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
1968 EXPECT_TRUE(getTetherEnableIPv6(ifName));
1969}
1970
1971void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
1972 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
1973 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
1974 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
1975 EXPECT_FALSE(getTetherEnableIPv6(ifName));
1976}
1977
1978void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
1979 const std::string& ifName) {
1980 EXPECT_TRUE(interfaceListContains(ifList, ifName));
1981}
1982
1983void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
1984 const std::string& ifName) {
1985 EXPECT_FALSE(interfaceListContains(ifList, ifName));
1986}
1987
1988void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
1989 const std::vector<std::string>& testDnsAddrs) {
1990 EXPECT_TRUE(dnsList == testDnsAddrs);
1991}
1992
1993} // namespace
1994
1995TEST_F(BinderTest, TetherStartStopStatus) {
1996 std::vector<std::string> noDhcpRange = {};
1997 static const char dnsdName[] = "dnsmasq";
1998
Luke Huang91bd3e12019-08-20 11:33:52 +08001999 for (bool usingLegacyDnsProxy : {true, false}) {
2000 binder::Status status =
2001 mNetd->tetherStartWithConfiguration(usingLegacyDnsProxy, noDhcpRange);
2002 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2003 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2004 if (usingLegacyDnsProxy == true) {
2005 expectProcessExists(dnsdName);
2006 } else {
2007 expectProcessDoesNotExist(dnsdName);
2008 }
Luke Huangb5733d72018-08-21 17:17:19 +08002009
Luke Huang91bd3e12019-08-20 11:33:52 +08002010 bool tetherEnabled;
2011 status = mNetd->tetherIsEnabled(&tetherEnabled);
2012 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2013 EXPECT_TRUE(tetherEnabled);
Luke Huangb5733d72018-08-21 17:17:19 +08002014
Luke Huang91bd3e12019-08-20 11:33:52 +08002015 status = mNetd->tetherStop();
2016 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2017 expectProcessDoesNotExist(dnsdName);
Luke Huangb5733d72018-08-21 17:17:19 +08002018
Luke Huang91bd3e12019-08-20 11:33:52 +08002019 status = mNetd->tetherIsEnabled(&tetherEnabled);
2020 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2021 EXPECT_FALSE(tetherEnabled);
2022 }
Luke Huangb5733d72018-08-21 17:17:19 +08002023}
2024
2025TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2026 // TODO: verify if dnsmasq update interface successfully
2027
2028 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2029 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2030 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2031
2032 std::vector<std::string> ifList;
2033 status = mNetd->tetherInterfaceList(&ifList);
2034 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2035 expectTetherInterfaceExists(ifList, sTun.name());
2036
2037 status = mNetd->tetherInterfaceRemove(sTun.name());
2038 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2039 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2040
2041 status = mNetd->tetherInterfaceList(&ifList);
2042 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2043 expectTetherInterfaceNotExists(ifList, sTun.name());
2044}
2045
2046TEST_F(BinderTest, TetherDnsSetList) {
2047 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002048 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2049 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002050
2051 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2052 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2053
2054 std::vector<std::string> dnsList;
2055 status = mNetd->tetherDnsList(&dnsList);
2056 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2057 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002058}
2059
2060namespace {
2061
2062constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2063constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2064constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2065constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2066constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2067constexpr char FIREWALL_STANDBY[] = "fw_standby";
2068constexpr char targetReturn[] = "RETURN";
2069constexpr char targetDrop[] = "DROP";
2070
2071void expectFirewallWhitelistMode() {
2072 static const char dropRule[] = "DROP all";
2073 static const char rejectRule[] = "REJECT all";
2074 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2075 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2076 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2077 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2078 }
2079}
2080
2081void expectFirewallBlacklistMode() {
2082 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2083 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2084 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2085 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2086 }
2087}
2088
2089bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2090 const std::string& expectedInterface,
2091 const std::string& expectedRule) {
2092 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2093 // Expected rule:
2094 // Chain fw_INPUT (1 references)
2095 // pkts bytes target prot opt in out source destination
2096 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2097 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2098 int firstRuleIndex = 2;
2099 if (rules.size() < 4) return false;
2100 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2101 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2102 return true;
2103 }
2104 }
2105 return false;
2106}
2107
2108// TODO: It is a duplicate function, need to remove it
2109bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2110 const std::string& expectedInterface,
2111 const std::string& expectedRule) {
2112 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2113 for (const auto& rule : rules) {
2114 if (rule.find(expectedInterface) != std::string::npos) {
2115 if (rule.find(expectedRule) != std::string::npos) {
2116 return true;
2117 }
2118 }
2119 }
2120 return false;
2121}
2122
2123void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2124 static const char returnRule[] = "RETURN all";
2125 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2126 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2127 returnRule));
2128 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2129 returnRule));
2130 }
2131}
2132
2133void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2134 static const char returnRule[] = "RETURN all";
2135 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2136 EXPECT_FALSE(
2137 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2138 EXPECT_FALSE(
2139 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2140 }
2141}
2142
2143bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2144 const std::string& expectedTarget,
2145 const std::string& expectedRule) {
2146 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2147 int firstRuleIndex = 2;
2148 if (rules.size() < 4) return false;
2149 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2150 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2151 return true;
2152 }
2153 }
2154 return false;
2155}
2156
2157bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2158 const std::string& expectedTarget,
2159 const std::string& expectedRule) {
2160 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2161 int lastRuleIndex = rules.size() - 1;
2162 if (lastRuleIndex < 0) return false;
2163 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2164 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2165 return true;
2166 }
2167 }
2168 return false;
2169}
2170
2171void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2172 std::string uidRule = StringPrintf("owner UID match %u", uid);
2173 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2174 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2175}
2176
2177void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2178 std::string uidRule = StringPrintf("owner UID match %u", uid);
2179 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2180 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2181}
2182
2183void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2184 std::string uidRule = StringPrintf("owner UID match %u", uid);
2185 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2186 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2187}
2188
2189void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2190 std::string uidRule = StringPrintf("owner UID match %u", uid);
2191 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2192 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2193}
2194
2195bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2196 std::vector<std::string> inputRules =
2197 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2198 std::vector<std::string> outputRules =
2199 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2200 int inputLastRuleIndex = inputRules.size() - 1;
2201 int outputLastRuleIndex = outputRules.size() - 1;
2202
2203 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2204 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2205 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2206 return true;
2207 }
2208 }
2209 return false;
2210}
2211
2212void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2213 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2214 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2215}
2216
2217void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2218 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2219 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2220 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2221 }
2222}
2223
2224} // namespace
2225
2226TEST_F(BinderTest, FirewallSetFirewallType) {
2227 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2228 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2229 expectFirewallWhitelistMode();
2230
2231 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2232 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2233 expectFirewallBlacklistMode();
2234
2235 // set firewall type blacklist twice
2236 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2237 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2238 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2239 expectFirewallBlacklistMode();
2240
2241 // set firewall type whitelist twice
2242 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2243 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2244 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2245 expectFirewallWhitelistMode();
2246
2247 // reset firewall type to default
2248 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2249 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2250 expectFirewallBlacklistMode();
2251}
2252
2253TEST_F(BinderTest, FirewallSetInterfaceRule) {
2254 // setinterfaceRule is not supported in BLACKLIST MODE
2255 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2256 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2257
2258 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2259 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2260
2261 // set WHITELIST mode first
2262 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2263 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2264
2265 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2266 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2267 expectFirewallInterfaceRuleAllowExists(sTun.name());
2268
2269 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2270 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2271 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2272
2273 // reset firewall mode to default
2274 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2275 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2276 expectFirewallBlacklistMode();
2277}
2278
2279TEST_F(BinderTest, FirewallSetUidRule) {
2280 SKIP_IF_BPF_SUPPORTED;
2281
2282 int32_t uid = randomUid();
2283
2284 // Doze allow
2285 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2286 INetd::FIREWALL_RULE_ALLOW);
2287 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2288 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2289
2290 // Doze deny
2291 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2292 INetd::FIREWALL_RULE_DENY);
2293 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2294 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2295
2296 // Powersave allow
2297 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2298 INetd::FIREWALL_RULE_ALLOW);
2299 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2300 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2301
2302 // Powersave deny
2303 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2304 INetd::FIREWALL_RULE_DENY);
2305 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2306 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2307
2308 // Standby deny
2309 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2310 INetd::FIREWALL_RULE_DENY);
2311 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2312 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2313
2314 // Standby allow
2315 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2316 INetd::FIREWALL_RULE_ALLOW);
2317 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2318 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2319
2320 // None deny in BLACKLIST
2321 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2322 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2323 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2324 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2325
2326 // None allow in BLACKLIST
2327 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2328 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2329 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2330 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2331
2332 // set firewall type whitelist twice
2333 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2334 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2335 expectFirewallWhitelistMode();
2336
2337 // None allow in WHITELIST
2338 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2339 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2340 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2341 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2342
2343 // None deny in WHITELIST
2344 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2345 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2346 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2347 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2348
2349 // reset firewall mode to default
2350 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2351 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2352 expectFirewallBlacklistMode();
2353}
2354
2355TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2356 SKIP_IF_BPF_SUPPORTED;
2357
2358 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2359 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2360 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2361
2362 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2363 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2364 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2365
2366 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2367 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2368 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2369
2370 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2371 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2372 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2373
2374 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2375 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2376 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2377
2378 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2379 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2380 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2381}
Luke Huangf7782042018-08-08 13:13:04 +08002382
2383namespace {
2384
2385std::string hwAddrToStr(unsigned char* hwaddr) {
2386 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2387 hwaddr[4], hwaddr[5]);
2388}
2389
2390int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2391 int prefixLength = 0;
2392 uint32_t m = ntohl(mask);
2393 while (m & (1 << 31)) {
2394 prefixLength++;
2395 m = m << 1;
2396 }
2397 return prefixLength;
2398}
2399
2400std::string toStdString(const String16& s) {
2401 return std::string(String8(s.string()));
2402}
2403
2404android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2405 const auto& sys = sSyscalls.get();
2406 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2407 EXPECT_TRUE(isOk(fd.status()));
2408
2409 struct ifreq ifr = {};
2410 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2411
2412 return sys.ioctl(fd.value(), flag, &ifr);
2413}
2414
2415std::string getInterfaceHwAddr(const std::string& ifName) {
2416 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2417
2418 unsigned char hwaddr[ETH_ALEN] = {};
2419 if (isOk(res.status())) {
2420 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2421 }
2422
2423 return hwAddrToStr(hwaddr);
2424}
2425
2426int getInterfaceIPv4Prefix(const std::string& ifName) {
2427 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2428
2429 int prefixLength = 0;
2430 if (isOk(res.status())) {
2431 prefixLength = ipv4NetmaskToPrefixLength(
2432 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2433 }
2434
2435 return prefixLength;
2436}
2437
2438std::string getInterfaceIPv4Addr(const std::string& ifName) {
2439 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2440
2441 struct in_addr addr = {};
2442 if (isOk(res.status())) {
2443 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2444 }
2445
2446 return std::string(inet_ntoa(addr));
2447}
2448
2449std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2450 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2451
2452 unsigned flags = 0;
2453 if (isOk(res.status())) {
2454 flags = res.value().ifr_flags;
2455 }
2456
2457 std::vector<std::string> ifFlags;
2458 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2459 : toStdString(INetd::IF_STATE_DOWN()));
2460
2461 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2462 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2463 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2464 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2465 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2466
2467 return ifFlags;
2468}
2469
2470bool compareListInterface(const std::vector<std::string>& interfaceList) {
2471 const auto& res = InterfaceController::getIfaceNames();
2472 EXPECT_TRUE(isOk(res));
2473
2474 std::vector<std::string> resIfList;
2475 resIfList.reserve(res.value().size());
2476 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2477
2478 return resIfList == interfaceList;
2479}
2480
2481int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2482 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2483 return readIntFromPath(path);
2484}
2485
2486bool getInterfaceEnableIPv6(const std::string& ifName) {
2487 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2488
2489 int disableIPv6 = readIntFromPath(path);
2490 return !disableIPv6;
2491}
2492
2493int getInterfaceMtu(const std::string& ifName) {
2494 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2495 return readIntFromPath(path);
2496}
2497
2498void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2499 EXPECT_TRUE(compareListInterface(interfaceList));
2500}
2501
2502void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2503 const InterfaceConfigurationParcel& interfaceCfg) {
2504 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2505 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2506 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2507 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2508}
2509
2510void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2511 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2512 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2513
2514 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2515 for (const auto& flag : setCfg.flags) {
2516 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2517 }
2518}
2519
2520void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2521 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2522 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2523}
2524
2525void expectInterfaceNoAddr(const std::string& ifName) {
2526 // noAddr
2527 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2528 // noPrefix
2529 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2530}
2531
2532void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2533 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2534 EXPECT_EQ(enableIPv6, enable);
2535}
2536
2537void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2538 int mtuSize = getInterfaceMtu(ifName);
2539 EXPECT_EQ(mtu, mtuSize);
2540}
2541
2542InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2543 const std::string& addr, int prefixLength,
2544 const std::vector<std::string>& flags) {
2545 InterfaceConfigurationParcel cfg;
2546 cfg.ifName = ifName;
2547 cfg.hwAddr = "";
2548 cfg.ipv4Addr = addr;
2549 cfg.prefixLength = prefixLength;
2550 cfg.flags = flags;
2551 return cfg;
2552}
2553
2554void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2555 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2556 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2557
2558 for (const auto& flag : expectedFlags) {
2559 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2560 interfaceCfg.flags.end());
2561 }
2562
2563 for (const auto& flag : unexpectedFlags) {
2564 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2565 interfaceCfg.flags.end());
2566 }
2567}
2568
2569} // namespace
2570
2571TEST_F(BinderTest, InterfaceList) {
2572 std::vector<std::string> interfaceListResult;
2573
2574 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2575 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2576 expectInterfaceList(interfaceListResult);
2577}
2578
2579TEST_F(BinderTest, InterfaceGetCfg) {
2580 InterfaceConfigurationParcel interfaceCfgResult;
2581
2582 // Add test physical network
2583 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2584 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2585
2586 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2587 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2588 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2589 expectTunFlags(interfaceCfgResult);
2590
2591 // Remove test physical network
2592 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2593}
2594
2595TEST_F(BinderTest, InterfaceSetCfg) {
2596 const std::string testAddr = "192.0.2.3";
2597 const int testPrefixLength = 24;
2598 std::vector<std::string> upFlags = {"up"};
2599 std::vector<std::string> downFlags = {"down"};
2600
2601 // Add test physical network
2602 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2603 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2604
2605 // Set tun interface down.
2606 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2607 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2608 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2609 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2610
2611 // Set tun interface up again.
2612 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2613 status = mNetd->interfaceSetCfg(interfaceCfg);
2614 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2615 status = mNetd->interfaceClearAddrs(sTun.name());
2616 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2617
2618 // Remove test physical network
2619 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2620}
2621
2622TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2623 // enable
2624 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2625 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2626 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2627
2628 // disable
2629 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2630 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2631 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2632}
2633
2634TEST_F(BinderTest, InterfaceClearAddr) {
2635 const std::string testAddr = "192.0.2.3";
2636 const int testPrefixLength = 24;
2637 std::vector<std::string> noFlags{};
2638
2639 // Add test physical network
2640 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2641 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2642
2643 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2644 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2645 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2646 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2647
2648 status = mNetd->interfaceClearAddrs(sTun.name());
2649 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2650 expectInterfaceNoAddr(sTun.name());
2651
2652 // Remove test physical network
2653 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2654}
2655
2656TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2657 // Add test physical network
2658 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2659 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2660
2661 // disable
2662 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2663 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2664 expectInterfaceEnableIPv6(sTun.name(), false);
2665
2666 // enable
2667 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2668 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2669 expectInterfaceEnableIPv6(sTun.name(), true);
2670
2671 // Remove test physical network
2672 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2673}
2674
2675TEST_F(BinderTest, InterfaceSetMtu) {
2676 const int testMtu = 1200;
2677
2678 // Add test physical network
2679 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2680 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2681
2682 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2683 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2684 expectInterfaceMtu(sTun.name(), testMtu);
2685
2686 // Remove test physical network
2687 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2688}
Luke Huang19b49c52018-10-22 12:12:05 +09002689
2690namespace {
2691
2692constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2693constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002694constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002695constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2696
Luke Huangae038f82018-11-05 11:17:31 +09002697int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002698 return listIptablesRuleByTable(binary, table, chainName).size();
2699}
2700
2701bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2702 const std::vector<std::string>& targetVec) {
2703 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2704 if (targetVec.size() != rules.size() - 2) {
2705 return false;
2706 }
2707
2708 /*
Luke Huangae038f82018-11-05 11:17:31 +09002709 * Check that the rules match. Note that this function matches substrings, not entire rules,
2710 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002711 * Skip first two lines since rules start from third line.
2712 * Chain chainName (x references)
2713 * pkts bytes target prot opt in out source destination
2714 * ...
2715 */
2716 int rIndex = 2;
2717 for (const auto& target : targetVec) {
2718 if (rules[rIndex].find(target) == std::string::npos) {
2719 return false;
2720 }
2721 rIndex++;
2722 }
2723 return true;
2724}
2725
2726void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2727 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2728 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2729 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002730 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002731 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2732 "DROP"};
2733
2734 // V4
2735 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2736 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002737 EXPECT_TRUE(
2738 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002739 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2740
Luke Huangae038f82018-11-05 11:17:31 +09002741 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002742 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2743
2744 // V6
2745 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002746 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2747 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002748
2749 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2750 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2751 extIf));
2752 }
2753}
2754
2755void expectNatDisable() {
2756 // It is the default DROP rule with tethering disable.
2757 // Chain tetherctrl_FORWARD (1 references)
2758 // pkts bytes target prot opt in out source destination
2759 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2760 std::vector<std::string> forwardV4Match = {"DROP"};
2761 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2762
2763 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002764 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2765 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002766
Luke Huangae038f82018-11-05 11:17:31 +09002767 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2768 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002769
2770 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2771}
2772
2773} // namespace
2774
2775TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002776 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2777 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2778 expectNatEnable(sTun.name(), sTun2.name());
2779
2780 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
2781 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2782 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09002783}
Chenbo Fengf5663d82018-11-08 16:10:48 -08002784
2785namespace {
2786
2787using TripleInt = std::array<int, 3>;
2788
2789TripleInt readProcFileToTripleInt(const std::string& path) {
2790 std::string valueString;
2791 int min, def, max;
2792 EXPECT_TRUE(ReadFileToString(path, &valueString));
2793 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
2794 return {min, def, max};
2795}
2796
2797void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
2798 std::string testRmemValues =
2799 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
2800 std::string testWmemValues =
2801 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
2802 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
2803
2804 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2805 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2806
2807 for (int i = 0; i < 3; i++) {
2808 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
2809 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
2810 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
2811 }
2812}
2813
2814} // namespace
2815
2816TEST_F(BinderTest, TcpBufferSet) {
2817 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
2818 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
2819 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
2820 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
2821
2822 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
2823 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
2824}
Luke Huang528af602018-08-29 19:06:05 +08002825
Chenbo Feng48eaed32018-12-26 17:40:21 -08002826namespace {
2827
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002828void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Chenbo Feng48eaed32018-12-26 17:40:21 -08002829 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
2830 android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
2831 for (int32_t uid : uids) {
2832 android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
2833 if (exist) {
2834 EXPECT_TRUE(isOk(permission));
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002835 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08002836 } else {
2837 EXPECT_FALSE(isOk(permission));
2838 EXPECT_EQ(ENOENT, permission.status().code());
2839 }
2840 }
2841}
2842
2843} // namespace
2844
2845TEST_F(BinderTest, TestInternetPermission) {
2846 SKIP_IF_BPF_NOT_SUPPORTED;
2847
2848 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
2849
2850 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002851 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07002852 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08002853 checkUidsInPermissionMap(appUids, true);
2854 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
2855 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08002856}
2857
Luke Huang528af602018-08-29 19:06:05 +08002858TEST_F(BinderTest, UnsolEvents) {
2859 auto testUnsolService = android::net::TestUnsolService::start();
2860 std::string oldTunName = sTun.name();
2861 std::string newTunName = "unsolTest";
2862 testUnsolService->tarVec.push_back(oldTunName);
2863 testUnsolService->tarVec.push_back(newTunName);
2864 auto& cv = testUnsolService->getCv();
2865 auto& cvMutex = testUnsolService->getCvMutex();
2866 binder::Status status = mNetd->registerUnsolicitedEventListener(
2867 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
2868 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2869
2870 // TODO: Add test for below events
2871 // StrictCleartextDetected / InterfaceDnsServersAdded
2872 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
2873
2874 {
2875 std::unique_lock lock(cvMutex);
2876
2877 // Re-init test Tun, and we expect that we will get some unsol events.
2878 // Use the test Tun device name to verify if we receive its unsol events.
2879 sTun.destroy();
2880 // Use predefined name
2881 sTun.init(newTunName);
2882
2883 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
2884 }
2885
2886 // bit mask 1101101000
2887 // Test only covers below events currently
2888 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
2889 InterfaceLinkStatusChanged | RouteChanged;
2890 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08002891
2892 // Re-init sTun to clear predefined name
2893 sTun.destroy();
2894 sTun.init();
2895}
2896
2897TEST_F(BinderTest, NDC) {
2898 struct Command {
2899 const std::string cmdString;
2900 const std::string expectedResult;
2901 };
2902
2903 // clang-format off
2904 // Do not change the commands order
2905 const Command networkCmds[] = {
2906 {StringPrintf("ndc network create %d", TEST_NETID1),
2907 "200 0 success"},
2908 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
2909 "200 0 success"},
2910 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
2911 "200 0 success"},
2912 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
2913 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
2914 {StringPrintf("ndc network destroy %d", TEST_NETID1),
2915 "200 0 success"},
2916 };
2917
2918 const std::vector<Command> ipfwdCmds = {
2919 {"ndc ipfwd enable " + sTun.name(),
2920 "200 0 ipfwd operation succeeded"},
2921 {"ndc ipfwd disable " + sTun.name(),
2922 "200 0 ipfwd operation succeeded"},
2923 {"ndc ipfwd add lo2 lo3",
2924 "400 0 ipfwd operation failed (No such process)"},
2925 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
2926 "200 0 ipfwd operation succeeded"},
2927 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
2928 "200 0 ipfwd operation succeeded"},
2929 };
2930
2931 static const struct {
2932 const char* ipVersion;
2933 const char* testDest;
2934 const char* testNextHop;
2935 const bool expectSuccess;
2936 const std::string expectedResult;
2937 } kTestData[] = {
2938 {IP_RULE_V4, "0.0.0.0/0", "", true,
2939 "200 0 success"},
2940 {IP_RULE_V4, "10.251.0.0/16", "", true,
2941 "200 0 success"},
2942 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
2943 "400 0 addRoute() failed (Invalid argument)",},
2944 {IP_RULE_V6, "::/0", "", true,
2945 "200 0 success"},
2946 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
2947 "200 0 success"},
2948 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
2949 "400 0 addRoute() failed (Invalid argument)"},
2950 };
2951 // clang-format on
2952
2953 for (const auto& cmd : networkCmds) {
2954 const std::vector<std::string> result = runCommand(cmd.cmdString);
2955 SCOPED_TRACE(cmd.cmdString);
2956 EXPECT_EQ(result.size(), 1U);
2957 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
2958 }
2959
2960 for (const auto& cmd : ipfwdCmds) {
2961 const std::vector<std::string> result = runCommand(cmd.cmdString);
2962 SCOPED_TRACE(cmd.cmdString);
2963 EXPECT_EQ(result.size(), 1U);
2964 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
2965 }
2966
2967 // Add test physical network
2968 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2969 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2970
2971 for (const auto& td : kTestData) {
2972 const std::string routeAddCmd =
2973 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
2974 td.testDest, td.testNextHop);
2975 const std::string routeRemoveCmd =
2976 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
2977 sTun.name().c_str(), td.testDest, td.testNextHop);
2978 std::vector<std::string> result = runCommand(routeAddCmd);
2979 SCOPED_TRACE(routeAddCmd);
2980 EXPECT_EQ(result.size(), 1U);
2981 EXPECT_EQ(td.expectedResult, Trim(result[0]));
2982 if (td.expectSuccess) {
2983 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2984 sTun.name().c_str());
2985 result = runCommand(routeRemoveCmd);
2986 EXPECT_EQ(result.size(), 1U);
2987 EXPECT_EQ(td.expectedResult, Trim(result[0]));
2988 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
2989 sTun.name().c_str());
2990 }
2991 }
2992 // Remove test physical network
2993 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09002994}
Luke Huang0e5e69d2019-03-06 15:42:38 +08002995
Luke Huang2ff8b342019-04-30 15:33:33 +08002996TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08002997 sp<IBinder> binder;
2998 binder::Status status = mNetd->getOemNetd(&binder);
2999 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3000 sp<com::android::internal::net::IOemNetd> oemNetd;
3001 if (binder != nullptr) {
3002 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3003 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003004 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003005
3006 TimedOperation t("OemNetd isAlive RPC");
3007 bool isAlive = false;
3008 oemNetd->isAlive(&isAlive);
3009 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003010
3011 class TestOemUnsolListener
3012 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3013 public:
3014 android::binder::Status onRegistered() override {
3015 std::lock_guard lock(mCvMutex);
3016 mCv.notify_one();
3017 return android::binder::Status::ok();
3018 }
3019 std::condition_variable& getCv() { return mCv; }
3020 std::mutex& getCvMutex() { return mCvMutex; }
3021
3022 private:
3023 std::mutex mCvMutex;
3024 std::condition_variable mCv;
3025 };
3026
3027 // Start the Binder thread pool.
3028 android::ProcessState::self()->startThreadPool();
3029
3030 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3031
3032 auto& cv = testListener->getCv();
3033 auto& cvMutex = testListener->getCvMutex();
3034
3035 {
3036 std::unique_lock lock(cvMutex);
3037
3038 status = oemNetd->registerOemUnsolicitedEventListener(
3039 ::android::interface_cast<
3040 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3041 testListener));
3042 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3043
3044 // Wait for receiving expected events.
3045 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3046 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003047}
Luke Huangd2861982019-05-17 19:47:28 +08003048
3049void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3050 int fallthroughNetId) {
3051 // Re-init sTun* to ensure route rule exists.
3052 sTun.destroy();
3053 sTun.init();
3054 sTun2.destroy();
3055 sTun2.init();
3056
3057 // Create physical network with fallthroughNetId but not set it as default network
3058 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3059 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3060
3061 // Create VPN with vpnNetId
3062 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3063
3064 // Add uid to VPN
3065 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3066 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3067
3068 // Add default route to fallthroughNetwork
3069 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3070 // Add limited route
3071 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3072}
3073
3074namespace {
3075
3076class ScopedUidChange {
3077 public:
3078 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3079 mStoredUid = getuid();
3080 if (mInputUid == mStoredUid) return;
3081 EXPECT_TRUE(seteuid(uid) == 0);
3082 }
3083 ~ScopedUidChange() {
3084 if (mInputUid == mStoredUid) return;
3085 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3086 }
3087
3088 private:
3089 uid_t mInputUid;
3090 uid_t mStoredUid;
3091};
3092
3093constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3094
3095void clearQueue(int tunFd) {
3096 char buf[4096];
3097 int ret;
3098 do {
3099 ret = read(tunFd, buf, sizeof(buf));
3100 } while (ret > 0);
3101}
3102
3103void checkDataReceived(int udpSocket, int tunFd) {
3104 char buf[4096] = {};
3105 // Clear tunFd's queue before write something because there might be some
3106 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3107 clearQueue(tunFd);
3108 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3109 // TODO: extract header and verify data
3110 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3111}
3112
3113bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3114 ScopedUidChange scopedUidChange(uid);
Bernie Innocentid26a04a2019-10-30 17:15:15 +09003115 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Luke Huangd2861982019-05-17 19:47:28 +08003116 if (testSocket < 0) return false;
3117
Nick Desaulniers6b357502019-10-11 09:26:44 -07003118 const sockaddr_in6 dst6 = {
3119 .sin6_family = AF_INET6,
3120 .sin6_port = 42,
3121 .sin6_addr = dstAddr,
3122 };
Luke Huangd2861982019-05-17 19:47:28 +08003123 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3124 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3125 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3126 if (res == -1) return false;
3127
3128 char addr[INET6_ADDRSTRLEN];
3129 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3130 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3131 checkDataReceived(testSocket, tunFd);
3132 return true;
3133}
3134
3135void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3136 std::string vpnFallthroughRule =
3137 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3138 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3139 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3140 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3141 }
3142}
3143
3144void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3145 const TunInterface& fallthroughNetwork,
3146 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3147 int fallthroughNetId = TEST_NETID1) {
3148 // Set default network to NETID_UNSET
3149 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3150
3151 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3152 in6_addr insideVpnAddr = {
3153 {// 2001:db8:cafe::1
3154 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3155 // outsideVpnAddr will hit the route in the fallthrough network route table
3156 // because we added default route in createVpnNetworkWithUid
3157 in6_addr outsideVpnAddr = {
3158 {// 2607:f0d0:1002::4
3159 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3160
3161 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3162 int vpnFd = vpnNetwork.getFdForTesting();
3163 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3164 // default network.
3165 Fwmark fwmark;
3166 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3167 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3168
3169 // Set default network
3170 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3171
3172 // Connections go on the default network because UID 0 is not subject to the VPN.
3173 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3174 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3175 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3176 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3177
3178 // Check if fallthrough rule exists
3179 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3180
3181 // Expect fallthrough to default network
3182 // The fwmark differs depending on whether the VPN is bypassable or not.
3183 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3184 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3185
3186 // Expect connect success, packet will be sent to vpnFd.
3187 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3188 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3189
3190 // Explicitly select vpn network
3191 setNetworkForProcess(vpnNetId);
3192
3193 // Expect fallthrough to default network
3194 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3195 // Expect the mark contains all the bit because we've selected network.
3196 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3197
3198 // Expect connect success, packet will be sent to vpnFd.
3199 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3200 // Expect the mark contains all the bit because we've selected network.
3201 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3202
3203 // Explicitly select fallthrough network
3204 setNetworkForProcess(fallthroughNetId);
3205
3206 // The mark is set to fallthrough network because we've selected it.
3207 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3208 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3209
3210 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3211 if (bypassable) {
3212 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3213 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3214 } else {
3215 // If not, no permission to bypass vpn.
3216 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3217 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3218 }
3219}
3220
3221} // namespace
3222
3223TEST_F(BinderTest, SecureVPNFallthrough) {
3224 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3225 // Get current default network NetId
3226 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3227 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3228}
3229
3230TEST_F(BinderTest, BypassableVPNFallthrough) {
3231 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3232 // Get current default network NetId
3233 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3234 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003235}