blob: 409d243cf1097e5e5e72252152be6d03f945d12b [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
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090017#include <regex>
18#include <set>
19#include <string>
20
21#include <android-base/strings.h>
Lorenzo Colitti05306fb2017-02-09 04:56:00 +090022#include <android-base/stringprintf.h>
23
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090024#define LOG_TAG "Netd"
Logan Chien3f461482018-04-23 14:31:32 +080025#include <log/log.h>
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090026
Pierre Imai1cfa5432016-02-24 18:00:03 +090027#include "Controllers.h"
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090028#include "IdletimerController.h"
29#include "NetworkController.h"
30#include "RouteController.h"
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +090031#include "Stopwatch.h"
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090032#include "oem_iptables_hook.h"
Nathan Harold21299f72018-03-16 20:13:03 -070033#include "XfrmController.h"
Pierre Imai1cfa5432016-02-24 18:00:03 +090034
35namespace android {
36namespace net {
37
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090038using android::base::Join;
39using android::base::StringPrintf;
40using android::base::StringAppendF;
41
Lorenzo Colitti341d3a02017-08-08 17:31:35 +090042auto Controllers::execIptablesRestore = ::execIptablesRestore;
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090043auto Controllers::execIptablesRestoreWithOutput = ::execIptablesRestoreWithOutput;
Lorenzo Colitti341d3a02017-08-08 17:31:35 +090044
Erik Klineb31fd692018-06-06 20:50:11 +090045netdutils::Log gLog("netd");
46
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090047namespace {
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090048
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090049/**
50 * List of module chains to be created, along with explicit ordering. ORDERING
51 * IS CRITICAL, AND SHOULD BE TRIPLE-CHECKED WITH EACH CHANGE.
52 */
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090053static const std::vector<const char*> FILTER_INPUT = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090054 // Bandwidth should always be early in input chain, to make sure we
55 // correctly count incoming traffic against data plan.
56 BandwidthController::LOCAL_INPUT,
57 FirewallController::LOCAL_INPUT,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090058};
59
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090060static const std::vector<const char*> FILTER_FORWARD = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090061 OEM_IPTABLES_FILTER_FORWARD,
62 FirewallController::LOCAL_FORWARD,
63 BandwidthController::LOCAL_FORWARD,
Lorenzo Colittia93126d2017-08-24 13:28:19 +090064 TetherController::LOCAL_FORWARD,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090065};
66
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090067static const std::vector<const char*> FILTER_OUTPUT = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090068 OEM_IPTABLES_FILTER_OUTPUT,
69 FirewallController::LOCAL_OUTPUT,
70 StrictController::LOCAL_OUTPUT,
71 BandwidthController::LOCAL_OUTPUT,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090072};
73
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090074static const std::vector<const char*> RAW_PREROUTING = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090075 BandwidthController::LOCAL_RAW_PREROUTING,
76 IdletimerController::LOCAL_RAW_PREROUTING,
Lorenzo Colittia93126d2017-08-24 13:28:19 +090077 TetherController::LOCAL_RAW_PREROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090078};
79
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090080static const std::vector<const char*> MANGLE_POSTROUTING = {
Lorenzo Colitti05306fb2017-02-09 04:56:00 +090081 OEM_IPTABLES_MANGLE_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090082 BandwidthController::LOCAL_MANGLE_POSTROUTING,
83 IdletimerController::LOCAL_MANGLE_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090084};
85
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090086static const std::vector<const char*> MANGLE_INPUT = {
Joel Scherpelz08b84cd2017-05-22 13:11:54 +090087 WakeupController::LOCAL_MANGLE_INPUT,
Lorenzo Colittid78843e2017-03-27 05:52:31 +090088 RouteController::LOCAL_MANGLE_INPUT,
Lorenzo Colittid78843e2017-03-27 05:52:31 +090089};
90
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090091static const std::vector<const char*> MANGLE_FORWARD = {
Lorenzo Colittia93126d2017-08-24 13:28:19 +090092 TetherController::LOCAL_MANGLE_FORWARD,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090093};
94
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090095static const std::vector<const char*> NAT_PREROUTING = {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090096 OEM_IPTABLES_NAT_PREROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +090097};
98
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +090099static const std::vector<const char*> NAT_POSTROUTING = {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900100 TetherController::LOCAL_NAT_POSTROUTING,
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900101};
102
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900103// Commands to create child chains and to match created chains in iptables -S output. Keep in sync.
104static const char* CHILD_CHAIN_TEMPLATE = "-A %s -j %s\n";
105static const std::regex CHILD_CHAIN_REGEX("^-A ([^ ]+) -j ([^ ]+)$",
106 std::regex_constants::extended);
107
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900108} // namespace
109
110/* static */
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900111std::set<std::string> Controllers::findExistingChildChains(const IptablesTarget target,
112 const char* table,
113 const char* parentChain) {
114 if (target == V4V6) {
115 ALOGE("findExistingChildChains only supports one protocol at a time");
116 abort();
117 }
118
119 std::set<std::string> existing;
120
121 // List the current contents of parentChain.
122 //
123 // TODO: there is no guarantee that nothing else modifies the chain in the few milliseconds
124 // between when we list the existing rules and when we delete them. However:
125 // - Since this code is only run on startup, nothing else in netd will be running.
126 // - While vendor code is known to add its own rules to chains created by netd, it should never
127 // be modifying the rules in childChains or the rules that hook said chains into their parent
128 // chains.
129 std::string command = StringPrintf("*%s\n-S %s\nCOMMIT\n", table, parentChain);
130 std::string output;
131 if (Controllers::execIptablesRestoreWithOutput(target, command, &output) == -1) {
132 ALOGE("Error listing chain %s in table %s\n", parentChain, table);
133 return existing;
134 }
135
136 // The only rules added by createChildChains are of the simple form "-A <parent> -j <child>".
137 // Find those rules and add each one's child chain to existing.
138 std::smatch matches;
139 std::stringstream stream(output);
140 std::string rule;
141 while (std::getline(stream, rule, '\n')) {
142 if (std::regex_search(rule, matches, CHILD_CHAIN_REGEX) && matches[1] == parentChain) {
143 existing.insert(matches[2]);
144 }
145 }
146
147 return existing;
148}
149
150/* static */
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900151void Controllers::createChildChains(IptablesTarget target, const char* table,
152 const char* parentChain,
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900153 const std::vector<const char*>& childChains,
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900154 bool exclusive) {
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900155 std::string command = StringPrintf("*%s\n", table);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900156
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900157 // We cannot just clear all the chains we create because vendor code modifies filter OUTPUT and
158 // mangle POSTROUTING directly. So:
159 //
160 // - If we're the exclusive owner of this chain, simply clear it entirely.
161 // - If not, then list the chain's current contents to ensure that if we restart after a crash,
162 // we leave the existing rules alone in the positions they currently occupy. This is faster
163 // than blindly deleting our rules and recreating them, because deleting a rule that doesn't
164 // exists causes iptables-restore to quit, which takes ~30ms per delete. It's also more
165 // correct, because if we delete rules and re-add them, they'll be in the wrong position with
166 // regards to the vendor rules.
167 //
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900168 // TODO: Make all chains exclusive once vendor code uses the oem_* rules.
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900169 std::set<std::string> existingChildChains;
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900170 if (exclusive) {
171 // Just running ":chain -" flushes user-defined chains, but not built-in chains like INPUT.
172 // Since at this point we don't know if parentChain is a built-in chain, do both.
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900173 StringAppendF(&command, ":%s -\n", parentChain);
174 StringAppendF(&command, "-F %s\n", parentChain);
175 } else {
176 existingChildChains = findExistingChildChains(target, table, parentChain);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900177 }
178
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900179 for (const auto& childChain : childChains) {
180 // Always clear the child chain.
181 StringAppendF(&command, ":%s -\n", childChain);
182 // But only add it to the parent chain if it's not already there.
183 if (existingChildChains.find(childChain) == existingChildChains.end()) {
184 StringAppendF(&command, CHILD_CHAIN_TEMPLATE, parentChain, childChain);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900185 }
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900186 }
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900187 command += "COMMIT\n";
Lorenzo Colitti05306fb2017-02-09 04:56:00 +0900188 execIptablesRestore(target, command);
189}
190
Joel Scherpelz08b84cd2017-05-22 13:11:54 +0900191Controllers::Controllers()
Erik Klined26a2c22018-05-11 19:33:19 +0900192 : resolverCtrl(netCtrl),
193 clatdCtrl(&netCtrl),
Joel Scherpelz08b84cd2017-05-22 13:11:54 +0900194 wakeupCtrl(
Erik Klineb31fd692018-06-06 20:50:11 +0900195 [this](const WakeupController::ReportArgs& args) {
196 const auto listener = eventReporter.getNetdEventListener();
197 if (listener == nullptr) {
198 gLog.error("getNetdEventListener() returned nullptr. dropping wakeup event");
199 return;
200 }
201 String16 prefix = String16(args.prefix.c_str());
202 String16 srcIp = String16(args.srcIp.c_str());
203 String16 dstIp = String16(args.dstIp.c_str());
204 listener->onWakeupEvent(prefix, args.uid, args.ethertype, args.ipNextHeader,
205 args.dstHw, srcIp, dstIp, args.srcPort, args.dstPort,
206 args.timestampNs);
207 },
208 &iptablesRestoreCtrl) {
Erik Kline2c5aaa12016-06-08 13:24:45 +0900209 InterfaceController::initializeAll();
210}
Pierre Imai1cfa5432016-02-24 18:00:03 +0900211
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900212void Controllers::initChildChains() {
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900213 /*
214 * This is the only time we touch top-level chains in iptables; controllers
215 * should only mutate rules inside of their children chains, as created by
216 * the constants above.
217 *
218 * Modules should never ACCEPT packets (except in well-justified cases);
219 * they should instead defer to any remaining modules using RETURN, or
220 * otherwise DROP/REJECT.
221 */
222
Lorenzo Colitti05306fb2017-02-09 04:56:00 +0900223 // Create chains for child modules.
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900224 createChildChains(V4V6, "filter", "INPUT", FILTER_INPUT, true);
225 createChildChains(V4V6, "filter", "FORWARD", FILTER_FORWARD, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900226 createChildChains(V4V6, "raw", "PREROUTING", RAW_PREROUTING, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900227 createChildChains(V4V6, "mangle", "FORWARD", MANGLE_FORWARD, true);
Lorenzo Colittid78843e2017-03-27 05:52:31 +0900228 createChildChains(V4V6, "mangle", "INPUT", MANGLE_INPUT, true);
Lorenzo Colitticda022e2017-02-03 12:35:46 +0900229 createChildChains(V4, "nat", "PREROUTING", NAT_PREROUTING, true);
230 createChildChains(V4, "nat", "POSTROUTING", NAT_POSTROUTING, true);
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900231
Lorenzo Colittiadc3a5f2017-08-08 17:23:12 +0900232 createChildChains(V4, "filter", "OUTPUT", FILTER_OUTPUT, false);
233 createChildChains(V6, "filter", "OUTPUT", FILTER_OUTPUT, false);
234 createChildChains(V4, "mangle", "POSTROUTING", MANGLE_POSTROUTING, false);
235 createChildChains(V6, "mangle", "POSTROUTING", MANGLE_POSTROUTING, false);
Lorenzo Colitti341d3a02017-08-08 17:31:35 +0900236}
237
238void Controllers::initIptablesRules() {
239 Stopwatch s;
240 initChildChains();
Erik Klineb31fd692018-06-06 20:50:11 +0900241 gLog.info("Creating child chains: %.1fms", s.getTimeAndReset());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900242
243 // Let each module setup their child chains
244 setupOemIptablesHook();
Erik Klineb31fd692018-06-06 20:50:11 +0900245 gLog.info("Setting up OEM hooks: %.1fms", s.getTimeAndReset());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900246
247 /* When enabled, DROPs all packets except those matching rules. */
248 firewallCtrl.setupIptablesHooks();
Erik Klineb31fd692018-06-06 20:50:11 +0900249 gLog.info("Setting up FirewallController hooks: %.1fms", s.getTimeAndReset());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900250
251 /* Does DROPs in FORWARD by default */
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900252 tetherCtrl.setupIptablesHooks();
Erik Klineb31fd692018-06-06 20:50:11 +0900253 gLog.info("Setting up TetherController hooks: %.1fms", s.getTimeAndReset());
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900254
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900255 /*
256 * Does REJECT in INPUT, OUTPUT. Does counting also.
257 * No DROP/REJECT allowed later in netfilter-flow hook order.
258 */
259 bandwidthCtrl.setupIptablesHooks();
Erik Klineb31fd692018-06-06 20:50:11 +0900260 gLog.info("Setting up BandwidthController hooks: %.1fms", s.getTimeAndReset());
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900261
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900262 /*
263 * Counts in nat: PREROUTING, POSTROUTING.
264 * No DROP/REJECT allowed later in netfilter-flow hook order.
265 */
266 idletimerCtrl.setupIptablesHooks();
Erik Klineb31fd692018-06-06 20:50:11 +0900267 gLog.info("Setting up IdletimerController hooks: %.1fms", s.getTimeAndReset());
Luke Huanga67dd562018-07-17 19:58:25 +0800268
269 /*
270 * Add rules for detecting IPv6/IPv4 TCP/UDP connections with TLS/DTLS header
271 */
272 strictCtrl.setupIptablesHooks();
273 gLog.info("Setting up StrictController hooks: %.1fms", s.getTimeAndReset());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900274}
275
276void Controllers::init() {
277 initIptablesRules();
Lorenzo Colitti19ee8a82017-02-02 12:59:05 +0900278 Stopwatch s;
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800279 netdutils::Status tcStatus = trafficCtrl.start();
280 if (!isOk(tcStatus)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900281 gLog.error("Failed to start trafficcontroller: (%s)", toString(tcStatus).c_str());
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800282 }
Erik Klineb31fd692018-06-06 20:50:11 +0900283 gLog.info("Initializing traffic control: %.1fms", s.getTimeAndReset());
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800284
Chenbo Feng44c0f442018-07-10 16:54:30 -0700285 bandwidthCtrl.setBpfEnabled(trafficCtrl.checkBpfStatsEnable());
Luke Huangf44a3c12018-09-07 12:10:12 +0800286 bandwidthCtrl.enableBandwidthControl();
287 gLog.info("Enabling bandwidth control: %.1fms", s.getTimeAndReset());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900288
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800289 if (int ret = RouteController::Init(NetworkController::LOCAL_NET_ID)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900290 gLog.error("Failed to initialize RouteController (%s)", strerror(-ret));
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900291 }
Erik Klineb31fd692018-06-06 20:50:11 +0900292 gLog.info("Initializing RouteController: %.1fms", s.getTimeAndReset());
Nathan Harold21299f72018-03-16 20:13:03 -0700293
294 netdutils::Status xStatus = XfrmController::Init();
295 if (!isOk(xStatus)) {
Erik Klineb31fd692018-06-06 20:50:11 +0900296 gLog.error("Failed to initialize XfrmController (%s)", netdutils::toString(xStatus).c_str());
Nathan Harold21299f72018-03-16 20:13:03 -0700297 };
Erik Klineb31fd692018-06-06 20:50:11 +0900298 gLog.info("Initializing XfrmController: %.1fms", s.getTimeAndReset());
Lorenzo Colitti1ed96e22017-02-02 12:21:56 +0900299}
300
Pierre Imai1cfa5432016-02-24 18:00:03 +0900301Controllers* gCtls = nullptr;
302
303} // namespace net
304} // namespace android