blob: 88a2207d53b6dd8498d515fd18de38b742ff45df [file] [log] [blame]
Ben Gruver4efe9402013-04-02 21:18:41 -07001/*
2 * Copyright (C) 2013 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
17package com.android.server.firewall;
18
Ben Gruver8be8df22013-04-05 19:21:19 -070019import android.app.AppGlobals;
20import android.content.ComponentName;
Ben Gruver4efe9402013-04-02 21:18:41 -070021import android.content.Intent;
22import android.content.IntentFilter;
Ben Gruverb6223792013-07-29 16:35:40 -070023import android.content.pm.ApplicationInfo;
Ben Gruver8be8df22013-04-05 19:21:19 -070024import android.content.pm.IPackageManager;
Ben Gruver4efe9402013-04-02 21:18:41 -070025import android.content.pm.PackageManager;
26import android.os.Environment;
Ben Gruvera4879c32013-04-08 14:27:37 -070027import android.os.FileObserver;
28import android.os.Handler;
Jeff Brown6f357d32014-01-15 20:40:55 -080029import android.os.Looper;
Ben Gruvera4879c32013-04-08 14:27:37 -070030import android.os.Message;
Ben Gruver8be8df22013-04-05 19:21:19 -070031import android.os.RemoteException;
Ben Gruverf157b482013-08-06 15:57:01 -070032import android.util.ArrayMap;
Ben Gruver4efe9402013-04-02 21:18:41 -070033import android.util.Slog;
34import android.util.Xml;
Ben Gruverf157b482013-08-06 15:57:01 -070035import com.android.internal.util.ArrayUtils;
Ben Gruver4efe9402013-04-02 21:18:41 -070036import com.android.internal.util.XmlUtils;
Ben Gruver8be8df22013-04-05 19:21:19 -070037import com.android.server.EventLogTags;
Ben Gruver4efe9402013-04-02 21:18:41 -070038import com.android.server.IntentResolver;
Ben Gruver4efe9402013-04-02 21:18:41 -070039import org.xmlpull.v1.XmlPullParser;
40import org.xmlpull.v1.XmlPullParserException;
41
42import java.io.File;
43import java.io.FileInputStream;
44import java.io.FileNotFoundException;
45import java.io.IOException;
46import java.util.ArrayList;
Ben Gruverf157b482013-08-06 15:57:01 -070047import java.util.Arrays;
Ben Gruver4efe9402013-04-02 21:18:41 -070048import java.util.HashMap;
49import java.util.List;
50
51public class IntentFirewall {
Ben Gruverdd72c9e2013-08-06 12:34:17 -070052 static final String TAG = "IntentFirewall";
Ben Gruver4efe9402013-04-02 21:18:41 -070053
Ben Gruverb7c1a172013-07-23 15:05:28 -070054 // e.g. /data/system/ifw or /data/secure/system/ifw
55 private static final File RULES_DIR = new File(Environment.getSystemSecureDirectory(), "ifw");
Ben Gruver4efe9402013-04-02 21:18:41 -070056
Ben Gruver8be8df22013-04-05 19:21:19 -070057 private static final int LOG_PACKAGES_MAX_LENGTH = 150;
58 private static final int LOG_PACKAGES_SUFFICIENT_LENGTH = 125;
59
Ben Gruver4efe9402013-04-02 21:18:41 -070060 private static final String TAG_RULES = "rules";
61 private static final String TAG_ACTIVITY = "activity";
62 private static final String TAG_SERVICE = "service";
63 private static final String TAG_BROADCAST = "broadcast";
64
Ben Gruver8be8df22013-04-05 19:21:19 -070065 private static final int TYPE_ACTIVITY = 0;
Ben Gruvera4879c32013-04-08 14:27:37 -070066 private static final int TYPE_BROADCAST = 1;
67 private static final int TYPE_SERVICE = 2;
Ben Gruver8be8df22013-04-05 19:21:19 -070068
Ben Gruver4efe9402013-04-02 21:18:41 -070069 private static final HashMap<String, FilterFactory> factoryMap;
70
71 private final AMSInterface mAms;
72
Ben Gruvera4879c32013-04-08 14:27:37 -070073 private final RuleObserver mObserver;
74
75 private FirewallIntentResolver mActivityResolver = new FirewallIntentResolver();
76 private FirewallIntentResolver mBroadcastResolver = new FirewallIntentResolver();
77 private FirewallIntentResolver mServiceResolver = new FirewallIntentResolver();
Ben Gruver4efe9402013-04-02 21:18:41 -070078
79 static {
80 FilterFactory[] factories = new FilterFactory[] {
81 AndFilter.FACTORY,
82 OrFilter.FACTORY,
83 NotFilter.FACTORY,
84
85 StringFilter.ACTION,
86 StringFilter.COMPONENT,
87 StringFilter.COMPONENT_NAME,
88 StringFilter.COMPONENT_PACKAGE,
89 StringFilter.DATA,
90 StringFilter.HOST,
91 StringFilter.MIME_TYPE,
Ben Gruver57e76b42013-07-31 15:41:24 -070092 StringFilter.SCHEME,
Ben Gruver4efe9402013-04-02 21:18:41 -070093 StringFilter.PATH,
Ben Gruver4efe9402013-04-02 21:18:41 -070094 StringFilter.SSP,
95
96 CategoryFilter.FACTORY,
97 SenderFilter.FACTORY,
98 SenderPermissionFilter.FACTORY,
99 PortFilter.FACTORY
100 };
101
102 // load factor ~= .75
103 factoryMap = new HashMap<String, FilterFactory>(factories.length * 4 / 3);
104 for (int i=0; i<factories.length; i++) {
105 FilterFactory factory = factories[i];
106 factoryMap.put(factory.getTagName(), factory);
107 }
108 }
109
Jeff Brown6f357d32014-01-15 20:40:55 -0800110 public IntentFirewall(AMSInterface ams, Handler handler) {
Ben Gruver4efe9402013-04-02 21:18:41 -0700111 mAms = ams;
Jeff Brown6f357d32014-01-15 20:40:55 -0800112 mHandler = new FirewallHandler(handler.getLooper());
Ben Gruverb7c1a172013-07-23 15:05:28 -0700113 File rulesDir = getRulesDir();
114 rulesDir.mkdirs();
Ben Gruvera4879c32013-04-08 14:27:37 -0700115
Ben Gruverb7c1a172013-07-23 15:05:28 -0700116 readRulesDir(rulesDir);
Ben Gruvera4879c32013-04-08 14:27:37 -0700117
Ben Gruverb7c1a172013-07-23 15:05:28 -0700118 mObserver = new RuleObserver(rulesDir);
Ben Gruvera4879c32013-04-08 14:27:37 -0700119 mObserver.startWatching();
Ben Gruver4efe9402013-04-02 21:18:41 -0700120 }
121
Ben Gruvera4879c32013-04-08 14:27:37 -0700122 /**
123 * This is called from ActivityManager to check if a start activity intent should be allowed.
124 * It is assumed the caller is already holding the global ActivityManagerService lock.
125 */
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700126 public boolean checkStartActivity(Intent intent, int callerUid, int callerPid,
Ben Gruverb6223792013-07-29 16:35:40 -0700127 String resolvedType, ApplicationInfo resolvedApp) {
Ben Gruverf5323fe2013-07-31 15:09:51 -0700128 return checkIntent(mActivityResolver, intent.getComponent(), TYPE_ACTIVITY, intent,
Ben Gruver49660c72013-08-06 19:54:08 -0700129 callerUid, callerPid, resolvedType, resolvedApp.uid);
Ben Gruverb6223792013-07-29 16:35:40 -0700130 }
131
Ben Gruverf5323fe2013-07-31 15:09:51 -0700132 public boolean checkService(ComponentName resolvedService, Intent intent, int callerUid,
133 int callerPid, String resolvedType, ApplicationInfo resolvedApp) {
134 return checkIntent(mServiceResolver, resolvedService, TYPE_SERVICE, intent, callerUid,
Ben Gruver49660c72013-08-06 19:54:08 -0700135 callerPid, resolvedType, resolvedApp.uid);
136 }
137
138 public boolean checkBroadcast(Intent intent, int callerUid, int callerPid,
139 String resolvedType, int receivingUid) {
140 return checkIntent(mBroadcastResolver, intent.getComponent(), TYPE_BROADCAST, intent,
141 callerUid, callerPid, resolvedType, receivingUid);
Ben Gruverf5323fe2013-07-31 15:09:51 -0700142 }
143
144 public boolean checkIntent(FirewallIntentResolver resolver, ComponentName resolvedComponent,
145 int intentType, Intent intent, int callerUid, int callerPid, String resolvedType,
Ben Gruver49660c72013-08-06 19:54:08 -0700146 int receivingUid) {
Ben Gruver4efe9402013-04-02 21:18:41 -0700147 boolean log = false;
148 boolean block = false;
149
Ben Gruverf157b482013-08-06 15:57:01 -0700150 // For the first pass, find all the rules that have at least one intent-filter or
151 // component-filter that matches this intent
152 List<Rule> candidateRules;
153 candidateRules = resolver.queryIntent(intent, resolvedType, false, 0);
154 if (candidateRules == null) {
155 candidateRules = new ArrayList<Rule>();
156 }
157 resolver.queryByComponent(resolvedComponent, candidateRules);
158
159 // For the second pass, try to match the potentially more specific conditions in each
160 // rule against the intent
161 for (int i=0; i<candidateRules.size(); i++) {
162 Rule rule = candidateRules.get(i);
Ben Gruverf5323fe2013-07-31 15:09:51 -0700163 if (rule.matches(this, resolvedComponent, intent, callerUid, callerPid, resolvedType,
Ben Gruver49660c72013-08-06 19:54:08 -0700164 receivingUid)) {
Ben Gruver4efe9402013-04-02 21:18:41 -0700165 block |= rule.getBlock();
166 log |= rule.getLog();
167
168 // if we've already determined that we should both block and log, there's no need
169 // to continue trying rules
170 if (block && log) {
171 break;
172 }
173 }
174 }
175
176 if (log) {
Ben Gruverb6223792013-07-29 16:35:40 -0700177 logIntent(intentType, intent, callerUid, resolvedType);
Ben Gruver4efe9402013-04-02 21:18:41 -0700178 }
179
180 return !block;
181 }
182
Ben Gruver8be8df22013-04-05 19:21:19 -0700183 private static void logIntent(int intentType, Intent intent, int callerUid,
184 String resolvedType) {
185 // The component shouldn't be null, but let's double check just to be safe
186 ComponentName cn = intent.getComponent();
187 String shortComponent = null;
188 if (cn != null) {
189 shortComponent = cn.flattenToShortString();
190 }
191
192 String callerPackages = null;
193 int callerPackageCount = 0;
194 IPackageManager pm = AppGlobals.getPackageManager();
195 if (pm != null) {
196 try {
197 String[] callerPackagesArray = pm.getPackagesForUid(callerUid);
198 if (callerPackagesArray != null) {
199 callerPackageCount = callerPackagesArray.length;
200 callerPackages = joinPackages(callerPackagesArray);
201 }
202 } catch (RemoteException ex) {
203 Slog.e(TAG, "Remote exception while retrieving packages", ex);
204 }
205 }
206
207 EventLogTags.writeIfwIntentMatched(intentType, shortComponent, callerUid,
208 callerPackageCount, callerPackages, intent.getAction(), resolvedType,
209 intent.getDataString(), intent.getFlags());
210 }
211
212 /**
213 * Joins a list of package names such that the resulting string is no more than
214 * LOG_PACKAGES_MAX_LENGTH.
215 *
216 * Only full package names will be added to the result, unless every package is longer than the
217 * limit, in which case one of the packages will be truncated and added. In this case, an
218 * additional '-' character will be added to the end of the string, to denote the truncation.
219 *
220 * If it encounters a package that won't fit in the remaining space, it will continue on to the
221 * next package, unless the total length of the built string so far is greater than
222 * LOG_PACKAGES_SUFFICIENT_LENGTH, in which case it will stop and return what it has.
223 */
224 private static String joinPackages(String[] packages) {
225 boolean first = true;
226 StringBuilder sb = new StringBuilder();
227 for (int i=0; i<packages.length; i++) {
228 String pkg = packages[i];
229
230 // + 1 length for the comma. This logic technically isn't correct for the first entry,
231 // but it's not critical.
232 if (sb.length() + pkg.length() + 1 < LOG_PACKAGES_MAX_LENGTH) {
233 if (!first) {
234 sb.append(',');
235 } else {
236 first = false;
237 }
238 sb.append(pkg);
239 } else if (sb.length() >= LOG_PACKAGES_SUFFICIENT_LENGTH) {
240 return sb.toString();
241 }
242 }
243 if (sb.length() == 0 && packages.length > 0) {
244 String pkg = packages[0];
245 // truncating from the end - the last part of the package name is more likely to be
246 // interesting/unique
247 return pkg.substring(pkg.length() - LOG_PACKAGES_MAX_LENGTH + 1) + '-';
248 }
249 return null;
250 }
251
Ben Gruverb7c1a172013-07-23 15:05:28 -0700252 public static File getRulesDir() {
253 return RULES_DIR;
Ben Gruver633dc9b2013-04-04 12:05:49 -0700254 }
255
Ben Gruvera4879c32013-04-08 14:27:37 -0700256 /**
Ben Gruverb7c1a172013-07-23 15:05:28 -0700257 * Reads rules from all xml files (*.xml) in the given directory, and replaces our set of rules
258 * with the newly read rules.
259 *
260 * We only check for files ending in ".xml", to allow for temporary files that are atomically
261 * renamed to .xml
Ben Gruvera4879c32013-04-08 14:27:37 -0700262 *
263 * All calls to this method from the file observer come through a handler and are inherently
264 * serialized
265 */
Ben Gruverb7c1a172013-07-23 15:05:28 -0700266 private void readRulesDir(File rulesDir) {
Ben Gruvera4879c32013-04-08 14:27:37 -0700267 FirewallIntentResolver[] resolvers = new FirewallIntentResolver[3];
268 for (int i=0; i<resolvers.length; i++) {
269 resolvers[i] = new FirewallIntentResolver();
270 }
271
Ben Gruverb7c1a172013-07-23 15:05:28 -0700272 File[] files = rulesDir.listFiles();
273 for (int i=0; i<files.length; i++) {
274 File file = files[i];
275
276 if (file.getName().endsWith(".xml")) {
277 readRules(file, resolvers);
278 }
279 }
280
281 Slog.i(TAG, "Read new rules (A:" + resolvers[TYPE_ACTIVITY].filterSet().size() +
282 " B:" + resolvers[TYPE_BROADCAST].filterSet().size() +
283 " S:" + resolvers[TYPE_SERVICE].filterSet().size() + ")");
284
285 synchronized (mAms.getAMSLock()) {
286 mActivityResolver = resolvers[TYPE_ACTIVITY];
287 mBroadcastResolver = resolvers[TYPE_BROADCAST];
288 mServiceResolver = resolvers[TYPE_SERVICE];
289 }
290 }
291
292 /**
293 * Reads rules from the given file and add them to the given resolvers
294 */
295 private void readRules(File rulesFile, FirewallIntentResolver[] resolvers) {
296 // some temporary lists to hold the rules while we parse the xml file, so that we can
297 // add the rules all at once, after we know there weren't any major structural problems
298 // with the xml file
299 List<List<Rule>> rulesByType = new ArrayList<List<Rule>>(3);
300 for (int i=0; i<3; i++) {
301 rulesByType.add(new ArrayList<Rule>());
302 }
303
Ben Gruver4efe9402013-04-02 21:18:41 -0700304 FileInputStream fis;
305 try {
306 fis = new FileInputStream(rulesFile);
307 } catch (FileNotFoundException ex) {
308 // Nope, no rules. Nothing else to do!
309 return;
310 }
311
312 try {
313 XmlPullParser parser = Xml.newPullParser();
314
315 parser.setInput(fis, null);
316
317 XmlUtils.beginDocument(parser, TAG_RULES);
318
319 int outerDepth = parser.getDepth();
320 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
Ben Gruvera4879c32013-04-08 14:27:37 -0700321 int ruleType = -1;
322
Ben Gruver4efe9402013-04-02 21:18:41 -0700323 String tagName = parser.getName();
324 if (tagName.equals(TAG_ACTIVITY)) {
Ben Gruvera4879c32013-04-08 14:27:37 -0700325 ruleType = TYPE_ACTIVITY;
Ben Gruver4efe9402013-04-02 21:18:41 -0700326 } else if (tagName.equals(TAG_BROADCAST)) {
Ben Gruvera4879c32013-04-08 14:27:37 -0700327 ruleType = TYPE_BROADCAST;
328 } else if (tagName.equals(TAG_SERVICE)) {
329 ruleType = TYPE_SERVICE;
Ben Gruver4efe9402013-04-02 21:18:41 -0700330 }
331
Ben Gruvera4879c32013-04-08 14:27:37 -0700332 if (ruleType != -1) {
Ben Gruver4efe9402013-04-02 21:18:41 -0700333 Rule rule = new Rule();
334
Ben Gruverb7c1a172013-07-23 15:05:28 -0700335 List<Rule> rules = rulesByType.get(ruleType);
Ben Gruvera4879c32013-04-08 14:27:37 -0700336
337 // if we get an error while parsing a particular rule, we'll just ignore
338 // that rule and continue on with the next rule
Ben Gruver4efe9402013-04-02 21:18:41 -0700339 try {
340 rule.readFromXml(parser);
341 } catch (XmlPullParserException ex) {
Ben Gruverb7c1a172013-07-23 15:05:28 -0700342 Slog.e(TAG, "Error reading an intent firewall rule from " + rulesFile, ex);
Ben Gruver4efe9402013-04-02 21:18:41 -0700343 continue;
Ben Gruver4efe9402013-04-02 21:18:41 -0700344 }
345
Ben Gruverb7c1a172013-07-23 15:05:28 -0700346 rules.add(rule);
Ben Gruver4efe9402013-04-02 21:18:41 -0700347 }
348 }
349 } catch (XmlPullParserException ex) {
Ben Gruvera4879c32013-04-08 14:27:37 -0700350 // if there was an error outside of a specific rule, then there are probably
351 // structural problems with the xml file, and we should completely ignore it
Ben Gruverb7c1a172013-07-23 15:05:28 -0700352 Slog.e(TAG, "Error reading intent firewall rules from " + rulesFile, ex);
353 return;
Ben Gruver4efe9402013-04-02 21:18:41 -0700354 } catch (IOException ex) {
Ben Gruverb7c1a172013-07-23 15:05:28 -0700355 Slog.e(TAG, "Error reading intent firewall rules from " + rulesFile, ex);
356 return;
Ben Gruver4efe9402013-04-02 21:18:41 -0700357 } finally {
358 try {
359 fis.close();
360 } catch (IOException ex) {
361 Slog.e(TAG, "Error while closing " + rulesFile, ex);
362 }
363 }
Ben Gruver4efe9402013-04-02 21:18:41 -0700364
Ben Gruverb7c1a172013-07-23 15:05:28 -0700365 for (int ruleType=0; ruleType<rulesByType.size(); ruleType++) {
366 List<Rule> rules = rulesByType.get(ruleType);
367 FirewallIntentResolver resolver = resolvers[ruleType];
Ben Gruvera4879c32013-04-08 14:27:37 -0700368
Ben Gruverb7c1a172013-07-23 15:05:28 -0700369 for (int ruleIndex=0; ruleIndex<rules.size(); ruleIndex++) {
370 Rule rule = rules.get(ruleIndex);
Ben Gruverf157b482013-08-06 15:57:01 -0700371 for (int i=0; i<rule.getIntentFilterCount(); i++) {
372 resolver.addFilter(rule.getIntentFilter(i));
373 }
374 for (int i=0; i<rule.getComponentFilterCount(); i++) {
375 resolver.addComponentFilter(rule.getComponentFilter(i), rule);
Ben Gruverb7c1a172013-07-23 15:05:28 -0700376 }
377 }
Ben Gruvera4879c32013-04-08 14:27:37 -0700378 }
379 }
380
Ben Gruver4efe9402013-04-02 21:18:41 -0700381 static Filter parseFilter(XmlPullParser parser) throws IOException, XmlPullParserException {
382 String elementName = parser.getName();
383
384 FilterFactory factory = factoryMap.get(elementName);
385
386 if (factory == null) {
387 throw new XmlPullParserException("Unknown element in filter list: " + elementName);
388 }
389 return factory.newFilter(parser);
390 }
391
Ben Gruverf157b482013-08-06 15:57:01 -0700392 /**
393 * Represents a single activity/service/broadcast rule within one of the xml files.
394 *
395 * Rules are matched against an incoming intent in two phases. The goal of the first phase
396 * is to select a subset of rules that might match a given intent.
397 *
398 * For the first phase, we use a combination of intent filters (via an IntentResolver)
399 * and component filters to select which rules to check. If a rule has multiple intent or
400 * component filters, only a single filter must match for the rule to be passed on to the
401 * second phase.
402 *
403 * In the second phase, we check the specific conditions in each rule against the values in the
404 * intent. All top level conditions (but not filters) in the rule must match for the rule as a
405 * whole to match.
406 *
407 * If the rule matches, then we block or log the intent, as specified by the rule. If multiple
408 * rules match, we combine the block/log flags from any matching rule.
409 */
Ben Gruver4efe9402013-04-02 21:18:41 -0700410 private static class Rule extends AndFilter {
411 private static final String TAG_INTENT_FILTER = "intent-filter";
Ben Gruverf157b482013-08-06 15:57:01 -0700412 private static final String TAG_COMPONENT_FILTER = "component-filter";
413 private static final String ATTR_NAME = "name";
Ben Gruver4efe9402013-04-02 21:18:41 -0700414
415 private static final String ATTR_BLOCK = "block";
416 private static final String ATTR_LOG = "log";
417
418 private final ArrayList<FirewallIntentFilter> mIntentFilters =
419 new ArrayList<FirewallIntentFilter>(1);
Ben Gruverf157b482013-08-06 15:57:01 -0700420 private final ArrayList<ComponentName> mComponentFilters = new ArrayList<ComponentName>(0);
Ben Gruver4efe9402013-04-02 21:18:41 -0700421 private boolean block;
422 private boolean log;
423
424 @Override
425 public Rule readFromXml(XmlPullParser parser) throws IOException, XmlPullParserException {
426 block = Boolean.parseBoolean(parser.getAttributeValue(null, ATTR_BLOCK));
427 log = Boolean.parseBoolean(parser.getAttributeValue(null, ATTR_LOG));
428
429 super.readFromXml(parser);
430 return this;
431 }
432
433 @Override
434 protected void readChild(XmlPullParser parser) throws IOException, XmlPullParserException {
Ben Gruverf157b482013-08-06 15:57:01 -0700435 String currentTag = parser.getName();
436
437 if (currentTag.equals(TAG_INTENT_FILTER)) {
Ben Gruver4efe9402013-04-02 21:18:41 -0700438 FirewallIntentFilter intentFilter = new FirewallIntentFilter(this);
439 intentFilter.readFromXml(parser);
440 mIntentFilters.add(intentFilter);
Ben Gruverf157b482013-08-06 15:57:01 -0700441 } else if (currentTag.equals(TAG_COMPONENT_FILTER)) {
442 String componentStr = parser.getAttributeValue(null, ATTR_NAME);
443 if (componentStr == null) {
444 throw new XmlPullParserException("Component name must be specified.",
445 parser, null);
446 }
447
448 ComponentName componentName = ComponentName.unflattenFromString(componentStr);
449 if (componentName == null) {
450 throw new XmlPullParserException("Invalid component name: " + componentStr);
451 }
452
453 mComponentFilters.add(componentName);
Ben Gruver4efe9402013-04-02 21:18:41 -0700454 } else {
455 super.readChild(parser);
456 }
457 }
458
459 public int getIntentFilterCount() {
460 return mIntentFilters.size();
461 }
462
463 public FirewallIntentFilter getIntentFilter(int index) {
464 return mIntentFilters.get(index);
465 }
466
Ben Gruverf157b482013-08-06 15:57:01 -0700467 public int getComponentFilterCount() {
468 return mComponentFilters.size();
469 }
470
471 public ComponentName getComponentFilter(int index) {
472 return mComponentFilters.get(index);
473 }
Ben Gruver4efe9402013-04-02 21:18:41 -0700474 public boolean getBlock() {
475 return block;
476 }
477
478 public boolean getLog() {
479 return log;
480 }
481 }
482
483 private static class FirewallIntentFilter extends IntentFilter {
484 private final Rule rule;
485
486 public FirewallIntentFilter(Rule rule) {
487 this.rule = rule;
488 }
489 }
490
491 private static class FirewallIntentResolver
492 extends IntentResolver<FirewallIntentFilter, Rule> {
493 @Override
494 protected boolean allowFilterResult(FirewallIntentFilter filter, List<Rule> dest) {
495 return !dest.contains(filter.rule);
496 }
497
498 @Override
499 protected boolean isPackageForFilter(String packageName, FirewallIntentFilter filter) {
500 return true;
501 }
502
503 @Override
504 protected FirewallIntentFilter[] newArray(int size) {
505 return new FirewallIntentFilter[size];
506 }
507
508 @Override
509 protected Rule newResult(FirewallIntentFilter filter, int match, int userId) {
510 return filter.rule;
511 }
512
513 @Override
514 protected void sortResults(List<Rule> results) {
515 // there's no need to sort the results
516 return;
517 }
Ben Gruverf157b482013-08-06 15:57:01 -0700518
519 public void queryByComponent(ComponentName componentName, List<Rule> candidateRules) {
520 Rule[] rules = mRulesByComponent.get(componentName);
521 if (rules != null) {
522 candidateRules.addAll(Arrays.asList(rules));
523 }
524 }
525
526 public void addComponentFilter(ComponentName componentName, Rule rule) {
527 Rule[] rules = mRulesByComponent.get(componentName);
528 rules = ArrayUtils.appendElement(Rule.class, rules, rule);
529 mRulesByComponent.put(componentName, rules);
530 }
531
532 private final ArrayMap<ComponentName, Rule[]> mRulesByComponent =
533 new ArrayMap<ComponentName, Rule[]>(0);
Ben Gruver4efe9402013-04-02 21:18:41 -0700534 }
535
Jeff Brown6f357d32014-01-15 20:40:55 -0800536 final FirewallHandler mHandler;
537
538 private final class FirewallHandler extends Handler {
539 public FirewallHandler(Looper looper) {
540 super(looper, null, true);
541 }
542
Ben Gruvera4879c32013-04-08 14:27:37 -0700543 @Override
544 public void handleMessage(Message msg) {
Ben Gruverb7c1a172013-07-23 15:05:28 -0700545 readRulesDir(getRulesDir());
Ben Gruvera4879c32013-04-08 14:27:37 -0700546 }
547 };
548
549 /**
Ben Gruverb7c1a172013-07-23 15:05:28 -0700550 * Monitors for the creation/deletion/modification of any .xml files in the rule directory
Ben Gruvera4879c32013-04-08 14:27:37 -0700551 */
552 private class RuleObserver extends FileObserver {
Ben Gruverb7c1a172013-07-23 15:05:28 -0700553 private static final int MONITORED_EVENTS = FileObserver.CREATE|FileObserver.MOVED_TO|
554 FileObserver.CLOSE_WRITE|FileObserver.DELETE|FileObserver.MOVED_FROM;
Ben Gruvera4879c32013-04-08 14:27:37 -0700555
Ben Gruverb7c1a172013-07-23 15:05:28 -0700556 public RuleObserver(File monitoredDir) {
557 super(monitoredDir.getAbsolutePath(), MONITORED_EVENTS);
Ben Gruvera4879c32013-04-08 14:27:37 -0700558 }
559
560 @Override
561 public void onEvent(int event, String path) {
Ben Gruverb7c1a172013-07-23 15:05:28 -0700562 if (path.endsWith(".xml")) {
Ben Gruvera4879c32013-04-08 14:27:37 -0700563 // we wait 250ms before taking any action on an event, in order to dedup multiple
564 // events. E.g. a delete event followed by a create event followed by a subsequent
Ben Gruverb7c1a172013-07-23 15:05:28 -0700565 // write+close event
566 mHandler.removeMessages(0);
567 mHandler.sendEmptyMessageDelayed(0, 250);
Ben Gruvera4879c32013-04-08 14:27:37 -0700568 }
569 }
570 }
571
Ben Gruver4efe9402013-04-02 21:18:41 -0700572 /**
573 * This interface contains the methods we need from ActivityManagerService. This allows AMS to
574 * export these methods to us without making them public, and also makes it easier to test this
575 * component.
576 */
577 public interface AMSInterface {
578 int checkComponentPermission(String permission, int pid, int uid,
579 int owningUid, boolean exported);
Ben Gruvera4879c32013-04-08 14:27:37 -0700580 Object getAMSLock();
Ben Gruver4efe9402013-04-02 21:18:41 -0700581 }
582
583 /**
584 * Checks if the caller has access to a component
585 *
586 * @param permission If present, the caller must have this permission
587 * @param pid The pid of the caller
588 * @param uid The uid of the caller
589 * @param owningUid The uid of the application that owns the component
590 * @param exported Whether the component is exported
591 * @return True if the caller can access the described component
592 */
593 boolean checkComponentPermission(String permission, int pid, int uid, int owningUid,
594 boolean exported) {
595 return mAms.checkComponentPermission(permission, pid, uid, owningUid, exported) ==
596 PackageManager.PERMISSION_GRANTED;
597 }
598
599 boolean signaturesMatch(int uid1, int uid2) {
Ben Gruver8be8df22013-04-05 19:21:19 -0700600 try {
601 IPackageManager pm = AppGlobals.getPackageManager();
602 return pm.checkUidSignatures(uid1, uid2) == PackageManager.SIGNATURE_MATCH;
603 } catch (RemoteException ex) {
604 Slog.e(TAG, "Remote exception while checking signatures", ex);
605 return false;
606 }
Ben Gruver4efe9402013-04-02 21:18:41 -0700607 }
Ben Gruverdd72c9e2013-08-06 12:34:17 -0700608
Ben Gruver4efe9402013-04-02 21:18:41 -0700609}