1 /*
2 * Copyright (C) 2012 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 <set>
18
19 #include <errno.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23
24 #define LOG_TAG "FirewallController"
25 #define LOG_NDEBUG 0
26
27 #include <android-base/strings.h>
28 #include <android-base/stringprintf.h>
29 #include <cutils/log.h>
30
31 #include "NetdConstants.h"
32 #include "FirewallController.h"
33
34 using android::base::Join;
35 using android::base::StringAppendF;
36 using android::base::StringPrintf;
37
38 auto FirewallController::execIptablesRestore = ::execIptablesRestore;
39
40 const char* FirewallController::TABLE = "filter";
41
42 const char* FirewallController::LOCAL_INPUT = "fw_INPUT";
43 const char* FirewallController::LOCAL_OUTPUT = "fw_OUTPUT";
44 const char* FirewallController::LOCAL_FORWARD = "fw_FORWARD";
45
46 const char* FirewallController::LOCAL_DOZABLE = "fw_dozable";
47 const char* FirewallController::LOCAL_STANDBY = "fw_standby";
48 const char* FirewallController::LOCAL_POWERSAVE = "fw_powersave";
49
50 // ICMPv6 types that are required for any form of IPv6 connectivity to work. Note that because the
51 // fw_dozable chain is called from both INPUT and OUTPUT, this includes both packets that we need
52 // to be able to send (e.g., RS, NS), and packets that we need to receive (e.g., RA, NA).
53 const char* FirewallController::ICMPV6_TYPES[] = {
54 "packet-too-big",
55 "router-solicitation",
56 "router-advertisement",
57 "neighbour-solicitation",
58 "neighbour-advertisement",
59 "redirect",
60 };
61
FirewallController(void)62 FirewallController::FirewallController(void) {
63 // If no rules are set, it's in BLACKLIST mode
64 mFirewallType = BLACKLIST;
65 mIfaceRules = {};
66 }
67
setupIptablesHooks(void)68 int FirewallController::setupIptablesHooks(void) {
69 int res = 0;
70 res |= createChain(LOCAL_DOZABLE, getFirewallType(DOZABLE));
71 res |= createChain(LOCAL_STANDBY, getFirewallType(STANDBY));
72 res |= createChain(LOCAL_POWERSAVE, getFirewallType(POWERSAVE));
73 return res;
74 }
75
enableFirewall(FirewallType ftype)76 int FirewallController::enableFirewall(FirewallType ftype) {
77 int res = 0;
78 if (mFirewallType != ftype) {
79 // flush any existing rules
80 disableFirewall();
81
82 if (ftype == WHITELIST) {
83 // create default rule to drop all traffic
84 std::string command =
85 "*filter\n"
86 "-A fw_INPUT -j DROP\n"
87 "-A fw_OUTPUT -j REJECT\n"
88 "-A fw_FORWARD -j REJECT\n"
89 "COMMIT\n";
90 res = execIptablesRestore(V4V6, command.c_str());
91 }
92
93 // Set this after calling disableFirewall(), since it defaults to WHITELIST there
94 mFirewallType = ftype;
95 }
96 return res;
97 }
98
disableFirewall(void)99 int FirewallController::disableFirewall(void) {
100 mFirewallType = WHITELIST;
101 mIfaceRules.clear();
102
103 // flush any existing rules
104 std::string command =
105 "*filter\n"
106 ":fw_INPUT -\n"
107 ":fw_OUTPUT -\n"
108 ":fw_FORWARD -\n"
109 "COMMIT\n";
110
111 return execIptablesRestore(V4V6, command.c_str());
112 }
113
enableChildChains(ChildChain chain,bool enable)114 int FirewallController::enableChildChains(ChildChain chain, bool enable) {
115 int res = 0;
116 const char* name;
117 switch(chain) {
118 case DOZABLE:
119 name = LOCAL_DOZABLE;
120 break;
121 case STANDBY:
122 name = LOCAL_STANDBY;
123 break;
124 case POWERSAVE:
125 name = LOCAL_POWERSAVE;
126 break;
127 default:
128 return res;
129 }
130
131 std::string command = "*filter\n";
132 for (const char *parent : { LOCAL_INPUT, LOCAL_OUTPUT }) {
133 StringAppendF(&command, "%s %s -j %s\n", (enable ? "-A" : "-D"), parent, name);
134 }
135 StringAppendF(&command, "COMMIT\n");
136
137 return execIptablesRestore(V4V6, command);
138 }
139
isFirewallEnabled(void)140 int FirewallController::isFirewallEnabled(void) {
141 // TODO: verify that rules are still in place near top
142 return -1;
143 }
144
setInterfaceRule(const char * iface,FirewallRule rule)145 int FirewallController::setInterfaceRule(const char* iface, FirewallRule rule) {
146 if (mFirewallType == BLACKLIST) {
147 // Unsupported in BLACKLIST mode
148 return -1;
149 }
150
151 if (!isIfaceName(iface)) {
152 errno = ENOENT;
153 return -1;
154 }
155
156 // Only delete rules if we actually added them, because otherwise our iptables-restore
157 // processes will terminate with "no such rule" errors and cause latency penalties while we
158 // spin up new ones.
159 const char* op;
160 if (rule == ALLOW && mIfaceRules.find(iface) == mIfaceRules.end()) {
161 op = "-I";
162 mIfaceRules.insert(iface);
163 } else if (rule == DENY && mIfaceRules.find(iface) != mIfaceRules.end()) {
164 op = "-D";
165 mIfaceRules.erase(iface);
166 } else {
167 return 0;
168 }
169
170 std::string command = Join(std::vector<std::string> {
171 "*filter",
172 StringPrintf("%s fw_INPUT -i %s -j RETURN", op, iface),
173 StringPrintf("%s fw_OUTPUT -o %s -j RETURN", op, iface),
174 "COMMIT\n"
175 }, "\n");
176 return execIptablesRestore(V4V6, command);
177 }
178
getFirewallType(ChildChain chain)179 FirewallType FirewallController::getFirewallType(ChildChain chain) {
180 switch(chain) {
181 case DOZABLE:
182 return WHITELIST;
183 case STANDBY:
184 return BLACKLIST;
185 case POWERSAVE:
186 return WHITELIST;
187 case NONE:
188 return mFirewallType;
189 default:
190 return BLACKLIST;
191 }
192 }
193
setUidRule(ChildChain chain,int uid,FirewallRule rule)194 int FirewallController::setUidRule(ChildChain chain, int uid, FirewallRule rule) {
195 const char* op;
196 const char* target;
197 FirewallType firewallType = getFirewallType(chain);
198 if (firewallType == WHITELIST) {
199 target = "RETURN";
200 // When adding, insert RETURN rules at the front, before the catch-all DROP at the end.
201 op = (rule == ALLOW)? "-I" : "-D";
202 } else { // BLACKLIST mode
203 target = "DROP";
204 // When adding, append DROP rules at the end, after the RETURN rule that matches TCP RSTs.
205 op = (rule == DENY)? "-A" : "-D";
206 }
207
208 std::vector<std::string> chainNames;
209 switch(chain) {
210 case DOZABLE:
211 chainNames = { LOCAL_DOZABLE };
212 break;
213 case STANDBY:
214 chainNames = { LOCAL_STANDBY };
215 break;
216 case POWERSAVE:
217 chainNames = { LOCAL_POWERSAVE };
218 break;
219 case NONE:
220 chainNames = { LOCAL_INPUT, LOCAL_OUTPUT };
221 break;
222 default:
223 ALOGW("Unknown child chain: %d", chain);
224 return -1;
225 }
226
227 std::string command = "*filter\n";
228 for (std::string chainName : chainNames) {
229 StringAppendF(&command, "%s %s -m owner --uid-owner %d -j %s\n",
230 op, chainName.c_str(), uid, target);
231 }
232 StringAppendF(&command, "COMMIT\n");
233
234 return execIptablesRestore(V4V6, command);
235 }
236
createChain(const char * chain,FirewallType type)237 int FirewallController::createChain(const char* chain, FirewallType type) {
238 static const std::vector<int32_t> NO_UIDS;
239 return replaceUidChain(chain, type == WHITELIST, NO_UIDS);
240 }
241
242 /* static */
makeCriticalCommands(IptablesTarget target,const char * chainName)243 std::string FirewallController::makeCriticalCommands(IptablesTarget target, const char* chainName) {
244 // Allow ICMPv6 packets necessary to make IPv6 connectivity work. http://b/23158230 .
245 std::string commands;
246 if (target == V6) {
247 for (size_t i = 0; i < ARRAY_SIZE(ICMPV6_TYPES); i++) {
248 StringAppendF(&commands, "-A %s -p icmpv6 --icmpv6-type %s -j RETURN\n",
249 chainName, ICMPV6_TYPES[i]);
250 }
251 }
252 return commands;
253 }
254
makeUidRules(IptablesTarget target,const char * name,bool isWhitelist,const std::vector<int32_t> & uids)255 std::string FirewallController::makeUidRules(IptablesTarget target, const char *name,
256 bool isWhitelist, const std::vector<int32_t>& uids) {
257 std::string commands;
258 StringAppendF(&commands, "*filter\n:%s -\n", name);
259
260 // Whitelist chains have UIDs at the beginning, and new UIDs are added with '-I'.
261 if (isWhitelist) {
262 for (auto uid : uids) {
263 StringAppendF(&commands, "-A %s -m owner --uid-owner %d -j RETURN\n", name, uid);
264 }
265
266 // Always whitelist system UIDs.
267 StringAppendF(&commands,
268 "-A %s -m owner --uid-owner %d-%d -j RETURN\n", name, 0, MAX_SYSTEM_UID);
269 }
270
271 // Always allow networking on loopback.
272 StringAppendF(&commands, "-A %s -i lo -j RETURN\n", name);
273 StringAppendF(&commands, "-A %s -o lo -j RETURN\n", name);
274
275 // Allow TCP RSTs so we can cleanly close TCP connections of apps that no longer have network
276 // access. Both incoming and outgoing RSTs are allowed.
277 StringAppendF(&commands, "-A %s -p tcp --tcp-flags RST RST -j RETURN\n", name);
278
279 if (isWhitelist) {
280 commands.append(makeCriticalCommands(target, name));
281 }
282
283 // Blacklist chains have UIDs at the end, and new UIDs are added with '-A'.
284 if (!isWhitelist) {
285 for (auto uid : uids) {
286 StringAppendF(&commands, "-A %s -m owner --uid-owner %d -j DROP\n", name, uid);
287 }
288 }
289
290 // If it's a whitelist chain, add a default DROP at the end. This is not necessary for a
291 // blacklist chain, because all user-defined chains implicitly RETURN at the end.
292 if (isWhitelist) {
293 StringAppendF(&commands, "-A %s -j DROP\n", name);
294 }
295
296 StringAppendF(&commands, "COMMIT\n");
297
298 return commands;
299 }
300
replaceUidChain(const char * name,bool isWhitelist,const std::vector<int32_t> & uids)301 int FirewallController::replaceUidChain(
302 const char *name, bool isWhitelist, const std::vector<int32_t>& uids) {
303 std::string commands4 = makeUidRules(V4, name, isWhitelist, uids);
304 std::string commands6 = makeUidRules(V6, name, isWhitelist, uids);
305 return execIptablesRestore(V4, commands4.c_str()) | execIptablesRestore(V6, commands6.c_str());
306 }
307