blob: 35677903b4f97ce6ff2571c721b43a82708595f6 [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>
Lorenzo Colitti56165db2020-05-29 21:37:09 +090035#include <net/ethernet.h>
Benedict Wonga450e722018-05-07 10:29:02 -070036#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080037#include <netdb.h>
38#include <netinet/in.h>
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +000039#include <netinet/tcp.h>
Ben Schwartze7601812017-04-28 16:38:29 -040040#include <openssl/base64.h>
Luke Huangf7782042018-08-08 13:13:04 +080041#include <sys/socket.h>
42#include <sys/types.h>
Lorenzo Colitti563d98b2016-04-24 13:13:14 +090043
Luke Huang531f5d32018-08-03 15:19:05 +080044#include <android-base/file.h>
Lorenzo Colitti56165db2020-05-29 21:37:09 +090045#include <android-base/format.h>
Erik Klinecc4f2732016-08-03 11:24:27 +090046#include <android-base/macros.h>
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +000047#include <android-base/scopeguard.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090048#include <android-base/stringprintf.h>
Lorenzo Colittidedd2712016-03-22 12:36:29 +090049#include <android-base/strings.h>
Chiachang Wang00fc62f2019-12-04 20:38:26 +080050#include <android/multinetwork.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080051#include <binder/IPCThreadState.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080052#include <bpf/BpfMap.h>
Chenbo Feng837ddfc2018-05-08 13:45:08 -070053#include <bpf/BpfUtils.h>
Luke Huang2ff8b342019-04-30 15:33:33 +080054#include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
55#include <com/android/internal/net/IOemNetd.h>
Robin Leeb8087362016-03-30 18:43:08 +010056#include <cutils/multiuser.h>
Lorenzo Colitti89faa342016-02-26 11:38:47 +090057#include <gtest/gtest.h>
Chenbo Feng48eaed32018-12-26 17:40:21 -080058#include <netdbpf/bpf_shared.h>
Lorenzo Colitti755faa92016-07-27 22:10:49 +090059#include <netutils/ifc.h>
Luke Huangd2861982019-05-17 19:47:28 +080060#include "Fwmark.h"
Nathan Harold21299f72018-03-16 20:13:03 -070061#include "InterfaceController.h"
Luke Huangd2861982019-05-17 19:47:28 +080062#include "NetdClient.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090063#include "NetdConstants.h"
Chiachang Wang00fc62f2019-12-04 20:38:26 +080064#include "NetworkController.h"
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +000065#include "SockDiag.h"
Luke Huang528af602018-08-29 19:06:05 +080066#include "TestUnsolService.h"
Nathan Harold21299f72018-03-16 20:13:03 -070067#include "XfrmController.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090068#include "android/net/INetd.h"
69#include "binder/IServiceManager.h"
Luke Huang25599322019-06-14 00:34:05 +080070#include "netdutils/InternetAddresses.h"
Mike Yue7e332f2019-03-13 17:15:48 +080071#include "netdutils/Stopwatch.h"
Nathan Harold21299f72018-03-16 20:13:03 -070072#include "netdutils/Syscalls.h"
Luke Huangd2861982019-05-17 19:47:28 +080073#include "netid_client.h" // NETID_UNSET
Lorenzo Colitti758bccc2019-06-26 22:12:35 +090074#include "test_utils.h"
Mike Yu5ae61542018-10-19 22:11:43 +080075#include "tun_interface.h"
Lorenzo Colitti89faa342016-02-26 11:38:47 +090076
Lorenzo Colitti5c68b9c2017-08-10 18:50:10 +090077#define IP6TABLES_PATH "/system/bin/ip6tables"
78#define IPTABLES_PATH "/system/bin/iptables"
Luke Huang0051a622018-07-23 20:30:16 +080079#define RAW_TABLE "raw"
80#define MANGLE_TABLE "mangle"
Luke Huang531f5d32018-08-03 15:19:05 +080081#define FILTER_TABLE "filter"
Luke Huang19b49c52018-10-22 12:12:05 +090082#define NAT_TABLE "nat"
Lorenzo Colitti755faa92016-07-27 22:10:49 +090083
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090084namespace binder = android::binder;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090085
86using android::IBinder;
87using android::IServiceManager;
88using android::sp;
89using android::String16;
90using android::String8;
91using android::base::Join;
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +000092using android::base::make_scope_guard;
Luke Huang531f5d32018-08-03 15:19:05 +080093using android::base::ReadFileToString;
Lorenzo Colittiaff28792017-09-26 17:46:18 +090094using android::base::StartsWith;
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +090095using android::base::StringPrintf;
Luke Huang531f5d32018-08-03 15:19:05 +080096using android::base::Trim;
Bernie Innocentid26a04a2019-10-30 17:15:15 +090097using android::base::unique_fd;
Lorenzo Colitti89faa342016-02-26 11:38:47 +090098using android::net::INetd;
Luke Huangf7782042018-08-08 13:13:04 +080099using android::net::InterfaceConfigurationParcel;
100using android::net::InterfaceController;
Chiachang Wang00fc62f2019-12-04 20:38:26 +0800101using android::net::MarkMaskParcel;
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +0000102using android::net::SockDiag;
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000103using android::net::TetherOffloadRuleParcel;
Luke Huangcaebcbb2018-09-27 20:37:14 +0800104using android::net::TetherStatsParcel;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900105using android::net::TunInterface;
Luke Huang94658ac2018-10-18 19:35:12 +0900106using android::net::UidRangeParcel;
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +0000107using android::netdutils::IPAddress;
Luke Huang25599322019-06-14 00:34:05 +0800108using android::netdutils::ScopedAddrinfo;
Luke Huangf7782042018-08-08 13:13:04 +0800109using android::netdutils::sSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +0800110using android::netdutils::Stopwatch;
Robin Leeb8087362016-03-30 18:43:08 +0100111
112static const char* IP_RULE_V4 = "-4";
113static const char* IP_RULE_V6 = "-6";
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900114static const int TEST_NETID1 = 65501;
115static const int TEST_NETID2 = 65502;
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +0000116static const char* DNSMASQ = "dnsmasq";
Chenbo Feng48eaed32018-12-26 17:40:21 -0800117
118// Use maximum reserved appId for applications to avoid conflict with existing
119// uids.
120static const int TEST_UID1 = 99999;
121static const int TEST_UID2 = 99998;
122
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900123constexpr int BASE_UID = AID_USER_OFFSET * 5;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900124
Benedict Wongb2daefb2017-12-06 22:05:46 -0800125static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
126static const std::string ESP_ALLOW_RULE("esp");
127
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900128class BinderTest : public ::testing::Test {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900129 public:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900130 BinderTest() {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900131 sp<IServiceManager> sm = android::defaultServiceManager();
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900132 sp<IBinder> binder = sm->getService(String16("netd"));
133 if (binder != nullptr) {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900134 mNetd = android::interface_cast<INetd>(binder);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900135 }
136 }
137
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900138 void SetUp() override {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900139 ASSERT_NE(nullptr, mNetd.get());
140 }
141
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900142 void TearDown() override {
143 mNetd->networkDestroy(TEST_NETID1);
144 mNetd->networkDestroy(TEST_NETID2);
Luke Huangd2861982019-05-17 19:47:28 +0800145 setNetworkForProcess(NETID_UNSET);
146 // Restore default network
147 if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900148 }
149
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900150 bool allocateIpSecResources(bool expectOk, int32_t* spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700151
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900152 // Static because setting up the tun interface takes about 40ms.
153 static void SetUpTestCase() {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900154 ASSERT_EQ(0, sTun.init());
Luke Huang19b49c52018-10-22 12:12:05 +0900155 ASSERT_EQ(0, sTun2.init());
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900156 ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
Luke Huang19b49c52018-10-22 12:12:05 +0900157 ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900158 }
159
160 static void TearDownTestCase() {
161 // Closing the socket removes the interface and IP addresses.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900162 sTun.destroy();
Luke Huang19b49c52018-10-22 12:12:05 +0900163 sTun2.destroy();
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900164 }
165
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900166 static void fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
167 unique_fd* acceptedSocket);
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900168
Luke Huangd2861982019-05-17 19:47:28 +0800169 void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
170 int fallthroughNetId = TEST_NETID1);
171
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900172 protected:
Luke Huangd2861982019-05-17 19:47:28 +0800173 // Use -1 to represent that default network was not modified because
174 // real netId must be an unsigned value.
175 int mStoredDefaultNetwork = -1;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900176 sp<INetd> mNetd;
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900177 static TunInterface sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900178 static TunInterface sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900179};
180
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900181TunInterface BinderTest::sTun;
Luke Huang19b49c52018-10-22 12:12:05 +0900182TunInterface BinderTest::sTun2;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900183
Lorenzo Colitti699aa992016-04-15 10:22:37 +0900184class TimedOperation : public Stopwatch {
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900185 public:
Chih-Hung Hsieh18051052016-05-06 10:36:13 -0700186 explicit TimedOperation(const std::string &name): mName(name) {}
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900187 virtual ~TimedOperation() {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900188 std::cerr << " " << mName << ": " << timeTakenUs() << "us" << std::endl;
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900189 }
190
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900191 private:
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900192 std::string mName;
193};
194
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900195TEST_F(BinderTest, IsAlive) {
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900196 TimedOperation t("isAlive RPC");
197 bool isAlive = false;
198 mNetd->isAlive(&isAlive);
199 ASSERT_TRUE(isAlive);
200}
201
Benedict Wongb2daefb2017-12-06 22:05:46 -0800202static bool iptablesNoSocketAllowRuleExists(const char *chainName){
203 return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
204 iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
205}
206
207static bool iptablesEspAllowRuleExists(const char *chainName){
208 return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
209 iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
210}
211
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900212TEST_F(BinderTest, FirewallReplaceUidChain) {
Chenbo Feng837ddfc2018-05-08 13:45:08 -0700213 SKIP_IF_BPF_SUPPORTED;
214
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900215 std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
216 const int kNumUids = 500;
217 std::vector<int32_t> noUids(0);
218 std::vector<int32_t> uids(kNumUids);
219 for (int i = 0; i < kNumUids; i++) {
220 uids[i] = randomUid();
221 }
222
223 bool ret;
224 {
225 TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900226 mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900227 }
228 EXPECT_EQ(true, ret);
Benedict Wongb2daefb2017-12-06 22:05:46 -0800229 EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
230 EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
231 EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
232 EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900233 {
234 TimedOperation op("Clearing whitelist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900235 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900236 }
237 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900238 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
239 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900240
241 {
242 TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
Erik Klinef52d4522018-03-14 15:01:46 +0900243 mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900244 }
245 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900246 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
247 EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Benedict Wongb2daefb2017-12-06 22:05:46 -0800248 EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
249 EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900250
251 {
252 TimedOperation op("Clearing blacklist chain");
Erik Klinef52d4522018-03-14 15:01:46 +0900253 mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900254 }
255 EXPECT_EQ(true, ret);
Lorenzo Colitti50b198a2017-03-30 02:50:09 +0900256 EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
257 EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900258
259 // Check that the call fails if iptables returns an error.
260 std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
Erik Klinef52d4522018-03-14 15:01:46 +0900261 mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
Lorenzo Colitti89faa342016-02-26 11:38:47 +0900262 EXPECT_EQ(false, ret);
263}
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900264
Benedict Wong319f17e2018-05-15 17:06:44 -0700265TEST_F(BinderTest, IpSecTunnelInterface) {
George Burgess IVc4a6d272018-05-21 14:41:57 -0700266 const struct TestData {
267 const std::string family;
268 const std::string deviceName;
269 const std::string localAddress;
270 const std::string remoteAddress;
manojboopathi8707f232018-01-02 14:45:47 -0800271 int32_t iKey;
272 int32_t oKey;
Benedict Wonga450e722018-05-07 10:29:02 -0700273 int32_t ifId;
manojboopathi8707f232018-01-02 14:45:47 -0800274 } kTestData[] = {
Benedict Wonga450e722018-05-07 10:29:02 -0700275 {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
276 {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
277 0xFFFE},
manojboopathi8707f232018-01-02 14:45:47 -0800278 };
279
Sehee Park8659b8d2018-11-16 10:53:16 +0900280 for (size_t i = 0; i < std::size(kTestData); i++) {
Nathan Harold21299f72018-03-16 20:13:03 -0700281 const auto& td = kTestData[i];
manojboopathi8707f232018-01-02 14:45:47 -0800282
283 binder::Status status;
284
Benedict Wong319f17e2018-05-15 17:06:44 -0700285 // Create Tunnel Interface.
286 status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700287 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800288 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
289
Benedict Wonga450e722018-05-07 10:29:02 -0700290 // Check that the interface exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900291 EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
Benedict Wonga450e722018-05-07 10:29:02 -0700292
Benedict Wong319f17e2018-05-15 17:06:44 -0700293 // Update Tunnel Interface.
294 status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
Benedict Wonga450e722018-05-07 10:29:02 -0700295 td.iKey, td.oKey, td.ifId);
manojboopathi8707f232018-01-02 14:45:47 -0800296 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
297
Benedict Wong319f17e2018-05-15 17:06:44 -0700298 // Remove Tunnel Interface.
299 status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
manojboopathi8707f232018-01-02 14:45:47 -0800300 EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
Benedict Wonga450e722018-05-07 10:29:02 -0700301
302 // Check that the interface no longer exists
Sehee Park8659b8d2018-11-16 10:53:16 +0900303 EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
manojboopathi8707f232018-01-02 14:45:47 -0800304 }
305}
306
Benedict Wong1cb73df2018-12-03 00:54:14 -0800307TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900308 unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Benedict Wong1cb73df2018-12-03 00:54:14 -0800309 android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
310
311 int sockOptVal = UDP_ENCAP_ESPINUDP;
312 setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
313
314 binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
315 EXPECT_TRUE(res.isOk());
316
317 struct stat info;
318 EXPECT_EQ(0, fstat(sockFd.get(), &info));
319 EXPECT_EQ(1001, (int) info.st_uid);
320}
321
Nathan Harold2deff322018-05-10 14:03:48 -0700322// IPsec tests are not run in 32 bit mode; both 32-bit kernels and
323// mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
324#if INTPTR_MAX != INT32_MAX
Bernie Innocentia5161a02019-01-30 22:40:53 +0900325
326using android::net::XfrmController;
327
Benedict Wonga04ffa72018-05-09 21:42:42 -0700328static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
329 static_cast<int>(android::net::XfrmDirection::OUT)};
330static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
331
Nathan Harold21299f72018-03-16 20:13:03 -0700332#define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
333 do { if ((_expect_) != (_ret_)) return false; } while(false)
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900334bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900335 android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
Nathan Harold21299f72018-03-16 20:13:03 -0700336 SCOPED_TRACE(status);
337 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
338
339 // Add a policy
Benedict Wonga450e722018-05-07 10:29:02 -0700340 status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700341 SCOPED_TRACE(status);
342 RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
343
344 // Add an ipsec interface
Benedict Wonga450e722018-05-07 10:29:02 -0700345 return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
346 0xD00D, 0xE00D, false)
347 .ok();
Nathan Harold21299f72018-03-16 20:13:03 -0700348}
349
Benedict Wonga04ffa72018-05-09 21:42:42 -0700350TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900351 android::binder::Status status;
Benedict Wonga04ffa72018-05-09 21:42:42 -0700352
353 // Repeat to ensure cleanup and recreation works correctly
354 for (int i = 0; i < 2; i++) {
355 for (int direction : XFRM_DIRECTIONS) {
356 for (int addrFamily : ADDRESS_FAMILIES) {
357 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
Benedict Wonga450e722018-05-07 10:29:02 -0700358 "127.0.0.6", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700359 EXPECT_TRUE(status.isOk())
360 << " family: " << addrFamily << " direction: " << direction;
361 }
362 }
363
364 // Cleanup
365 for (int direction : XFRM_DIRECTIONS) {
366 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700367 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700368 EXPECT_TRUE(status.isOk());
369 }
370 }
371 }
372}
373
374TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
375 binder::Status status;
376
377 // Repeat to ensure cleanup and recreation works correctly
378 for (int i = 0; i < 2; i++) {
379 for (int direction : XFRM_DIRECTIONS) {
380 for (int addrFamily : ADDRESS_FAMILIES) {
381 status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
Benedict Wonga450e722018-05-07 10:29:02 -0700382 "2001:db8::d00d", 123, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700383 EXPECT_TRUE(status.isOk())
384 << " family: " << addrFamily << " direction: " << direction;
385 }
386 }
387
388 // Cleanup
389 for (int direction : XFRM_DIRECTIONS) {
390 for (int addrFamily : ADDRESS_FAMILIES) {
Benedict Wonga450e722018-05-07 10:29:02 -0700391 status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
Benedict Wonga04ffa72018-05-09 21:42:42 -0700392 EXPECT_TRUE(status.isOk());
393 }
394 }
395 }
396}
397
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900398TEST_F(BinderTest, XfrmControllerInit) {
Bernie Innocentia5161a02019-01-30 22:40:53 +0900399 android::netdutils::Status status;
Nathan Harold21299f72018-03-16 20:13:03 -0700400 status = XfrmController::Init();
401 SCOPED_TRACE(status);
Nathan Harold2deff322018-05-10 14:03:48 -0700402
403 // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
404 // feature.
405 if (status.code() == EOPNOTSUPP) return;
406
Nathan Harold21299f72018-03-16 20:13:03 -0700407 ASSERT_TRUE(status.ok());
408
409 int32_t spi = 0;
410
411 ASSERT_TRUE(allocateIpSecResources(true, &spi));
412 ASSERT_TRUE(allocateIpSecResources(false, &spi));
413
414 status = XfrmController::Init();
Nathan Harold39ad6622018-04-25 12:56:56 -0700415 ASSERT_TRUE(status.ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700416 ASSERT_TRUE(allocateIpSecResources(true, &spi));
417
418 // Clean up
Benedict Wonga450e722018-05-07 10:29:02 -0700419 status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700420 SCOPED_TRACE(status);
421 ASSERT_TRUE(status.ok());
422
Benedict Wonga450e722018-05-07 10:29:02 -0700423 status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
Nathan Harold21299f72018-03-16 20:13:03 -0700424 SCOPED_TRACE(status);
425 ASSERT_TRUE(status.ok());
426
427 // Remove Virtual Tunnel Interface.
Benedict Wong319f17e2018-05-15 17:06:44 -0700428 ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
Nathan Harold21299f72018-03-16 20:13:03 -0700429}
Bernie Innocentia5161a02019-01-30 22:40:53 +0900430
431#endif // INTPTR_MAX != INT32_MAX
Nathan Harold21299f72018-03-16 20:13:03 -0700432
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900433static int bandwidthDataSaverEnabled(const char *binary) {
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900434 std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900435
436 // Output looks like this:
437 //
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900438 // Chain bw_data_saver (1 references)
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900439 // target prot opt source destination
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900440 // RETURN all -- 0.0.0.0/0 0.0.0.0/0
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900441 //
442 // or:
443 //
444 // Chain bw_data_saver (1 references)
445 // target prot opt source destination
446 // ... possibly connectivity critical packet rules here ...
447 // REJECT all -- ::/0 ::/0
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900448
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900449 EXPECT_GE(lines.size(), 3U);
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900450
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900451 if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
452 // Data saver disabled.
453 return 0;
454 }
455
456 size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
457
458 if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
459 // Data saver enabled.
460 return 1;
461 }
462
463 return -1;
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900464}
465
466bool enableDataSaver(sp<INetd>& netd, bool enable) {
467 TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
468 bool ret;
469 netd->bandwidthEnableDataSaver(enable, &ret);
470 return ret;
471}
472
473int getDataSaverState() {
474 const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
475 const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
476 EXPECT_EQ(enabled4, enabled6);
477 EXPECT_NE(-1, enabled4);
478 EXPECT_NE(-1, enabled6);
479 if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
480 return -1;
481 }
482 return enabled6;
483}
484
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900485TEST_F(BinderTest, BandwidthEnableDataSaver) {
Lorenzo Colittidedd2712016-03-22 12:36:29 +0900486 const int wasEnabled = getDataSaverState();
487 ASSERT_NE(-1, wasEnabled);
488
489 if (wasEnabled) {
490 ASSERT_TRUE(enableDataSaver(mNetd, false));
491 EXPECT_EQ(0, getDataSaverState());
492 }
493
494 ASSERT_TRUE(enableDataSaver(mNetd, false));
495 EXPECT_EQ(0, getDataSaverState());
496
497 ASSERT_TRUE(enableDataSaver(mNetd, true));
498 EXPECT_EQ(1, getDataSaverState());
499
500 ASSERT_TRUE(enableDataSaver(mNetd, true));
501 EXPECT_EQ(1, getDataSaverState());
502
503 if (!wasEnabled) {
504 ASSERT_TRUE(enableDataSaver(mNetd, false));
505 EXPECT_EQ(0, getDataSaverState());
506 }
507}
Robin Leeb8087362016-03-30 18:43:08 +0100508
Luke Huang94658ac2018-10-18 19:35:12 +0900509static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
510 const std::string& action, const char* ipVersion) {
Robin Leeb8087362016-03-30 18:43:08 +0100511 // Output looks like this:
Robin Lee6c84ef62016-05-03 13:17:58 +0100512 // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
Robin Leeb8087362016-03-30 18:43:08 +0100513 std::vector<std::string> rules = listIpRules(ipVersion);
514
515 std::string prefix = StringPrintf("%" PRIu32 ":", priority);
Luke Huang94658ac2018-10-18 19:35:12 +0900516 std::string suffix =
517 StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
Bernie Innocentif6918262018-06-11 17:37:35 +0900518 for (const auto& line : rules) {
Elliott Hughes2f445082017-12-20 12:39:35 -0800519 if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
Robin Leeb8087362016-03-30 18:43:08 +0100520 return true;
521 }
522 }
523 return false;
524}
525
Luke Huang94658ac2018-10-18 19:35:12 +0900526static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
527 const std::string& action) {
Robin Leeb8087362016-03-30 18:43:08 +0100528 bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
529 bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
530 EXPECT_EQ(existsIp4, existsIp6);
531 return existsIp4;
532}
533
Luke Huang94658ac2018-10-18 19:35:12 +0900534namespace {
535
536UidRangeParcel makeUidRangeParcel(int start, int stop) {
537 UidRangeParcel res;
538 res.start = start;
539 res.stop = stop;
540
541 return res;
542}
543
544} // namespace
545
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900546TEST_F(BinderTest, NetworkInterfaces) {
Luke Huangb670d162018-08-23 20:01:13 +0800547 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
548 EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
549 .serviceSpecificErrorCode());
cken67cd14c2018-12-05 17:26:59 +0900550 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
551 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900552
553 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
554 EXPECT_EQ(EBUSY,
555 mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
556
557 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
558 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
559 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
Luke Huangb670d162018-08-23 20:01:13 +0800560 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900561}
562
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900563TEST_F(BinderTest, NetworkUidRules) {
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900564 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
565
cken67cd14c2018-12-05 17:26:59 +0900566 EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
567 EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900568 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
569
Luke Huang94658ac2018-10-18 19:35:12 +0900570 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
571 makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
572 UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
Lorenzo Colittid33e96d2016-12-15 23:59:01 +0900573 std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
574
575 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
576
577 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
578 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
579 EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
580 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
581
582 EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
583 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
584 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
585 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
586
587 EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
588}
589
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900590TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
Robin Lee6c84ef62016-05-03 13:17:58 +0100591 constexpr uint32_t RULE_PRIORITY = 12500;
Robin Leeb8087362016-03-30 18:43:08 +0100592
Luke Huang94658ac2018-10-18 19:35:12 +0900593 std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
594 makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
Luke Huang841f3ef2019-05-30 15:09:19 +0800595 // Make sure no rules existed before calling commands.
596 for (auto const& range : uidRanges) {
597 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
598 }
Robin Leeb8087362016-03-30 18:43:08 +0100599 // Create two valid rules.
600 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100601 for (auto const& range : uidRanges) {
602 EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
603 }
604
605 // Remove the rules.
606 ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
Robin Leeb8087362016-03-30 18:43:08 +0100607 for (auto const& range : uidRanges) {
608 EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
609 }
610
611 // Fail to remove the rules a second time after they are already deleted.
612 binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
613 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
614 EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
Robin Leeb8087362016-03-30 18:43:08 +0100615}
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900616
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900617// Create a socket pair that isLoopbackSocket won't think is local.
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900618void BinderTest::fakeRemoteSocketPair(unique_fd* clientSocket, unique_fd* serverSocket,
619 unique_fd* acceptedSocket) {
620 serverSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900621 struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900622 ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
623
624 socklen_t addrlen = sizeof(server6);
625 ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
626 ASSERT_EQ(0, listen(*serverSocket, 10));
627
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900628 clientSocket->reset(socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900629 struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900630 ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900631 ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
632 ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
633
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900634 acceptedSocket->reset(
635 accept4(*serverSocket, (struct sockaddr*)&server6, &addrlen, SOCK_CLOEXEC));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900636 ASSERT_NE(-1, *acceptedSocket);
637
638 ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
639}
640
641void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
642 char buf[4096];
643 EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
644 EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
645 EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
646}
647
648void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
649 // Check that the client socket was closed with ECONNABORTED.
650 int ret = write(clientSocket, "foo", sizeof("foo"));
651 int err = errno;
652 EXPECT_EQ(-1, ret);
653 EXPECT_EQ(ECONNABORTED, err);
654
655 // Check that it sent a RST to the server.
656 ret = write(acceptedSocket, "foo", sizeof("foo"));
657 err = errno;
658 EXPECT_EQ(-1, ret);
659 EXPECT_EQ(ECONNRESET, err);
660}
661
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900662TEST_F(BinderTest, SocketDestroy) {
Bernie Innocentid26a04a2019-10-30 17:15:15 +0900663 unique_fd clientSocket, serverSocket, acceptedSocket;
Lorenzo Colitti755faa92016-07-27 22:10:49 +0900664 ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900665
666 // Pick a random UID in the system UID range.
667 constexpr int baseUid = AID_APP - 2000;
668 static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
669 int uid = baseUid + 500 + arc4random_uniform(1000);
670 EXPECT_EQ(0, fchown(clientSocket, uid, -1));
671
672 // UID ranges that don't contain uid.
Luke Huang94658ac2018-10-18 19:35:12 +0900673 std::vector<UidRangeParcel> uidRanges = {
674 makeUidRangeParcel(baseUid + 42, baseUid + 449),
675 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
676 makeUidRangeParcel(baseUid + 498, uid - 1),
677 makeUidRangeParcel(uid + 1, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900678 };
679 // A skip list that doesn't contain UID.
680 std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
681
682 // Close sockets. Our test socket should be intact.
683 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
684 checkSocketpairOpen(clientSocket, acceptedSocket);
685
686 // UID ranges that do contain uid.
687 uidRanges = {
Luke Huang94658ac2018-10-18 19:35:12 +0900688 makeUidRangeParcel(baseUid + 42, baseUid + 449),
689 makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
690 makeUidRangeParcel(baseUid + 498, baseUid + 1520),
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900691 };
692 // Add uid to the skip list.
693 skipUids.push_back(uid);
694
695 // Close sockets. Our test socket should still be intact because it's in the skip list.
696 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
697 checkSocketpairOpen(clientSocket, acceptedSocket);
698
699 // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
700 skipUids.resize(skipUids.size() - 1);
701 EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
702 checkSocketpairClosed(clientSocket, acceptedSocket);
Lorenzo Colitti563d98b2016-04-24 13:13:14 +0900703}
Erik Klinecc4f2732016-08-03 11:24:27 +0900704
705namespace {
706
707int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
708 if (buf == nullptr) return -1;
709
710 int prefixLength = 0;
711 bool endOfContiguousBits = false;
712 for (unsigned int i = 0; i < buflen; i++) {
713 const uint8_t value = buf[i];
714
715 // Bad bit sequence: check for a contiguous set of bits from the high
716 // end by verifying that the inverted value + 1 is a power of 2
717 // (power of 2 iff. (v & (v - 1)) == 0).
718 const uint8_t inverse = ~value + 1;
719 if ((inverse & (inverse - 1)) != 0) return -1;
720
721 prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
722
723 // Bogus netmask.
724 if (endOfContiguousBits && value != 0) return -1;
725
726 if (value != 0xff) endOfContiguousBits = true;
727 }
728
729 return prefixLength;
730}
731
732template<typename T>
733int netmaskToPrefixLength(const T *p) {
734 return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
735}
736
737
738static bool interfaceHasAddress(
739 const std::string &ifname, const char *addrString, int prefixLength) {
740 struct addrinfo *addrinfoList = nullptr;
Erik Klinecc4f2732016-08-03 11:24:27 +0900741
742 const struct addrinfo hints = {
743 .ai_flags = AI_NUMERICHOST,
744 .ai_family = AF_UNSPEC,
745 .ai_socktype = SOCK_DGRAM,
746 };
747 if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
748 addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
749 return false;
750 }
Bernie Innocenti9bf749f2018-08-30 08:37:22 +0900751 ScopedAddrinfo addrinfoCleanup(addrinfoList);
Erik Klinecc4f2732016-08-03 11:24:27 +0900752
753 struct ifaddrs *ifaddrsList = nullptr;
754 ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
755
756 if (getifaddrs(&ifaddrsList) != 0) {
757 return false;
758 }
759
760 for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
761 if (std::string(addr->ifa_name) != ifname ||
762 addr->ifa_addr == nullptr ||
763 addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
764 continue;
765 }
766
767 switch (addr->ifa_addr->sa_family) {
768 case AF_INET: {
769 auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
770 auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
771 if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
772 continue;
773 }
774
775 if (prefixLength < 0) return true; // not checking prefix lengths
776
777 if (addr->ifa_netmask == nullptr) return false;
778 auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
779 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
780 return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
781 }
782 case AF_INET6: {
783 auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
784 auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
785 if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
786 continue;
787 }
788
789 if (prefixLength < 0) return true; // not checking prefix lengths
790
791 if (addr->ifa_netmask == nullptr) return false;
792 auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
793 EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
794 return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
795 }
796 default:
797 // Cannot happen because we have already screened for matching
798 // address families at the top of each iteration.
799 continue;
800 }
801 }
802
803 return false;
804}
805
806} // namespace
807
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900808TEST_F(BinderTest, InterfaceAddRemoveAddress) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900809 static const struct TestData {
810 const char *addrString;
811 const int prefixLength;
Lorenzo Colitti01118982019-12-02 13:19:44 +0900812 const int expectAddResult;
813 const int expectRemoveResult;
Erik Klinecc4f2732016-08-03 11:24:27 +0900814 } kTestData[] = {
Lorenzo Colitti01118982019-12-02 13:19:44 +0900815 {"192.0.2.1", 24, 0, 0},
816 {"192.0.2.2", 25, 0, 0},
817 {"192.0.2.3", 32, 0, 0},
818 {"192.0.2.4", 33, EINVAL, EADDRNOTAVAIL},
819 {"192.not.an.ip", 24, EINVAL, EINVAL},
820 {"2001:db8::1", 64, 0, 0},
821 {"2001:db8::2", 65, 0, 0},
822 {"2001:db8::3", 128, 0, 0},
823 {"2001:db8::4", 129, EINVAL, EINVAL},
824 {"foo:bar::bad", 64, EINVAL, EINVAL},
825 {"2001:db8::1/64", 64, EINVAL, EINVAL},
Erik Klinecc4f2732016-08-03 11:24:27 +0900826 };
827
Sehee Park8659b8d2018-11-16 10:53:16 +0900828 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900829 const auto &td = kTestData[i];
830
Lorenzo Colitti01118982019-12-02 13:19:44 +0900831 SCOPED_TRACE(String8::format("Offending IP address %s/%d", td.addrString, td.prefixLength));
832
Erik Klinecc4f2732016-08-03 11:24:27 +0900833 // [1.a] Add the address.
834 binder::Status status = mNetd->interfaceAddAddress(
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900835 sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900836 if (td.expectAddResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900837 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
838 } else {
839 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900840 ASSERT_EQ(td.expectAddResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900841 }
842
843 // [1.b] Verify the addition meets the expectation.
Lorenzo Colitti01118982019-12-02 13:19:44 +0900844 if (td.expectAddResult == 0) {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900845 EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
Erik Klinecc4f2732016-08-03 11:24:27 +0900846 } else {
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900847 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900848 }
849
850 // [2.a] Try to remove the address. If it was not previously added, removing it fails.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900851 status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
Lorenzo Colitti01118982019-12-02 13:19:44 +0900852 if (td.expectRemoveResult == 0) {
Erik Klinecc4f2732016-08-03 11:24:27 +0900853 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
854 } else {
855 ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
Lorenzo Colitti01118982019-12-02 13:19:44 +0900856 ASSERT_EQ(td.expectRemoveResult, status.serviceSpecificErrorCode());
Erik Klinecc4f2732016-08-03 11:24:27 +0900857 }
858
859 // [2.b] No matter what, the address should not be present.
Lorenzo Colitti1e299c62017-02-27 17:16:10 +0900860 EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
Erik Klinecc4f2732016-08-03 11:24:27 +0900861 }
Lorenzo Colitti9ae17712019-12-02 17:28:49 +0900862
863 // Check that netlink errors are returned correctly.
864 // We do this by attempting to create an IPv6 address on an interface that has IPv6 disabled,
865 // which returns EACCES.
866 TunInterface tun;
867 ASSERT_EQ(0, tun.init());
868 binder::Status status =
869 mNetd->setProcSysNet(INetd::IPV6, INetd::CONF, tun.name(), "disable_ipv6", "1");
870 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
871 status = mNetd->interfaceAddAddress(tun.name(), "2001:db8::1", 64);
872 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
873 EXPECT_EQ(EACCES, status.serviceSpecificErrorCode());
874 tun.destroy();
Erik Klinecc4f2732016-08-03 11:24:27 +0900875}
Erik Kline55b06f82016-07-04 09:57:18 +0900876
Erik Kline38e51f12018-09-06 20:14:44 +0900877TEST_F(BinderTest, GetProcSysNet) {
878 const char LOOPBACK[] = "lo";
879 static const struct {
880 const int ipversion;
Erik Kline55b06f82016-07-04 09:57:18 +0900881 const int which;
Erik Kline38e51f12018-09-06 20:14:44 +0900882 const char* ifname;
883 const char* parameter;
884 const char* expectedValue;
Erik Kline55b06f82016-07-04 09:57:18 +0900885 const int expectedReturnCode;
886 } kTestData[] = {
Erik Kline38e51f12018-09-06 20:14:44 +0900887 {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
888 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
889 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
890 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
891 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
892 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
893 {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
Erik Kline55b06f82016-07-04 09:57:18 +0900894 };
895
Sehee Park8659b8d2018-11-16 10:53:16 +0900896 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900897 const auto& td = kTestData[i];
Erik Kline55b06f82016-07-04 09:57:18 +0900898
Erik Kline38e51f12018-09-06 20:14:44 +0900899 std::string value;
900 const binder::Status status =
901 mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
902
903 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900904 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900905 EXPECT_EQ(0, status.exceptionCode());
906 EXPECT_EQ(0, status.serviceSpecificErrorCode());
907 EXPECT_EQ(td.expectedValue, value);
908 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900909 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline38e51f12018-09-06 20:14:44 +0900910 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
911 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
912 }
913 }
914}
915
916TEST_F(BinderTest, SetProcSysNet) {
917 static const struct {
918 const int ipversion;
919 const int which;
920 const char* ifname;
921 const char* parameter;
922 const char* value;
923 const int expectedReturnCode;
924 } kTestData[] = {
925 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
926 {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
927 {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
928 {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
929 {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
930 {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
931 {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
932 };
933
Sehee Park8659b8d2018-11-16 10:53:16 +0900934 for (size_t i = 0; i < std::size(kTestData); i++) {
Erik Kline38e51f12018-09-06 20:14:44 +0900935 const auto& td = kTestData[i];
Erik Kline38e51f12018-09-06 20:14:44 +0900936 const binder::Status status =
937 mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
Erik Kline55b06f82016-07-04 09:57:18 +0900938
939 if (td.expectedReturnCode == 0) {
Sehee Park8659b8d2018-11-16 10:53:16 +0900940 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900941 EXPECT_EQ(0, status.exceptionCode());
942 EXPECT_EQ(0, status.serviceSpecificErrorCode());
943 } else {
Sehee Park8659b8d2018-11-16 10:53:16 +0900944 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
Erik Kline55b06f82016-07-04 09:57:18 +0900945 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
946 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
947 }
948 }
949}
Ben Schwartze7601812017-04-28 16:38:29 -0400950
Erik Kline38e51f12018-09-06 20:14:44 +0900951TEST_F(BinderTest, GetSetProcSysNet) {
952 const int ipversion = INetd::IPV6;
953 const int category = INetd::NEIGH;
954 const std::string& tun = sTun.name();
955 const std::string parameter("ucast_solicit");
956
957 std::string value{};
958 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
Maciej Żenczykowski7b789b92019-04-09 15:55:06 -0700959 ASSERT_FALSE(value.empty());
Erik Kline38e51f12018-09-06 20:14:44 +0900960 const int ival = std::stoi(value);
961 EXPECT_GT(ival, 0);
962 // Try doubling the parameter value (always best!).
963 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
964 .isOk());
965 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
966 EXPECT_EQ(2 * ival, std::stoi(value));
967 // Try resetting the parameter.
968 EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
969 .isOk());
970 EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
971 EXPECT_EQ(ival, std::stoi(value));
972}
973
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +0900974namespace {
975
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900976void expectNoTestCounterRules() {
977 for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
978 std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
979 std::string allRules = Join(runCommand(command), "\n");
980 EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
981 }
982}
983
Bernie Innocentif6918262018-06-11 17:37:35 +0900984void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
985 int byte, int pkt) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900986 runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
987 path, if1.c_str(), if2.c_str(), pkt, byte));
988}
989
Bernie Innocentif6918262018-06-11 17:37:35 +0900990void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900991 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
992 path, if1.c_str(), if2.c_str()));
993 runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
994 path, if2.c_str(), if1.c_str()));
995}
996
Luke Huangcaebcbb2018-09-27 20:37:14 +0800997std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
998 const std::string& iface) {
999 for (auto& stats : statsVec) {
1000 if (stats.iface == iface) {
1001 return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
1002 }
1003 }
1004 return {};
1005}
1006
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001007} // namespace
1008
1009TEST_F(BinderTest, TetherGetStats) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001010 expectNoTestCounterRules();
1011
1012 // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
1013 // disabling tethering. We don't check the return value because these commands will fail if
1014 // tethering is already enabled.
1015 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
1016 runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
1017
1018 std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1019 std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
1020 std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
Luke Huang0f91cdc2019-05-29 17:55:51 +08001021
1022 // Ensure we won't use the same interface name, otherwise the test will fail.
1023 u_int32_t rNumber = arc4random_uniform(10000);
1024 std::string extIface1 = StringPrintf("netdtest_%u", rNumber);
1025 std::string extIface2 = StringPrintf("netdtest_%u", rNumber + 1);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001026
1027 addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
1028 addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
1029 addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
1030 addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
1031 // RX is from external to internal, and TX is from internal to external.
1032 // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
1033 std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
1034
1035 addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
1036 addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
1037
1038 addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
1039 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
1040
1041 addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
1042 addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
1043 std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
1044
Luke Huangcaebcbb2018-09-27 20:37:14 +08001045 std::vector<TetherStatsParcel> statsVec;
1046 binder::Status status = mNetd->tetherGetStats(&statsVec);
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001047 EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
1048
Luke Huangcaebcbb2018-09-27 20:37:14 +08001049 EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001050
Luke Huangcaebcbb2018-09-27 20:37:14 +08001051 EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001052
1053 for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
1054 delTetherCounterValues(path, intIface1, extIface1);
1055 delTetherCounterValues(path, intIface2, extIface2);
1056 if (path == IP6TABLES_PATH) {
1057 delTetherCounterValues(path, intIface3, extIface2);
1058 }
1059 }
1060
1061 expectNoTestCounterRules();
1062}
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001063
Luke Huang0051a622018-07-23 20:30:16 +08001064namespace {
1065
Luke Huanga5211072018-08-01 23:36:29 +08001066constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
1067constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
Luke Huang0051a622018-07-23 20:30:16 +08001068
1069static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
1070 const char* chainName) {
1071 std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
1072 return runCommand(command);
1073}
1074
Luke Huang19b49c52018-10-22 12:12:05 +09001075// TODO: It is a duplicate function, need to remove it
Luke Huanga5211072018-08-01 23:36:29 +08001076bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
Luke Huang0051a622018-07-23 20:30:16 +08001077 const std::string& expectedInterface,
1078 const std::string& expectedRule, const char* table) {
1079 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1080 for (const auto& rule : rules) {
1081 if (rule.find(expectedInterface) != std::string::npos) {
1082 if (rule.find(expectedRule) != std::string::npos) {
1083 return true;
1084 }
1085 }
1086 }
1087 return false;
1088}
1089
1090void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001091 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001092 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001093 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001094 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001095 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1096 IdletimerRule, RAW_TABLE));
1097 EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001098 ifname, IdletimerRule, MANGLE_TABLE));
1099 }
1100}
1101
1102void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
Luke Huanga5211072018-08-01 23:36:29 +08001103 const std::string& classLabel) {
Luke Huang0051a622018-07-23 20:30:16 +08001104 std::string IdletimerRule =
Luke Huanga5211072018-08-01 23:36:29 +08001105 StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
Luke Huang0051a622018-07-23 20:30:16 +08001106 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huanga5211072018-08-01 23:36:29 +08001107 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
1108 IdletimerRule, RAW_TABLE));
1109 EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
Luke Huang0051a622018-07-23 20:30:16 +08001110 ifname, IdletimerRule, MANGLE_TABLE));
1111 }
1112}
1113
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001114} // namespace
1115
1116TEST_F(BinderTest, IdletimerAddRemoveInterface) {
Luke Huang0051a622018-07-23 20:30:16 +08001117 // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
1118 // rule in the table. Because we only check the result after calling remove function. We might
1119 // check the actual rule which is removed by our function (maybe compare the results between
1120 // calling function before and after)
1121 binder::Status status;
1122 const struct TestData {
1123 const std::string ifname;
1124 int32_t timeout;
1125 const std::string classLabel;
1126 } idleTestData[] = {
1127 {"wlan0", 1234, "happyday"},
1128 {"rmnet_data0", 4567, "friday"},
1129 };
1130 for (const auto& td : idleTestData) {
1131 status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
1132 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1133 expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
1134
1135 status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
1136 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1137 expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
1138 }
1139}
1140
Luke Huanga67dd562018-07-17 19:58:25 +08001141namespace {
1142
1143constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
1144constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
1145
1146void expectStrictSetUidAccept(const int uid) {
1147 std::string uidRule = StringPrintf("owner UID match %u", uid);
1148 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1149 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001150 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1151 EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001152 EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
1153 }
1154}
1155
1156void expectStrictSetUidLog(const int uid) {
1157 static const char logRule[] = "st_penalty_log all";
1158 std::string uidRule = StringPrintf("owner UID match %u", uid);
1159 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1160 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001161 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1162 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001163 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
1164 }
1165}
1166
1167void expectStrictSetUidReject(const int uid) {
1168 static const char rejectRule[] = "st_penalty_reject all";
1169 std::string uidRule = StringPrintf("owner UID match %u", uid);
1170 std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
1171 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001172 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
1173 EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
Luke Huanga67dd562018-07-17 19:58:25 +08001174 EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
1175 }
1176}
1177
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001178} // namespace
1179
1180TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
Luke Huanga67dd562018-07-17 19:58:25 +08001181 binder::Status status;
1182 int32_t uid = randomUid();
1183
1184 // setUidCleartextPenalty Policy:Log with randomUid
1185 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
1186 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1187 expectStrictSetUidLog(uid);
1188
1189 // setUidCleartextPenalty Policy:Accept with randomUid
1190 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1191 expectStrictSetUidAccept(uid);
1192
1193 // setUidCleartextPenalty Policy:Reject with randomUid
1194 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
1195 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1196 expectStrictSetUidReject(uid);
1197
1198 // setUidCleartextPenalty Policy:Accept with randomUid
1199 status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
1200 expectStrictSetUidAccept(uid);
1201
1202 // test wrong policy
1203 int32_t wrongPolicy = -123;
1204 status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
1205 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1206}
1207
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001208namespace {
Luke Huang6d301232018-08-01 14:05:18 +08001209
Luke Huangd1675922019-03-11 17:29:27 +08001210std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
Luke Huang728cf4c2019-03-14 19:43:02 +08001211 uint32_t intervalMs = 50) {
Luke Huangd1675922019-03-11 17:29:27 +08001212 // Output looks like:(clatd)
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001213 // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
1214 // ...
1215 // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
1216
Luke Huangd1675922019-03-11 17:29:27 +08001217 // (dnsmasq)
1218 // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
1219
1220 if (maxTries == 0) return {};
1221
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001222 std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
Luke Huangd1675922019-03-11 17:29:27 +08001223 std::vector<std::string> result;
1224 for (uint32_t run = 1;;) {
Greg Kaiser46a1d532019-03-26 12:10:58 -07001225 result = runCommand(cmd);
Luke Huangd1675922019-03-11 17:29:27 +08001226 if (result.size() || ++run > maxTries) {
1227 break;
1228 }
1229
Luke Huang728cf4c2019-03-14 19:43:02 +08001230 usleep(intervalMs * 1000);
Luke Huangd1675922019-03-11 17:29:27 +08001231 }
1232 return result;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001233}
1234
Luke Huangd1675922019-03-11 17:29:27 +08001235void expectProcessExists(const std::string& processName) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001236 EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
Luke Huangd1675922019-03-11 17:29:27 +08001237}
1238
Luke Huang728cf4c2019-03-14 19:43:02 +08001239void expectProcessDoesNotExist(const std::string& processName) {
Luke Huangd1675922019-03-11 17:29:27 +08001240 EXPECT_FALSE(tryToFindProcesses(processName).size());
Luke Huang6d301232018-08-01 14:05:18 +08001241}
1242
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001243} // namespace
1244
1245TEST_F(BinderTest, ClatdStartStop) {
Luke Huang6d301232018-08-01 14:05:18 +08001246 binder::Status status;
Luke Huang6d301232018-08-01 14:05:18 +08001247
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001248 const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
1249 std::string clatAddress;
1250 std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
Luke Huang6d301232018-08-01 14:05:18 +08001251
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001252 // Can't start clatd on an interface that's not part of any network...
1253 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1254 EXPECT_FALSE(status.isOk());
1255 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
1256
1257 // ... so create a test physical network and add our tun to it.
1258 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1259 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1260
1261 // Prefix must be 96 bits long.
1262 status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
1263 EXPECT_FALSE(status.isOk());
1264 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
1265
1266 // Can't start clatd unless there's a default route...
1267 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1268 EXPECT_FALSE(status.isOk());
1269 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1270
1271 // so add a default route.
1272 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1273
1274 // Can't start clatd unless there's a global address...
1275 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1276 EXPECT_FALSE(status.isOk());
1277 EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
1278
1279 // ... so add a global address.
1280 const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
Lorenzo Colitti8a9f1ad2019-02-26 00:30:18 +09001281 EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001282
1283 // Now expect clatd to start successfully.
1284 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1285 EXPECT_TRUE(status.isOk());
1286 EXPECT_EQ(0, status.serviceSpecificErrorCode());
1287
1288 // Starting it again returns EBUSY.
1289 status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
1290 EXPECT_FALSE(status.isOk());
1291 EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
1292
Luke Huangd1675922019-03-11 17:29:27 +08001293 expectProcessExists(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001294
1295 // Expect clatd to stop successfully.
1296 status = mNetd->clatdStop(sTun.name());
Luke Huang6d301232018-08-01 14:05:18 +08001297 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang728cf4c2019-03-14 19:43:02 +08001298 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001299
1300 // Stopping a clatd that doesn't exist returns ENODEV.
1301 status = mNetd->clatdStop(sTun.name());
1302 EXPECT_FALSE(status.isOk());
1303 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
Luke Huang728cf4c2019-03-14 19:43:02 +08001304 expectProcessDoesNotExist(clatdName);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +09001305
1306 // Clean up.
1307 EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
1308 EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
1309 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Luke Huang6d301232018-08-01 14:05:18 +08001310}
Luke Huang457d4702018-08-16 15:39:15 +08001311
1312namespace {
1313
1314bool getIpfwdV4Enable() {
1315 static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
1316 std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
1317 EXPECT_TRUE(!result.empty());
1318 int v4Enable = std::stoi(result[0]);
1319 return v4Enable;
1320}
1321
1322bool getIpfwdV6Enable() {
Lorenzo Colitti76edb4b2019-05-09 11:46:45 +09001323 static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
Luke Huang457d4702018-08-16 15:39:15 +08001324 std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
1325 EXPECT_TRUE(!result.empty());
1326 int v6Enable = std::stoi(result[0]);
1327 return v6Enable;
1328}
1329
1330void expectIpfwdEnable(bool enable) {
1331 int enableIPv4 = getIpfwdV4Enable();
1332 int enableIPv6 = getIpfwdV6Enable();
1333 EXPECT_EQ(enable, enableIPv4);
1334 EXPECT_EQ(enable, enableIPv6);
1335}
1336
Bernie Innocenti1bdf10d2018-09-10 18:46:07 +09001337bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
Luke Huang457d4702018-08-16 15:39:15 +08001338 std::vector<std::string> rules = listIpRules(ipVersion);
1339 for (const auto& rule : rules) {
1340 if (rule.find(ipfwdRule) != std::string::npos) {
1341 return true;
1342 }
1343 }
1344 return false;
1345}
1346
1347void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
1348 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1349
1350 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1351 EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1352 }
1353}
1354
1355void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
1356 std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
1357
1358 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1359 EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
1360 }
1361}
1362
1363} // namespace
1364
1365TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
Luke Huang728cf4c2019-03-14 19:43:02 +08001366 // Get ipfwd requester list from Netd
1367 std::vector<std::string> requesterList;
1368 binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
Luke Huang457d4702018-08-16 15:39:15 +08001369 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001370
1371 bool ipfwdEnabled;
Luke Huang728cf4c2019-03-14 19:43:02 +08001372 if (requesterList.size() == 0) {
1373 // No requester in Netd, ipfwd should be disabled
1374 // So add one test requester and verify
1375 status = mNetd->ipfwdEnableForwarding("TestRequester");
1376 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang457d4702018-08-16 15:39:15 +08001377
Luke Huang728cf4c2019-03-14 19:43:02 +08001378 expectIpfwdEnable(true);
1379 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1380 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1381 EXPECT_TRUE(ipfwdEnabled);
Luke Huang457d4702018-08-16 15:39:15 +08001382
Luke Huang728cf4c2019-03-14 19:43:02 +08001383 // Remove test one, verify again
1384 status = mNetd->ipfwdDisableForwarding("TestRequester");
1385 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1386
1387 expectIpfwdEnable(false);
1388 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1389 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1390 EXPECT_FALSE(ipfwdEnabled);
1391 } else {
1392 // Disable all requesters
1393 for (const auto& requester : requesterList) {
1394 status = mNetd->ipfwdDisableForwarding(requester);
1395 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1396 }
1397
1398 // After disable all requester, ipfwd should be disabled
1399 expectIpfwdEnable(false);
1400 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1401 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1402 EXPECT_FALSE(ipfwdEnabled);
1403
1404 // Enable them back
1405 for (const auto& requester : requesterList) {
1406 status = mNetd->ipfwdEnableForwarding(requester);
1407 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1408 }
1409
1410 // ipfwd should be enabled
1411 expectIpfwdEnable(true);
1412 status = mNetd->ipfwdEnabled(&ipfwdEnabled);
1413 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1414 EXPECT_TRUE(ipfwdEnabled);
1415 }
Luke Huang457d4702018-08-16 15:39:15 +08001416}
1417
1418TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
Luke Huangd1827b82019-02-15 15:03:27 +08001419 // Add test physical network
1420 EXPECT_TRUE(
1421 mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1422 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1423 EXPECT_TRUE(
1424 mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
1425 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
Luke Huang457d4702018-08-16 15:39:15 +08001426
Luke Huangd1827b82019-02-15 15:03:27 +08001427 binder::Status status =
1428 mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
1429 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1430 expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
Luke Huang457d4702018-08-16 15:39:15 +08001431
Luke Huangd1827b82019-02-15 15:03:27 +08001432 status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
1433 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1434 expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
Bernie Innocenti1bcc25a2018-08-10 17:15:00 +09001435}
Luke Huang531f5d32018-08-03 15:19:05 +08001436
1437namespace {
1438
1439constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
1440constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
1441constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
1442constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
1443constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
Luke Huangae038f82018-11-05 11:17:31 +09001444constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
Luke Huang531f5d32018-08-03 15:19:05 +08001445
Luke Huang19b49c52018-10-22 12:12:05 +09001446// TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
1447// Use either a std::vector<std::string> of things to match, or a variadic function.
Luke Huang531f5d32018-08-03 15:19:05 +08001448bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
1449 const char* chainName, const std::string& expectedTargetA,
1450 const std::string& expectedTargetB) {
1451 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1452 int matchCount = 0;
1453
1454 for (const auto& rule : rules) {
1455 if (rule.find(expectedTargetA) != std::string::npos) {
1456 if (rule.find(expectedTargetB) != std::string::npos) {
1457 matchCount++;
1458 }
1459 }
1460 }
1461 return matchCount == expectedCount;
1462}
1463
1464void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
1465 std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
1466 std::string result = "";
1467
1468 EXPECT_TRUE(ReadFileToString(path, &result));
Luke Huang4953ca22018-09-14 14:08:50 +08001469 // Quota value might be decreased while matching packets
1470 EXPECT_GE(quotaBytes, std::stol(Trim(result)));
Luke Huang531f5d32018-08-03 15:19:05 +08001471}
1472
1473void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
1474 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1475 std::string quotaRule = StringPrintf("quota %s", ifname);
1476
1477 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1478 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1479 BANDWIDTH_COSTLY_IF));
1480 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1481 BANDWIDTH_COSTLY_IF));
1482 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1483 BANDWIDTH_COSTLY_IF));
1484 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1485 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1486 }
1487 expectXtQuotaValueEqual(ifname, quotaBytes);
1488}
1489
1490void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
1491 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1492 std::string quotaRule = StringPrintf("quota %s", ifname);
1493
1494 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1495 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
1496 BANDWIDTH_COSTLY_IF));
1497 EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
1498 BANDWIDTH_COSTLY_IF));
1499 EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
1500 BANDWIDTH_COSTLY_IF));
1501 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
1502 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
1503 }
1504}
1505
1506void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
1507 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1508 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1509 std::string alertName = StringPrintf("%sAlert", ifname);
1510
1511 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1512 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1513 }
1514 expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
1515}
1516
1517void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
1518 std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
1519 std::string alertRule = StringPrintf("quota %sAlert", ifname);
1520
1521 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1522 EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
1523 }
1524}
1525
1526void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
1527 static const char globalAlertRule[] = "quota globalAlert";
1528 static const char globalAlertName[] = "globalAlert";
1529
1530 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
Luke Huangae038f82018-11-05 11:17:31 +09001531 EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
Luke Huang531f5d32018-08-03 15:19:05 +08001532 }
1533 expectXtQuotaValueEqual(globalAlertName, alertBytes);
1534}
1535
1536void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
1537 std::string uidRule = StringPrintf("owner UID match %u", uid);
1538
1539 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1540 EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
1541 }
1542}
1543
1544void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
1545 std::string uidRule = StringPrintf("owner UID match %u", uid);
1546
1547 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1548 EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
1549 }
1550}
1551
1552} // namespace
1553
1554TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
1555 long testQuotaBytes = 5550;
1556
1557 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001558 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001559 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1560
1561 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
1562 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1563 expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
1564
1565 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1566 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1567 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1568
1569 // Remove test physical network
1570 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1571}
1572
1573TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
1574 long testAlertBytes = 373;
Luke Huang531f5d32018-08-03 15:19:05 +08001575 // Add test physical network
Luke Huangb670d162018-08-23 20:01:13 +08001576 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001577 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
Luke Huang531f5d32018-08-03 15:19:05 +08001578 // Need to have a prior interface quota set to set an alert
1579 binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
1580 status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
1581 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1582 expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
1583
1584 status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
1585 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1586 expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
1587
1588 // Remove interface quota
1589 status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
1590 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1591 expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
1592
1593 // Remove test physical network
1594 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1595}
1596
1597TEST_F(BinderTest, BandwidthSetGlobalAlert) {
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001598 int64_t testAlertBytes = 2097200;
Luke Huang531f5d32018-08-03 15:19:05 +08001599
1600 binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1601 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1602 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1603
Luke Huang8ca0f1c2019-05-29 15:56:42 +08001604 testAlertBytes = 2098230;
Luke Huang531f5d32018-08-03 15:19:05 +08001605 status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
1606 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1607 expectBandwidthGlobalAlertRuleExists(testAlertBytes);
1608}
1609
1610TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
1611 SKIP_IF_BPF_SUPPORTED;
1612
1613 int32_t uid = randomUid();
1614 static const char targetReject[] = "REJECT";
1615 static const char targetReturn[] = "RETURN";
1616
1617 // add NaughtyApp
1618 binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
1619 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1620 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
1621
1622 // remove NaughtyApp
1623 status = mNetd->bandwidthRemoveNaughtyApp(uid);
1624 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1625 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
1626
1627 // add NiceApp
1628 status = mNetd->bandwidthAddNiceApp(uid);
1629 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1630 expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
1631
1632 // remove NiceApp
1633 status = mNetd->bandwidthRemoveNiceApp(uid);
1634 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1635 expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
1636}
Luke Huangb5733d72018-08-21 17:17:19 +08001637
1638namespace {
1639
Luke Huangc3252cc2018-10-16 15:43:23 +08001640std::string ipRouteString(const std::string& ifName, const std::string& dst,
Tyler Wearfa94a272019-12-05 15:01:48 -08001641 const std::string& nextHop, const std::string& mtu) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001642 std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
1643
1644 if (!nextHop.empty()) {
1645 dstString += " via " + nextHop;
Luke Huangb670d162018-08-23 20:01:13 +08001646 }
1647
Tyler Wearfa94a272019-12-05 15:01:48 -08001648 dstString += " dev " + ifName;
1649
1650 if (!mtu.empty()) {
1651 dstString += " proto static";
1652 // IPv6 routes report the metric, IPv4 routes report the scope.
1653 // TODO: move away from specifying the entire string and use a regexp instead.
1654 if (dst.find(':') != std::string::npos) {
1655 dstString += " metric 1024";
1656 } else {
1657 if (nextHop.empty()) {
1658 dstString += " scope link";
1659 }
1660 }
1661 dstString += " mtu " + mtu;
1662 }
1663
1664 return dstString;
1665}
1666
1667void expectNetworkRouteExistsWithMtu(const char* ipVersion, const std::string& ifName,
1668 const std::string& dst, const std::string& nextHop,
1669 const std::string& mtu, const char* table) {
1670 std::string routeString = ipRouteString(ifName, dst, nextHop, mtu);
1671 EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, mtu)))
1672 << "Couldn't find route to " << dst << ": '" << routeString << "' in table " << table;
Luke Huangb670d162018-08-23 20:01:13 +08001673}
1674
Luke Huangc3252cc2018-10-16 15:43:23 +08001675void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
1676 const std::string& dst, const std::string& nextHop,
1677 const char* table) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001678 expectNetworkRouteExistsWithMtu(ipVersion, ifName, dst, nextHop, "", table);
Luke Huangc3252cc2018-10-16 15:43:23 +08001679}
1680
1681void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
Luke Huangb670d162018-08-23 20:01:13 +08001682 const std::string& dst, const std::string& nextHop,
1683 const char* table) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001684 std::string routeString = ipRouteString(ifName, dst, nextHop, "");
1685 EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop, "")))
1686 << "Found unexpected route " << routeString << " in table " << table;
Luke Huangb670d162018-08-23 20:01:13 +08001687}
1688
1689bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
1690 std::vector<std::string> rules = listIpRules(ipVersion);
1691 for (const auto& rule : rules) {
1692 if (rule.find(ipRule) != std::string::npos) {
1693 return true;
1694 }
1695 }
1696 return false;
1697}
1698
1699void expectNetworkDefaultIpRuleExists(const char* ifName) {
1700 std::string networkDefaultRule =
1701 StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
1702
1703 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1704 EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
1705 }
1706}
1707
1708void expectNetworkDefaultIpRuleDoesNotExist() {
1709 static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
1710
1711 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1712 EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
1713 }
1714}
1715
1716void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
1717 std::string networkPermissionRule = "";
1718 switch (permission) {
1719 case INetd::PERMISSION_NONE:
1720 networkPermissionRule = StringPrintf(
1721 "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
1722 break;
1723 case INetd::PERMISSION_NETWORK:
1724 networkPermissionRule = StringPrintf(
1725 "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
1726 break;
1727 case INetd::PERMISSION_SYSTEM:
1728 networkPermissionRule = StringPrintf(
1729 "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
1730 break;
1731 }
1732
1733 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
1734 EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
1735 }
1736}
1737
1738// TODO: It is a duplicate function, need to remove it
1739bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
1740 const std::string& expectedInterface,
1741 const std::string& expectedRule,
1742 const char* table) {
1743 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
1744 for (const auto& rule : rules) {
1745 if (rule.find(expectedInterface) != std::string::npos) {
1746 if (rule.find(expectedRule) != std::string::npos) {
1747 return true;
1748 }
1749 }
1750 }
1751 return false;
1752}
1753
1754void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
1755 static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
1756 std::string networkIncomingPacketMarkRule = "";
1757 switch (permission) {
1758 case INetd::PERMISSION_NONE:
1759 networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
1760 break;
1761 case INetd::PERMISSION_NETWORK:
1762 networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
1763 break;
1764 case INetd::PERMISSION_SYSTEM:
1765 networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
1766 break;
1767 }
1768
1769 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1770 EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
1771 binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
1772 }
1773}
1774
1775} // namespace
1776
1777TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001778 static const struct {
Luke Huangb670d162018-08-23 20:01:13 +08001779 const char* ipVersion;
1780 const char* testDest;
1781 const char* testNextHop;
1782 const bool expectSuccess;
1783 } kTestData[] = {
1784 {IP_RULE_V4, "0.0.0.0/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001785 {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
1786 {IP_RULE_V4, "10.251.0.0/16", "", true},
1787 {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
1788 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
Luke Huangb670d162018-08-23 20:01:13 +08001789 {IP_RULE_V6, "::/0", "", true},
Luke Huangc3252cc2018-10-16 15:43:23 +08001790 {IP_RULE_V6, "::/0", "2001:db8::", true},
1791 {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
Luke Huangb670d162018-08-23 20:01:13 +08001792 {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
1793 };
1794
Luke Huangc3252cc2018-10-16 15:43:23 +08001795 static const struct {
1796 const char* ipVersion;
1797 const char* testDest;
1798 const char* testNextHop;
1799 } kTestDataWithNextHop[] = {
1800 {IP_RULE_V4, "10.251.10.0/30", ""},
1801 {IP_RULE_V6, "2001:db8::/32", ""},
1802 };
1803
Luke Huangb670d162018-08-23 20:01:13 +08001804 static const char testTableLegacySystem[] = "legacy_system";
Luke Huangc3252cc2018-10-16 15:43:23 +08001805 static const char testTableLegacyNetwork[] = "legacy_network";
Luke Huangb670d162018-08-23 20:01:13 +08001806 const int testUid = randomUid();
1807 const std::vector<int32_t> testUids = {testUid};
1808
1809 // Add test physical network
1810 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1811 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1812
Luke Huangc3252cc2018-10-16 15:43:23 +08001813 // Setup route for testing nextHop
Sehee Park8659b8d2018-11-16 10:53:16 +09001814 for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
Luke Huangc3252cc2018-10-16 15:43:23 +08001815 const auto& td = kTestDataWithNextHop[i];
1816
1817 // All route for test tun will disappear once the tun interface is deleted.
1818 binder::Status status =
1819 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1820 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1821 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1822 sTun.name().c_str());
1823
1824 // Add system permission for test uid, setup route in legacy system table.
1825 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
1826
1827 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1828 testUid);
1829 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1830 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1831 testTableLegacySystem);
1832
1833 // Remove system permission for test uid, setup route in legacy network table.
1834 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1835
1836 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1837 testUid);
1838 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1839 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1840 testTableLegacyNetwork);
1841 }
1842
Sehee Park8659b8d2018-11-16 10:53:16 +09001843 for (size_t i = 0; i < std::size(kTestData); i++) {
Luke Huangb670d162018-08-23 20:01:13 +08001844 const auto& td = kTestData[i];
1845
1846 binder::Status status =
1847 mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1848 if (td.expectSuccess) {
1849 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001850 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001851 sTun.name().c_str());
1852 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001853 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1854 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001855 }
1856
1857 status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
1858 if (td.expectSuccess) {
1859 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001860 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1861 sTun.name().c_str());
Luke Huangb670d162018-08-23 20:01:13 +08001862 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001863 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1864 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001865 }
1866
Luke Huangc3252cc2018-10-16 15:43:23 +08001867 // Add system permission for test uid, route will be added into legacy system table.
1868 EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
Luke Huangb670d162018-08-23 20:01:13 +08001869
1870 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1871 testUid);
1872 if (td.expectSuccess) {
1873 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001874 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
Luke Huangb670d162018-08-23 20:01:13 +08001875 testTableLegacySystem);
1876 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001877 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1878 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001879 }
1880
1881 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1882 td.testNextHop, testUid);
1883 if (td.expectSuccess) {
1884 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangc3252cc2018-10-16 15:43:23 +08001885 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1886 testTableLegacySystem);
Luke Huangb670d162018-08-23 20:01:13 +08001887 } else {
Luke Huangc3252cc2018-10-16 15:43:23 +08001888 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1889 EXPECT_NE(0, status.serviceSpecificErrorCode());
Luke Huangb670d162018-08-23 20:01:13 +08001890 }
1891
Luke Huangc3252cc2018-10-16 15:43:23 +08001892 // Remove system permission for test uid, route will be added into legacy network table.
1893 EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
1894
1895 status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
1896 testUid);
1897 if (td.expectSuccess) {
1898 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1899 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1900 testTableLegacyNetwork);
1901 } else {
1902 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1903 EXPECT_NE(0, status.serviceSpecificErrorCode());
1904 }
1905
1906 status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
1907 td.testNextHop, testUid);
1908 if (td.expectSuccess) {
1909 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1910 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1911 testTableLegacyNetwork);
1912 } else {
1913 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1914 EXPECT_NE(0, status.serviceSpecificErrorCode());
1915 }
Luke Huangb670d162018-08-23 20:01:13 +08001916 }
1917
Tyler Wearfa94a272019-12-05 15:01:48 -08001918 for (size_t i = 0; i < std::size(kTestData); i++) {
1919 const auto& td = kTestData[i];
1920 int mtu = (i % 2) ? 1480 : 1280;
1921
1922 android::net::RouteInfoParcel parcel;
1923 parcel.ifName = sTun.name();
1924 parcel.destination = td.testDest;
1925 parcel.nextHop = td.testNextHop;
1926 parcel.mtu = mtu;
1927 binder::Status status = mNetd->networkAddRouteParcel(TEST_NETID1, parcel);
1928 if (td.expectSuccess) {
1929 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1930 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1931 std::to_string(parcel.mtu), sTun.name().c_str());
1932 } else {
1933 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1934 EXPECT_NE(0, status.serviceSpecificErrorCode());
1935 }
1936
1937 parcel.mtu = 1337;
1938 status = mNetd->networkUpdateRouteParcel(TEST_NETID1, parcel);
1939 if (td.expectSuccess) {
1940 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1941 expectNetworkRouteExistsWithMtu(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1942 std::to_string(parcel.mtu), sTun.name().c_str());
1943 } else {
1944 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1945 EXPECT_NE(0, status.serviceSpecificErrorCode());
1946 }
1947
1948 status = mNetd->networkRemoveRouteParcel(TEST_NETID1, parcel);
1949 if (td.expectSuccess) {
1950 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1951 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
1952 sTun.name().c_str());
1953 } else {
1954 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
1955 EXPECT_NE(0, status.serviceSpecificErrorCode());
1956 }
1957 }
Luke Huangb670d162018-08-23 20:01:13 +08001958 // Remove test physical network
1959 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1960}
1961
1962TEST_F(BinderTest, NetworkPermissionDefault) {
1963 // Add test physical network
1964 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
1965 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
1966
Luke Huangc3252cc2018-10-16 15:43:23 +08001967 // Get current default network NetId
Luke Huangd2861982019-05-17 19:47:28 +08001968 binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
1969 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huangb670d162018-08-23 20:01:13 +08001970
1971 // Test SetDefault
1972 status = mNetd->networkSetDefault(TEST_NETID1);
1973 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1974 expectNetworkDefaultIpRuleExists(sTun.name().c_str());
1975
1976 status = mNetd->networkClearDefault();
1977 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1978 expectNetworkDefaultIpRuleDoesNotExist();
1979
Luke Huangd2861982019-05-17 19:47:28 +08001980 // Set default network back
1981 status = mNetd->networkSetDefault(mStoredDefaultNetwork);
Luke Huangb670d162018-08-23 20:01:13 +08001982 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1983
1984 // Test SetPermission
1985 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
1986 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1987 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1988 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
1989
1990 status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
1991 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
1992 expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1993 expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
1994
1995 // Remove test physical network
1996 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
1997}
1998
1999TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
Luke Huang854e2992019-05-29 16:42:48 +08002000 binder::Status status = mNetd->networkSetProtectAllow(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002001 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2002 bool ret = false;
Luke Huang854e2992019-05-29 16:42:48 +08002003 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002004 EXPECT_TRUE(ret);
2005
Luke Huang854e2992019-05-29 16:42:48 +08002006 status = mNetd->networkSetProtectDeny(TEST_UID1);
Luke Huangb670d162018-08-23 20:01:13 +08002007 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Luke Huang854e2992019-05-29 16:42:48 +08002008
2009 // Clear uid permission before calling networkCanProtect to ensure
2010 // the call won't be affected by uid permission.
2011 EXPECT_TRUE(mNetd->networkClearPermissionForUser({TEST_UID1}).isOk());
2012
2013 status = mNetd->networkCanProtect(TEST_UID1, &ret);
Luke Huangb670d162018-08-23 20:01:13 +08002014 EXPECT_FALSE(ret);
2015}
2016
2017namespace {
2018
Luke Huangb5733d72018-08-21 17:17:19 +08002019int readIntFromPath(const std::string& path) {
2020 std::string result = "";
2021 EXPECT_TRUE(ReadFileToString(path, &result));
2022 return std::stoi(result);
2023}
2024
2025int getTetherAcceptIPv6Ra(const std::string& ifName) {
2026 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
2027 return readIntFromPath(path);
2028}
2029
2030bool getTetherAcceptIPv6Dad(const std::string& ifName) {
2031 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
2032 return readIntFromPath(path);
2033}
2034
2035int getTetherIPv6DadTransmits(const std::string& ifName) {
2036 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
2037 return readIntFromPath(path);
2038}
2039
2040bool getTetherEnableIPv6(const std::string& ifName) {
2041 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2042 int disableIPv6 = readIntFromPath(path);
2043 return !disableIPv6;
2044}
2045
2046bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
2047 for (const auto& iface : ifList) {
2048 if (iface == ifName) {
2049 return true;
2050 }
2051 }
2052 return false;
2053}
2054
2055void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
2056 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
2057 EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
2058 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
2059 EXPECT_TRUE(getTetherEnableIPv6(ifName));
2060}
2061
2062void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
2063 EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
2064 EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
2065 EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
2066 EXPECT_FALSE(getTetherEnableIPv6(ifName));
2067}
2068
2069void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
2070 const std::string& ifName) {
2071 EXPECT_TRUE(interfaceListContains(ifList, ifName));
2072}
2073
2074void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
2075 const std::string& ifName) {
2076 EXPECT_FALSE(interfaceListContains(ifList, ifName));
2077}
2078
2079void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
2080 const std::vector<std::string>& testDnsAddrs) {
2081 EXPECT_TRUE(dnsList == testDnsAddrs);
2082}
2083
2084} // namespace
2085
2086TEST_F(BinderTest, TetherStartStopStatus) {
2087 std::vector<std::string> noDhcpRange = {};
Luke Huang91bd3e12019-08-20 11:33:52 +08002088 for (bool usingLegacyDnsProxy : {true, false}) {
Chiachang Wang08cb2112019-12-10 09:53:24 +08002089 android::net::TetherConfigParcel config;
2090 config.usingLegacyDnsProxy = usingLegacyDnsProxy;
2091 config.dhcpRanges = noDhcpRange;
2092 binder::Status status = mNetd->tetherStartWithConfiguration(config);
Luke Huang91bd3e12019-08-20 11:33:52 +08002093 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2094 SCOPED_TRACE(StringPrintf("usingLegacyDnsProxy: %d", usingLegacyDnsProxy));
2095 if (usingLegacyDnsProxy == true) {
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +00002096 expectProcessExists(DNSMASQ);
Luke Huang91bd3e12019-08-20 11:33:52 +08002097 } else {
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +00002098 expectProcessDoesNotExist(DNSMASQ);
Luke Huang91bd3e12019-08-20 11:33:52 +08002099 }
Luke Huangb5733d72018-08-21 17:17:19 +08002100
Luke Huang91bd3e12019-08-20 11:33:52 +08002101 bool tetherEnabled;
2102 status = mNetd->tetherIsEnabled(&tetherEnabled);
2103 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2104 EXPECT_TRUE(tetherEnabled);
Luke Huangb5733d72018-08-21 17:17:19 +08002105
Luke Huang91bd3e12019-08-20 11:33:52 +08002106 status = mNetd->tetherStop();
2107 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +00002108 expectProcessDoesNotExist(DNSMASQ);
Luke Huangb5733d72018-08-21 17:17:19 +08002109
Luke Huang91bd3e12019-08-20 11:33:52 +08002110 status = mNetd->tetherIsEnabled(&tetherEnabled);
2111 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2112 EXPECT_FALSE(tetherEnabled);
2113 }
Luke Huangb5733d72018-08-21 17:17:19 +08002114}
2115
2116TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
2117 // TODO: verify if dnsmasq update interface successfully
2118
2119 binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
2120 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2121 expectTetherInterfaceConfigureForIPv6Router(sTun.name());
2122
2123 std::vector<std::string> ifList;
2124 status = mNetd->tetherInterfaceList(&ifList);
2125 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2126 expectTetherInterfaceExists(ifList, sTun.name());
2127
2128 status = mNetd->tetherInterfaceRemove(sTun.name());
2129 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2130 expectTetherInterfaceConfigureForIPv6Client(sTun.name());
2131
2132 status = mNetd->tetherInterfaceList(&ifList);
2133 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2134 expectTetherInterfaceNotExists(ifList, sTun.name());
2135}
2136
2137TEST_F(BinderTest, TetherDnsSetList) {
2138 // TODO: verify if dnsmasq update dns successfully
Luke Huang8dc1cac2019-03-30 16:12:31 +08002139 std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
2140 "fe80::1%" + sTun.name()};
Luke Huangb5733d72018-08-21 17:17:19 +08002141
2142 binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
2143 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2144
2145 std::vector<std::string> dnsList;
2146 status = mNetd->tetherDnsList(&dnsList);
2147 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2148 expectTetherDnsListEquals(dnsList, testDnsAddrs);
Luke Huange64fa382018-07-24 16:38:22 +08002149}
2150
2151namespace {
2152
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +00002153std::vector<IPAddress> findDnsSockets(SockDiag* sd, unsigned numExpected) {
2154 std::vector<IPAddress> listenAddrs;
2155
2156 // Callback lambda that finds all IPv4 sockets with source port 53.
2157 auto findDnsSockets = [&](uint8_t /* proto */, const inet_diag_msg* msg) {
2158 // Always return false, which means do not destroy this socket.
2159 if (msg->id.idiag_sport != htons(53)) return false;
2160 IPAddress addr(*(in_addr*)msg->id.idiag_src);
2161 listenAddrs.push_back(addr);
2162 return false;
2163 };
2164
2165 // There is no way to know if dnsmasq has finished processing the update_interfaces command and
2166 // opened listening sockets. So, just spin a few times and return the first list of sockets
2167 // that is at least numExpected long.
Treehugger Robot528cd652020-04-30 11:36:56 +00002168 // Pick a relatively large timeout to avoid flaky tests, particularly when running on shared
2169 // devices.
2170 constexpr int kMaxAttempts = 50;
Lorenzo Colitti5c53ae52020-04-15 17:26:21 +00002171 constexpr int kSleepMs = 100;
2172 for (int i = 0; i < kMaxAttempts; i++) {
2173 listenAddrs.clear();
2174 EXPECT_EQ(0, sd->sendDumpRequest(IPPROTO_TCP, AF_INET, 1 << TCP_LISTEN))
2175 << "Failed to dump sockets, attempt " << i << " of " << kMaxAttempts;
2176 sd->readDiagMsg(IPPROTO_TCP, findDnsSockets);
2177 if (listenAddrs.size() >= numExpected) {
2178 break;
2179 }
2180 usleep(kSleepMs * 1000);
2181 }
2182
2183 return listenAddrs;
2184}
2185
2186} // namespace
2187
2188// Checks that when starting dnsmasq on an interface that no longer exists, it doesn't attempt to
2189// start on other interfaces instead.
2190TEST_F(BinderTest, TetherDeletedInterface) {
2191 // Do this first so we don't need to clean up anything else if it fails.
2192 SockDiag sd;
2193 ASSERT_TRUE(sd.open()) << "Failed to open SOCK_DIAG socket";
2194
2195 // Create our own TunInterfaces (so we can delete them without affecting other tests), and add
2196 // IP addresses to them. They must be IPv4 because tethering an interface disables and
2197 // re-enables IPv6 on the interface, which clears all addresses.
2198 TunInterface tun1, tun2;
2199 ASSERT_EQ(0, tun1.init());
2200 ASSERT_EQ(0, tun2.init());
2201
2202 // Clean up. It is safe to call TunInterface::destroy multiple times.
2203 auto guard = android::base::make_scope_guard([&] {
2204 tun1.destroy();
2205 tun2.destroy();
2206 mNetd->tetherStop();
2207 mNetd->tetherInterfaceRemove(tun1.name());
2208 mNetd->tetherInterfaceRemove(tun2.name());
2209 });
2210
2211 IPAddress addr1, addr2;
2212 ASSERT_TRUE(IPAddress::forString("192.0.2.1", &addr1));
2213 ASSERT_TRUE(IPAddress::forString("192.0.2.2", &addr2));
2214 EXPECT_EQ(0, tun1.addAddress(addr1.toString(), 32));
2215 EXPECT_EQ(0, tun2.addAddress(addr2.toString(), 32));
2216
2217 // Stop tethering.
2218 binder::Status status = mNetd->tetherStop();
2219 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2220
2221 // Start dnsmasq on an interface that doesn't exist.
2222 // First, tether our tun interface...
2223 status = mNetd->tetherInterfaceAdd(tun1.name());
2224 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2225 expectTetherInterfaceConfigureForIPv6Router(tun1.name());
2226
2227 // ... then delete it...
2228 tun1.destroy();
2229
2230 // ... then start dnsmasq.
2231 android::net::TetherConfigParcel config;
2232 config.usingLegacyDnsProxy = true;
2233 config.dhcpRanges = {};
2234 status = mNetd->tetherStartWithConfiguration(config);
2235 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2236
2237 // Wait for dnsmasq to start.
2238 expectProcessExists(DNSMASQ);
2239
2240 // Make sure that netd thinks the interface is tethered (even though it doesn't exist).
2241 std::vector<std::string> ifList;
2242 status = mNetd->tetherInterfaceList(&ifList);
2243 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2244 ASSERT_EQ(1U, ifList.size());
2245 EXPECT_EQ(tun1.name(), ifList[0]);
2246
2247 // Give dnsmasq some time to start up.
2248 usleep(200 * 1000);
2249
2250 // Check that dnsmasq is not listening on any IP addresses. It shouldn't, because it was only
2251 // told to run on tun1, and tun1 does not exist. Ensure it stays running and doesn't listen on
2252 // any IP addresses.
2253 std::vector<IPAddress> listenAddrs = findDnsSockets(&sd, 0);
2254 EXPECT_EQ(0U, listenAddrs.size()) << "Unexpectedly found IPv4 socket(s) listening on port 53";
2255
2256 // Now add an interface to dnsmasq and check that we can see the sockets. This confirms that
2257 // findDnsSockets is actually able to see sockets when they exist.
2258 status = mNetd->tetherInterfaceAdd(tun2.name());
2259 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2260
2261 in_addr loopback = {htonl(INADDR_LOOPBACK)};
2262 listenAddrs = findDnsSockets(&sd, 2);
2263 EXPECT_EQ(2U, listenAddrs.size()) << "Expected exactly 2 IPv4 sockets listening on port 53";
2264 EXPECT_EQ(1, std::count(listenAddrs.begin(), listenAddrs.end(), addr2));
2265 EXPECT_EQ(1, std::count(listenAddrs.begin(), listenAddrs.end(), IPAddress(loopback)));
2266
2267 // Clean up.
2268 status = mNetd->tetherStop();
2269 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2270
2271 expectProcessDoesNotExist(DNSMASQ);
2272
2273 status = mNetd->tetherInterfaceRemove(tun1.name());
2274 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2275
2276 status = mNetd->tetherInterfaceRemove(tun2.name());
2277 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2278}
2279
2280namespace {
2281
Luke Huange64fa382018-07-24 16:38:22 +08002282constexpr char FIREWALL_INPUT[] = "fw_INPUT";
2283constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
2284constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
2285constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
2286constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
2287constexpr char FIREWALL_STANDBY[] = "fw_standby";
2288constexpr char targetReturn[] = "RETURN";
2289constexpr char targetDrop[] = "DROP";
2290
2291void expectFirewallWhitelistMode() {
2292 static const char dropRule[] = "DROP all";
2293 static const char rejectRule[] = "REJECT all";
2294 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2295 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
2296 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
2297 EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
2298 }
2299}
2300
2301void expectFirewallBlacklistMode() {
2302 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2303 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
2304 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
2305 EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
2306 }
2307}
2308
2309bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
2310 const std::string& expectedInterface,
2311 const std::string& expectedRule) {
2312 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2313 // Expected rule:
2314 // Chain fw_INPUT (1 references)
2315 // pkts bytes target prot opt in out source destination
2316 // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
2317 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2318 int firstRuleIndex = 2;
2319 if (rules.size() < 4) return false;
2320 if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
2321 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2322 return true;
2323 }
2324 }
2325 return false;
2326}
2327
2328// TODO: It is a duplicate function, need to remove it
2329bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
2330 const std::string& expectedInterface,
2331 const std::string& expectedRule) {
2332 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2333 for (const auto& rule : rules) {
2334 if (rule.find(expectedInterface) != std::string::npos) {
2335 if (rule.find(expectedRule) != std::string::npos) {
2336 return true;
2337 }
2338 }
2339 }
2340 return false;
2341}
2342
2343void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
2344 static const char returnRule[] = "RETURN all";
2345 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2346 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
2347 returnRule));
2348 EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
2349 returnRule));
2350 }
2351}
2352
2353void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
2354 static const char returnRule[] = "RETURN all";
2355 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2356 EXPECT_FALSE(
2357 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
2358 EXPECT_FALSE(
2359 iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
2360 }
2361}
2362
2363bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
2364 const std::string& expectedTarget,
2365 const std::string& expectedRule) {
2366 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2367 int firstRuleIndex = 2;
2368 if (rules.size() < 4) return false;
2369 if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
2370 if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
2371 return true;
2372 }
2373 }
2374 return false;
2375}
2376
2377bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
2378 const std::string& expectedTarget,
2379 const std::string& expectedRule) {
2380 std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
2381 int lastRuleIndex = rules.size() - 1;
2382 if (lastRuleIndex < 0) return false;
2383 if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
2384 if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
2385 return true;
2386 }
2387 }
2388 return false;
2389}
2390
2391void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
2392 std::string uidRule = StringPrintf("owner UID match %u", uid);
2393 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2394 EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2395}
2396
2397void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
2398 std::string uidRule = StringPrintf("owner UID match %u", uid);
2399 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2400 EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
2401}
2402
2403void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
2404 std::string uidRule = StringPrintf("owner UID match %u", uid);
2405 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2406 EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2407}
2408
2409void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
2410 std::string uidRule = StringPrintf("owner UID match %u", uid);
2411 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2412 EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
2413}
2414
2415bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
2416 std::vector<std::string> inputRules =
2417 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
2418 std::vector<std::string> outputRules =
2419 listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
2420 int inputLastRuleIndex = inputRules.size() - 1;
2421 int outputLastRuleIndex = outputRules.size() - 1;
2422
2423 if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
2424 if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
2425 if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
2426 return true;
2427 }
2428 }
2429 return false;
2430}
2431
2432void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
2433 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
2434 EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
2435}
2436
2437void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
2438 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2439 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
2440 EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
2441 }
2442}
2443
2444} // namespace
2445
2446TEST_F(BinderTest, FirewallSetFirewallType) {
2447 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2448 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2449 expectFirewallWhitelistMode();
2450
2451 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2452 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2453 expectFirewallBlacklistMode();
2454
2455 // set firewall type blacklist twice
2456 mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2457 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2458 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2459 expectFirewallBlacklistMode();
2460
2461 // set firewall type whitelist twice
2462 mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2463 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2464 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2465 expectFirewallWhitelistMode();
2466
2467 // reset firewall type to default
2468 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2469 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2470 expectFirewallBlacklistMode();
2471}
2472
2473TEST_F(BinderTest, FirewallSetInterfaceRule) {
2474 // setinterfaceRule is not supported in BLACKLIST MODE
2475 binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2476 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2477
2478 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2479 EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
2480
2481 // set WHITELIST mode first
2482 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2483 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2484
2485 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
2486 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2487 expectFirewallInterfaceRuleAllowExists(sTun.name());
2488
2489 status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
2490 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2491 expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
2492
2493 // reset firewall mode to default
2494 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2495 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2496 expectFirewallBlacklistMode();
2497}
2498
2499TEST_F(BinderTest, FirewallSetUidRule) {
2500 SKIP_IF_BPF_SUPPORTED;
2501
2502 int32_t uid = randomUid();
2503
2504 // Doze allow
2505 binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2506 INetd::FIREWALL_RULE_ALLOW);
2507 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2508 expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
2509
2510 // Doze deny
2511 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
2512 INetd::FIREWALL_RULE_DENY);
2513 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2514 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
2515
2516 // Powersave allow
2517 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2518 INetd::FIREWALL_RULE_ALLOW);
2519 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2520 expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
2521
2522 // Powersave deny
2523 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
2524 INetd::FIREWALL_RULE_DENY);
2525 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2526 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
2527
2528 // Standby deny
2529 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2530 INetd::FIREWALL_RULE_DENY);
2531 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2532 expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
2533
2534 // Standby allow
2535 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
2536 INetd::FIREWALL_RULE_ALLOW);
2537 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2538 expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
2539
2540 // None deny in BLACKLIST
2541 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2542 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2543 expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
2544 expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
2545
2546 // None allow in BLACKLIST
2547 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2548 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2549 expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
2550 expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2551
2552 // set firewall type whitelist twice
2553 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
2554 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2555 expectFirewallWhitelistMode();
2556
2557 // None allow in WHITELIST
2558 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
2559 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2560 expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
2561 expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
2562
2563 // None deny in WHITELIST
2564 status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
2565 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2566 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
2567 expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
2568
2569 // reset firewall mode to default
2570 status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
2571 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2572 expectFirewallBlacklistMode();
2573}
2574
2575TEST_F(BinderTest, FirewallEnableDisableChildChains) {
2576 SKIP_IF_BPF_SUPPORTED;
2577
2578 binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
2579 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2580 expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
2581
2582 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
2583 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2584 expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
2585
2586 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
2587 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2588 expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
2589
2590 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
2591 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2592 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
2593
2594 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
2595 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2596 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
2597
2598 status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
2599 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2600 expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
2601}
Luke Huangf7782042018-08-08 13:13:04 +08002602
2603namespace {
2604
2605std::string hwAddrToStr(unsigned char* hwaddr) {
2606 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
2607 hwaddr[4], hwaddr[5]);
2608}
2609
2610int ipv4NetmaskToPrefixLength(in_addr_t mask) {
2611 int prefixLength = 0;
2612 uint32_t m = ntohl(mask);
2613 while (m & (1 << 31)) {
2614 prefixLength++;
2615 m = m << 1;
2616 }
2617 return prefixLength;
2618}
2619
2620std::string toStdString(const String16& s) {
2621 return std::string(String8(s.string()));
2622}
2623
2624android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
2625 const auto& sys = sSyscalls.get();
2626 auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
2627 EXPECT_TRUE(isOk(fd.status()));
2628
2629 struct ifreq ifr = {};
2630 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
2631
2632 return sys.ioctl(fd.value(), flag, &ifr);
2633}
2634
2635std::string getInterfaceHwAddr(const std::string& ifName) {
2636 auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
2637
2638 unsigned char hwaddr[ETH_ALEN] = {};
2639 if (isOk(res.status())) {
2640 memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
2641 }
2642
2643 return hwAddrToStr(hwaddr);
2644}
2645
2646int getInterfaceIPv4Prefix(const std::string& ifName) {
2647 auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
2648
2649 int prefixLength = 0;
2650 if (isOk(res.status())) {
2651 prefixLength = ipv4NetmaskToPrefixLength(
2652 ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
2653 }
2654
2655 return prefixLength;
2656}
2657
2658std::string getInterfaceIPv4Addr(const std::string& ifName) {
2659 auto res = ioctlByIfName(ifName, SIOCGIFADDR);
2660
2661 struct in_addr addr = {};
2662 if (isOk(res.status())) {
2663 addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
2664 }
2665
2666 return std::string(inet_ntoa(addr));
2667}
2668
2669std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
2670 auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
2671
2672 unsigned flags = 0;
2673 if (isOk(res.status())) {
2674 flags = res.value().ifr_flags;
2675 }
2676
2677 std::vector<std::string> ifFlags;
2678 ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
2679 : toStdString(INetd::IF_STATE_DOWN()));
2680
2681 if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
2682 if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
2683 if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
2684 if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
2685 if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
2686
2687 return ifFlags;
2688}
2689
2690bool compareListInterface(const std::vector<std::string>& interfaceList) {
2691 const auto& res = InterfaceController::getIfaceNames();
2692 EXPECT_TRUE(isOk(res));
2693
2694 std::vector<std::string> resIfList;
2695 resIfList.reserve(res.value().size());
2696 resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
2697
2698 return resIfList == interfaceList;
2699}
2700
2701int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
2702 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
2703 return readIntFromPath(path);
2704}
2705
2706bool getInterfaceEnableIPv6(const std::string& ifName) {
2707 std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
2708
2709 int disableIPv6 = readIntFromPath(path);
2710 return !disableIPv6;
2711}
2712
2713int getInterfaceMtu(const std::string& ifName) {
2714 std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
2715 return readIntFromPath(path);
2716}
2717
2718void expectInterfaceList(const std::vector<std::string>& interfaceList) {
2719 EXPECT_TRUE(compareListInterface(interfaceList));
2720}
2721
2722void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
2723 const InterfaceConfigurationParcel& interfaceCfg) {
2724 EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
2725 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
2726 EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
2727 EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
2728}
2729
2730void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
2731 EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
2732 EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
2733
2734 const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
2735 for (const auto& flag : setCfg.flags) {
2736 EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
2737 }
2738}
2739
2740void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
2741 int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
2742 EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
2743}
2744
2745void expectInterfaceNoAddr(const std::string& ifName) {
2746 // noAddr
2747 EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
2748 // noPrefix
2749 EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
2750}
2751
2752void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
2753 int enableIPv6 = getInterfaceEnableIPv6(ifName);
2754 EXPECT_EQ(enableIPv6, enable);
2755}
2756
2757void expectInterfaceMtu(const std::string& ifName, const int mtu) {
2758 int mtuSize = getInterfaceMtu(ifName);
2759 EXPECT_EQ(mtu, mtuSize);
2760}
2761
2762InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
2763 const std::string& addr, int prefixLength,
2764 const std::vector<std::string>& flags) {
2765 InterfaceConfigurationParcel cfg;
2766 cfg.ifName = ifName;
2767 cfg.hwAddr = "";
2768 cfg.ipv4Addr = addr;
2769 cfg.prefixLength = prefixLength;
2770 cfg.flags = flags;
2771 return cfg;
2772}
2773
2774void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
2775 std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
2776 std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
2777
2778 for (const auto& flag : expectedFlags) {
2779 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
2780 interfaceCfg.flags.end());
2781 }
2782
2783 for (const auto& flag : unexpectedFlags) {
2784 EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
2785 interfaceCfg.flags.end());
2786 }
2787}
2788
2789} // namespace
2790
2791TEST_F(BinderTest, InterfaceList) {
2792 std::vector<std::string> interfaceListResult;
2793
2794 binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
2795 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2796 expectInterfaceList(interfaceListResult);
2797}
2798
2799TEST_F(BinderTest, InterfaceGetCfg) {
2800 InterfaceConfigurationParcel interfaceCfgResult;
2801
2802 // Add test physical network
2803 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2804 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2805
2806 binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
2807 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2808 expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
2809 expectTunFlags(interfaceCfgResult);
2810
2811 // Remove test physical network
2812 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2813}
2814
2815TEST_F(BinderTest, InterfaceSetCfg) {
2816 const std::string testAddr = "192.0.2.3";
2817 const int testPrefixLength = 24;
2818 std::vector<std::string> upFlags = {"up"};
2819 std::vector<std::string> downFlags = {"down"};
2820
2821 // Add test physical network
2822 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2823 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2824
2825 // Set tun interface down.
2826 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
2827 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2828 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2829 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2830
2831 // Set tun interface up again.
2832 interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
2833 status = mNetd->interfaceSetCfg(interfaceCfg);
2834 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2835 status = mNetd->interfaceClearAddrs(sTun.name());
2836 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2837
2838 // Remove test physical network
2839 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2840}
2841
2842TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
2843 // enable
2844 binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
2845 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2846 expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
2847
2848 // disable
2849 status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
2850 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2851 expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
2852}
2853
2854TEST_F(BinderTest, InterfaceClearAddr) {
2855 const std::string testAddr = "192.0.2.3";
2856 const int testPrefixLength = 24;
2857 std::vector<std::string> noFlags{};
2858
2859 // Add test physical network
2860 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2861 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2862
2863 auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
2864 binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
2865 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2866 expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
2867
2868 status = mNetd->interfaceClearAddrs(sTun.name());
2869 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2870 expectInterfaceNoAddr(sTun.name());
2871
2872 // Remove test physical network
2873 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2874}
2875
2876TEST_F(BinderTest, InterfaceSetEnableIPv6) {
2877 // Add test physical network
2878 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2879 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2880
2881 // disable
2882 binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
2883 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2884 expectInterfaceEnableIPv6(sTun.name(), false);
2885
2886 // enable
2887 status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
2888 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2889 expectInterfaceEnableIPv6(sTun.name(), true);
2890
2891 // Remove test physical network
2892 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2893}
2894
2895TEST_F(BinderTest, InterfaceSetMtu) {
2896 const int testMtu = 1200;
2897
2898 // Add test physical network
2899 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
2900 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
2901
2902 binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
2903 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2904 expectInterfaceMtu(sTun.name(), testMtu);
2905
2906 // Remove test physical network
2907 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
2908}
Luke Huang19b49c52018-10-22 12:12:05 +09002909
2910namespace {
2911
2912constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
2913constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
Luke Huangae038f82018-11-05 11:17:31 +09002914constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
Luke Huang19b49c52018-10-22 12:12:05 +09002915constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
2916
Luke Huangae038f82018-11-05 11:17:31 +09002917int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
Luke Huang19b49c52018-10-22 12:12:05 +09002918 return listIptablesRuleByTable(binary, table, chainName).size();
2919}
2920
2921bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
2922 const std::vector<std::string>& targetVec) {
2923 std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
2924 if (targetVec.size() != rules.size() - 2) {
2925 return false;
2926 }
2927
2928 /*
Luke Huangae038f82018-11-05 11:17:31 +09002929 * Check that the rules match. Note that this function matches substrings, not entire rules,
2930 * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
Luke Huang19b49c52018-10-22 12:12:05 +09002931 * Skip first two lines since rules start from third line.
2932 * Chain chainName (x references)
2933 * pkts bytes target prot opt in out source destination
2934 * ...
2935 */
2936 int rIndex = 2;
2937 for (const auto& target : targetVec) {
2938 if (rules[rIndex].find(target) == std::string::npos) {
2939 return false;
2940 }
2941 rIndex++;
2942 }
2943 return true;
2944}
2945
2946void expectNatEnable(const std::string& intIf, const std::string& extIf) {
2947 std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
2948 std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
2949 std::vector<std::string> forwardV4Match = {
Luke Huangae038f82018-11-05 11:17:31 +09002950 "bw_global_alert", "state RELATED", "state INVALID",
Luke Huang19b49c52018-10-22 12:12:05 +09002951 StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
2952 "DROP"};
2953
2954 // V4
2955 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
2956 postroutingV4Match));
Luke Huangae038f82018-11-05 11:17:31 +09002957 EXPECT_TRUE(
2958 iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002959 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2960
Luke Huangae038f82018-11-05 11:17:31 +09002961 std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
Luke Huang19b49c52018-10-22 12:12:05 +09002962 std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
2963
2964 // V6
2965 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
Luke Huangae038f82018-11-05 11:17:31 +09002966 EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
2967 preroutingV6Match));
Luke Huang19b49c52018-10-22 12:12:05 +09002968
2969 for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
2970 EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
2971 extIf));
2972 }
2973}
2974
2975void expectNatDisable() {
2976 // It is the default DROP rule with tethering disable.
2977 // Chain tetherctrl_FORWARD (1 references)
2978 // pkts bytes target prot opt in out source destination
2979 // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
2980 std::vector<std::string> forwardV4Match = {"DROP"};
2981 EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
2982
2983 // We expect that these chains should be empty.
Luke Huangae038f82018-11-05 11:17:31 +09002984 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
2985 EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002986
Luke Huangae038f82018-11-05 11:17:31 +09002987 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
2988 EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
Luke Huang19b49c52018-10-22 12:12:05 +09002989
2990 // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
2991}
2992
2993} // namespace
2994
2995TEST_F(BinderTest, TetherForwardAddRemove) {
Luke Huang19b49c52018-10-22 12:12:05 +09002996 binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
2997 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
2998 expectNatEnable(sTun.name(), sTun2.name());
2999
3000 status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
3001 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3002 expectNatDisable();
Luke Huang19b49c52018-10-22 12:12:05 +09003003}
Chenbo Fengf5663d82018-11-08 16:10:48 -08003004
3005namespace {
3006
3007using TripleInt = std::array<int, 3>;
3008
3009TripleInt readProcFileToTripleInt(const std::string& path) {
3010 std::string valueString;
3011 int min, def, max;
3012 EXPECT_TRUE(ReadFileToString(path, &valueString));
3013 EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
3014 return {min, def, max};
3015}
3016
3017void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
3018 std::string testRmemValues =
3019 StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
3020 std::string testWmemValues =
3021 StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
3022 EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
3023
3024 TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
3025 TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
3026
3027 for (int i = 0; i < 3; i++) {
3028 SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
3029 EXPECT_EQ(rmemValues[i], newRmemValues[i]);
3030 EXPECT_EQ(wmemValues[i], newWmemValues[i]);
3031 }
3032}
3033
3034} // namespace
3035
3036TEST_F(BinderTest, TcpBufferSet) {
3037 TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
3038 TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
3039 TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
3040 TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
3041
3042 updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
3043 updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
3044}
Luke Huang528af602018-08-29 19:06:05 +08003045
Chenbo Feng48eaed32018-12-26 17:40:21 -08003046namespace {
3047
Chenbo Fengbf660aa2019-02-26 16:12:27 -08003048void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
Maciej Żenczykowskif879a7f2020-01-20 03:18:06 -08003049 android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(UID_PERMISSION_MAP_PATH);
Chenbo Feng48eaed32018-12-26 17:40:21 -08003050 for (int32_t uid : uids) {
Steven Morelanda3074542020-01-13 14:13:44 -08003051 android::base::Result<uint8_t> permission = uidPermissionMap.readValue(uid);
Chenbo Feng48eaed32018-12-26 17:40:21 -08003052 if (exist) {
Bernie Innocentidfd5a432020-02-12 09:21:56 +09003053 ASSERT_RESULT_OK(permission);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07003054 EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
Chenbo Feng48eaed32018-12-26 17:40:21 -08003055 } else {
Bernie Innocentidfd5a432020-02-12 09:21:56 +09003056 ASSERT_FALSE(permission.ok());
Steven Morelanda3074542020-01-13 14:13:44 -08003057 EXPECT_EQ(ENOENT, permission.error().code());
Chenbo Feng48eaed32018-12-26 17:40:21 -08003058 }
3059 }
3060}
3061
3062} // namespace
3063
3064TEST_F(BinderTest, TestInternetPermission) {
3065 SKIP_IF_BPF_NOT_SUPPORTED;
3066
3067 std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
3068
3069 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08003070 checkUidsInPermissionMap(appUids, false);
Chenbo Feng84f48cd2019-04-22 15:34:40 -07003071 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
Chenbo Fengbf660aa2019-02-26 16:12:27 -08003072 checkUidsInPermissionMap(appUids, true);
3073 mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
3074 checkUidsInPermissionMap(appUids, false);
Chenbo Feng48eaed32018-12-26 17:40:21 -08003075}
3076
Luke Huang528af602018-08-29 19:06:05 +08003077TEST_F(BinderTest, UnsolEvents) {
3078 auto testUnsolService = android::net::TestUnsolService::start();
3079 std::string oldTunName = sTun.name();
3080 std::string newTunName = "unsolTest";
3081 testUnsolService->tarVec.push_back(oldTunName);
3082 testUnsolService->tarVec.push_back(newTunName);
3083 auto& cv = testUnsolService->getCv();
3084 auto& cvMutex = testUnsolService->getCvMutex();
3085 binder::Status status = mNetd->registerUnsolicitedEventListener(
3086 android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
3087 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3088
3089 // TODO: Add test for below events
3090 // StrictCleartextDetected / InterfaceDnsServersAdded
3091 // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
3092
3093 {
3094 std::unique_lock lock(cvMutex);
3095
3096 // Re-init test Tun, and we expect that we will get some unsol events.
3097 // Use the test Tun device name to verify if we receive its unsol events.
3098 sTun.destroy();
3099 // Use predefined name
3100 sTun.init(newTunName);
3101
3102 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3103 }
3104
3105 // bit mask 1101101000
3106 // Test only covers below events currently
3107 const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
3108 InterfaceLinkStatusChanged | RouteChanged;
3109 EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
Luke Huangcfd04b22019-03-18 15:53:21 +08003110
3111 // Re-init sTun to clear predefined name
3112 sTun.destroy();
3113 sTun.init();
3114}
3115
3116TEST_F(BinderTest, NDC) {
3117 struct Command {
3118 const std::string cmdString;
3119 const std::string expectedResult;
3120 };
3121
3122 // clang-format off
3123 // Do not change the commands order
3124 const Command networkCmds[] = {
3125 {StringPrintf("ndc network create %d", TEST_NETID1),
3126 "200 0 success"},
3127 {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
3128 "200 0 success"},
3129 {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
3130 "200 0 success"},
3131 {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
3132 "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
3133 {StringPrintf("ndc network destroy %d", TEST_NETID1),
3134 "200 0 success"},
3135 };
3136
3137 const std::vector<Command> ipfwdCmds = {
3138 {"ndc ipfwd enable " + sTun.name(),
3139 "200 0 ipfwd operation succeeded"},
3140 {"ndc ipfwd disable " + sTun.name(),
3141 "200 0 ipfwd operation succeeded"},
3142 {"ndc ipfwd add lo2 lo3",
3143 "400 0 ipfwd operation failed (No such process)"},
3144 {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
3145 "200 0 ipfwd operation succeeded"},
3146 {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
3147 "200 0 ipfwd operation succeeded"},
3148 };
3149
3150 static const struct {
3151 const char* ipVersion;
3152 const char* testDest;
3153 const char* testNextHop;
3154 const bool expectSuccess;
3155 const std::string expectedResult;
3156 } kTestData[] = {
3157 {IP_RULE_V4, "0.0.0.0/0", "", true,
3158 "200 0 success"},
3159 {IP_RULE_V4, "10.251.0.0/16", "", true,
3160 "200 0 success"},
3161 {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
3162 "400 0 addRoute() failed (Invalid argument)",},
3163 {IP_RULE_V6, "::/0", "", true,
3164 "200 0 success"},
3165 {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
3166 "200 0 success"},
3167 {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
3168 "400 0 addRoute() failed (Invalid argument)"},
3169 };
3170 // clang-format on
3171
3172 for (const auto& cmd : networkCmds) {
3173 const std::vector<std::string> result = runCommand(cmd.cmdString);
3174 SCOPED_TRACE(cmd.cmdString);
3175 EXPECT_EQ(result.size(), 1U);
3176 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3177 }
3178
3179 for (const auto& cmd : ipfwdCmds) {
3180 const std::vector<std::string> result = runCommand(cmd.cmdString);
3181 SCOPED_TRACE(cmd.cmdString);
3182 EXPECT_EQ(result.size(), 1U);
3183 EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
3184 }
3185
3186 // Add test physical network
3187 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3188 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3189
3190 for (const auto& td : kTestData) {
3191 const std::string routeAddCmd =
3192 StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
3193 td.testDest, td.testNextHop);
3194 const std::string routeRemoveCmd =
3195 StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
3196 sTun.name().c_str(), td.testDest, td.testNextHop);
3197 std::vector<std::string> result = runCommand(routeAddCmd);
3198 SCOPED_TRACE(routeAddCmd);
3199 EXPECT_EQ(result.size(), 1U);
3200 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3201 if (td.expectSuccess) {
3202 expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3203 sTun.name().c_str());
3204 result = runCommand(routeRemoveCmd);
3205 EXPECT_EQ(result.size(), 1U);
3206 EXPECT_EQ(td.expectedResult, Trim(result[0]));
3207 expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
3208 sTun.name().c_str());
3209 }
3210 }
3211 // Remove test physical network
3212 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
Bernie Innocentia5161a02019-01-30 22:40:53 +09003213}
Luke Huang0e5e69d2019-03-06 15:42:38 +08003214
Luke Huang2ff8b342019-04-30 15:33:33 +08003215TEST_F(BinderTest, OemNetdRelated) {
Luke Huang0e5e69d2019-03-06 15:42:38 +08003216 sp<IBinder> binder;
3217 binder::Status status = mNetd->getOemNetd(&binder);
3218 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3219 sp<com::android::internal::net::IOemNetd> oemNetd;
3220 if (binder != nullptr) {
3221 oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
3222 }
Luke Huang2ff8b342019-04-30 15:33:33 +08003223 ASSERT_NE(nullptr, oemNetd.get());
Luke Huang0e5e69d2019-03-06 15:42:38 +08003224
3225 TimedOperation t("OemNetd isAlive RPC");
3226 bool isAlive = false;
3227 oemNetd->isAlive(&isAlive);
3228 ASSERT_TRUE(isAlive);
Luke Huang2ff8b342019-04-30 15:33:33 +08003229
3230 class TestOemUnsolListener
3231 : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
3232 public:
3233 android::binder::Status onRegistered() override {
3234 std::lock_guard lock(mCvMutex);
3235 mCv.notify_one();
3236 return android::binder::Status::ok();
3237 }
3238 std::condition_variable& getCv() { return mCv; }
3239 std::mutex& getCvMutex() { return mCvMutex; }
3240
3241 private:
3242 std::mutex mCvMutex;
3243 std::condition_variable mCv;
3244 };
3245
3246 // Start the Binder thread pool.
3247 android::ProcessState::self()->startThreadPool();
3248
3249 android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
3250
3251 auto& cv = testListener->getCv();
3252 auto& cvMutex = testListener->getCvMutex();
3253
3254 {
3255 std::unique_lock lock(cvMutex);
3256
3257 status = oemNetd->registerOemUnsolicitedEventListener(
3258 ::android::interface_cast<
3259 com::android::internal::net::IOemNetdUnsolicitedEventListener>(
3260 testListener));
3261 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3262
3263 // Wait for receiving expected events.
3264 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
3265 }
Luke Huang0e5e69d2019-03-06 15:42:38 +08003266}
Luke Huangd2861982019-05-17 19:47:28 +08003267
3268void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
3269 int fallthroughNetId) {
3270 // Re-init sTun* to ensure route rule exists.
3271 sTun.destroy();
3272 sTun.init();
3273 sTun2.destroy();
3274 sTun2.init();
3275
3276 // Create physical network with fallthroughNetId but not set it as default network
3277 EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
3278 EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
3279
3280 // Create VPN with vpnNetId
3281 EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
3282
3283 // Add uid to VPN
3284 EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
3285 EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
3286
3287 // Add default route to fallthroughNetwork
3288 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
3289 // Add limited route
3290 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
3291}
3292
3293namespace {
3294
3295class ScopedUidChange {
3296 public:
3297 explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
3298 mStoredUid = getuid();
3299 if (mInputUid == mStoredUid) return;
3300 EXPECT_TRUE(seteuid(uid) == 0);
3301 }
3302 ~ScopedUidChange() {
3303 if (mInputUid == mStoredUid) return;
3304 EXPECT_TRUE(seteuid(mStoredUid) == 0);
3305 }
3306
3307 private:
3308 uid_t mInputUid;
3309 uid_t mStoredUid;
3310};
3311
3312constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
3313
3314void clearQueue(int tunFd) {
3315 char buf[4096];
3316 int ret;
3317 do {
3318 ret = read(tunFd, buf, sizeof(buf));
3319 } while (ret > 0);
3320}
3321
3322void checkDataReceived(int udpSocket, int tunFd) {
3323 char buf[4096] = {};
3324 // Clear tunFd's queue before write something because there might be some
3325 // arbitrary packets in the queue. (e.g. ICMPv6 packet)
3326 clearQueue(tunFd);
3327 EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
3328 // TODO: extract header and verify data
3329 EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
3330}
3331
3332bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
3333 ScopedUidChange scopedUidChange(uid);
Bernie Innocentid26a04a2019-10-30 17:15:15 +09003334 unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Luke Huangd2861982019-05-17 19:47:28 +08003335 if (testSocket < 0) return false;
3336
Nick Desaulniers6b357502019-10-11 09:26:44 -07003337 const sockaddr_in6 dst6 = {
3338 .sin6_family = AF_INET6,
3339 .sin6_port = 42,
3340 .sin6_addr = dstAddr,
3341 };
Luke Huangd2861982019-05-17 19:47:28 +08003342 int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
3343 socklen_t fwmarkLen = sizeof(fwmark->intValue);
3344 EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
3345 if (res == -1) return false;
3346
3347 char addr[INET6_ADDRSTRLEN];
3348 inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
3349 SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
3350 checkDataReceived(testSocket, tunFd);
3351 return true;
3352}
3353
3354void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
3355 std::string vpnFallthroughRule =
3356 StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
3357 RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
3358 for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
3359 EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
3360 }
3361}
3362
3363void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
3364 const TunInterface& fallthroughNetwork,
3365 const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
3366 int fallthroughNetId = TEST_NETID1) {
3367 // Set default network to NETID_UNSET
3368 EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
3369
3370 // insideVpnAddr based on the route we added in createVpnNetworkWithUid
3371 in6_addr insideVpnAddr = {
3372 {// 2001:db8:cafe::1
3373 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
3374 // outsideVpnAddr will hit the route in the fallthrough network route table
3375 // because we added default route in createVpnNetworkWithUid
3376 in6_addr outsideVpnAddr = {
3377 {// 2607:f0d0:1002::4
3378 .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
3379
3380 int fallthroughFd = fallthroughNetwork.getFdForTesting();
3381 int vpnFd = vpnNetwork.getFdForTesting();
3382 // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
3383 // default network.
3384 Fwmark fwmark;
3385 EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3386 EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3387
3388 // Set default network
3389 EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
3390
3391 // Connections go on the default network because UID 0 is not subject to the VPN.
3392 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3393 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3394 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3395 EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
3396
3397 // Check if fallthrough rule exists
3398 expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
3399
3400 // Expect fallthrough to default network
3401 // The fwmark differs depending on whether the VPN is bypassable or not.
3402 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3403 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3404
3405 // Expect connect success, packet will be sent to vpnFd.
3406 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
3407 EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
3408
3409 // Explicitly select vpn network
3410 setNetworkForProcess(vpnNetId);
3411
3412 // Expect fallthrough to default network
3413 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3414 // Expect the mark contains all the bit because we've selected network.
3415 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3416
3417 // Expect connect success, packet will be sent to vpnFd.
3418 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
3419 // Expect the mark contains all the bit because we've selected network.
3420 EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
3421
3422 // Explicitly select fallthrough network
3423 setNetworkForProcess(fallthroughNetId);
3424
3425 // The mark is set to fallthrough network because we've selected it.
3426 EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
3427 EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
3428
3429 // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
3430 if (bypassable) {
3431 EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3432 EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3433 } else {
3434 // If not, no permission to bypass vpn.
3435 EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
3436 EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
3437 }
3438}
3439
3440} // namespace
3441
3442TEST_F(BinderTest, SecureVPNFallthrough) {
3443 createVpnNetworkWithUid(true /* secure */, TEST_UID1);
3444 // Get current default network NetId
3445 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3446 expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
3447}
3448
3449TEST_F(BinderTest, BypassableVPNFallthrough) {
3450 createVpnNetworkWithUid(false /* secure */, TEST_UID1);
3451 // Get current default network NetId
3452 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3453 expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
Bernie Innocenti80ffd0f2019-06-05 15:27:46 +09003454}
Chiachang Wang00fc62f2019-12-04 20:38:26 +08003455
3456namespace {
3457
3458int32_t createIpv6SocketAndCheckMark(int type, const in6_addr& dstAddr) {
3459 const sockaddr_in6 dst6 = {
3460 .sin6_family = AF_INET6,
3461 .sin6_port = 1234,
3462 .sin6_addr = dstAddr,
3463 };
3464 // create non-blocking socket.
3465 int sockFd = socket(AF_INET6, type | SOCK_NONBLOCK, 0);
3466 EXPECT_NE(-1, sockFd);
3467 EXPECT_EQ((type == SOCK_STREAM) ? -1 : 0, connect(sockFd, (sockaddr*)&dst6, sizeof(dst6)));
3468
3469 // Get socket fwmark.
3470 Fwmark fwmark;
3471 socklen_t fwmarkLen = sizeof(fwmark.intValue);
3472 EXPECT_EQ(0, getsockopt(sockFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen));
3473 EXPECT_EQ(0, close(sockFd));
3474 return fwmark.intValue;
3475}
3476
3477} // namespace
3478
3479TEST_F(BinderTest, GetFwmarkForNetwork) {
Maciej Żenczykowskibfe00b72020-05-20 02:01:23 -07003480 // Save current default network.
3481 ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
3482
Chiachang Wang00fc62f2019-12-04 20:38:26 +08003483 in6_addr v6Addr = {
3484 {// 2001:db8:cafe::8888
3485 .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0x88, 0x88}}};
3486 // Add test physical network 1 and set as default network.
3487 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3488 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3489 EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "2001:db8::/32", "").isOk());
3490 EXPECT_TRUE(mNetd->networkSetDefault(TEST_NETID1).isOk());
3491 // Add test physical network 2
3492 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
3493 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
3494
3495 // Get fwmark for network 1.
3496 MarkMaskParcel maskMarkNet1;
3497 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID1, &maskMarkNet1).isOk());
3498
3499 uint32_t fwmarkTcp = createIpv6SocketAndCheckMark(SOCK_STREAM, v6Addr);
3500 uint32_t fwmarkUdp = createIpv6SocketAndCheckMark(SOCK_DGRAM, v6Addr);
3501 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkTcp & maskMarkNet1.mask));
3502 EXPECT_EQ(maskMarkNet1.mark, static_cast<int>(fwmarkUdp & maskMarkNet1.mask));
3503
3504 // Get fwmark for network 2.
3505 MarkMaskParcel maskMarkNet2;
3506 ASSERT_TRUE(mNetd->getFwmarkForNetwork(TEST_NETID2, &maskMarkNet2).isOk());
3507 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkTcp & maskMarkNet2.mask));
3508 EXPECT_NE(maskMarkNet2.mark, static_cast<int>(fwmarkUdp & maskMarkNet2.mask));
3509
3510 // Remove test physical network.
3511 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
3512 EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
3513}
Hungming Chen92571042020-02-20 17:01:31 +08003514
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003515namespace {
3516
3517TetherOffloadRuleParcel makeTetherOffloadRule(int inputInterfaceIndex, int outputInterfaceIndex,
3518 const std::vector<uint8_t>& destination,
3519 int prefixLength,
3520 const std::vector<uint8_t>& srcL2Address,
3521 const std::vector<uint8_t>& dstL2Address) {
3522 android::net::TetherOffloadRuleParcel parcel;
3523 parcel.inputInterfaceIndex = inputInterfaceIndex;
3524 parcel.outputInterfaceIndex = outputInterfaceIndex;
3525 parcel.destination = destination;
3526 parcel.prefixLength = prefixLength;
3527 parcel.srcL2Address = srcL2Address;
3528 parcel.dstL2Address = dstL2Address;
3529 return parcel;
3530}
3531
3532} // namespace
3533
3534TEST_F(BinderTest, TetherOffloadRule) {
Hungming Chen92571042020-02-20 17:01:31 +08003535 SKIP_IF_BPF_NOT_SUPPORTED;
3536
3537 // TODO: Perhaps verify invalid interface index once the netd handle the error in methods.
3538 constexpr uint32_t kIfaceInt = 101;
3539 constexpr uint32_t kIfaceExt = 102;
3540 constexpr uint32_t kIfaceNonExistent = 103;
3541
3542 const std::vector<uint8_t> kAddr6 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0x00, 0x00,
3543 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88};
3544 const std::vector<uint8_t> kSrcMac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x0a};
3545 const std::vector<uint8_t> kDstMac = {0x00, 0x00, 0x00, 0x00, 0x00, 0x0b};
3546
3547 const std::vector<uint8_t> kInvalidAddr4 = {0xac, 0x0a, 0x0d, 0xb8}; // should be IPv6 address
3548 const std::vector<uint8_t> kInvalidMac = {0xde, 0xad, 0xbe, 0xef}; // should be 6-byte length
3549
3550 // Invalid IP address, add rule
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003551 TetherOffloadRuleParcel rule = makeTetherOffloadRule(
3552 kIfaceExt, kIfaceInt, kInvalidAddr4 /*bad*/, 128, kSrcMac, kDstMac);
3553 auto status = mNetd->tetherOffloadRuleAdd(rule);
Hungming Chen92571042020-02-20 17:01:31 +08003554 EXPECT_FALSE(status.isOk());
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003555 EXPECT_EQ(EAFNOSUPPORT, status.serviceSpecificErrorCode());
Hungming Chen92571042020-02-20 17:01:31 +08003556
3557 // Invalid source L2 address, add rule
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003558 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kInvalidMac /*bad*/, kDstMac);
3559 status = mNetd->tetherOffloadRuleAdd(rule);
Hungming Chen92571042020-02-20 17:01:31 +08003560 EXPECT_FALSE(status.isOk());
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003561 EXPECT_EQ(ENXIO, status.serviceSpecificErrorCode());
Hungming Chen92571042020-02-20 17:01:31 +08003562
3563 // Invalid destination L2 address, add rule
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003564 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kInvalidMac /*bad*/);
3565 status = mNetd->tetherOffloadRuleAdd(rule);
Hungming Chen92571042020-02-20 17:01:31 +08003566 EXPECT_FALSE(status.isOk());
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003567 EXPECT_EQ(ENXIO, status.serviceSpecificErrorCode());
Hungming Chen92571042020-02-20 17:01:31 +08003568
3569 // Invalid IP address, remove rule
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003570 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kInvalidAddr4 /*bad*/, 128, kSrcMac,
3571 kDstMac);
3572 status = mNetd->tetherOffloadRuleRemove(rule);
3573 EXPECT_FALSE(status.isOk());
3574 EXPECT_EQ(EAFNOSUPPORT, status.serviceSpecificErrorCode());
3575
3576 // Invalid prefix length
3577 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 64 /*bad*/, kSrcMac, kDstMac);
3578 status = mNetd->tetherOffloadRuleAdd(rule);
3579 EXPECT_FALSE(status.isOk());
3580 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3581 status = mNetd->tetherOffloadRuleRemove(rule);
Hungming Chen92571042020-02-20 17:01:31 +08003582 EXPECT_FALSE(status.isOk());
3583 EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
3584
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003585 // Invalid interface index
3586 rule = makeTetherOffloadRule(kIfaceExt, 0, kAddr6, 128, kSrcMac, kDstMac);
3587 status = mNetd->tetherOffloadRuleAdd(rule);
3588 EXPECT_FALSE(status.isOk());
3589 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
3590 rule = makeTetherOffloadRule(0, kIfaceInt, kAddr6, 64, kSrcMac, kDstMac);
3591 status = mNetd->tetherOffloadRuleRemove(rule);
3592 EXPECT_FALSE(status.isOk());
3593 EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
3594
Hungming Chen92571042020-02-20 17:01:31 +08003595 // Remove non existent rule. Expect that silently return success if the rule did not exist.
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003596 rule = makeTetherOffloadRule(kIfaceNonExistent, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac);
3597 EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
Hungming Chen92571042020-02-20 17:01:31 +08003598
3599 // Add and remove rule normally.
Lorenzo Colittif0e051c2020-04-06 09:19:57 +00003600 rule = makeTetherOffloadRule(kIfaceExt, kIfaceInt, kAddr6, 128, kSrcMac, kDstMac);
3601 EXPECT_TRUE(mNetd->tetherOffloadRuleAdd(rule).isOk());
3602 EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
Hungming Chen92571042020-02-20 17:01:31 +08003603}
Lorenzo Colitti56165db2020-05-29 21:37:09 +09003604
3605static bool expectPacket(int fd, uint8_t* ipPacket, ssize_t ipLen) {
3606 constexpr bool kDebug = false;
3607
3608 uint8_t buf[ETHER_HDR_LEN + 1500];
3609
3610 // Wait a bit to ensure that the packet we're interested in has arrived.
3611 // TODO: speed this up.
3612 usleep(100 * 1000);
3613
3614 ssize_t bytesRead;
3615 ssize_t expectedLen = ipLen + ETHER_HDR_LEN;
3616 while ((bytesRead = read(fd, buf, sizeof(buf))) >= 0) {
3617 if (kDebug) {
3618 std::cerr << fmt::format(
3619 "Expected: {:02x}\n Actual: {:02x}\n",
3620 fmt::join(ipPacket, ipPacket + ipLen, " "),
3621 fmt::join(buf + ETHER_HDR_LEN, buf + ETHER_HDR_LEN + ipLen, " "));
3622 }
3623
3624 if (bytesRead != expectedLen) {
3625 continue;
3626 }
3627
3628 if (!memcmp(ipPacket, buf + ETHER_HDR_LEN, ipLen)) {
3629 return true;
3630 }
3631 }
3632
3633 return false;
3634}
3635
3636TEST_F(BinderTest, TetherOffloadForwarding) {
3637 SKIP_IF_EXTENDED_BPF_NOT_SUPPORTED;
3638
3639 constexpr const char* kDownstreamPrefix = "2001:db8:2::/64";
3640
Lorenzo Colitti6d4f2b92020-05-29 22:16:52 +09003641 // 1486-byte packet.
3642 // TODO: increase to 1500 bytes when kernels are fixed.
3643 struct packet {
3644 ipv6hdr hdr;
3645 char data[1446];
3646 } __attribute__((packed)) pkt = {
3647 .hdr =
3648 {
3649 .version = 6,
3650 .payload_len = htons(1446),
3651 .nexthdr = 59, // No next header.
3652 .hop_limit = 64,
3653 .saddr = {{{0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
3654 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}},
3655 .daddr = {{{0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
3656 0x00, 0x00, 0x0f, 0x00, 0xca, 0xfe}}},
3657 },
Lorenzo Colitti56165db2020-05-29 21:37:09 +09003658 };
Lorenzo Colitti6d4f2b92020-05-29 22:16:52 +09003659 ASSERT_EQ(1486U, sizeof(pkt));
Lorenzo Colitti56165db2020-05-29 21:37:09 +09003660
3661 // Use one of the test's tun interfaces as upstream.
3662 // It must be part of a network or it will not have the clsact attached.
3663 EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
3664 EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
3665 int fd1 = sTun.getFdForTesting();
3666
3667 // Create our own tap as a downstream.
3668 TunInterface tap;
3669 ASSERT_EQ(0, tap.init(true /* isTap */));
3670 ASSERT_LE(tap.name().size(), static_cast<size_t>(IFNAMSIZ));
3671 int fd2 = tap.getFdForTesting();
3672
3673 // Set it to nonblocking so that expectPacket can work.
3674 int flags = fcntl(fd2, F_GETFL, 0);
3675 fcntl(fd2, F_SETFL, flags | O_NONBLOCK);
3676
3677 // Downstream interface setup. Add to local network, add directly-connected route, etc.
3678 binder::Status status = mNetd->networkAddInterface(INetd::LOCAL_NET_ID, tap.name());
3679 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3680 status = mNetd->tetherInterfaceAdd(tap.name());
3681 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3682 expectTetherInterfaceConfigureForIPv6Router(tap.name());
3683
3684 // Can't easily use INetd::NEXTHOP_NONE because it is a String16 constant. Use "" instead.
3685 status = mNetd->networkAddRoute(INetd::LOCAL_NET_ID, tap.name(), kDownstreamPrefix, "");
3686 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3687
3688 // Set up forwarding. All methods take intIface first and extIface second.
3689 status = mNetd->tetherAddForward(tap.name(), sTun.name());
3690 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3691 status = mNetd->ipfwdAddInterfaceForward(tap.name(), sTun.name());
3692 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3693
3694 std::vector<uint8_t> kDummyMac = {02, 00, 00, 00, 00, 00};
Lorenzo Colitti6d4f2b92020-05-29 22:16:52 +09003695 uint8_t* daddr = reinterpret_cast<uint8_t*>(&pkt.hdr.daddr);
3696 std::vector<uint8_t> dstAddr(daddr, daddr + sizeof(pkt.hdr.daddr));
Lorenzo Colitti56165db2020-05-29 21:37:09 +09003697
3698 TetherOffloadRuleParcel rule = makeTetherOffloadRule(sTun.ifindex(), tap.ifindex(), dstAddr,
3699 128, kDummyMac, kDummyMac);
3700 status = mNetd->tetherOffloadRuleAdd(rule);
3701 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
3702
3703 // Receive a packet on sTun.
Lorenzo Colitti6d4f2b92020-05-29 22:16:52 +09003704 EXPECT_EQ((ssize_t)sizeof(pkt), write(fd1, &pkt, sizeof(pkt)));
Lorenzo Colitti56165db2020-05-29 21:37:09 +09003705
Lorenzo Colitti6d4f2b92020-05-29 22:16:52 +09003706 // Expect a packet identical to pkt, except with a TTL of 63.
3707 struct packet pkt2 = pkt;
3708 ASSERT_EQ(1486U, sizeof(pkt));
3709 pkt2.hdr.hop_limit = pkt.hdr.hop_limit - 1;
3710 EXPECT_TRUE(expectPacket(fd2, (uint8_t*)&pkt2, sizeof(pkt2)));
Lorenzo Colitti56165db2020-05-29 21:37:09 +09003711
3712 // Clean up.
3713 EXPECT_TRUE(mNetd->tetherOffloadRuleRemove(rule).isOk());
3714 EXPECT_TRUE(mNetd->ipfwdRemoveInterfaceForward(tap.name(), sTun.name()).isOk());
3715 EXPECT_TRUE(mNetd->tetherRemoveForward(tap.name(), sTun.name()).isOk());
3716 EXPECT_TRUE(mNetd->networkRemoveRoute(INetd::LOCAL_NET_ID, tap.name(), kDownstreamPrefix, "")
3717 .isOk());
3718 EXPECT_TRUE(mNetd->tetherInterfaceRemove(tap.name()).isOk());
3719 EXPECT_TRUE(mNetd->networkRemoveInterface(INetd::LOCAL_NET_ID, tap.name()).isOk());
3720 EXPECT_TRUE(mNetd->networkRemoveInterface(TEST_NETID1, sTun.name()).isOk());
3721}