• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 #include <cinttypes>
18 #include <regex>
19 #include <set>
20 #include <string>
21 
22 #include <android-base/stringprintf.h>
23 #include <android-base/strings.h>
24 #include <netdutils/Stopwatch.h>
25 
26 #define LOG_TAG "Netd"
27 #include <log/log.h>
28 
29 #include "Controllers.h"
30 #include "IdletimerController.h"
31 #include "NetworkController.h"
32 #include "RouteController.h"
33 #include "XfrmController.h"
34 #include "oem_iptables_hook.h"
35 
36 namespace android {
37 namespace net {
38 
39 using android::base::StringAppendF;
40 using android::base::StringPrintf;
41 using android::netdutils::Stopwatch;
42 
43 auto Controllers::execIptablesRestore  = ::execIptablesRestore;
44 auto Controllers::execIptablesRestoreWithOutput = ::execIptablesRestoreWithOutput;
45 
46 netdutils::Log gLog("netd");
47 netdutils::Log gUnsolicitedLog("netdUnsolicited");
48 
49 namespace {
50 
51 /**
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  */
55 static const std::vector<const char*> FILTER_INPUT = {
56         // 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,
60 };
61 
62 static const std::vector<const char*> FILTER_FORWARD = {
63         OEM_IPTABLES_FILTER_FORWARD,
64         FirewallController::LOCAL_FORWARD,
65         BandwidthController::LOCAL_FORWARD,
66         TetherController::LOCAL_FORWARD,
67 };
68 
69 static const std::vector<const char*> FILTER_OUTPUT = {
70         OEM_IPTABLES_FILTER_OUTPUT,
71         FirewallController::LOCAL_OUTPUT,
72         StrictController::LOCAL_OUTPUT,
73         BandwidthController::LOCAL_OUTPUT,
74 };
75 
76 static const std::vector<const char*> RAW_PREROUTING = {
77         IdletimerController::LOCAL_RAW_PREROUTING,
78         BandwidthController::LOCAL_RAW_PREROUTING,
79         TetherController::LOCAL_RAW_PREROUTING,
80 };
81 
82 static const std::vector<const char*> MANGLE_POSTROUTING = {
83         OEM_IPTABLES_MANGLE_POSTROUTING,
84         BandwidthController::LOCAL_MANGLE_POSTROUTING,
85         IdletimerController::LOCAL_MANGLE_POSTROUTING,
86 };
87 
88 static const std::vector<const char*> MANGLE_INPUT = {
89         WakeupController::LOCAL_MANGLE_INPUT,
90         RouteController::LOCAL_MANGLE_INPUT,
91 };
92 
93 static const std::vector<const char*> MANGLE_FORWARD = {
94         TetherController::LOCAL_MANGLE_FORWARD,
95 };
96 
97 static const std::vector<const char*> NAT_PREROUTING = {
98         OEM_IPTABLES_NAT_PREROUTING,
99 };
100 
101 static const std::vector<const char*> NAT_POSTROUTING = {
102         TetherController::LOCAL_NAT_POSTROUTING,
103 };
104 
105 // Commands to create child chains and to match created chains in iptables -S output. Keep in sync.
106 static const char* CHILD_CHAIN_TEMPLATE = "-A %s -j %s\n";
107 static const std::regex CHILD_CHAIN_REGEX("^-A ([^ ]+) -j ([^ ]+)$",
108                                           std::regex_constants::extended);
109 
110 }  // namespace
111 
112 /* static */
findExistingChildChains(const IptablesTarget target,const char * table,const char * parentChain)113 std::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", 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 */
createChildChains(IptablesTarget target,const char * table,const char * parentChain,const std::vector<const char * > & childChains,bool exclusive)153 void Controllers::createChildChains(IptablesTarget target, const char* table,
154                                     const char* parentChain,
155                                     const std::vector<const char*>& childChains,
156                                     bool exclusive) {
157     std::string command = StringPrintf("*%s\n", table);
158 
159     // 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     //
170     // TODO: Make all chains exclusive once vendor code uses the oem_* rules.
171     std::set<std::string> existingChildChains;
172     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.
175         StringAppendF(&command, ":%s -\n", parentChain);
176         StringAppendF(&command, "-F %s\n", parentChain);
177     } else {
178         existingChildChains = findExistingChildChains(target, table, parentChain);
179     }
180 
181     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);
187         }
188     }
189     command += "COMMIT\n";
190     execIptablesRestore(target, command);
191 }
192 
Controllers()193 Controllers::Controllers()
194     : wakeupCtrl(
195               [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) {
209     InterfaceController::initializeAll();
210 }
211 
initChildChains()212 void Controllers::initChildChains() {
213     /*
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 
223     // Create chains for child modules.
224     createChildChains(V4V6, "filter", "INPUT", FILTER_INPUT, true);
225     createChildChains(V4V6, "filter", "FORWARD", FILTER_FORWARD, true);
226     createChildChains(V4V6, "raw", "PREROUTING", RAW_PREROUTING, true);
227     createChildChains(V4V6, "mangle", "FORWARD", MANGLE_FORWARD, true);
228     createChildChains(V4V6, "mangle", "INPUT", MANGLE_INPUT, true);
229     createChildChains(V4, "nat", "PREROUTING", NAT_PREROUTING, true);
230     createChildChains(V4, "nat", "POSTROUTING", NAT_POSTROUTING, true);
231 
232     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);
236 }
237 
initIptablesRules()238 void Controllers::initIptablesRules() {
239     Stopwatch s;
240     initChildChains();
241     gLog.info("Creating child chains: %" PRId64 "us", s.getTimeAndResetUs());
242 
243     // Let each module setup their child chains
244     setupOemIptablesHook();
245     gLog.info("Setting up OEM hooks: %" PRId64 "us", s.getTimeAndResetUs());
246 
247     /* When enabled, DROPs all packets except those matching rules. */
248     firewallCtrl.setupIptablesHooks();
249     gLog.info("Setting up FirewallController hooks: %" PRId64 "us", s.getTimeAndResetUs());
250 
251     /* Does DROPs in FORWARD by default */
252     tetherCtrl.setupIptablesHooks();
253     gLog.info("Setting up TetherController hooks: %" PRId64 "us", s.getTimeAndResetUs());
254 
255     /*
256      * Does REJECT in INPUT, OUTPUT. Does counting also.
257      * No DROP/REJECT allowed later in netfilter-flow hook order.
258      */
259     bandwidthCtrl.setupIptablesHooks();
260     gLog.info("Setting up BandwidthController hooks: %" PRId64 "us", s.getTimeAndResetUs());
261 
262     /*
263      * Counts in nat: PREROUTING, POSTROUTING.
264      * No DROP/REJECT allowed later in netfilter-flow hook order.
265      */
266     idletimerCtrl.setupIptablesHooks();
267     gLog.info("Setting up IdletimerController hooks: %" PRId64 "us", s.getTimeAndResetUs());
268 
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: %" PRId64 "us", s.getTimeAndResetUs());
274 }
275 
init()276 void Controllers::init() {
277     initIptablesRules();
278     Stopwatch s;
279 
280     if (int ret = bandwidthCtrl.enableBandwidthControl()) {
281         gLog.error("Failed to initialize BandwidthController (%s)", strerror(-ret));
282         // A failure to init almost definitely means that iptables failed to load
283         // our static ruleset, which then basically means network accounting will not work.
284         // As such simply exit netd.  This may crash loop the system, but by failing
285         // to bootup we will trigger rollback and thus this offers us protection against
286         // a mainline update breaking things.
287         exit(1);
288     }
289     gLog.info("Enabling bandwidth control: %" PRId64 "us", s.getTimeAndResetUs());
290 
291     if (int ret = RouteController::Init(NetworkController::LOCAL_NET_ID)) {
292         gLog.error("Failed to initialize RouteController (%s)", strerror(-ret));
293     }
294     gLog.info("Initializing RouteController: %" PRId64 "us", s.getTimeAndResetUs());
295 
296     netdutils::Status xStatus = XfrmController::Init();
297     if (!isOk(xStatus)) {
298         gLog.error("Failed to initialize XfrmController (%s)", netdutils::toString(xStatus).c_str());
299     };
300     gLog.info("Initializing XfrmController: %" PRId64 "us", s.getTimeAndResetUs());
301 }
302 
303 Controllers* gCtls = nullptr;
304 
305 }  // namespace net
306 }  // namespace android
307