-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathRule.java
More file actions
577 lines (502 loc) · 25.8 KB
/
Rule.java
File metadata and controls
577 lines (502 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/*
* This file is from NetGuard.
*
* NetGuard is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NetGuard is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NetGuard. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright © 2015–2020 by Marcel Bokhorst (M66B), Konrad
* Kollnig (University of Oxford)
*/
package eu.faircode.netguard;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.os.Build;
import android.os.Process;
import android.util.Log;
import androidx.preference.PreferenceManager;
import com.google.android.material.snackbar.Snackbar;
import net.kollnig.missioncontrol.Common;
import net.kollnig.missioncontrol.R;
import net.kollnig.missioncontrol.data.Pair;
import net.kollnig.missioncontrol.data.BlockingMode;
import net.kollnig.missioncontrol.data.TrackerBlocklist;
import net.kollnig.missioncontrol.data.TrackerList;
import org.xmlpull.v1.XmlPullParser;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class Rule {
private static final String TAG = "TrackerControl.Rule";
public int uid;
public String packageName;
public int icon;
public String name;
public String version;
public boolean system;
public boolean internet;
public boolean enabled;
public boolean pkg = true;
public boolean wifi_default = false;
public boolean other_default = false;
public boolean screen_wifi_default = false;
public boolean screen_other_default = false;
public boolean roaming_default = false;
public boolean wifi_blocked = false;
public boolean other_blocked = false;
public boolean screen_wifi = false;
public boolean screen_other = false;
public boolean roaming = false;
public boolean apply = true; // If false, completely exclude from VPN (no DNS, no routing)
public boolean tracker_protect = true; // If false, don't block trackers (but still route through VPN)
public boolean notify = true;
public boolean relateduids = false;
public String[] related = null;
public long hosts;
public boolean changed;
public boolean expanded = false;
private static List<PackageInfo> cachePackageInfo = null;
private static Map<PackageInfo, String> cacheLabel = new HashMap<>();
private static Map<String, Boolean> cacheSystem = new HashMap<>();
private static Map<String, Boolean> cacheInternet = new HashMap<>();
private static Map<PackageInfo, Boolean> cacheEnabled = new HashMap<>();
private static Map<Integer, Long> trackerRecent = new HashMap<>();
public long getLastTrackerTime() {
Long time = trackerRecent.get(uid);
return time == null ? 0L : time;
}
static List<PackageInfo> getPackages(Context context) {
if (cachePackageInfo == null) {
PackageManager pm = context.getPackageManager();
cachePackageInfo = pm.getInstalledPackages(0);
}
return new ArrayList<>(cachePackageInfo);
}
private static String getLabel(PackageInfo info, Context context) {
if (!cacheLabel.containsKey(info)) {
PackageManager pm = context.getPackageManager();
cacheLabel.put(info, info.applicationInfo.loadLabel(pm).toString());
}
return cacheLabel.get(info);
}
public static boolean isSystem(String packageName, Context context) {
if (!cacheSystem.containsKey(packageName))
cacheSystem.put(packageName, Util.isSystem(packageName, context));
return cacheSystem.get(packageName);
}
private static boolean hasInternet(String packageName, Context context) {
if (!cacheInternet.containsKey(packageName))
cacheInternet.put(packageName, Util.hasInternet(packageName, context));
return cacheInternet.get(packageName);
}
private static boolean isEnabled(PackageInfo info, Context context) {
if (!cacheEnabled.containsKey(info))
cacheEnabled.put(info, Util.isEnabled(info, context));
return cacheEnabled.get(info);
}
public static void clearCache(Context context) {
Log.i(TAG, "Clearing cache");
synchronized (context.getApplicationContext()) {
cachePackageInfo = null;
cacheLabel.clear();
cacheSystem.clear();
cacheInternet.clear();
cacheEnabled.clear();
}
DatabaseHelper dh = DatabaseHelper.getInstance(context);
dh.clearApps();
}
private Rule(DatabaseHelper dh, PackageInfo info, Context context) {
this.uid = info.applicationInfo.uid;
this.packageName = info.packageName;
this.icon = info.applicationInfo.icon;
this.version = info.versionName;
if (info.applicationInfo.uid == 0) {
this.name = context.getString(R.string.title_root);
this.system = true;
this.internet = true;
this.enabled = true;
this.pkg = false;
} else if (info.applicationInfo.uid == 1013) {
this.name = context.getString(R.string.title_mediaserver);
this.system = true;
this.internet = true;
this.enabled = true;
this.pkg = false;
} else if (info.applicationInfo.uid == 1020) {
this.name = "MulticastDNSResponder";
this.system = true;
this.internet = true;
this.enabled = true;
this.pkg = false;
} else if (info.applicationInfo.uid == 1021) {
this.name = context.getString(R.string.title_gpsdaemon);
this.system = true;
this.internet = true;
this.enabled = true;
this.pkg = false;
} else if (info.applicationInfo.uid == 1051) {
this.name = context.getString(R.string.title_dnsdaemon);
this.system = true;
this.internet = true;
this.enabled = true;
this.pkg = false;
} else if (info.applicationInfo.uid == 9999) {
this.name = context.getString(R.string.title_nobody);
this.system = true;
this.internet = true;
this.enabled = true;
this.pkg = false;
} else {
Cursor cursor = null;
try {
cursor = dh.getApp(this.packageName);
if (cursor.moveToNext()) {
this.name = cursor.getString(cursor.getColumnIndex("label"));
this.system = cursor.getInt(cursor.getColumnIndex("system")) > 0;
this.internet = cursor.getInt(cursor.getColumnIndex("internet")) > 0;
this.enabled = cursor.getInt(cursor.getColumnIndex("enabled")) > 0;
} else {
this.name = getLabel(info, context);
this.system = isSystem(info.packageName, context);
this.internet = hasInternet(info.packageName, context);
this.enabled = isEnabled(info, context);
dh.addApp(this.packageName, this.name, this.system, this.internet, this.enabled);
}
} finally {
if (cursor != null)
cursor.close();
}
}
}
// Custom code: tracker counts
private static Map<Integer, Integer> trackerCounts;
private static Map<Integer, Integer> trackerCountsPastWeek;
public int getTrackerCount(boolean pastWeekOnly) {
Map<Integer, Integer> c = (pastWeekOnly) ? trackerCountsPastWeek : trackerCounts;
Integer trackerCount = c.get(uid);
if (trackerCount == null)
trackerCount = 0;
return trackerCount;
}
public static List<Rule> getRules(final boolean all, Context context) {
return getRules(all, false, context);
}
public static List<Rule> getRules(final boolean all, boolean self, Context context) {
synchronized (context.getApplicationContext()) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences wifi = context.getSharedPreferences("wifi", Context.MODE_PRIVATE);
SharedPreferences other = context.getSharedPreferences("other", Context.MODE_PRIVATE);
SharedPreferences screen_wifi = context.getSharedPreferences("screen_wifi", Context.MODE_PRIVATE);
SharedPreferences screen_other = context.getSharedPreferences("screen_other", Context.MODE_PRIVATE);
SharedPreferences roaming = context.getSharedPreferences("roaming", Context.MODE_PRIVATE);
SharedPreferences apply = context.getSharedPreferences("apply", Context.MODE_PRIVATE);
SharedPreferences tracker_protect = context.getSharedPreferences("tracker_protect", Context.MODE_PRIVATE);
SharedPreferences notify = context.getSharedPreferences("notify", Context.MODE_PRIVATE);
// Get settings
boolean default_wifi = prefs.getBoolean("whitelist_wifi", true);
boolean default_other = prefs.getBoolean("whitelist_other", true);
boolean default_screen_wifi = prefs.getBoolean("screen_wifi", false);
boolean default_screen_other = prefs.getBoolean("screen_other", false);
boolean default_roaming = prefs.getBoolean("whitelist_roaming", true);
boolean manage_system = prefs.getBoolean("manage_system", false);
boolean screen_on = prefs.getBoolean("screen_on", true);
boolean show_user = prefs.getBoolean("show_user", true);
boolean show_system = prefs.getBoolean("show_system", false);
boolean show_nointernet = prefs.getBoolean("show_nointernet", true);
boolean show_unprotected = prefs.getBoolean("show_unprotected", false);
boolean show_frozen = prefs.getBoolean("show_frozen", false);
boolean strict_blocking = BlockingMode.isStrictMode(context);
default_screen_wifi = default_screen_wifi && screen_on;
default_screen_other = default_screen_other && screen_on;
// Get predefined rules
Map<String, Boolean> pre_wifi_blocked = new HashMap<>();
Map<String, Boolean> pre_other_blocked = new HashMap<>();
Map<String, Boolean> pre_roaming = new HashMap<>();
Map<String, String[]> pre_related = new HashMap<>();
Map<String, Boolean> pre_system = new HashMap<>();
try {
XmlResourceParser xml = context.getResources().getXml(R.xml.predefined);
int eventType = xml.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG)
if ("wifi".equals(xml.getName())) {
String pkg = xml.getAttributeValue(null, "package");
boolean pblocked = xml.getAttributeBooleanValue(null, "blocked", false);
pre_wifi_blocked.put(pkg, pblocked);
} else if ("other".equals(xml.getName())) {
String pkg = xml.getAttributeValue(null, "package");
boolean pblocked = xml.getAttributeBooleanValue(null, "blocked", false);
boolean proaming = xml.getAttributeBooleanValue(null, "roaming", default_roaming);
pre_other_blocked.put(pkg, pblocked);
pre_roaming.put(pkg, proaming);
} else if ("relation".equals(xml.getName())) {
String pkg = xml.getAttributeValue(null, "package");
String[] rel = xml.getAttributeValue(null, "related").split(",");
pre_related.put(pkg, rel);
} else if ("type".equals(xml.getName())) {
String pkg = xml.getAttributeValue(null, "package");
boolean system = xml.getAttributeBooleanValue(null, "system", true);
pre_system.put(pkg, system);
}
eventType = xml.next();
}
} catch (Throwable ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
}
// Build rule list
List<Rule> listRules = new ArrayList<>();
List<PackageInfo> listPI = getPackages(context);
int userId = Process.myUid() / 100000;
// Add root
PackageInfo root = new PackageInfo();
root.packageName = "root";
root.versionCode = Build.VERSION.SDK_INT;
root.versionName = Build.VERSION.RELEASE;
root.applicationInfo = new ApplicationInfo();
root.applicationInfo.uid = 0;
root.applicationInfo.icon = 0;
listPI.add(root);
// Add mediaserver
PackageInfo media = new PackageInfo();
media.packageName = "android.media";
media.versionCode = Build.VERSION.SDK_INT;
media.versionName = Build.VERSION.RELEASE;
media.applicationInfo = new ApplicationInfo();
media.applicationInfo.uid = 1013 + userId * 100000;
media.applicationInfo.icon = 0;
listPI.add(media);
// MulticastDNSResponder
PackageInfo mdr = new PackageInfo();
mdr.packageName = "android.multicast";
mdr.versionCode = Build.VERSION.SDK_INT;
mdr.versionName = Build.VERSION.RELEASE;
mdr.applicationInfo = new ApplicationInfo();
mdr.applicationInfo.uid = 1020 + userId * 100000;
mdr.applicationInfo.icon = 0;
listPI.add(mdr);
// Add GPS daemon
PackageInfo gps = new PackageInfo();
gps.packageName = "android.gps";
gps.versionCode = Build.VERSION.SDK_INT;
gps.versionName = Build.VERSION.RELEASE;
gps.applicationInfo = new ApplicationInfo();
gps.applicationInfo.uid = 1021 + userId * 100000;
gps.applicationInfo.icon = 0;
listPI.add(gps);
// Add DNS daemon
PackageInfo dns = new PackageInfo();
dns.packageName = "android.dns";
dns.versionCode = Build.VERSION.SDK_INT;
dns.versionName = Build.VERSION.RELEASE;
dns.applicationInfo = new ApplicationInfo();
dns.applicationInfo.uid = 1051 + userId * 100000;
dns.applicationInfo.icon = 0;
listPI.add(dns);
// Add nobody
PackageInfo nobody = new PackageInfo();
nobody.packageName = "nobody";
nobody.versionCode = Build.VERSION.SDK_INT;
nobody.versionName = Build.VERSION.RELEASE;
nobody.applicationInfo = new ApplicationInfo();
nobody.applicationInfo.uid = 9999;
nobody.applicationInfo.icon = 0;
listPI.add(nobody);
DatabaseHelper dh = DatabaseHelper.getInstance(context);
TrackerBlocklist trackerBlocklist = TrackerBlocklist.getInstance(context);
boolean trackerDefaultsChanged = false;
for (PackageInfo info : listPI)
try {
// Skip self
if (!self && info.applicationInfo.uid == Process.myUid())
continue;
Rule rule = new Rule(dh, info, context);
trackerDefaultsChanged |= trackerBlocklist.ensureDefaults(rule.uid, strict_blocking);
if (pre_system.containsKey(info.packageName))
rule.system = pre_system.get(info.packageName);
// if (info.applicationInfo.uid == Process.myUid())
// rule.system = true;
if (all ||
((rule.system ? show_system : show_user) &&
(show_nointernet || rule.internet) &&
(show_frozen || rule.enabled))) {
rule.wifi_default = (pre_wifi_blocked.containsKey(info.packageName)
? pre_wifi_blocked.get(info.packageName)
: default_wifi);
rule.other_default = (pre_other_blocked.containsKey(info.packageName)
? pre_other_blocked.get(info.packageName)
: default_other);
rule.screen_wifi_default = default_screen_wifi;
rule.screen_other_default = default_screen_other;
rule.roaming_default = (pre_roaming.containsKey(info.packageName)
? pre_roaming.get(info.packageName)
: default_roaming);
rule.wifi_blocked = (!(rule.system && !manage_system)
&& wifi.getBoolean(info.packageName, rule.wifi_default));
rule.other_blocked = (!(rule.system && !manage_system)
&& other.getBoolean(info.packageName, rule.other_default));
rule.screen_wifi = screen_wifi.getBoolean(info.packageName, rule.screen_wifi_default)
&& screen_on;
rule.screen_other = screen_other.getBoolean(info.packageName, rule.screen_other_default)
&& screen_on;
rule.roaming = roaming.getBoolean(info.packageName, rule.roaming_default);
rule.apply = apply.getBoolean(info.packageName, true);
rule.tracker_protect = BlockingMode.isTrackerProtectionEnabled(
context, tracker_protect, info.packageName);
rule.notify = notify.getBoolean(info.packageName, true);
// Related packages
List<String> listPkg = new ArrayList<>();
if (pre_related.containsKey(info.packageName))
listPkg.addAll(Arrays.asList(pre_related.get(info.packageName)));
for (PackageInfo pi : listPI)
if (pi.applicationInfo.uid == rule.uid && !pi.packageName.equals(rule.packageName)) {
rule.relateduids = true;
listPkg.add(pi.packageName);
}
rule.related = listPkg.toArray(new String[0]);
rule.hosts = dh.getHostCount(rule.uid, true);
rule.updateChanged(default_wifi, default_other, default_roaming);
// Check unprotected filter: when enabled, only show apps that are not protected
boolean isUnprotected = !rule.apply || !rule.tracker_protect;
if (!show_unprotected || isUnprotected) {
listRules.add(rule);
}
}
} catch (Throwable ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
}
if (trackerDefaultsChanged)
trackerBlocklist.saveSettings(context);
// Load tracking counts
TrackerList trackerList = TrackerList.getInstance(context);
Pair<Pair<Map<Integer, Integer>, Integer>, Pair<Map<Integer, Integer>, Integer>> trackerCountsAndTotal = trackerList
.getTrackerCountsAndTotal();
Pair<Map<Integer, Integer>, Integer> trackerCountsAndTotalAll = trackerCountsAndTotal.first();
Pair<Map<Integer, Integer>, Integer> trackerCountsAndTotalPastWeek = trackerCountsAndTotal.second();
trackerCounts = trackerCountsAndTotalAll.first();
trackerCountsPastWeek = trackerCountsAndTotalPastWeek.first();
trackerRecent = trackerList.getLastTrackerTimes();
int trackerTotal = trackerCountsAndTotalAll.second();
if (trackerTotal == 0
&& context instanceof Activity) {
int instructionsString = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
? R.string.instructions_monitoring_private_dns
: R.string.instructions_monitoring;
Snackbar s = Common.getSnackbar((Activity) context, instructionsString);
if (s != null) {
s.setAction(R.string.ok, v1 -> s.dismiss());
s.show();
}
}
// Sort rule list
final Collator collator = Collator.getInstance(Locale.getDefault());
collator.setStrength(Collator.SECONDARY); // Case insensitive, process accents etc
String sort = prefs.getString("sort", "trackers_week");
if ("uid".equals(sort))
Collections.sort(listRules, new Comparator<Rule>() {
@Override
public int compare(Rule rule, Rule other) {
if (rule.uid < other.uid)
return -1;
else if (rule.uid > other.uid)
return 1;
else {
int i = collator.compare(rule.name, other.name);
return (i == 0 ? rule.packageName.compareTo(other.packageName) : i);
}
}
});
else if ("name".equals(sort))
Collections.sort(listRules, new Comparator<Rule>() {
@Override
public int compare(Rule rule, Rule other) {
if (all || rule.changed == other.changed) {
int i = collator.compare(rule.name, other.name);
return (i == 0 ? rule.packageName.compareTo(other.packageName) : i);
}
return (rule.changed ? -1 : 1);
}
});
else if ("trackers_recent".equals(sort)) {
Collections.sort(listRules, (a, b) -> {
// Most recent tracker contact first
int timeCmp = Long.compare(b.getLastTrackerTime(), a.getLastTrackerTime());
if (timeCmp != 0) return timeCmp;
// Tiebreak: alphabetical by app name, then package name
int nameCmp = collator.compare(a.name, b.name);
return nameCmp != 0 ? nameCmp : a.packageName.compareTo(b.packageName);
});
}
else
Collections.sort(listRules, new Comparator<Rule>() {
@Override
public int compare(Rule rule, Rule other) {
boolean pastWeekOnly = !("trackers_all".equals(sort));
if (rule.getTrackerCount(pastWeekOnly) < other.getTrackerCount(pastWeekOnly))
return 1;
else if (rule.getTrackerCount(pastWeekOnly) > other.getTrackerCount(pastWeekOnly))
return -1;
else {
int i = collator.compare(rule.name, other.name);
return (i == 0 ? rule.packageName.compareTo(other.packageName) : i);
}
}
});
return listRules;
}
}
private static List<String> getHandlingPackages(PackageManager pm, Intent intent) {
List<String> packagesList = new ArrayList<>();
int flag = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
flag = PackageManager.MATCH_ALL;
List<ResolveInfo> activityList = pm.queryIntentActivities(intent, flag);
for (ResolveInfo info : activityList)
packagesList.add(info.activityInfo.packageName);
return packagesList;
}
private void updateChanged(boolean default_wifi, boolean default_other, boolean default_roaming) {
changed = (wifi_blocked != default_wifi ||
(other_blocked != default_other) ||
(wifi_blocked && screen_wifi != screen_wifi_default) ||
(other_blocked && screen_other != screen_other_default) ||
((!other_blocked || screen_other) && roaming != default_roaming) ||
hosts > 0 || !tracker_protect || !apply);
}
public void updateChanged(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean screen_on = prefs.getBoolean("screen_on", false);
boolean default_wifi = prefs.getBoolean("whitelist_wifi", true) && screen_on;
boolean default_other = prefs.getBoolean("whitelist_other", true) && screen_on;
boolean default_roaming = prefs.getBoolean("whitelist_roaming", true);
updateChanged(default_wifi, default_other, default_roaming);
}
@Override
public String toString() {
// This is used in the port forwarding dialog application selector
return this.name;
}
}