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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.connectivity;
import static android.Manifest.permission.CHANGE_NETWORK_STATE;
import static android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS;
import static android.Manifest.permission.INTERNET;
import static android.Manifest.permission.NETWORK_STACK;
import static android.Manifest.permission.UPDATE_DEVICE_STATS;
import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
import static android.content.pm.PackageManager.GET_PERMISSIONS;
import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOCKDOWN_VPN;
import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
import static android.net.ConnectivitySettingsManager.UIDS_ALLOWED_ON_RESTRICTED_NETWORKS;
import static android.net.INetd.PERMISSION_INTERNET;
import static android.net.INetd.PERMISSION_NETWORK;
import static android.net.INetd.PERMISSION_NONE;
import static android.net.INetd.PERMISSION_SYSTEM;
import static android.net.INetd.PERMISSION_UNINSTALLED;
import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
import static android.os.Process.INVALID_UID;
import static android.os.Process.SYSTEM_UID;
import static com.android.net.module.util.CollectionUtils.toIntArray;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.ContentObserver;
import android.net.ConnectivitySettingsManager;
import android.net.INetd;
import android.net.UidRange;
import android.net.Uri;
import android.net.util.SharedLog;
import android.os.Build;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceSpecificException;
import android.os.SystemConfigManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;
import android.util.SparseIntArray;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.IndentingPrintWriter;
import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.CollectionUtils;
import com.android.networkstack.apishim.ProcessShimImpl;
import com.android.networkstack.apishim.common.ProcessShim;
import com.android.server.BpfNetMaps;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A utility class to inform Netd of UID permissions.
* Does a mass update at boot and then monitors for app install/remove.
*
* @hide
*/
public class PermissionMonitor {
private static final String TAG = "PermissionMonitor";
private static final boolean DBG = true;
private static final int VERSION_Q = Build.VERSION_CODES.Q;
private final PackageManager mPackageManager;
private final UserManager mUserManager;
private final SystemConfigManager mSystemConfigManager;
private final INetd mNetd;
private final Dependencies mDeps;
private final Context mContext;
private final BpfNetMaps mBpfNetMaps;
private static final ProcessShim sProcessShim = ProcessShimImpl.newInstance();
@GuardedBy("this")
private final Set<UserHandle> mUsers = new HashSet<>();
// Keys are uids. Values are netd network permissions.
@GuardedBy("this")
private final SparseIntArray mUidToNetworkPerm = new SparseIntArray();
// NonNull keys are active non-bypassable and fully-routed VPN's interface name, Values are uid
// ranges for apps under the VPNs which enable interface filtering.
// If key is null, Values are uid ranges for apps under the VPNs which are connected but do not
// enable interface filtering.
@GuardedBy("this")
private final Map<String, Set<UidRange>> mVpnInterfaceUidRanges = new ArrayMap<>();
// Items are uid ranges for apps under the VPN Lockdown
// Ranges were given through ConnectivityManager#setRequireVpnForUids, and ranges are allowed to
// have duplicates. Also, it is allowed to give ranges that are already subject to lockdown.
// So we need to maintain uid range with multiset.
@GuardedBy("this")
private final MultiSet<UidRange> mVpnLockdownUidRanges = new MultiSet<>();
// A set of appIds for apps across all users on the device. We track appIds instead of uids
// directly to reduce its size and also eliminate the need to update this set when user is
// added/removed.
@GuardedBy("this")
private final Set<Integer> mAllApps = new HashSet<>();
// A set of uids which are allowed to use restricted networks. The packages of these uids can't
// hold the CONNECTIVITY_USE_RESTRICTED_NETWORKS permission because they can't be
// signature|privileged apps. However, these apps should still be able to use restricted
// networks under certain conditions (e.g. government app using emergency services). So grant
// netd system permission to these uids which is listed in UIDS_ALLOWED_ON_RESTRICTED_NETWORKS.
@GuardedBy("this")
private final Set<Integer> mUidsAllowedOnRestrictedNetworks = new ArraySet<>();
// Store PackageManager for each user.
// Keys are users, Values are PackageManagers which get from each user.
@GuardedBy("this")
private final Map<UserHandle, PackageManager> mUsersPackageManager = new ArrayMap<>();
// Store appIds traffic permissions for each user.
// Keys are users, Values are SparseArrays where each entry maps an appId to the permissions
// that appId has within that user. The permissions are a bitmask of PERMISSION_INTERNET and
// PERMISSION_UPDATE_DEVICE_STATS, or 0 (PERMISSION_NONE) if the app has neither of those
// permissions. They can never be PERMISSION_UNINSTALLED.
@GuardedBy("this")
private final Map<UserHandle, SparseIntArray> mUsersTrafficPermissions = new ArrayMap<>();
private static final int SYSTEM_APPID = SYSTEM_UID;
private static final int MAX_PERMISSION_UPDATE_LOGS = 40;
private final SharedLog mPermissionUpdateLogs = new SharedLog(MAX_PERMISSION_UPDATE_LOGS, TAG);
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
final Uri packageData = intent.getData();
final String packageName =
packageData != null ? packageData.getSchemeSpecificPart() : null;
onPackageAdded(packageName, uid);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
final Uri packageData = intent.getData();
final String packageName =
packageData != null ? packageData.getSchemeSpecificPart() : null;
onPackageRemoved(packageName, uid);
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
final String[] pkgList =
intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
onExternalApplicationsAvailable(pkgList);
} else {
Log.wtf(TAG, "received unexpected intent: " + action);
}
}
};
/**
* Dependencies of PermissionMonitor, for injection in tests.
*/
@VisibleForTesting
public static class Dependencies {
/**
* Get device first sdk version.
*/
public int getDeviceFirstSdkInt() {
return Build.VERSION.DEVICE_INITIAL_SDK_INT;
}
/**
* Get uids allowed to use restricted networks via ConnectivitySettingsManager.
*/
public Set<Integer> getUidsAllowedOnRestrictedNetworks(@NonNull Context context) {
return ConnectivitySettingsManager.getUidsAllowedOnRestrictedNetworks(context);
}
/**
* Register ContentObserver for given Uri.
*/
public void registerContentObserver(@NonNull Context context, @NonNull Uri uri,
boolean notifyForDescendants, @NonNull ContentObserver observer) {
context.getContentResolver().registerContentObserver(
uri, notifyForDescendants, observer);
}
}
private static class MultiSet<T> {
private final Map<T, Integer> mMap = new ArrayMap<>();
/**
* Returns the number of key in the set before this addition.
*/
public int add(T key) {
final int oldCount = mMap.getOrDefault(key, 0);
mMap.put(key, oldCount + 1);
return oldCount;
}
/**
* Return the number of key in the set before this removal.
*/
public int remove(T key) {
final int oldCount = mMap.getOrDefault(key, 0);
if (oldCount == 0) {
Log.wtf(TAG, "Attempt to remove non existing key = " + key.toString());
} else if (oldCount == 1) {
mMap.remove(key);
} else {
mMap.put(key, oldCount - 1);
}
return oldCount;
}
public Set<T> getSet() {
return mMap.keySet();
}
}
public PermissionMonitor(@NonNull final Context context, @NonNull final INetd netd,
@NonNull final BpfNetMaps bpfNetMaps) {
this(context, netd, bpfNetMaps, new Dependencies());
}
@VisibleForTesting
PermissionMonitor(@NonNull final Context context, @NonNull final INetd netd,
@NonNull final BpfNetMaps bpfNetMaps,
@NonNull final Dependencies deps) {
mPackageManager = context.getPackageManager();
mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
mSystemConfigManager = context.getSystemService(SystemConfigManager.class);
mNetd = netd;
mDeps = deps;
mContext = context;
mBpfNetMaps = bpfNetMaps;
}
private int getPackageNetdNetworkPermission(@NonNull final PackageInfo app) {
if (hasRestrictedNetworkPermission(app)) {
return PERMISSION_SYSTEM;
}
if (hasNetworkPermission(app)) {
return PERMISSION_NETWORK;
}
return PERMISSION_NONE;
}
static boolean isHigherNetworkPermission(final int targetPermission,
final int currentPermission) {
// This is relied on strict order of network permissions (SYSTEM > NETWORK > NONE), and it
// is enforced in tests.
return targetPermission > currentPermission;
}
private List<PackageInfo> getInstalledPackagesAsUser(final UserHandle user) {
return mPackageManager.getInstalledPackagesAsUser(GET_PERMISSIONS, user.getIdentifier());
}
private synchronized void updateAllApps(final List<PackageInfo> apps) {
for (PackageInfo app : apps) {
final int appId = app.applicationInfo != null
? UserHandle.getAppId(app.applicationInfo.uid) : INVALID_UID;
if (appId < 0) {
continue;
}
mAllApps.add(appId);
}
}
private static boolean hasSdkSandbox(final int uid) {
return SdkLevel.isAtLeastT() && Process.isApplicationUid(uid);
}
// Return the network permission for the passed list of apps. Note that this depends on the
// current settings of the device (See isUidAllowedOnRestrictedNetworks).
private SparseIntArray makeUidsNetworkPerm(final List<PackageInfo> apps) {
final SparseIntArray uidsPerm = new SparseIntArray();
for (PackageInfo app : apps) {
final int uid = app.applicationInfo != null ? app.applicationInfo.uid : INVALID_UID;
if (uid < 0) {
continue;
}
final int permission = getPackageNetdNetworkPermission(app);
if (isHigherNetworkPermission(permission, uidsPerm.get(uid, PERMISSION_NONE))) {
uidsPerm.put(uid, permission);
if (hasSdkSandbox(uid)) {
int sdkSandboxUid = sProcessShim.toSdkSandboxUid(uid);
uidsPerm.put(sdkSandboxUid, permission);
}
}
}
return uidsPerm;
}
private static SparseIntArray makeAppIdsTrafficPerm(final List<PackageInfo> apps) {
final SparseIntArray appIdsPerm = new SparseIntArray();
for (PackageInfo app : apps) {
final int appId = app.applicationInfo != null
? UserHandle.getAppId(app.applicationInfo.uid) : INVALID_UID;
if (appId < 0) {
continue;
}
final int otherNetdPerms = getNetdPermissionMask(app.requestedPermissions,
app.requestedPermissionsFlags);
final int permission = appIdsPerm.get(appId) | otherNetdPerms;
appIdsPerm.put(appId, permission);
if (hasSdkSandbox(appId)) {
appIdsPerm.put(sProcessShim.toSdkSandboxUid(appId), permission);
}
}
return appIdsPerm;
}
private synchronized void updateUidsNetworkPermission(final SparseIntArray uids) {
for (int i = 0; i < uids.size(); i++) {
mUidToNetworkPerm.put(uids.keyAt(i), uids.valueAt(i));
}
sendUidsNetworkPermission(uids, true /* add */);
}
/**
* Calculates permissions for appIds.
* Maps each appId to the union of all traffic permissions that the appId has in all users.
*
* @return The appIds traffic permissions.
*/
private synchronized SparseIntArray makeAppIdsTrafficPermForAllUsers() {
final SparseIntArray appIds = new SparseIntArray();
// Check appIds permissions from each user.
for (UserHandle user : mUsersTrafficPermissions.keySet()) {
final SparseIntArray userAppIds = mUsersTrafficPermissions.get(user);
for (int i = 0; i < userAppIds.size(); i++) {
final int appId = userAppIds.keyAt(i);
final int permission = userAppIds.valueAt(i);
appIds.put(appId, appIds.get(appId) | permission);
}
}
return appIds;
}
private SparseIntArray getSystemTrafficPerm() {
final SparseIntArray appIdsPerm = new SparseIntArray();
for (final int uid : mSystemConfigManager.getSystemPermissionUids(INTERNET)) {
final int appId = UserHandle.getAppId(uid);
final int permission = appIdsPerm.get(appId) | PERMISSION_INTERNET;
appIdsPerm.put(appId, permission);
if (hasSdkSandbox(appId)) {
appIdsPerm.put(sProcessShim.toSdkSandboxUid(appId), permission);
}
}
for (final int uid : mSystemConfigManager.getSystemPermissionUids(UPDATE_DEVICE_STATS)) {
final int appId = UserHandle.getAppId(uid);
final int permission = appIdsPerm.get(appId) | PERMISSION_UPDATE_DEVICE_STATS;
appIdsPerm.put(appId, permission);
if (hasSdkSandbox(appId)) {
appIdsPerm.put(sProcessShim.toSdkSandboxUid(appId), permission);
}
}
return appIdsPerm;
}
// Intended to be called only once at startup, after the system is ready. Installs a broadcast
// receiver to monitor ongoing UID changes, so this shouldn't/needn't be called again.
public synchronized void startMonitoring() {
log("Monitoring");
final Context userAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
userAllContext.registerReceiver(
mIntentReceiver, intentFilter, null /* broadcastPermission */,
null /* scheduler */);
// Listen to EXTERNAL_APPLICATIONS_AVAILABLE is that an app becoming available means it may
// need to gain a permission. But an app that becomes unavailable can neither gain nor lose
// permissions on that account, it just can no longer run. Thus, doesn't need to listen to
// EXTERNAL_APPLICATIONS_UNAVAILABLE.
final IntentFilter externalIntentFilter =
new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
userAllContext.registerReceiver(
mIntentReceiver, externalIntentFilter, null /* broadcastPermission */,
null /* scheduler */);
// Register UIDS_ALLOWED_ON_RESTRICTED_NETWORKS setting observer
mDeps.registerContentObserver(
userAllContext,
Settings.Global.getUriFor(UIDS_ALLOWED_ON_RESTRICTED_NETWORKS),
false /* notifyForDescendants */,
new ContentObserver(null) {
@Override
public void onChange(boolean selfChange) {
onSettingChanged();
}
});
// Read UIDS_ALLOWED_ON_RESTRICTED_NETWORKS setting and update
// mUidsAllowedOnRestrictedNetworks.
updateUidsAllowedOnRestrictedNetworks(mDeps.getUidsAllowedOnRestrictedNetworks(mContext));
// Read system traffic permissions when a user removed and put them to USER_ALL because they
// are not specific to any particular user.
mUsersTrafficPermissions.put(UserHandle.ALL, getSystemTrafficPerm());
final List<UserHandle> usrs = mUserManager.getUserHandles(true /* excludeDying */);
// Update netd permissions for all users.
for (UserHandle user : usrs) {
onUserAdded(user);
}
log("Users: " + mUsers.size() + ", UidToNetworkPerm: " + mUidToNetworkPerm.size());
}
@VisibleForTesting
synchronized void updateUidsAllowedOnRestrictedNetworks(final Set<Integer> uids) {
mUidsAllowedOnRestrictedNetworks.clear();
mUidsAllowedOnRestrictedNetworks.addAll(uids);
}
@VisibleForTesting
static boolean isVendorApp(@NonNull ApplicationInfo appInfo) {
return appInfo.isVendor() || appInfo.isOem() || appInfo.isProduct();
}
@VisibleForTesting
boolean isCarryoverPackage(final ApplicationInfo appInfo) {
if (appInfo == null) return false;
return (appInfo.targetSdkVersion < VERSION_Q && isVendorApp(appInfo))
// Backward compatibility for b/114245686, on devices that launched before Q daemons
// and apps running as the system UID are exempted from this check.
|| (UserHandle.getAppId(appInfo.uid) == SYSTEM_APPID
&& mDeps.getDeviceFirstSdkInt() < VERSION_Q);
}
@VisibleForTesting
synchronized boolean isUidAllowedOnRestrictedNetworks(final ApplicationInfo appInfo) {
if (appInfo == null) return false;
// Check whether package's uid is in allowed on restricted networks uid list. If so, this
// uid can have netd system permission.
return isUidAllowedOnRestrictedNetworks(appInfo.uid);
}
/**
* Returns whether the given uid is in allowed on restricted networks list.
*/
public synchronized boolean isUidAllowedOnRestrictedNetworks(final int uid) {
return mUidsAllowedOnRestrictedNetworks.contains(uid);
}
@VisibleForTesting
boolean hasPermission(@NonNull final PackageInfo app, @NonNull final String permission) {
if (app.requestedPermissions == null || app.requestedPermissionsFlags == null) {
return false;
}
final int index = CollectionUtils.indexOf(app.requestedPermissions, permission);
if (index < 0 || index >= app.requestedPermissionsFlags.length) return false;
return (app.requestedPermissionsFlags[index] & REQUESTED_PERMISSION_GRANTED) != 0;
}
@VisibleForTesting
boolean hasNetworkPermission(@NonNull final PackageInfo app) {
return hasPermission(app, CHANGE_NETWORK_STATE);
}
@VisibleForTesting
boolean hasRestrictedNetworkPermission(@NonNull final PackageInfo app) {
// TODO : remove carryover package check in the future(b/31479477). All apps should just
// request the appropriate permission for their use case since android Q.
return isCarryoverPackage(app.applicationInfo)
|| hasPermission(app, PERMISSION_MAINLINE_NETWORK_STACK)
|| hasPermission(app, NETWORK_STACK)
|| hasPermission(app, CONNECTIVITY_USE_RESTRICTED_NETWORKS);
}
/** Returns whether the given uid has using background network permission. */
public synchronized boolean hasUseBackgroundNetworksPermission(final int uid) {
// Apps with any of the CHANGE_NETWORK_STATE, NETWORK_STACK, CONNECTIVITY_INTERNAL or
// CONNECTIVITY_USE_RESTRICTED_NETWORKS permission has the permission to use background
// networks. mUidToNetworkPerm contains the result of checks for hasNetworkPermission and
// hasRestrictedNetworkPermission, as well as the list of UIDs allowed on restricted
// networks. If uid is in the mUidToNetworkPerm list that means uid has one of permissions
// at least.
return mUidToNetworkPerm.get(uid, PERMISSION_NONE) != PERMISSION_NONE;
}
/**
* Returns whether the given uid has permission to use restricted networks.
*/
public synchronized boolean hasRestrictedNetworksPermission(int uid) {
return PERMISSION_SYSTEM == mUidToNetworkPerm.get(uid, PERMISSION_NONE);
}
private void sendUidsNetworkPermission(SparseIntArray uids, boolean add) {
List<Integer> network = new ArrayList<>();
List<Integer> system = new ArrayList<>();
for (int i = 0; i < uids.size(); i++) {
final int permission = uids.valueAt(i);
if (PERMISSION_NONE == permission) {
continue; // Normally NONE is not stored in this map, but just in case
}
List<Integer> list = (PERMISSION_SYSTEM == permission) ? system : network;
list.add(uids.keyAt(i));
}
try {
if (add) {
mNetd.networkSetPermissionForUser(PERMISSION_NETWORK, toIntArray(network));
mNetd.networkSetPermissionForUser(PERMISSION_SYSTEM, toIntArray(system));
} else {
mNetd.networkClearPermissionForUser(toIntArray(network));
mNetd.networkClearPermissionForUser(toIntArray(system));
}
} catch (RemoteException e) {
loge("Exception when updating permissions: " + e);
}
}
/**
* Called when a user is added. See {link #ACTION_USER_ADDED}.
*
* @param user The integer userHandle of the added user. See {@link #EXTRA_USER_HANDLE}.
*
* @hide
*/
public synchronized void onUserAdded(@NonNull UserHandle user) {
mUsers.add(user);
final List<PackageInfo> apps = getInstalledPackagesAsUser(user);
// Save all apps
updateAllApps(apps);
// Uids network permissions
final SparseIntArray uids = makeUidsNetworkPerm(apps);
updateUidsNetworkPermission(uids);
// Add new user appIds permissions.
final SparseIntArray addedUserAppIds = makeAppIdsTrafficPerm(apps);
mUsersTrafficPermissions.put(user, addedUserAppIds);
// Generate appIds from all users and send result to netd.
final SparseIntArray appIds = makeAppIdsTrafficPermForAllUsers();
sendAppIdsTrafficPermission(appIds);
// Log user added
mPermissionUpdateLogs.log("New user(" + user.getIdentifier() + ") added: nPerm uids="
+ uids + ", tPerm appIds=" + addedUserAppIds);
}
/**
* Called when an user is removed. See {link #ACTION_USER_REMOVED}.
*
* @param user The integer userHandle of the removed user. See {@link #EXTRA_USER_HANDLE}.
*
* @hide
*/
public synchronized void onUserRemoved(@NonNull UserHandle user) {
mUsers.remove(user);
// Remove uids network permissions that belongs to the user.
final SparseIntArray removedUids = new SparseIntArray();
final SparseIntArray allUids = mUidToNetworkPerm.clone();
for (int i = 0; i < allUids.size(); i++) {
final int uid = allUids.keyAt(i);
if (user.equals(UserHandle.getUserHandleForUid(uid))) {
mUidToNetworkPerm.delete(uid);
removedUids.put(uid, allUids.valueAt(i));
}
}
sendUidsNetworkPermission(removedUids, false /* add */);
// Remove appIds traffic permission that belongs to the user
final SparseIntArray removedUserAppIds = mUsersTrafficPermissions.remove(user);
// Generate appIds from the remaining users.
final SparseIntArray appIds = makeAppIdsTrafficPermForAllUsers();
if (removedUserAppIds == null) {
Log.wtf(TAG, "onUserRemoved: Receive unknown user=" + user);
return;
}
// Clear permission on those appIds belong to this user only, set the permission to
// PERMISSION_UNINSTALLED.
for (int i = 0; i < removedUserAppIds.size(); i++) {
final int appId = removedUserAppIds.keyAt(i);
// Need to clear permission if the removed appId is not found in the array.
if (appIds.indexOfKey(appId) < 0) {
appIds.put(appId, PERMISSION_UNINSTALLED);
}
}
sendAppIdsTrafficPermission(appIds);
// Log user removed
mPermissionUpdateLogs.log("User(" + user.getIdentifier() + ") removed: nPerm uids="
+ removedUids + ", tPerm appIds=" + removedUserAppIds);
}
/**
* Compare the current network permission and the given package's permission to find out highest
* permission for the uid.
*
* @param uid The target uid
* @param currentPermission Current uid network permission
* @param name The package has same uid that need compare its permission to update uid network
* permission.
*/
@VisibleForTesting
protected int highestPermissionForUid(int uid, int currentPermission, String name) {
// If multiple packages share a UID (cf: android:sharedUserId) and ask for different
// permissions, don't downgrade (i.e., if it's already SYSTEM, leave it as is).
if (currentPermission == PERMISSION_SYSTEM) {
return currentPermission;
}
final PackageInfo app = getPackageInfoAsUser(name, UserHandle.getUserHandleForUid(uid));
if (app == null) return currentPermission;
final int permission = getPackageNetdNetworkPermission(app);
if (isHigherNetworkPermission(permission, currentPermission)) {
return permission;
}
return currentPermission;
}
private int getTrafficPermissionForUid(final int uid) {
int permission = PERMISSION_NONE;
// Check all the packages for this UID. The UID has the permission if any of the
// packages in it has the permission.
final String[] packages = mPackageManager.getPackagesForUid(uid);
if (packages != null && packages.length > 0) {
for (String name : packages) {
final PackageInfo app = getPackageInfoAsUser(name,
UserHandle.getUserHandleForUid(uid));
if (app != null && app.requestedPermissions != null) {
permission |= getNetdPermissionMask(app.requestedPermissions,
app.requestedPermissionsFlags);
}
}
} else {
// The last package of this uid is removed from device. Clean the package up.
permission = PERMISSION_UNINSTALLED;
}
return permission;
}
private synchronized void updateVpnUid(int uid, boolean add) {
// Apps that can use restricted networks can always bypass VPNs.
if (hasRestrictedNetworksPermission(uid)) {
return;
}
for (Map.Entry<String, Set<UidRange>> vpn : mVpnInterfaceUidRanges.entrySet()) {
if (UidRange.containsUid(vpn.getValue(), uid)) {
final Set<Integer> changedUids = new HashSet<>();
changedUids.add(uid);
updateVpnUidsInterfaceRules(vpn.getKey(), changedUids, add);
}
}
}
private synchronized void updateLockdownUid(int uid, boolean add) {
if (UidRange.containsUid(mVpnLockdownUidRanges.getSet(), uid)
&& !hasRestrictedNetworksPermission(uid)) {
updateLockdownUidRule(uid, add);
}
}
/**
* This handles both network and traffic permission, because there is no overlap in actual
* values, where network permission is NETWORK or SYSTEM, and traffic permission is INTERNET
* or UPDATE_DEVICE_STATS
*/
private String permissionToString(int permission) {
switch (permission) {
case PERMISSION_NONE:
return "NONE";
case PERMISSION_NETWORK:
return "NETWORK";
case PERMISSION_SYSTEM:
return "SYSTEM";
case PERMISSION_INTERNET:
return "INTERNET";
case PERMISSION_UPDATE_DEVICE_STATS:
return "UPDATE_DEVICE_STATS";
case (PERMISSION_INTERNET | PERMISSION_UPDATE_DEVICE_STATS):
return "ALL";
case PERMISSION_UNINSTALLED:
return "UNINSTALLED";
default:
return "UNKNOWN";
}
}
private synchronized void updateAppIdTrafficPermission(int uid) {
final int uidTrafficPerm = getTrafficPermissionForUid(uid);
final SparseIntArray userTrafficPerms =
mUsersTrafficPermissions.get(UserHandle.getUserHandleForUid(uid));
if (userTrafficPerms == null) {
Log.wtf(TAG, "Can't get user traffic permission from uid=" + uid);
return;
}
// Do not put PERMISSION_UNINSTALLED into the array. If no package left on the uid
// (PERMISSION_UNINSTALLED), remove the appId from the array. Otherwise, update the latest
// permission to the appId.
final int appId = UserHandle.getAppId(uid);
if (uidTrafficPerm == PERMISSION_UNINSTALLED) {
userTrafficPerms.delete(appId);
} else {
userTrafficPerms.put(appId, uidTrafficPerm);
}
}
private synchronized int getAppIdTrafficPermission(int appId) {
int permission = PERMISSION_NONE;
boolean installed = false;
for (UserHandle user : mUsersTrafficPermissions.keySet()) {
final SparseIntArray userApps = mUsersTrafficPermissions.get(user);
final int appIdx = userApps.indexOfKey(appId);
if (appIdx >= 0) {
permission |= userApps.valueAt(appIdx);
installed = true;
}
}
return installed ? permission : PERMISSION_UNINSTALLED;
}
/**
* Called when a package is added.
*
* @param packageName The name of the new package.
* @param uid The uid of the new package.
*
* @hide
*/
public synchronized void onPackageAdded(@NonNull final String packageName, final int uid) {
// Update uid permission.
updateAppIdTrafficPermission(uid);
// Get the appId permission from all users then send the latest permission to netd.
final int appId = UserHandle.getAppId(uid);
final int appIdTrafficPerm = getAppIdTrafficPermission(appId);
sendPackagePermissionsForAppId(appId, appIdTrafficPerm);
final int currentPermission = mUidToNetworkPerm.get(uid, PERMISSION_NONE);
final int permission = highestPermissionForUid(uid, currentPermission, packageName);
if (permission != currentPermission) {
mUidToNetworkPerm.put(uid, permission);
SparseIntArray apps = new SparseIntArray();
apps.put(uid, permission);
if (hasSdkSandbox(uid)) {
int sdkSandboxUid = sProcessShim.toSdkSandboxUid(uid);
mUidToNetworkPerm.put(sdkSandboxUid, permission);
apps.put(sdkSandboxUid, permission);
}
sendUidsNetworkPermission(apps, true /* add */);
}
// If the newly-installed package falls within some VPN's uid range, update Netd with it.
// This needs to happen after the mUidToNetworkPerm update above, since
// hasRestrictedNetworksPermission() in updateVpnUid() and updateLockdownUid() depends on
// mUidToNetworkPerm to check if the package can bypass VPN.
updateVpnUid(uid, true /* add */);
updateLockdownUid(uid, true /* add */);
mAllApps.add(appId);
// Log package added.
mPermissionUpdateLogs.log("Package add: name=" + packageName + ", uid=" + uid
+ ", nPerm=(" + permissionToString(permission) + "/"
+ permissionToString(currentPermission) + ")"
+ ", tPerm=" + permissionToString(appIdTrafficPerm));
}
private int highestUidNetworkPermission(int uid) {
int permission = PERMISSION_NONE;
final String[] packages = mPackageManager.getPackagesForUid(uid);
if (!CollectionUtils.isEmpty(packages)) {
for (String name : packages) {
// If multiple packages have the same UID, give the UID all permissions that
// any package in that UID has.
permission = highestPermissionForUid(uid, permission, name);
if (permission == PERMISSION_SYSTEM) {
break;
}
}
}
return permission;
}
/**
* Called when a package is removed.
*
* @param packageName The name of the removed package or null.
* @param uid containing the integer uid previously assigned to the package.
*
* @hide
*/
public synchronized void onPackageRemoved(@NonNull final String packageName, final int uid) {
// Update uid permission.
updateAppIdTrafficPermission(uid);
// Get the appId permission from all users then send the latest permission to netd.
final int appId = UserHandle.getAppId(uid);
final int appIdTrafficPerm = getAppIdTrafficPermission(appId);
sendPackagePermissionsForAppId(appId, appIdTrafficPerm);
// If the newly-removed package falls within some VPN's uid range, update Netd with it.
// This needs to happen before the mUidToNetworkPerm update below, since
// hasRestrictedNetworksPermission() in updateVpnUid() and updateLockdownUid() depends on
// mUidToNetworkPerm to check if the package can bypass VPN.
updateVpnUid(uid, false /* add */);
updateLockdownUid(uid, false /* add */);
// If the package has been removed from all users on the device, clear it form mAllApps.
if (mPackageManager.getNameForUid(uid) == null) {
mAllApps.remove(appId);
}
final int currentPermission = mUidToNetworkPerm.get(uid, PERMISSION_NONE);
final int permission = highestUidNetworkPermission(uid);
// Log package removed.
mPermissionUpdateLogs.log("Package remove: name=" + packageName + ", uid=" + uid
+ ", nPerm=(" + permissionToString(permission) + "/"
+ permissionToString(currentPermission) + ")"
+ ", tPerm=" + permissionToString(appIdTrafficPerm));
if (permission != currentPermission) {
final SparseIntArray apps = new SparseIntArray();
int sdkSandboxUid = -1;
if (hasSdkSandbox(uid)) {
sdkSandboxUid = sProcessShim.toSdkSandboxUid(uid);
}
if (permission == PERMISSION_NONE) {
mUidToNetworkPerm.delete(uid);
apps.put(uid, PERMISSION_NETWORK); // doesn't matter which permission we pick here
if (sdkSandboxUid != -1) {
mUidToNetworkPerm.delete(sdkSandboxUid);
apps.put(sdkSandboxUid, PERMISSION_NETWORK);
}
sendUidsNetworkPermission(apps, false);
} else {
mUidToNetworkPerm.put(uid, permission);
apps.put(uid, permission);
if (sdkSandboxUid != -1) {
mUidToNetworkPerm.put(sdkSandboxUid, permission);
apps.put(sdkSandboxUid, permission);
}
sendUidsNetworkPermission(apps, true);
}
}
}
private static int getNetdPermissionMask(String[] requestedPermissions,
int[] requestedPermissionsFlags) {
int permissions = PERMISSION_NONE;
if (requestedPermissions == null || requestedPermissionsFlags == null) return permissions;
for (int i = 0; i < requestedPermissions.length; i++) {
if (requestedPermissions[i].equals(INTERNET)
&& ((requestedPermissionsFlags[i] & REQUESTED_PERMISSION_GRANTED) != 0)) {
permissions |= PERMISSION_INTERNET;
}
if (requestedPermissions[i].equals(UPDATE_DEVICE_STATS)
&& ((requestedPermissionsFlags[i] & REQUESTED_PERMISSION_GRANTED) != 0)) {
permissions |= PERMISSION_UPDATE_DEVICE_STATS;
}
}
return permissions;
}
private synchronized PackageManager getPackageManagerAsUser(UserHandle user) {
PackageManager pm = mUsersPackageManager.get(user);
if (pm == null) {
pm = mContext.createContextAsUser(user, 0 /* flag */).getPackageManager();
mUsersPackageManager.put(user, pm);
}
return pm;
}
private PackageInfo getPackageInfoAsUser(String packageName, UserHandle user) {
try {
final PackageInfo info = getPackageManagerAsUser(user)
.getPackageInfo(packageName, GET_PERMISSIONS);
return info;
} catch (NameNotFoundException e) {
// App not found.
loge("NameNotFoundException " + packageName);
return null;
}
}
/**
* Called when a new set of UID ranges are added to an active VPN network
*
* @param iface The active VPN network's interface name. Null iface indicates that the app is
* allowed to receive packets on all interfaces.
* @param rangesToAdd The new UID ranges to be added to the network
* @param vpnAppUid The uid of the VPN app
*/
public synchronized void onVpnUidRangesAdded(@Nullable String iface, Set<UidRange> rangesToAdd,
int vpnAppUid) {
// Calculate the list of new app uids under the VPN due to the new UID ranges and update
// Netd about them. Because mAllApps only contains appIds instead of uids, the result might
// be an overestimation if an app is not installed on the user on which the VPN is running,
// but that's safe: if an app is not installed, it cannot receive any packets, so dropping
// packets to that UID is fine.
final Set<Integer> changedUids = intersectUids(rangesToAdd, mAllApps);
removeBypassingUids(changedUids, vpnAppUid);
updateVpnUidsInterfaceRules(iface, changedUids, true /* add */);
if (mVpnInterfaceUidRanges.containsKey(iface)) {
mVpnInterfaceUidRanges.get(iface).addAll(rangesToAdd);
} else {
mVpnInterfaceUidRanges.put(iface, new HashSet<UidRange>(rangesToAdd));
}
}
/**
* Called when a set of UID ranges are removed from an active VPN network
*
* @param iface The VPN network's interface name. Null iface indicates that the app is allowed
* to receive packets on all interfaces.
* @param rangesToRemove Existing UID ranges to be removed from the VPN network
* @param vpnAppUid The uid of the VPN app
*/
public synchronized void onVpnUidRangesRemoved(@Nullable String iface,
Set<UidRange> rangesToRemove, int vpnAppUid) {
// Calculate the list of app uids that are no longer under the VPN due to the removed UID
// ranges and update Netd about them.
final Set<Integer> changedUids = intersectUids(rangesToRemove, mAllApps);
removeBypassingUids(changedUids, vpnAppUid);
updateVpnUidsInterfaceRules(iface, changedUids, false /* add */);
Set<UidRange> existingRanges = mVpnInterfaceUidRanges.getOrDefault(iface, null);
if (existingRanges == null) {
loge("Attempt to remove unknown vpn uid Range iface = " + iface);
return;
}
existingRanges.removeAll(rangesToRemove);
if (existingRanges.size() == 0) {
mVpnInterfaceUidRanges.remove(iface);
}
}
/**
* Called when UID ranges under VPN Lockdown are updated
*
* @param add {@code true} if the uids are to be added to the Lockdown, {@code false} if they
* are to be removed from the Lockdown.
* @param ranges The updated UID ranges under VPN Lockdown. This function does not treat the VPN
* app's UID in any special way. The caller is responsible for excluding the VPN
* app UID from the passed-in ranges.
* Ranges can have duplications and/or contain the range that is already subject
* to lockdown. However, ranges can not have overlaps with other ranges including
* ranges that are currently subject to lockdown.
*/
public synchronized void updateVpnLockdownUidRanges(boolean add, UidRange[] ranges) {
final Set<UidRange> affectedUidRanges = new HashSet<>();
for (final UidRange range : ranges) {
if (add) {
// Rule will be added if mVpnLockdownUidRanges does not have this uid range entry
// currently.
if (mVpnLockdownUidRanges.add(range) == 0) {
affectedUidRanges.add(range);
}
} else {
// Rule will be removed if the number of the range in the set is 1 before the
// removal.
if (mVpnLockdownUidRanges.remove(range) == 1) {
affectedUidRanges.add(range);
}
}
}
// mAllApps only contains appIds instead of uids. So the generated uid list might contain
// apps that are installed only on some users but not others. But that's safe: if an app is
// not installed, it cannot receive any packets, so dropping packets to that UID is fine.
final Set<Integer> affectedUids = intersectUids(affectedUidRanges, mAllApps);
// We skip adding rule to privileged apps and allow them to bypass incoming packet
// filtering. The behaviour is consistent with how lockdown works for outgoing packets, but
// the implementation is different: while ConnectivityService#setRequireVpnForUids does not
// exclude privileged apps from the prohibit routing rules used to implement outgoing packet
// filtering, privileged apps can still bypass outgoing packet filtering because the
// prohibit rules observe the protected from VPN bit.
for (final int uid: affectedUids) {
if (!hasRestrictedNetworksPermission(uid)) {
updateLockdownUidRule(uid, add);
}
}
}
/**
* Compute the intersection of a set of UidRanges and appIds. Returns a set of uids
* that satisfies:
* 1. falls into one of the UidRange
* 2. matches one of the appIds
*/
private Set<Integer> intersectUids(Set<UidRange> ranges, Set<Integer> appIds) {
Set<Integer> result = new HashSet<>();
for (UidRange range : ranges) {
for (int userId = range.getStartUser(); userId <= range.getEndUser(); userId++) {
for (int appId : appIds) {
final UserHandle handle = UserHandle.of(userId);
if (handle == null) continue;
final int uid = handle.getUid(appId);
if (range.contains(uid)) {
result.add(uid);
}
}
}
}
return result;
}
/**
* Remove all apps which can elect to bypass the VPN from the list of uids
*
* An app can elect to bypass the VPN if it holds SYSTEM permission, or if it's the active VPN
* app itself.
*
* @param uids The list of uids to operate on
* @param vpnAppUid The uid of the VPN app
*/
private void removeBypassingUids(Set<Integer> uids, int vpnAppUid) {
uids.remove(vpnAppUid);
uids.removeIf(this::hasRestrictedNetworksPermission);
}
/**
* Update netd about the list of uids that are under an active VPN connection which they cannot
* bypass.
*
* This is to instruct netd to set up appropriate filtering rules for these uids, such that they
* can only receive ingress packets from the VPN's tunnel interface (and loopback).
* Null iface set up a wildcard rule that allow app to receive packets on all interfaces.
*
* @param iface the interface name of the active VPN connection
* @param add {@code true} if the uids are to be added to the interface, {@code false} if they
* are to be removed from the interface.
*/
private void updateVpnUidsInterfaceRules(String iface, Set<Integer> uids, boolean add) {
if (uids.size() == 0) {
return;
}
try {
if (add) {
mBpfNetMaps.addUidInterfaceRules(iface, toIntArray(uids));
} else {
mBpfNetMaps.removeUidInterfaceRules(toIntArray(uids));
}
} catch (RemoteException | ServiceSpecificException e) {
loge("Exception when updating permissions: ", e);
}
}
private void updateLockdownUidRule(int uid, boolean add) {
try {
if (add) {
mBpfNetMaps.setUidRule(FIREWALL_CHAIN_LOCKDOWN_VPN, uid, FIREWALL_RULE_DENY);
} else {
mBpfNetMaps.setUidRule(FIREWALL_CHAIN_LOCKDOWN_VPN, uid, FIREWALL_RULE_ALLOW);
}
} catch (ServiceSpecificException e) {
loge("Failed to " + (add ? "add" : "remove") + " Lockdown rule: " + e);
}
}
/**
* Send the updated permission information to netd. Called upon package install/uninstall.
*
* @param appId the appId of the package installed
* @param permissions the permissions the app requested and netd cares about.
*
* @hide
*/
@VisibleForTesting
void sendPackagePermissionsForAppId(int appId, int permissions) {
SparseIntArray netdPermissionsAppIds = new SparseIntArray();
netdPermissionsAppIds.put(appId, permissions);
if (hasSdkSandbox(appId)) {
int sdkSandboxAppId = sProcessShim.toSdkSandboxUid(appId);
netdPermissionsAppIds.put(sdkSandboxAppId, permissions);
}
sendAppIdsTrafficPermission(netdPermissionsAppIds);
}
/**
* Grant or revoke the INTERNET and/or UPDATE_DEVICE_STATS permission of the appIds in array.
*
* @param netdPermissionsAppIds integer pairs of appIds and the permission granted to it. If the
* permission is 0, revoke all permissions of that appId.
*
* @hide
*/
@VisibleForTesting
void sendAppIdsTrafficPermission(SparseIntArray netdPermissionsAppIds) {
final ArrayList<Integer> allPermissionAppIds = new ArrayList<>();
final ArrayList<Integer> internetPermissionAppIds = new ArrayList<>();
final ArrayList<Integer> updateStatsPermissionAppIds = new ArrayList<>();
final ArrayList<Integer> noPermissionAppIds = new ArrayList<>();
final ArrayList<Integer> uninstalledAppIds = new ArrayList<>();
for (int i = 0; i < netdPermissionsAppIds.size(); i++) {
int permissions = netdPermissionsAppIds.valueAt(i);
switch(permissions) {
case (PERMISSION_INTERNET | PERMISSION_UPDATE_DEVICE_STATS):
allPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
break;
case PERMISSION_INTERNET:
internetPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
break;
case PERMISSION_UPDATE_DEVICE_STATS:
updateStatsPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
break;
case PERMISSION_NONE:
noPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
break;
case PERMISSION_UNINSTALLED:
uninstalledAppIds.add(netdPermissionsAppIds.keyAt(i));
break;
default:
Log.e(TAG, "unknown permission type: " + permissions + "for uid: "
+ netdPermissionsAppIds.keyAt(i));
}
}
try {
// TODO: add a lock inside netd to protect IPC trafficSetNetPermForUids()
if (allPermissionAppIds.size() != 0) {
mBpfNetMaps.setNetPermForUids(
PERMISSION_INTERNET | PERMISSION_UPDATE_DEVICE_STATS,
toIntArray(allPermissionAppIds));
}
if (internetPermissionAppIds.size() != 0) {
mBpfNetMaps.setNetPermForUids(PERMISSION_INTERNET,
toIntArray(internetPermissionAppIds));
}
if (updateStatsPermissionAppIds.size() != 0) {
mBpfNetMaps.setNetPermForUids(PERMISSION_UPDATE_DEVICE_STATS,
toIntArray(updateStatsPermissionAppIds));
}
if (noPermissionAppIds.size() != 0) {
mBpfNetMaps.setNetPermForUids(PERMISSION_NONE,
toIntArray(noPermissionAppIds));
}
if (uninstalledAppIds.size() != 0) {
mBpfNetMaps.setNetPermForUids(PERMISSION_UNINSTALLED,
toIntArray(uninstalledAppIds));
}
} catch (RemoteException | ServiceSpecificException e) {
Log.e(TAG, "Pass appId list of special permission failed." + e);
}
}
/** Should only be used by unit tests */
@VisibleForTesting
public Set<UidRange> getVpnInterfaceUidRanges(String iface) {
return mVpnInterfaceUidRanges.get(iface);
}
/** Should only be used by unit tests */
@VisibleForTesting
public Set<UidRange> getVpnLockdownUidRanges() {
return mVpnLockdownUidRanges.getSet();
}
private synchronized void onSettingChanged() {
// Step1. Update uids allowed to use restricted networks and compute the set of uids to
// update.
final Set<Integer> uidsToUpdate = new ArraySet<>(mUidsAllowedOnRestrictedNetworks);
updateUidsAllowedOnRestrictedNetworks(mDeps.getUidsAllowedOnRestrictedNetworks(mContext));
uidsToUpdate.addAll(mUidsAllowedOnRestrictedNetworks);
final SparseIntArray updatedUids = new SparseIntArray();
final SparseIntArray removedUids = new SparseIntArray();
// Step2. For each uid to update, find out its new permission.
for (Integer uid : uidsToUpdate) {
final int permission = highestUidNetworkPermission(uid);
if (PERMISSION_NONE == permission) {
// Doesn't matter which permission is set here.
removedUids.put(uid, PERMISSION_NETWORK);
mUidToNetworkPerm.delete(uid);
if (hasSdkSandbox(uid)) {
int sdkSandboxUid = sProcessShim.toSdkSandboxUid(uid);
removedUids.put(sdkSandboxUid, PERMISSION_NETWORK);
mUidToNetworkPerm.delete(sdkSandboxUid);
}
} else {
updatedUids.put(uid, permission);
mUidToNetworkPerm.put(uid, permission);
if (hasSdkSandbox(uid)) {
int sdkSandboxUid = sProcessShim.toSdkSandboxUid(uid);
updatedUids.put(sdkSandboxUid, permission);
mUidToNetworkPerm.put(sdkSandboxUid, permission);
}
}
}
// Step3. Update or revoke permission for uids with netd.
sendUidsNetworkPermission(updatedUids, true /* add */);
sendUidsNetworkPermission(removedUids, false /* add */);
mPermissionUpdateLogs.log("Setting change: update=" + updatedUids
+ ", remove=" + removedUids);
}
private synchronized void onExternalApplicationsAvailable(String[] pkgList) {
if (CollectionUtils.isEmpty(pkgList)) {
Log.e(TAG, "No available external application.");
return;
}
for (String app : pkgList) {
for (UserHandle user : mUsers) {
final PackageInfo info = getPackageInfoAsUser(app, user);
if (info == null || info.applicationInfo == null) continue;
final int uid = info.applicationInfo.uid;
onPackageAdded(app, uid); // Use onPackageAdded to add package one by one.
}
}
}
/** Dump info to dumpsys */
public void dump(IndentingPrintWriter pw) {
pw.println("Interface filtering rules:");
pw.increaseIndent();
for (Map.Entry<String, Set<UidRange>> vpn : mVpnInterfaceUidRanges.entrySet()) {
pw.println("Interface: " + vpn.getKey());
pw.println("UIDs: " + vpn.getValue().toString());
pw.println();
}
pw.decreaseIndent();
pw.println();
pw.println("Lockdown filtering rules:");
pw.increaseIndent();
for (final UidRange range : mVpnLockdownUidRanges.getSet()) {
pw.println("UIDs: " + range.toString());
}
pw.decreaseIndent();
pw.println();
pw.println("Update logs:");
pw.increaseIndent();
mPermissionUpdateLogs.reverseDump(pw);
pw.decreaseIndent();
}
private static void log(String s) {
if (DBG) {
Log.d(TAG, s);
}
}
private static void loge(String s) {
Log.e(TAG, s);
}
private static void loge(String s, Throwable e) {
Log.e(TAG, s, e);
}
}
|