blob: c072400cc65023359ab69a4a8badd97dd6a9e6c6 [file] [log] [blame]
Pierre Imai1cfa5432016-02-24 18:00:03 +09001/*
2 * Copyright (C) 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
Bernie Innocenti196f1b82019-05-20 16:34:16 +090017#include <cinttypes>
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090018#include <regex>
19#include <set>
20#include <string>
21
Lorenzo Colitti05306fb2017-02-09 04:56:00 +090022#include <android-base/stringprintf.h>
Mike Yue7e332f2019-03-13 17:15:48 +080023#include <android-base/strings.h>
24#include <netdutils/Stopwatch.h>
Lorenzo Colitti05306fb2017-02-09 04:56:00 +090025
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090026#define LOG_TAG "Netd"
Logan Chien3f461482018-04-23 14:31:32 +080027#include <log/log.h>
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090028
Pierre Imai1cfa5432016-02-24 18:00:03 +090029#include "Controllers.h"
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090030#include "IdletimerController.h"
31#include "NetworkController.h"
32#include "RouteController.h"
Nathan Harold21299f72018-03-16 20:13:03 -070033#include "XfrmController.h"
Mike Yue7e332f2019-03-13 17:15:48 +080034#include "oem_iptables_hook.h"
Pierre Imai1cfa5432016-02-24 18:00:03 +090035
36namespace android {
37namespace net {
38
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090039using android::base::StringAppendF;
Mike Yue7e332f2019-03-13 17:15:48 +080040using android::base::StringPrintf;
41using android::netdutils::Stopwatch;
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090042
Lorenzo Colitti341d3a02017-08-08 17:31:35 +090043auto Controllers::execIptablesRestore = ::execIptablesRestore;
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090044auto Controllers::execIptablesRestoreWithOutput = ::execIptablesRestoreWithOutput;
Lorenzo Colitti341d3a02017-08-08 17:31:35 +090045
Erik Klineb31fd692018-06-06 20:50:11 +090046netdutils::Log gLog("netd");
Luke Huang528af602018-08-29 19:06:05 +080047netdutils::Log gUnsolicitedLog("netdUnsolicited");
Erik Klineb31fd692018-06-06 20:50:11 +090048
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090049namespace {
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090050
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090051/**
52 * List of module chains to be created, along with explicit ordering. ORDERING
53 * IS CRITICAL, AND SHOULD BE TRIPLE-CHECKED WITH EACH CHANGE.
54 */
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090055static const std::vector<const char*> FILTER_INPUT = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090056 // Bandwidth should always be early in input chain, to make sure we
57 // correctly count incoming traffic against data plan.
58 BandwidthController::LOCAL_INPUT,
59 FirewallController::LOCAL_INPUT,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090060};
61
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090062static const std::vector<const char*> FILTER_FORWARD = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090063 OEM_IPTABLES_FILTER_FORWARD,
64 FirewallController::LOCAL_FORWARD,
65 BandwidthController::LOCAL_FORWARD,
Lorenzo Colittia93126d2017-08-24 13:28:19 +090066 TetherController::LOCAL_FORWARD,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090067};
68
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090069static const std::vector<const char*> FILTER_OUTPUT = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090070 OEM_IPTABLES_FILTER_OUTPUT,
71 FirewallController::LOCAL_OUTPUT,
72 StrictController::LOCAL_OUTPUT,
73 BandwidthController::LOCAL_OUTPUT,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090074};
75
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090076static const std::vector<const char*> RAW_PREROUTING = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090077 BandwidthController::LOCAL_RAW_PREROUTING,
78 IdletimerController::LOCAL_RAW_PREROUTING,
Lorenzo Colittia93126d2017-08-24 13:28:19 +090079 TetherController::LOCAL_RAW_PREROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090080};
81
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090082static const std::vector<const char*> MANGLE_POSTROUTING = {
Lorenzo Colitti05306fb2017-02-09 04:56:00 +090083 OEM_IPTABLES_MANGLE_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090084 BandwidthController::LOCAL_MANGLE_POSTROUTING,
85 IdletimerController::LOCAL_MANGLE_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090086};
87
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090088static const std::vector<const char*> MANGLE_INPUT = {
Joel Scherpelz08b84cd2017-05-22 13:11:54 +090089 WakeupController::LOCAL_MANGLE_INPUT,
Lorenzo Colittid78843e2017-03-27 05:52:31 +090090 RouteController::LOCAL_MANGLE_INPUT,
Lorenzo Colittid78843e2017-03-27 05:52:31 +090091};
92
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090093static const std::vector<const char*> MANGLE_FORWARD = {
Lorenzo Colittia93126d2017-08-24 13:28:19 +090094 TetherController::LOCAL_MANGLE_FORWARD,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090095};
96
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090097static const std::vector<const char*> NAT_PREROUTING = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090098 OEM_IPTABLES_NAT_PREROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090099};
100
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900101static const std::vector<const char*> NAT_POSTROUTING = {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900102 TetherController::LOCAL_NAT_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900103};
104
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900105// Commands to create child chains and to match created chains in iptables -S output. Keep in sync.
106static const char* CHILD_CHAIN_TEMPLATE = "-A %s -j %s\n";
107static const std::regex CHILD_CHAIN_REGEX("^-A ([^ ]+) -j ([^ ]+)$",
108 std::regex_constants::extended);
109
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900110} // namespace
111
112/* static */
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900113std::set<std::string> Controllers::findExistingChildChains(const IptablesTarget target,
114 const char* table,
115 const char* parentChain) {
116 if (target == V4V6) {
117 ALOGE("findExistingChildChains only supports one protocol at a time");
118 abort();
119 }
120
121 std::set<std::string> existing;
122
123 // List the current contents of parentChain.
124 //
125 // TODO: there is no guarantee that nothing else modifies the chain in the few milliseconds
126 // between when we list the existing rules and when we delete them. However:
127 // - Since this code is only run on startup, nothing else in netd will be running.
128 // - While vendor code is known to add its own rules to chains created by netd, it should never
129 // be modifying the rules in childChains or the rules that hook said chains into their parent
130 // chains.
131 std::string command = StringPrintf("*%s\n-S %s\nCOMMIT\n", table, parentChain);
132 std::string output;
133 if (Controllers::execIptablesRestoreWithOutput(target, command, &output) == -1) {
134 ALOGE("Error listing chain %s in table %s\n", parentChain, table);
135 return existing;
136 }
137
138 // The only rules added by createChildChains are of the simple form "-A <parent> -j <child>".
139 // Find those rules and add each one's child chain to existing.
140 std::smatch matches;
141 std::stringstream stream(output);
142 std::string rule;
143 while (std::getline(stream, rule, '\n')) {
144 if (std::regex_search(rule, matches, CHILD_CHAIN_REGEX) && matches[1] == parentChain) {
145 existing.insert(matches[2]);
146 }
147 }
148
149 return existing;
150}
151
152/* static */
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900153void Controllers::createChildChains(IptablesTarget target, const char* table,
154 const char* parentChain,
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900155 const std::vector<const char*>& childChains,
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900156 bool exclusive) {
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900157 std::string command = StringPrintf("*%s\n", table);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900158
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900159 // We cannot just clear all the chains we create because vendor code modifies filter OUTPUT and
160 // mangle POSTROUTING directly. So:
161 //
162 // - If we're the exclusive owner of this chain, simply clear it entirely.
163 // - If not, then list the chain's current contents to ensure that if we restart after a crash,
164 // we leave the existing rules alone in the positions they currently occupy. This is faster
165 // than blindly deleting our rules and recreating them, because deleting a rule that doesn't
166 // exists causes iptables-restore to quit, which takes ~30ms per delete. It's also more
167 // correct, because if we delete rules and re-add them, they'll be in the wrong position with
168 // regards to the vendor rules.
169 //
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900170 // TODO: Make all chains exclusive once vendor code uses the oem_* rules.
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900171 std::set<std::string> existingChildChains;
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900172 if (exclusive) {
173 // Just running ":chain -" flushes user-defined chains, but not built-in chains like INPUT.
174 // Since at this point we don't know if parentChain is a built-in chain, do both.
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900175 StringAppendF(&command, ":%s -\n", parentChain);
176 StringAppendF(&command, "-F %s\n", parentChain);
177 } else {
178 existingChildChains = findExistingChildChains(target, table, parentChain);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900179 }
180
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900181 for (const auto& childChain : childChains) {
182 // Always clear the child chain.
183 StringAppendF(&command, ":%s -\n", childChain);
184 // But only add it to the parent chain if it's not already there.
185 if (existingChildChains.find(childChain) == existingChildChains.end()) {
186 StringAppendF(&command, CHILD_CHAIN_TEMPLATE, parentChain, childChain);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900187 }
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900188 }
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900189 command += "COMMIT\n";
Lorenzo Colitti05306fb2017-02-09 04:56:00 +0900190 execIptablesRestore(target, command);
191}
192
Joel Scherpelz08b84cd2017-05-22 13:11:54 +0900193Controllers::Controllers()
Luke Huangf29fe682019-03-26 15:15:44 +0800194 : clatdCtrl(&netCtrl),
Joel Scherpelz08b84cd2017-05-22 13:11:54 +0900195 wakeupCtrl(
Erik Klineb31fd692018-06-06 20:50:11 +0900196 [this](const WakeupController::ReportArgs& args) {
197 const auto listener = eventReporter.getNetdEventListener();
198 if (listener == nullptr) {
199 gLog.error("getNetdEventListener() returned nullptr. dropping wakeup event");
200 return;
201 }
202 String16 prefix = String16(args.prefix.c_str());
203 String16 srcIp = String16(args.srcIp.c_str());
204 String16 dstIp = String16(args.dstIp.c_str());
205 listener->onWakeupEvent(prefix, args.uid, args.ethertype, args.ipNextHeader,
206 args.dstHw, srcIp, dstIp, args.srcPort, args.dstPort,
207 args.timestampNs);
208 },
209 &iptablesRestoreCtrl) {
Erik Kline2c5aaa12016-06-08 13:24:45 +0900210 InterfaceController::initializeAll();
211}
Pierre Imai1cfa5432016-02-24 18:00:03 +0900212
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900213void Controllers::initChildChains() {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900214 /*
215 * This is the only time we touch top-level chains in iptables; controllers
216 * should only mutate rules inside of their children chains, as created by
217 * the constants above.
218 *
219 * Modules should never ACCEPT packets (except in well-justified cases);
220 * they should instead defer to any remaining modules using RETURN, or
221 * otherwise DROP/REJECT.
222 */
223
Lorenzo Colitti05306fb2017-02-09 04:56:00 +0900224 // Create chains for child modules.
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900225 createChildChains(V4V6, "filter", "INPUT", FILTER_INPUT, true);
226 createChildChains(V4V6, "filter", "FORWARD", FILTER_FORWARD, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900227 createChildChains(V4V6, "raw", "PREROUTING", RAW_PREROUTING, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900228 createChildChains(V4V6, "mangle", "FORWARD", MANGLE_FORWARD, true);
Lorenzo Colittid78843e2017-03-27 05:52:31 +0900229 createChildChains(V4V6, "mangle", "INPUT", MANGLE_INPUT, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900230 createChildChains(V4, "nat", "PREROUTING", NAT_PREROUTING, true);
231 createChildChains(V4, "nat", "POSTROUTING", NAT_POSTROUTING, true);
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900232
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900233 createChildChains(V4, "filter", "OUTPUT", FILTER_OUTPUT, false);
234 createChildChains(V6, "filter", "OUTPUT", FILTER_OUTPUT, false);
235 createChildChains(V4, "mangle", "POSTROUTING", MANGLE_POSTROUTING, false);
236 createChildChains(V6, "mangle", "POSTROUTING", MANGLE_POSTROUTING, false);
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900237}
238
239void Controllers::initIptablesRules() {
240 Stopwatch s;
241 initChildChains();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900242 gLog.info("Creating child chains: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900243
244 // Let each module setup their child chains
245 setupOemIptablesHook();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900246 gLog.info("Setting up OEM hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900247
248 /* When enabled, DROPs all packets except those matching rules. */
249 firewallCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900250 gLog.info("Setting up FirewallController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900251
252 /* Does DROPs in FORWARD by default */
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900253 tetherCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900254 gLog.info("Setting up TetherController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900255
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900256 /*
257 * Does REJECT in INPUT, OUTPUT. Does counting also.
258 * No DROP/REJECT allowed later in netfilter-flow hook order.
259 */
260 bandwidthCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900261 gLog.info("Setting up BandwidthController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900262
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900263 /*
264 * Counts in nat: PREROUTING, POSTROUTING.
265 * No DROP/REJECT allowed later in netfilter-flow hook order.
266 */
267 idletimerCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900268 gLog.info("Setting up IdletimerController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Luke Huanga67dd562018-07-17 19:58:25 +0800269
270 /*
271 * Add rules for detecting IPv6/IPv4 TCP/UDP connections with TLS/DTLS header
272 */
273 strictCtrl.setupIptablesHooks();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900274 gLog.info("Setting up StrictController hooks: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900275}
276
277void Controllers::init() {
278 initIptablesRules();
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900279 Stopwatch s;
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700280
Maciej Żenczykowski56280272019-03-30 03:32:51 -0700281 clatdCtrl.init();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900282 gLog.info("Initializing ClatdController: %" PRId64 "us", s.getTimeAndResetUs());
Maciej Żenczykowski1c086e52019-03-29 23:13:49 -0700283
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800284 netdutils::Status tcStatus = trafficCtrl.start();
285 if (!isOk(tcStatus)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900286 gLog.error("Failed to start trafficcontroller: (%s)", toString(tcStatus).c_str());
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800287 }
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900288 gLog.info("Initializing traffic control: %" PRId64 "us", s.getTimeAndResetUs());
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800289
Chenbo Feng47dd0732018-12-11 12:23:24 -0800290 bandwidthCtrl.setBpfEnabled(trafficCtrl.getBpfLevel() != android::bpf::BpfLevel::NONE);
Luke Huangf44a3c12018-09-07 12:10:12 +0800291 bandwidthCtrl.enableBandwidthControl();
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900292 gLog.info("Enabling bandwidth control: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900293
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800294 if (int ret = RouteController::Init(NetworkController::LOCAL_NET_ID)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900295 gLog.error("Failed to initialize RouteController (%s)", strerror(-ret));
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900296 }
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900297 gLog.info("Initializing RouteController: %" PRId64 "us", s.getTimeAndResetUs());
Nathan Harold21299f72018-03-16 20:13:03 -0700298
299 netdutils::Status xStatus = XfrmController::Init();
300 if (!isOk(xStatus)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900301 gLog.error("Failed to initialize XfrmController (%s)", netdutils::toString(xStatus).c_str());
Nathan Harold21299f72018-03-16 20:13:03 -0700302 };
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900303 gLog.info("Initializing XfrmController: %" PRId64 "us", s.getTimeAndResetUs());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900304}
305
Pierre Imai1cfa5432016-02-24 18:00:03 +0900306Controllers* gCtls = nullptr;
307
308} // namespace net
309} // namespace android