This repository has been archived by the owner on Sep 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 527
/
PrivacyManager.java
1419 lines (1219 loc) · 46.9 KB
/
PrivacyManager.java
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package biz.bokhorst.xprivacy;
import java.lang.reflect.Field;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.os.Build;
import android.os.Process;
import android.os.RemoteException;
import android.util.Log;
import android.util.SparseArray;
public class PrivacyManager {
public static final boolean cVersion3 = true;
// This should correspond with restrict_<name> in strings.xml
public static final String cAccounts = "accounts";
public static final String cBrowser = "browser";
public static final String cCalendar = "calendar";
public static final String cCalling = "calling";
public static final String cClipboard = "clipboard";
public static final String cContacts = "contacts";
public static final String cDictionary = "dictionary";
public static final String cEMail = "email";
public static final String cIdentification = "identification";
public static final String cInternet = "internet";
public static final String cIPC = "ipc";
public static final String cLocation = "location";
public static final String cMedia = "media";
public static final String cMessages = "messages";
public static final String cNetwork = "network";
public static final String cNfc = "nfc";
public static final String cNotifications = "notifications";
public static final String cOverlay = "overlay";
public static final String cPhone = "phone";
public static final String cSensors = "sensors";
public static final String cShell = "shell";
public static final String cStorage = "storage";
public static final String cSystem = "system";
public static final String cView = "view";
// This should correspond with the above definitions
private static final String cRestrictionNames[] = new String[] { cAccounts, cBrowser, cCalendar, cCalling,
cClipboard, cContacts, cDictionary, cEMail, cIdentification, cInternet, cIPC, cLocation, cMedia, cMessages,
cNetwork, cNfc, cNotifications, cOverlay, cPhone, cSensors, cShell, cStorage, cSystem, cView };
public static List<String> cMethodNoState = Arrays.asList(new String[] { "IntentFirewall", "checkPermission",
"checkUidPermission" });
// Setting names
public final static String cSettingSerial = "Serial";
public final static String cSettingLatitude = "Latitude";
public final static String cSettingLongitude = "Longitude";
public final static String cSettingAltitude = "Altitude";
public final static String cSettingMac = "Mac";
public final static String cSettingIP = "IP";
public final static String cSettingImei = "IMEI";
public final static String cSettingPhone = "Phone";
public final static String cSettingId = "ID";
public final static String cSettingGsfId = "GSF_ID";
public final static String cSettingAdId = "AdId";
public final static String cSettingMcc = "MCC";
public final static String cSettingMnc = "MNC";
public final static String cSettingCountry = "Country";
public final static String cSettingOperator = "Operator";
public final static String cSettingIccId = "ICC_ID";
public final static String cSettingSubscriber = "Subscriber";
public final static String cSettingSSID = "SSID";
public final static String cSettingUa = "UA";
public final static String cSettingOpenTab = "OpenTab";
public final static String cSettingSelectedCategory = "SelectedCategory";
public final static String cSettingFUsed = "FUsed";
public final static String cSettingFInternet = "FInternet";
public final static String cSettingFRestriction = "FRestriction";
public final static String cSettingFRestrictionNot = "FRestrictionNot";
public final static String cSettingFPermission = "FPermission";
public final static String cSettingFOnDemand = "FOnDemand";
public final static String cSettingFOnDemandNot = "FOnDemandNot";
public final static String cSettingFUser = "FUser";
public final static String cSettingFSystem = "FSystem";
public final static String cSettingSortMode = "SortMode";
public final static String cSettingSortInverted = "SortInverted";
public final static String cSettingModifyTime = "ModifyTime";
public final static String cSettingTheme = "Theme";
public final static String cSettingSalt = "Salt";
public final static String cSettingVersion = "Version";
public final static String cSettingFirstRun = "FirstRun";
public final static String cSettingTutorialMain = "TutorialMain";
public final static String cSettingTutorialDetails = "TutorialDetails";
public final static String cSettingNotify = "Notify";
public final static String cSettingLog = "Log";
public final static String cSettingDangerous = "Dangerous";
public final static String cSettingExperimental = "Experimental";
public final static String cSettingRandom = "Random@boot";
public final static String cSettingState = "State";
public final static String cSettingConfidence = "Confidence";
public final static String cSettingHttps = "Https";
public final static String cSettingRegistered = "Registered";
public final static String cSettingUsage = "UsageData";
public final static String cSettingParameters = "Parameters";
public final static String cSettingValues = "Values";
public final static String cSettingSystem = "RestrictSystem";
public final static String cSettingRestricted = "Retricted";
public final static String cSettingOnDemand = "OnDemand";
public final static String cSettingMigrated = "Migrated";
public final static String cSettingCid = "Cid";
public final static String cSettingLac = "Lac";
public final static String cSettingBlacklist = "Blacklist";
public final static String cSettingResolve = "Resolve";
public final static String cSettingNoResolve = "NoResolve";
public final static String cSettingFreeze = "Freeze";
public final static String cSettingPermMan = "PermMan";
public final static String cSettingIntentWall = "IntentWall";
public final static String cSettingSafeMode = "SafeMode";
public final static String cSettingTestVersions = "TestVersions";
public final static String cSettingOnDemandSystem = "OnDemandSystem";
public final static String cSettingLegacy = "Legacy";
public final static String cSettingAOSPMode = "AOSPMode";
public final static String cSettingChangelog = "Changelog";
public final static String cSettingUpdates = "Updates";
public final static String cSettingMethodExpert = "MethodExpert";
public final static String cSettingWhitelistNoModify = "WhitelistNoModify";
public final static String cSettingNoUsageData = "NoUsageData";
public final static String cSettingODExpert = "ODExpert";
public final static String cSettingODCategory = "ODCategory";
public final static String cSettingODOnce = "ODOnce";
public final static String cSettingODOnceDuration = "ODOnceDuration";
// Special value names
public final static String cValueRandom = "#Random#";
public final static String cValueRandomLegacy = "\nRandom\n";
// Constants
public final static int cXposedAppProcessMinVersion = 46;
public final static int cWarnServiceDelayMs = 200;
public final static int cWarnHookDelayMs = 200;
private final static int cMaxExtra = 128;
private final static String cDeface = "DEFACE";
// Caching
public final static int cRestrictionCacheTimeoutMs = 15 * 1000;
public final static int cSettingCacheTimeoutMs = 30 * 1000;
private static Map<String, Map<String, Hook>> mMethod = new LinkedHashMap<String, Map<String, Hook>>();
private static Map<String, List<String>> mRestart = new LinkedHashMap<String, List<String>>();
private static Map<String, List<Hook>> mPermission = new LinkedHashMap<String, List<Hook>>();
private static Map<CSetting, CSetting> mSettingsCache = new HashMap<CSetting, CSetting>();
private static Map<CSetting, CSetting> mTransientCache = new HashMap<CSetting, CSetting>();
private static Map<CRestriction, CRestriction> mRestrictionCache = new HashMap<CRestriction, CRestriction>();
private static SparseArray<Map<String, Boolean>> mPermissionRestrictionCache = new SparseArray<Map<String, Boolean>>();
private static SparseArray<Map<Hook, Boolean>> mPermissionHookCache = new SparseArray<Map<Hook, Boolean>>();
// Meta data
static {
List<Hook> listHook = Meta.get();
List<String> listRestriction = getRestrictions();
for (Hook hook : listHook) {
String restrictionName = hook.getRestrictionName();
if (restrictionName == null)
restrictionName = "";
// Check restriction
else if (!listRestriction.contains(restrictionName))
if (hook.isAvailable())
Util.log(null, Log.WARN, "Not found restriction=" + restrictionName + " hook=" + hook);
// Enlist method
if (!mMethod.containsKey(restrictionName))
mMethod.put(restrictionName, new HashMap<String, Hook>());
mMethod.get(restrictionName).put(hook.getName(), hook);
// Cache restart required methods
if (hook.isRestartRequired()) {
if (!mRestart.containsKey(restrictionName))
mRestart.put(restrictionName, new ArrayList<String>());
mRestart.get(restrictionName).add(hook.getName());
}
// Enlist permissions
String[] permissions = hook.getPermissions();
if (permissions != null)
for (String perm : permissions)
if (!perm.equals("")) {
String aPermission = (perm.contains(".") ? perm : "android.permission." + perm);
if (!mPermission.containsKey(aPermission))
mPermission.put(aPermission, new ArrayList<Hook>());
if (!mPermission.get(aPermission).contains(hook))
mPermission.get(aPermission).add(hook);
}
}
// Util.log(null, Log.WARN, listHook.size() + " hooks");
}
public static List<String> getRestrictions() {
List<String> listRestriction = new ArrayList<String>(Arrays.asList(cRestrictionNames));
if (Hook.isAOSP(19))
listRestriction.remove(cIPC);
return listRestriction;
}
public static TreeMap<String, String> getRestrictions(Context context) {
Collator collator = Collator.getInstance(Locale.getDefault());
TreeMap<String, String> tmRestriction = new TreeMap<String, String>(collator);
for (String restrictionName : getRestrictions()) {
int stringId = context.getResources().getIdentifier("restrict_" + restrictionName, "string",
context.getPackageName());
tmRestriction.put(stringId == 0 ? restrictionName : context.getString(stringId), restrictionName);
}
return tmRestriction;
}
public static Hook getHook(String _restrictionName, String methodName) {
String restrictionName = (_restrictionName == null ? "" : _restrictionName);
if (mMethod.containsKey(restrictionName))
if (mMethod.get(restrictionName).containsKey(methodName))
return mMethod.get(restrictionName).get(methodName);
return null;
}
public static List<Hook> getHooks(String restrictionName, Version version) {
List<Hook> listMethod = new ArrayList<Hook>();
for (String methodName : mMethod.get(restrictionName).keySet()) {
Hook hook = mMethod.get(restrictionName).get(methodName);
if (!hook.isAvailable())
continue;
if (version != null && hook.getFrom() != null && version.compareTo(hook.getFrom()) < 0)
continue;
if ("IntentFirewall".equals(hook.getName()))
if (!PrivacyManager.getSettingBool(0, PrivacyManager.cSettingIntentWall, false))
continue;
if ("checkPermission".equals(hook.getName()) || "checkUidPermission".equals(hook.getName()))
if (!PrivacyManager.getSettingBool(0, PrivacyManager.cSettingPermMan, false))
continue;
listMethod.add(mMethod.get(restrictionName).get(methodName));
}
Collections.sort(listMethod);
return listMethod;
}
public static List<String> getPermissions(String restrictionName, Version version) {
List<String> listPermission = new ArrayList<String>();
for (Hook md : getHooks(restrictionName, version))
if (md.getPermissions() != null)
for (String permission : md.getPermissions())
if (!listPermission.contains(permission))
listPermission.add(permission);
return listPermission;
}
// Restrictions
public static PRestriction getRestrictionEx(int uid, String restrictionName, String methodName) {
PRestriction query = new PRestriction(uid, restrictionName, methodName, false);
PRestriction result = new PRestriction(uid, restrictionName, methodName, false, true);
try {
// Check cache
boolean cached = false;
CRestriction key = new CRestriction(uid, restrictionName, methodName, null);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key)) {
CRestriction entry = mRestrictionCache.get(key);
if (!entry.isExpired()) {
cached = true;
result.restricted = entry.restricted;
result.asked = entry.asked;
}
}
}
if (!cached) {
// Get restriction
result = PrivacyService.getRestrictionProxy(query, false, "");
if (result.debug)
Util.logStack(null, Log.WARN);
// Add to cache
key.restricted = result.restricted;
key.asked = result.asked;
if (result.time > 0) {
key.setExpiry(result.time);
Util.log(null, Log.WARN, "Caching " + result + " until " + new Date(result.time));
}
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
mRestrictionCache.remove(key);
mRestrictionCache.put(key, key);
}
}
} catch (RemoteException ex) {
Util.bug(null, ex);
}
return result;
}
public static boolean getRestriction(final XHook hook, int uid, String restrictionName, String methodName,
String secret) {
return getRestrictionExtra(hook, uid, restrictionName, methodName, null, null, secret);
}
public static boolean getRestrictionExtra(final XHook hook, int uid, String restrictionName, String methodName,
String extra, String secret) {
return getRestrictionExtra(hook, uid, restrictionName, methodName, extra, null, secret);
}
public static boolean getRestrictionExtra(final XHook hook, int uid, String restrictionName, String methodName,
String extra, String value, String secret) {
long start = System.currentTimeMillis();
PRestriction result = new PRestriction(uid, restrictionName, methodName, false, true);
// Check uid
if (uid <= 0)
return false;
// Check secret
if (secret == null) {
Util.log(null, Log.ERROR, "Secret missing restriction=" + restrictionName + "/" + methodName);
Util.logStack(hook, Log.ERROR);
secret = "";
}
// Check restriction
if (restrictionName == null || restrictionName.equals("")) {
Util.log(hook, Log.ERROR, "restriction empty method=" + methodName);
Util.logStack(hook, Log.ERROR);
return false;
}
// Check usage
if (methodName == null || methodName.equals("")) {
Util.log(hook, Log.ERROR, "Method empty");
Util.logStack(hook, Log.ERROR);
} else if (getHook(restrictionName, methodName) == null) {
Util.log(hook, Log.ERROR, "Unknown method=" + methodName);
Util.logStack(hook, Log.ERROR);
}
// Check extra
if (extra != null && extra.length() > cMaxExtra)
extra = extra.substring(0, cMaxExtra) + "...";
result.extra = extra;
// Check cache
boolean cached = false;
CRestriction key = new CRestriction(uid, restrictionName, methodName, extra);
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key)) {
CRestriction entry = mRestrictionCache.get(key);
if (!entry.isExpired()) {
cached = true;
result.restricted = entry.restricted;
result.asked = entry.asked;
}
}
}
// Get restriction
if (!cached)
try {
PRestriction query = new PRestriction(uid, restrictionName, methodName, false);
query.extra = extra;
query.value = value;
PRestriction restriction = PrivacyService.getRestrictionProxy(query, true, secret);
result.restricted = restriction.restricted;
if (restriction.debug)
Util.logStack(null, Log.WARN);
// Add to cache
if (result.time >= 0) {
key.restricted = result.restricted;
key.asked = result.asked;
if (result.time > 0) {
key.setExpiry(result.time);
Util.log(null, Log.WARN, "Caching " + result + " until " + new Date(result.time));
}
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(key))
mRestrictionCache.remove(key);
mRestrictionCache.put(key, key);
}
}
} catch (Throwable ex) {
Util.bug(hook, ex);
}
// Result
long ms = System.currentTimeMillis() - start;
Util.log(hook, ms < cWarnServiceDelayMs ? Log.INFO : Log.WARN,
String.format("Get client %s%s %d ms", result, (cached ? " (cached)" : ""), ms));
return result.restricted;
}
public static void setRestriction(int uid, String restrictionName, String methodName, boolean restricted,
boolean asked) {
checkCaller();
// Check uid
if (uid == 0) {
Util.log(null, Log.WARN, "uid=0");
return;
}
// Build list of restrictions
List<String> listRestriction = new ArrayList<String>();
if (restrictionName == null)
listRestriction.addAll(PrivacyManager.getRestrictions());
else
listRestriction.add(restrictionName);
// Create list of restrictions to set
List<PRestriction> listPRestriction = new ArrayList<PRestriction>();
for (String rRestrictionName : listRestriction)
listPRestriction.add(new PRestriction(uid, rRestrictionName, methodName, restricted, asked));
// Make exceptions
if (methodName == null)
for (String rRestrictionName : listRestriction)
for (Hook md : getHooks(rRestrictionName, null)) {
if (!canRestrict(uid, Process.myUid(), rRestrictionName, md.getName(), false))
listPRestriction.add(new PRestriction(uid, rRestrictionName, md.getName(), false, true));
else if (md.isDangerous())
listPRestriction.add(new PRestriction(uid, rRestrictionName, md.getName(), false, md
.whitelist() == null));
}
setRestrictionList(listPRestriction);
}
public static List<String> cIDCant = Arrays.asList(new String[] { "getString", "Srv_Android_ID", "%serialno",
"SERIAL" });
public static boolean canRestrict(int uid, int xuid, String restrictionName, String methodName, boolean system) {
int _uid = Util.getAppId(uid);
int userId = Util.getUserId(uid);
if (_uid == Process.SYSTEM_UID) {
if (PrivacyManager.cIdentification.equals(restrictionName))
return false;
if (PrivacyManager.cShell.equals(restrictionName) && "loadLibrary".equals(methodName))
return false;
}
if (system)
if (!isApplication(_uid))
if (!getSettingBool(userId, PrivacyManager.cSettingSystem, false))
return false;
// @formatter:off
if (_uid == Util.getAppId(xuid) &&
((PrivacyManager.cIdentification.equals(restrictionName) && cIDCant.contains(methodName))
|| PrivacyManager.cIPC.equals(restrictionName)
|| PrivacyManager.cStorage.equals(restrictionName)
|| PrivacyManager.cSystem.equals(restrictionName)
|| PrivacyManager.cView.equals(restrictionName)))
return false;
// @formatter:on
Hook hook = getHook(restrictionName, methodName);
if (hook != null && hook.isUnsafe())
if (getSettingBool(userId, PrivacyManager.cSettingSafeMode, false))
return false;
return true;
}
public static void updateState(int uid) {
setSetting(uid, cSettingState, Integer.toString(ApplicationInfoEx.STATE_CHANGED));
setSetting(uid, cSettingModifyTime, Long.toString(System.currentTimeMillis()));
}
public static void setRestrictionList(List<PRestriction> listRestriction) {
checkCaller();
if (listRestriction.size() > 0)
try {
PrivacyService.getClient().setRestrictionList(listRestriction);
// Clear cache
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
public static List<PRestriction> getRestrictionList(int uid, String restrictionName) {
checkCaller();
try {
return PrivacyService.getClient().getRestrictionList(new PRestriction(uid, restrictionName, null, false));
} catch (Throwable ex) {
Util.bug(null, ex);
}
return new ArrayList<PRestriction>();
}
public static boolean isRestrictionSet(PRestriction restriction) {
try {
return PrivacyService.getClient().isRestrictionSet(restriction);
} catch (Throwable ex) {
Util.bug(null, ex);
return false;
}
}
public static void deleteRestrictions(int uid, String restrictionName, boolean deleteWhitelists) {
checkCaller();
try {
// Delete restrictions
PrivacyService.getClient().deleteRestrictions(uid, restrictionName == null ? "" : restrictionName);
// Clear associated whitelists
if (deleteWhitelists && uid > 0) {
for (PSetting setting : getSettingList(uid, null))
if (Meta.isWhitelist(setting.type))
setSetting(uid, setting.type, setting.name, null);
}
// Clear cache
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Mark as new/changed
setSetting(uid, cSettingState, Integer.toString(restrictionName == null ? ApplicationInfoEx.STATE_CHANGED
: ApplicationInfoEx.STATE_ATTENTION));
// Change app modification time
setSetting(uid, cSettingModifyTime, Long.toString(System.currentTimeMillis()));
}
public static List<Boolean> getRestartStates(int uid, String restrictionName) {
// Returns a list of restriction states for functions whose application
// requires the app to be restarted.
List<Boolean> listRestartRestriction = new ArrayList<Boolean>();
Set<String> listRestriction = new HashSet<String>();
if (restrictionName == null)
listRestriction = mRestart.keySet();
else if (mRestart.keySet().contains(restrictionName))
listRestriction.add(restrictionName);
try {
for (String restriction : listRestriction) {
for (String method : mRestart.get(restriction))
listRestartRestriction.add(getRestrictionEx(uid, restriction, method).restricted);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
return listRestartRestriction;
}
public static void applyTemplate(int uid, String templateName, String restrictionName, boolean methods,
boolean clear, boolean invert) {
checkCaller();
int userId = Util.getUserId(uid);
// Check on-demand
boolean ondemand = getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
// Build list of restrictions
List<String> listRestriction = new ArrayList<String>();
if (restrictionName == null)
listRestriction.addAll(getRestrictions());
else
listRestriction.add(restrictionName);
// Apply template
Util.log(null, Log.WARN, "Applying template=" + templateName);
boolean hasOndemand = false;
List<PRestriction> listPRestriction = new ArrayList<PRestriction>();
for (String rRestrictionName : listRestriction) {
// Cleanup
if (clear)
deleteRestrictions(uid, rRestrictionName, false);
// Parent
String parentValue = getSetting(userId, templateName, rRestrictionName, Boolean.toString(!ondemand)
+ "+ask");
boolean parentRestricted = parentValue.contains("true");
boolean parentAsked = (!ondemand || parentValue.contains("asked"));
hasOndemand = hasOndemand || !parentAsked;
// Merge
PRestriction parentMerge;
if (clear)
parentMerge = new PRestriction(uid, rRestrictionName, null, parentRestricted, parentAsked);
else
parentMerge = getRestrictionEx(uid, rRestrictionName, null);
// Apply
if (canRestrict(uid, Process.myUid(), rRestrictionName, null, true))
if (invert && ((parentRestricted && parentMerge.restricted) || (!parentAsked && !parentMerge.asked))) {
listPRestriction.add(new PRestriction(uid, rRestrictionName, null, parentRestricted ? false
: parentMerge.restricted, !parentAsked ? true : parentMerge.asked));
continue; // leave functions
} else
listPRestriction.add(new PRestriction(uid, rRestrictionName, null, parentMerge.restricted
|| parentRestricted, parentMerge.asked && parentAsked));
// Childs
if (methods)
for (Hook hook : getHooks(rRestrictionName, null))
if (canRestrict(uid, Process.myUid(), rRestrictionName, hook.getName(), true)) {
// Child
String settingName = rRestrictionName + "." + hook.getName();
String childValue = getSetting(userId, templateName, settingName, null);
if (childValue == null)
childValue = Boolean.toString(parentRestricted && !hook.isDangerous())
+ (parentAsked || (hook.isDangerous() && hook.whitelist() == null) ? "+asked"
: "+ask");
boolean restricted = childValue.contains("true");
boolean asked = (!ondemand || childValue.contains("asked"));
// Merge
PRestriction childMerge;
if (clear)
childMerge = new PRestriction(uid, rRestrictionName, hook.getName(), parentRestricted
&& restricted, parentAsked || asked);
else
childMerge = getRestrictionEx(uid, rRestrictionName, hook.getName());
// Invert
if (invert && parentRestricted && restricted) {
restricted = false;
childMerge.restricted = false;
}
if (invert && !parentAsked && !asked) {
asked = true;
childMerge.asked = true;
}
// Apply
if ((parentRestricted && !restricted) || (!parentAsked && asked)
|| (invert ? false : hook.isDangerous() || !clear)) {
PRestriction child = new PRestriction(uid, rRestrictionName, hook.getName(),
(parentRestricted && restricted) || childMerge.restricted, (parentAsked || asked)
&& childMerge.asked);
listPRestriction.add(child);
}
}
}
// Apply result
setRestrictionList(listPRestriction);
if (hasOndemand)
PrivacyManager.setSetting(uid, PrivacyManager.cSettingOnDemand, Boolean.toString(true));
}
// White/black listing
public static Map<String, TreeMap<String, Boolean>> listWhitelisted(int uid, String type) {
checkCaller();
Map<String, TreeMap<String, Boolean>> mapWhitelisted = new HashMap<String, TreeMap<String, Boolean>>();
for (PSetting setting : getSettingList(uid, type))
if (Meta.isWhitelist(setting.type)) {
if (!mapWhitelisted.containsKey(setting.type))
mapWhitelisted.put(setting.type, new TreeMap<String, Boolean>());
mapWhitelisted.get(setting.type).put(setting.name, Boolean.parseBoolean(setting.value));
}
return mapWhitelisted;
}
// Usage
public static long getUsage(int uid, String restrictionName, String methodName) {
checkCaller();
try {
List<PRestriction> listRestriction = new ArrayList<PRestriction>();
if (restrictionName == null)
for (String sRestrictionName : getRestrictions())
listRestriction.add(new PRestriction(uid, sRestrictionName, methodName, false));
else
listRestriction.add(new PRestriction(uid, restrictionName, methodName, false));
return PrivacyService.getClient().getUsage(listRestriction);
} catch (Throwable ex) {
Util.bug(null, ex);
return 0;
}
}
public static List<PRestriction> getUsageList(Context context, int uid, String restrictionName) {
checkCaller();
List<PRestriction> listUsage = new ArrayList<PRestriction>();
try {
listUsage.addAll(PrivacyService.getClient().getUsageList(uid,
restrictionName == null ? "" : restrictionName));
} catch (Throwable ex) {
Util.log(null, Log.ERROR, "getUsageList");
Util.bug(null, ex);
}
Collections.sort(listUsage, new ParcelableRestrictionCompare());
return listUsage;
}
public static class ParcelableRestrictionCompare implements Comparator<PRestriction> {
@Override
public int compare(PRestriction one, PRestriction another) {
if (one.time < another.time)
return 1;
else if (one.time > another.time)
return -1;
else
return 0;
}
}
public static void deleteUsage(int uid) {
checkCaller();
try {
PrivacyService.getClient().deleteUsage(uid);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
// Settings
public static String getSalt(int userId) {
String def = (Build.SERIAL == null ? "" : Build.SERIAL);
return getSetting(userId, cSettingSalt, def);
}
public static void removeLegacySalt(int userId) {
String def = (Build.SERIAL == null ? "" : Build.SERIAL);
String salt = getSetting(userId, cSettingSalt, null);
if (def.equals(salt))
setSetting(userId, cSettingSalt, null);
}
public static boolean getSettingBool(int uid, String name, boolean defaultValue) {
return Boolean.parseBoolean(getSetting(uid, name, Boolean.toString(defaultValue)));
}
public static boolean getSettingBool(int uid, String type, String name, boolean defaultValue) {
return Boolean.parseBoolean(getSetting(uid, type, name, Boolean.toString(defaultValue)));
}
public static String getSetting(int uid, String name, String defaultValue) {
return getSetting(uid, "", name, defaultValue);
}
public static String getSetting(int uid, String type, String name, String defaultValue) {
long start = System.currentTimeMillis();
String value = null;
// Check cache
boolean cached = false;
boolean willExpire = false;
CSetting key = new CSetting(uid, type, name);
synchronized (mSettingsCache) {
if (mSettingsCache.containsKey(key)) {
CSetting entry = mSettingsCache.get(key);
if (!entry.isExpired()) {
cached = true;
value = entry.getValue();
willExpire = entry.willExpire();
}
}
}
// Get settings
if (!cached)
try {
value = PrivacyService.getSettingProxy(new PSetting(Math.abs(uid), type, name, null)).value;
if (value == null)
if (uid > 99) {
int userId = Util.getUserId(uid);
value = PrivacyService.getSettingProxy(new PSetting(userId, type, name, null)).value;
}
// Add to cache
if (value == null)
key.setValue(defaultValue);
else
key.setValue(value);
synchronized (mSettingsCache) {
if (mSettingsCache.containsKey(key))
mSettingsCache.remove(key);
mSettingsCache.put(key, key);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
if (value == null)
value = defaultValue;
long ms = System.currentTimeMillis() - start;
if (!willExpire && !cSettingLog.equals(name))
Util.log(null, ms < cWarnServiceDelayMs ? Log.INFO : Log.WARN, String.format(
"Get setting uid=%d %s/%s=%s%s %d ms", uid, type, name, value, (cached ? " (cached)" : ""), ms));
return value;
}
public static void setSetting(int uid, String name, String value) {
setSetting(uid, "", name, value);
}
public static void setSetting(int uid, String type, String name, String value) {
checkCaller();
try {
PrivacyService.getClient().setSetting(new PSetting(uid, type, name, value));
// Update cache
CSetting key = new CSetting(uid, type, name);
key.setValue(value);
synchronized (mSettingsCache) {
if (mSettingsCache.containsKey(key))
mSettingsCache.remove(key);
mSettingsCache.put(key, key);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
public static void setSettingList(List<PSetting> listSetting) {
checkCaller();
if (listSetting.size() > 0)
try {
PrivacyService.getClient().setSettingList(listSetting);
// Clear cache
synchronized (mSettingsCache) {
mSettingsCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
public static List<PSetting> getSettingList(int uid, String type) {
checkCaller();
try {
return PrivacyService.getClient().getSettingList(new PSetting(uid, type, null, null));
} catch (Throwable ex) {
Util.bug(null, ex);
}
return new ArrayList<PSetting>();
}
public static void deleteSettings(int uid) {
checkCaller();
try {
PrivacyService.getClient().deleteSettings(uid);
// Clear cache
synchronized (mSettingsCache) {
mSettingsCache.clear();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private static final List<String> cSettingAppSpecific = Arrays.asList(new String[] { cSettingRandom,
cSettingSerial, cSettingLatitude, cSettingLongitude, cSettingAltitude, cSettingMac, cSettingIP,
cSettingImei, cSettingPhone, cSettingId, cSettingGsfId, cSettingAdId, cSettingMcc, cSettingMnc,
cSettingCountry, cSettingOperator, cSettingIccId, cSettingCid, cSettingLac, cSettingSubscriber,
cSettingSSID, cSettingUa });
public static boolean hasSpecificSettings(int uid) {
boolean specific = false;
for (PSetting setting : getSettingList(uid, ""))
if (cSettingAppSpecific.contains(setting.name)) {
specific = true;
break;
}
return specific;
}
public static String getTransient(String name, String defaultValue) {
CSetting csetting = new CSetting(0, "", name);
synchronized (mTransientCache) {
if (mTransientCache.containsKey(csetting))
return mTransientCache.get(csetting).getValue();
}
return defaultValue;
}
public static void setTransient(String name, String value) {
CSetting setting = new CSetting(0, "", name);
setting.setValue(value);
synchronized (mTransientCache) {
mTransientCache.put(setting, setting);
}
}
// Common
public static void clear() {
checkCaller();
try {
PrivacyService.getClient().clear();
flush();
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
public static void flush() {
synchronized (mSettingsCache) {
mSettingsCache.clear();
}
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mPermissionRestrictionCache) {
mPermissionRestrictionCache.clear();
}
synchronized (mPermissionHookCache) {
mPermissionHookCache.clear();
}
}
// Defacing
@SuppressLint("DefaultLocale")
public static Object getDefacedProp(int uid, String name) {
// Serial number
if (name.equals("SERIAL") || name.equals("%serialno")) {
String value = getSetting(uid, cSettingSerial, cDeface);
return (cValueRandom.equals(value) ? getRandomProp("SERIAL") : value);
}
// Host name
if (name.equals("%hostname"))
return cDeface;
// MAC addresses
if (name.equals("MAC") || name.equals("%macaddr")) {
String mac = getSetting(uid, cSettingMac, "DE:FA:CE:DE:FA:CE");
if (cValueRandom.equals(mac))
return getRandomProp("MAC");
StringBuilder sb = new StringBuilder(mac.replace(":", ""));
while (sb.length() != 12)
sb.insert(0, '0');
while (sb.length() > 12)
sb.deleteCharAt(sb.length() - 1);
for (int i = 10; i > 0; i -= 2)
sb.insert(i, ':');
return sb.toString();
}
// cid
if (name.equals("%cid"))
return cDeface;
// IMEI
if (name.equals("getDeviceId") || name.equals("%imei")) {
String value = getSetting(uid, cSettingImei, "000000000000000");