blob: 18c6a3d0b361bdd17dea80a2a91ca5251b45bd1f [file] [log] [blame]
Todd Kennedy0eb97382017-10-03 16:57:22 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm.permission;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
Todd Kennedy3bc94722017-10-10 09:55:53 -070021import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
Hongwei Wangf391b552018-04-06 13:52:46 -070022import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
23
Todd Kennedyc29b11a2017-10-23 15:55:59 -070024import static com.android.server.pm.PackageManagerService.DEBUG_INSTALL;
25import static com.android.server.pm.PackageManagerService.DEBUG_PACKAGE_SCANNING;
26import static com.android.server.pm.PackageManagerService.DEBUG_PERMISSIONS;
27import static com.android.server.pm.PackageManagerService.DEBUG_REMOVE;
28import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
Todd Kennedy0eb97382017-10-03 16:57:22 -070029
30import android.Manifest;
31import android.annotation.NonNull;
32import android.annotation.Nullable;
Todd Kennedy0eb97382017-10-03 16:57:22 -070033import android.content.Context;
34import android.content.pm.PackageManager;
35import android.content.pm.PackageManagerInternal;
36import android.content.pm.PackageParser;
Hongwei Wangf391b552018-04-06 13:52:46 -070037import android.content.pm.PackageParser.Package;
Todd Kennedy460f28c2017-10-06 13:46:22 -070038import android.content.pm.PermissionGroupInfo;
Todd Kennedy0eb97382017-10-03 16:57:22 -070039import android.content.pm.PermissionInfo;
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -070040import android.metrics.LogMaker;
Todd Kennedy0eb97382017-10-03 16:57:22 -070041import android.os.Binder;
42import android.os.Build;
43import android.os.Handler;
44import android.os.HandlerThread;
45import android.os.Process;
Todd Kennedyc29b11a2017-10-23 15:55:59 -070046import android.os.Trace;
Todd Kennedy0eb97382017-10-03 16:57:22 -070047import android.os.UserHandle;
48import android.os.UserManager;
49import android.os.UserManagerInternal;
Todd Kennedyc29b11a2017-10-23 15:55:59 -070050import android.os.storage.StorageManager;
Todd Kennedy0eb97382017-10-03 16:57:22 -070051import android.os.storage.StorageManagerInternal;
Todd Kennedyc29b11a2017-10-23 15:55:59 -070052import android.text.TextUtils;
Todd Kennedy0eb97382017-10-03 16:57:22 -070053import android.util.ArrayMap;
54import android.util.ArraySet;
Philip P. Moltmannfae8a5282018-04-10 12:15:32 -070055import android.util.EventLog;
Todd Kennedy0eb97382017-10-03 16:57:22 -070056import android.util.Log;
57import android.util.Slog;
Todd Kennedy3bc94722017-10-10 09:55:53 -070058import android.util.SparseArray;
Todd Kennedy0eb97382017-10-03 16:57:22 -070059
Todd Kennedyc29b11a2017-10-23 15:55:59 -070060import com.android.internal.annotations.GuardedBy;
Todd Kennedy0eb97382017-10-03 16:57:22 -070061import com.android.internal.logging.MetricsLogger;
62import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Todd Kennedyc29b11a2017-10-23 15:55:59 -070063import com.android.internal.os.RoSystemProperties;
Todd Kennedy0eb97382017-10-03 16:57:22 -070064import com.android.internal.util.ArrayUtils;
Todd Kennedy0eb97382017-10-03 16:57:22 -070065import com.android.server.LocalServices;
66import com.android.server.ServiceThread;
67import com.android.server.SystemConfig;
68import com.android.server.Watchdog;
Todd Kennedy0eb97382017-10-03 16:57:22 -070069import com.android.server.pm.PackageManagerServiceUtils;
70import com.android.server.pm.PackageSetting;
Todd Kennedy0eb97382017-10-03 16:57:22 -070071import com.android.server.pm.SharedUserSetting;
Todd Kennedy3bc94722017-10-10 09:55:53 -070072import com.android.server.pm.UserManagerService;
Hongwei Wangf391b552018-04-06 13:52:46 -070073import com.android.server.pm.permission.DefaultPermissionGrantPolicy
74 .DefaultPermissionGrantedCallback;
Todd Kennedy0eb97382017-10-03 16:57:22 -070075import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
76import com.android.server.pm.permission.PermissionsState.PermissionState;
77
78import libcore.util.EmptyArray;
79
80import java.util.ArrayList;
Todd Kennedy0eb97382017-10-03 16:57:22 -070081import java.util.Collection;
Hongwei Wangf391b552018-04-06 13:52:46 -070082import java.util.HashMap;
Todd Kennedy0eb97382017-10-03 16:57:22 -070083import java.util.Iterator;
84import java.util.List;
Hongwei Wangf391b552018-04-06 13:52:46 -070085import java.util.Map;
Todd Kennedyc29b11a2017-10-23 15:55:59 -070086import java.util.Objects;
Todd Kennedyc8423932017-10-05 08:58:36 -070087import java.util.Set;
Todd Kennedy0eb97382017-10-03 16:57:22 -070088
89/**
90 * Manages all permissions and handles permissions related tasks.
91 */
92public class PermissionManagerService {
93 private static final String TAG = "PackageManager";
94
Todd Kennedyc29b11a2017-10-23 15:55:59 -070095 /** Permission grant: not grant the permission. */
96 private static final int GRANT_DENIED = 1;
97 /** Permission grant: grant the permission as an install permission. */
98 private static final int GRANT_INSTALL = 2;
99 /** Permission grant: grant the permission as a runtime one. */
100 private static final int GRANT_RUNTIME = 3;
101 /** Permission grant: grant as runtime a permission that was granted as an install time one. */
102 private static final int GRANT_UPGRADE = 4;
103
104 /** Cap the size of permission trees that 3rd party apps can define; in characters of text */
105 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;
106 /** Empty array to avoid allocations */
107 private static final int[] EMPTY_INT_ARRAY = new int[0];
Todd Kennedy0eb97382017-10-03 16:57:22 -0700108
Hongwei Wangf391b552018-04-06 13:52:46 -0700109 /** If the permission of the value is granted, so is the key */
110 private static final Map<String, String> FULLER_PERMISSION_MAP = new HashMap<>();
111
112 static {
113 FULLER_PERMISSION_MAP.put(Manifest.permission.ACCESS_COARSE_LOCATION,
114 Manifest.permission.ACCESS_FINE_LOCATION);
115 FULLER_PERMISSION_MAP.put(Manifest.permission.INTERACT_ACROSS_USERS,
116 Manifest.permission.INTERACT_ACROSS_USERS_FULL);
117 }
118
Todd Kennedy0eb97382017-10-03 16:57:22 -0700119 /** Lock to protect internal data access */
120 private final Object mLock;
121
122 /** Internal connection to the package manager */
123 private final PackageManagerInternal mPackageManagerInt;
124
125 /** Internal connection to the user manager */
126 private final UserManagerInternal mUserManagerInt;
127
128 /** Default permission policy to provide proper behaviour out-of-the-box */
129 private final DefaultPermissionGrantPolicy mDefaultPermissionGrantPolicy;
130
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700131 /**
132 * Built-in permissions. Read from system configuration files. Mapping is from
133 * UID to permission name.
134 */
Todd Kennedy3bc94722017-10-10 09:55:53 -0700135 private final SparseArray<ArraySet<String>> mSystemPermissions;
Todd Kennedy3bc94722017-10-10 09:55:53 -0700136
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700137 /** Built-in group IDs given to all packages. Read from system configuration files. */
138 private final int[] mGlobalGids;
Todd Kennedy0eb97382017-10-03 16:57:22 -0700139
140 private final HandlerThread mHandlerThread;
141 private final Handler mHandler;
142 private final Context mContext;
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -0700143 private final MetricsLogger mMetricsLogger = new MetricsLogger();
Todd Kennedy0eb97382017-10-03 16:57:22 -0700144
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700145 /** Internal storage for permissions and related settings */
146 @GuardedBy("mLock")
147 private final PermissionSettings mSettings;
148
149 @GuardedBy("mLock")
150 private ArraySet<String> mPrivappPermissionsViolations;
151
152 @GuardedBy("mLock")
153 private boolean mSystemReady;
154
Todd Kennedy0eb97382017-10-03 16:57:22 -0700155 PermissionManagerService(Context context,
156 @Nullable DefaultPermissionGrantedCallback defaultGrantCallback,
157 @NonNull Object externalLock) {
158 mContext = context;
159 mLock = externalLock;
160 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
161 mUserManagerInt = LocalServices.getService(UserManagerInternal.class);
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700162 mSettings = new PermissionSettings(mLock);
Todd Kennedy0eb97382017-10-03 16:57:22 -0700163
164 mHandlerThread = new ServiceThread(TAG,
165 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
166 mHandlerThread.start();
167 mHandler = new Handler(mHandlerThread.getLooper());
168 Watchdog.getInstance().addThread(mHandler);
169
170 mDefaultPermissionGrantPolicy = new DefaultPermissionGrantPolicy(
171 context, mHandlerThread.getLooper(), defaultGrantCallback, this);
Todd Kennedy3bc94722017-10-10 09:55:53 -0700172 SystemConfig systemConfig = SystemConfig.getInstance();
173 mSystemPermissions = systemConfig.getSystemPermissions();
174 mGlobalGids = systemConfig.getGlobalGids();
Todd Kennedy0eb97382017-10-03 16:57:22 -0700175
176 // propagate permission configuration
177 final ArrayMap<String, SystemConfig.PermissionEntry> permConfig =
178 SystemConfig.getInstance().getPermissions();
179 synchronized (mLock) {
180 for (int i=0; i<permConfig.size(); i++) {
181 final SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
182 BasePermission bp = mSettings.getPermissionLocked(perm.name);
183 if (bp == null) {
184 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
185 mSettings.putPermissionLocked(perm.name, bp);
186 }
187 if (perm.gids != null) {
188 bp.setGids(perm.gids, perm.perUser);
189 }
190 }
191 }
192
193 LocalServices.addService(
194 PermissionManagerInternal.class, new PermissionManagerInternalImpl());
195 }
196
197 /**
198 * Creates and returns an initialized, internal service for use by other components.
199 * <p>
200 * The object returned is identical to the one returned by the LocalServices class using:
201 * {@code LocalServices.getService(PermissionManagerInternal.class);}
202 * <p>
203 * NOTE: The external lock is temporary and should be removed. This needs to be a
204 * lock created by the permission manager itself.
205 */
206 public static PermissionManagerInternal create(Context context,
207 @Nullable DefaultPermissionGrantedCallback defaultGrantCallback,
208 @NonNull Object externalLock) {
209 final PermissionManagerInternal permMgrInt =
210 LocalServices.getService(PermissionManagerInternal.class);
211 if (permMgrInt != null) {
212 return permMgrInt;
213 }
214 new PermissionManagerService(context, defaultGrantCallback, externalLock);
215 return LocalServices.getService(PermissionManagerInternal.class);
216 }
217
218 @Nullable BasePermission getPermission(String permName) {
219 synchronized (mLock) {
220 return mSettings.getPermissionLocked(permName);
221 }
222 }
223
224 private int checkPermission(String permName, String pkgName, int callingUid, int userId) {
225 if (!mUserManagerInt.exists(userId)) {
226 return PackageManager.PERMISSION_DENIED;
227 }
228
Patrick Baumann97b9b532018-04-11 14:51:30 +0000229 final PackageParser.Package pkg = mPackageManagerInt.getPackage(pkgName);
230 if (pkg != null && pkg.mExtras != null) {
231 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700232 return PackageManager.PERMISSION_DENIED;
233 }
Patrick Baumann97b9b532018-04-11 14:51:30 +0000234 final PackageSetting ps = (PackageSetting) pkg.mExtras;
Todd Kennedy0eb97382017-10-03 16:57:22 -0700235 final boolean instantApp = ps.getInstantApp(userId);
236 final PermissionsState permissionsState = ps.getPermissionsState();
237 if (permissionsState.hasPermission(permName, userId)) {
238 if (instantApp) {
239 synchronized (mLock) {
240 BasePermission bp = mSettings.getPermissionLocked(permName);
241 if (bp != null && bp.isInstant()) {
242 return PackageManager.PERMISSION_GRANTED;
243 }
244 }
245 } else {
246 return PackageManager.PERMISSION_GRANTED;
247 }
248 }
Hongwei Wangf391b552018-04-06 13:52:46 -0700249 if (isImpliedPermissionGranted(permissionsState, permName, userId)) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700250 return PackageManager.PERMISSION_GRANTED;
251 }
252 }
253
254 return PackageManager.PERMISSION_DENIED;
255 }
256
Todd Kennedy3c714492017-10-27 09:12:50 -0700257 private int checkUidPermission(String permName, PackageParser.Package pkg, int uid,
258 int callingUid) {
Todd Kennedy3bc94722017-10-10 09:55:53 -0700259 final int callingUserId = UserHandle.getUserId(callingUid);
260 final boolean isCallerInstantApp =
261 mPackageManagerInt.getInstantAppPackageName(callingUid) != null;
262 final boolean isUidInstantApp =
263 mPackageManagerInt.getInstantAppPackageName(uid) != null;
264 final int userId = UserHandle.getUserId(uid);
265 if (!mUserManagerInt.exists(userId)) {
266 return PackageManager.PERMISSION_DENIED;
267 }
268
Todd Kennedy3c714492017-10-27 09:12:50 -0700269 if (pkg != null) {
Todd Kennedy3bc94722017-10-10 09:55:53 -0700270 if (pkg.mSharedUserId != null) {
271 if (isCallerInstantApp) {
272 return PackageManager.PERMISSION_DENIED;
273 }
Todd Kennedy3c714492017-10-27 09:12:50 -0700274 } else if (mPackageManagerInt.filterAppAccess(pkg, callingUid, callingUserId)) {
275 return PackageManager.PERMISSION_DENIED;
Todd Kennedy3bc94722017-10-10 09:55:53 -0700276 }
277 final PermissionsState permissionsState =
278 ((PackageSetting) pkg.mExtras).getPermissionsState();
279 if (permissionsState.hasPermission(permName, userId)) {
280 if (isUidInstantApp) {
281 if (mSettings.isPermissionInstant(permName)) {
282 return PackageManager.PERMISSION_GRANTED;
283 }
284 } else {
285 return PackageManager.PERMISSION_GRANTED;
286 }
287 }
Hongwei Wangf391b552018-04-06 13:52:46 -0700288 if (isImpliedPermissionGranted(permissionsState, permName, userId)) {
Todd Kennedy3bc94722017-10-10 09:55:53 -0700289 return PackageManager.PERMISSION_GRANTED;
290 }
291 } else {
292 ArraySet<String> perms = mSystemPermissions.get(uid);
293 if (perms != null) {
294 if (perms.contains(permName)) {
295 return PackageManager.PERMISSION_GRANTED;
296 }
Hongwei Wangf391b552018-04-06 13:52:46 -0700297 if (FULLER_PERMISSION_MAP.containsKey(permName)
298 && perms.contains(FULLER_PERMISSION_MAP.get(permName))) {
Todd Kennedy3bc94722017-10-10 09:55:53 -0700299 return PackageManager.PERMISSION_GRANTED;
300 }
301 }
302 }
303 return PackageManager.PERMISSION_DENIED;
304 }
305
Hongwei Wangf391b552018-04-06 13:52:46 -0700306 /**
307 * Returns {@code true} if the permission can be implied from another granted permission.
308 * <p>Some permissions, such as ACCESS_FINE_LOCATION, imply other permissions,
309 * such as ACCESS_COURSE_LOCATION. If the caller holds an umbrella permission, give
310 * it access to any implied permissions.
311 */
312 private static boolean isImpliedPermissionGranted(PermissionsState permissionsState,
313 String permName, int userId) {
314 return FULLER_PERMISSION_MAP.containsKey(permName)
315 && permissionsState.hasPermission(FULLER_PERMISSION_MAP.get(permName), userId);
316 }
317
Todd Kennedy460f28c2017-10-06 13:46:22 -0700318 private PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags,
319 int callingUid) {
320 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
321 return null;
322 }
323 synchronized (mLock) {
324 return PackageParser.generatePermissionGroupInfo(
325 mSettings.mPermissionGroups.get(groupName), flags);
326 }
327 }
328
329 private List<PermissionGroupInfo> getAllPermissionGroups(int flags, int callingUid) {
330 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
331 return null;
332 }
333 synchronized (mLock) {
334 final int N = mSettings.mPermissionGroups.size();
335 final ArrayList<PermissionGroupInfo> out
336 = new ArrayList<PermissionGroupInfo>(N);
337 for (PackageParser.PermissionGroup pg : mSettings.mPermissionGroups.values()) {
338 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
339 }
340 return out;
341 }
342 }
343
344 private PermissionInfo getPermissionInfo(String permName, String packageName, int flags,
Todd Kennedy0eb97382017-10-03 16:57:22 -0700345 int callingUid) {
346 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
347 return null;
348 }
349 // reader
350 synchronized (mLock) {
Todd Kennedy460f28c2017-10-06 13:46:22 -0700351 final BasePermission bp = mSettings.getPermissionLocked(permName);
Todd Kennedy0eb97382017-10-03 16:57:22 -0700352 if (bp == null) {
353 return null;
354 }
355 final int adjustedProtectionLevel = adjustPermissionProtectionFlagsLocked(
356 bp.getProtectionLevel(), packageName, callingUid);
357 return bp.generatePermissionInfo(adjustedProtectionLevel, flags);
358 }
359 }
360
361 private List<PermissionInfo> getPermissionInfoByGroup(
362 String groupName, int flags, int callingUid) {
363 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
364 return null;
365 }
Todd Kennedy0eb97382017-10-03 16:57:22 -0700366 synchronized (mLock) {
Todd Kennedy460f28c2017-10-06 13:46:22 -0700367 if (groupName != null && !mSettings.mPermissionGroups.containsKey(groupName)) {
368 return null;
369 }
Todd Kennedy0eb97382017-10-03 16:57:22 -0700370 final ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
Todd Kennedyc8423932017-10-05 08:58:36 -0700371 for (BasePermission bp : mSettings.mPermissions.values()) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700372 final PermissionInfo pi = bp.generatePermissionInfo(groupName, flags);
373 if (pi != null) {
374 out.add(pi);
375 }
376 }
377 return out;
378 }
379 }
380
381 private int adjustPermissionProtectionFlagsLocked(
382 int protectionLevel, String packageName, int uid) {
383 // Signature permission flags area always reported
384 final int protectionLevelMasked = protectionLevel
385 & (PermissionInfo.PROTECTION_NORMAL
386 | PermissionInfo.PROTECTION_DANGEROUS
387 | PermissionInfo.PROTECTION_SIGNATURE);
388 if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
389 return protectionLevel;
390 }
391 // System sees all flags.
392 final int appId = UserHandle.getAppId(uid);
393 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
394 || appId == Process.SHELL_UID) {
395 return protectionLevel;
396 }
397 // Normalize package name to handle renamed packages and static libs
398 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
399 if (pkg == null) {
400 return protectionLevel;
401 }
402 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
403 return protectionLevelMasked;
404 }
405 // Apps that target O see flags for all protection levels.
406 final PackageSetting ps = (PackageSetting) pkg.mExtras;
407 if (ps == null) {
408 return protectionLevel;
409 }
410 if (ps.getAppId() != appId) {
411 return protectionLevel;
412 }
413 return protectionLevel;
414 }
415
Philip P. Moltmannfae8a5282018-04-10 12:15:32 -0700416 /**
417 * We might auto-grant permissions if any permission of the group is already granted. Hence if
418 * the group of a granted permission changes we need to revoke it to avoid having permissions of
419 * the new group auto-granted.
420 *
421 * @param newPackage The new package that was installed
422 * @param oldPackage The old package that was updated
423 * @param allPackageNames All package names
424 * @param permissionCallback Callback for permission changed
425 */
426 private void revokeRuntimePermissionsIfGroupChanged(
427 @NonNull PackageParser.Package newPackage,
428 @NonNull PackageParser.Package oldPackage,
429 @NonNull ArrayList<String> allPackageNames,
430 @NonNull PermissionCallback permissionCallback) {
431 final int numOldPackagePermissions = oldPackage.permissions.size();
432 final ArrayMap<String, String> oldPermissionNameToGroupName
433 = new ArrayMap<>(numOldPackagePermissions);
434
435 for (int i = 0; i < numOldPackagePermissions; i++) {
436 final PackageParser.Permission permission = oldPackage.permissions.get(i);
437
438 if (permission.group != null) {
439 oldPermissionNameToGroupName.put(permission.info.name,
440 permission.group.info.name);
441 }
442 }
443
444 final int numNewPackagePermissions = newPackage.permissions.size();
445 for (int newPermissionNum = 0; newPermissionNum < numNewPackagePermissions;
446 newPermissionNum++) {
447 final PackageParser.Permission newPermission =
448 newPackage.permissions.get(newPermissionNum);
449 final int newProtection = newPermission.info.getProtection();
450
451 if ((newProtection & PermissionInfo.PROTECTION_DANGEROUS) != 0) {
452 final String permissionName = newPermission.info.name;
453 final String newPermissionGroupName =
454 newPermission.group == null ? null : newPermission.group.info.name;
455 final String oldPermissionGroupName = oldPermissionNameToGroupName.get(
456 permissionName);
457
458 if (newPermissionGroupName != null
459 && !newPermissionGroupName.equals(oldPermissionGroupName)) {
460 final int[] userIds = mUserManagerInt.getUserIds();
461 final int numUserIds = userIds.length;
462 for (int userIdNum = 0; userIdNum < numUserIds; userIdNum++) {
463 final int userId = userIds[userIdNum];
464
465 final int numPackages = allPackageNames.size();
466 for (int packageNum = 0; packageNum < numPackages; packageNum++) {
467 final String packageName = allPackageNames.get(packageNum);
468
469 if (checkPermission(permissionName, packageName, UserHandle.USER_SYSTEM,
470 userId) == PackageManager.PERMISSION_GRANTED) {
471 EventLog.writeEvent(0x534e4554, "72710897",
472 newPackage.applicationInfo.uid,
Koji Fukuiacae3ef2018-05-09 11:38:01 +0900473 "Revoking permission " + permissionName +
474 " from package " + packageName +
475 " as the group changed from " + oldPermissionGroupName +
476 " to " + newPermissionGroupName);
Philip P. Moltmannfae8a5282018-04-10 12:15:32 -0700477
478 try {
Hongming Jinae750fb2018-09-27 23:00:20 +0000479 revokeRuntimePermission(permissionName, packageName, false,
480 Process.SYSTEM_UID, userId, permissionCallback);
Philip P. Moltmannfae8a5282018-04-10 12:15:32 -0700481 } catch (IllegalArgumentException e) {
482 Slog.e(TAG, "Could not revoke " + permissionName + " from "
483 + packageName, e);
484 }
485 }
486 }
487 }
488 }
489 }
490 }
491 }
492
Todd Kennedyc8423932017-10-05 08:58:36 -0700493 private void addAllPermissions(PackageParser.Package pkg, boolean chatty) {
494 final int N = pkg.permissions.size();
495 for (int i=0; i<N; i++) {
496 PackageParser.Permission p = pkg.permissions.get(i);
497
498 // Assume by default that we did not install this permission into the system.
499 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
500
Todd Kennedyc8423932017-10-05 08:58:36 -0700501 synchronized (PermissionManagerService.this.mLock) {
Todd Kennedy460f28c2017-10-06 13:46:22 -0700502 // Now that permission groups have a special meaning, we ignore permission
503 // groups for legacy apps to prevent unexpected behavior. In particular,
504 // permissions for one app being granted to someone just because they happen
505 // to be in a group defined by another app (before this had no implications).
506 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
507 p.group = mSettings.mPermissionGroups.get(p.info.group);
508 // Warn for a permission in an unknown group.
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700509 if (DEBUG_PERMISSIONS
Todd Kennedy460f28c2017-10-06 13:46:22 -0700510 && p.info.group != null && p.group == null) {
511 Slog.i(TAG, "Permission " + p.info.name + " from package "
512 + p.info.packageName + " in an unknown group " + p.info.group);
513 }
514 }
515
Todd Kennedyc8423932017-10-05 08:58:36 -0700516 if (p.tree) {
517 final BasePermission bp = BasePermission.createOrUpdate(
518 mSettings.getPermissionTreeLocked(p.info.name), p, pkg,
519 mSettings.getAllPermissionTreesLocked(), chatty);
520 mSettings.putPermissionTreeLocked(p.info.name, bp);
521 } else {
522 final BasePermission bp = BasePermission.createOrUpdate(
523 mSettings.getPermissionLocked(p.info.name),
524 p, pkg, mSettings.getAllPermissionTreesLocked(), chatty);
525 mSettings.putPermissionLocked(p.info.name, bp);
526 }
527 }
528 }
529 }
530
Todd Kennedy460f28c2017-10-06 13:46:22 -0700531 private void addAllPermissionGroups(PackageParser.Package pkg, boolean chatty) {
532 final int N = pkg.permissionGroups.size();
533 StringBuilder r = null;
534 for (int i=0; i<N; i++) {
535 final PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
536 final PackageParser.PermissionGroup cur = mSettings.mPermissionGroups.get(pg.info.name);
537 final String curPackageName = (cur == null) ? null : cur.info.packageName;
538 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
539 if (cur == null || isPackageUpdate) {
540 mSettings.mPermissionGroups.put(pg.info.name, pg);
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700541 if (chatty && DEBUG_PACKAGE_SCANNING) {
Todd Kennedy460f28c2017-10-06 13:46:22 -0700542 if (r == null) {
543 r = new StringBuilder(256);
544 } else {
545 r.append(' ');
546 }
547 if (isPackageUpdate) {
548 r.append("UPD:");
549 }
550 r.append(pg.info.name);
551 }
552 } else {
553 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
554 + pg.info.packageName + " ignored: original from "
555 + cur.info.packageName);
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700556 if (chatty && DEBUG_PACKAGE_SCANNING) {
Todd Kennedy460f28c2017-10-06 13:46:22 -0700557 if (r == null) {
558 r = new StringBuilder(256);
559 } else {
560 r.append(' ');
561 }
562 r.append("DUP:");
563 r.append(pg.info.name);
564 }
565 }
566 }
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700567 if (r != null && DEBUG_PACKAGE_SCANNING) {
Todd Kennedy460f28c2017-10-06 13:46:22 -0700568 Log.d(TAG, " Permission Groups: " + r);
569 }
570
571 }
572
Hongming Jinae750fb2018-09-27 23:00:20 +0000573 private void removeAllPermissions(PackageParser.Package pkg, boolean chatty) {
Todd Kennedyc8423932017-10-05 08:58:36 -0700574 synchronized (mLock) {
575 int N = pkg.permissions.size();
576 StringBuilder r = null;
577 for (int i=0; i<N; i++) {
578 PackageParser.Permission p = pkg.permissions.get(i);
579 BasePermission bp = (BasePermission) mSettings.mPermissions.get(p.info.name);
580 if (bp == null) {
581 bp = mSettings.mPermissionTrees.get(p.info.name);
582 }
583 if (bp != null && bp.isPermission(p)) {
584 bp.setPermission(null);
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700585 if (DEBUG_REMOVE && chatty) {
Todd Kennedyc8423932017-10-05 08:58:36 -0700586 if (r == null) {
587 r = new StringBuilder(256);
588 } else {
589 r.append(' ');
590 }
591 r.append(p.info.name);
592 }
593 }
594 if (p.isAppOp()) {
595 ArraySet<String> appOpPkgs =
596 mSettings.mAppOpPermissionPackages.get(p.info.name);
597 if (appOpPkgs != null) {
598 appOpPkgs.remove(pkg.packageName);
599 }
600 }
601 }
602 if (r != null) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700603 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
Todd Kennedyc8423932017-10-05 08:58:36 -0700604 }
605
606 N = pkg.requestedPermissions.size();
607 r = null;
608 for (int i=0; i<N; i++) {
609 String perm = pkg.requestedPermissions.get(i);
610 if (mSettings.isPermissionAppOp(perm)) {
611 ArraySet<String> appOpPkgs = mSettings.mAppOpPermissionPackages.get(perm);
612 if (appOpPkgs != null) {
613 appOpPkgs.remove(pkg.packageName);
614 if (appOpPkgs.isEmpty()) {
615 mSettings.mAppOpPermissionPackages.remove(perm);
616 }
617 }
618 }
619 }
620 if (r != null) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700621 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
Todd Kennedyc8423932017-10-05 08:58:36 -0700622 }
623 }
624 }
625
626 private boolean addDynamicPermission(
Todd Kennedy0eb97382017-10-03 16:57:22 -0700627 PermissionInfo info, int callingUid, PermissionCallback callback) {
628 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
629 throw new SecurityException("Instant apps can't add permissions");
630 }
631 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
632 throw new SecurityException("Label must be specified in permission");
633 }
Todd Kennedyc8423932017-10-05 08:58:36 -0700634 final BasePermission tree = mSettings.enforcePermissionTree(info.name, callingUid);
Todd Kennedy0eb97382017-10-03 16:57:22 -0700635 final boolean added;
636 final boolean changed;
637 synchronized (mLock) {
638 BasePermission bp = mSettings.getPermissionLocked(info.name);
639 added = bp == null;
640 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
641 if (added) {
642 enforcePermissionCapLocked(info, tree);
643 bp = new BasePermission(info.name, tree.getSourcePackageName(),
644 BasePermission.TYPE_DYNAMIC);
Svet Ganov2808cbc2018-05-09 15:27:43 -0700645 } else if (!bp.isDynamic()) {
646 throw new SecurityException("Not allowed to modify non-dynamic permission "
Todd Kennedy0eb97382017-10-03 16:57:22 -0700647 + info.name);
648 }
649 changed = bp.addToTree(fixedLevel, info, tree);
650 if (added) {
651 mSettings.putPermissionLocked(info.name, bp);
652 }
653 }
654 if (changed && callback != null) {
655 callback.onPermissionChanged();
656 }
657 return added;
658 }
659
Todd Kennedyc8423932017-10-05 08:58:36 -0700660 private void removeDynamicPermission(
Todd Kennedy0eb97382017-10-03 16:57:22 -0700661 String permName, int callingUid, PermissionCallback callback) {
662 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
663 throw new SecurityException("Instant applications don't have access to this method");
664 }
Todd Kennedyc8423932017-10-05 08:58:36 -0700665 final BasePermission tree = mSettings.enforcePermissionTree(permName, callingUid);
Todd Kennedy0eb97382017-10-03 16:57:22 -0700666 synchronized (mLock) {
667 final BasePermission bp = mSettings.getPermissionLocked(permName);
668 if (bp == null) {
669 return;
670 }
671 if (bp.isDynamic()) {
Jeff Sharkey4dc50522017-10-17 15:29:41 -0600672 // TODO: switch this back to SecurityException
673 Slog.wtf(TAG, "Not allowed to modify non-dynamic permission "
Todd Kennedy0eb97382017-10-03 16:57:22 -0700674 + permName);
675 }
676 mSettings.removePermissionLocked(permName);
677 if (callback != null) {
678 callback.onPermissionRemoved();
679 }
680 }
681 }
682
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700683 private void grantPermissions(PackageParser.Package pkg, boolean replace,
684 String packageOfInterest, PermissionCallback callback) {
685 // IMPORTANT: There are two types of permissions: install and runtime.
686 // Install time permissions are granted when the app is installed to
687 // all device users and users added in the future. Runtime permissions
688 // are granted at runtime explicitly to specific users. Normal and signature
689 // protected permissions are install time permissions. Dangerous permissions
690 // are install permissions if the app's target SDK is Lollipop MR1 or older,
691 // otherwise they are runtime permissions. This function does not manage
692 // runtime permissions except for the case an app targeting Lollipop MR1
693 // being upgraded to target a newer SDK, in which case dangerous permissions
694 // are transformed from install time to runtime ones.
695
696 final PackageSetting ps = (PackageSetting) pkg.mExtras;
697 if (ps == null) {
698 return;
699 }
700 final boolean isLegacySystemApp = mPackageManagerInt.isLegacySystemApp(pkg);
701
702 final PermissionsState permissionsState = ps.getPermissionsState();
703 PermissionsState origPermissions = permissionsState;
704
705 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
706
707 boolean runtimePermissionsRevoked = false;
708 int[] updatedUserIds = EMPTY_INT_ARRAY;
709
710 boolean changedInstallPermission = false;
711
712 if (replace) {
713 ps.setInstallPermissionsFixed(false);
714 if (!ps.isSharedUser()) {
715 origPermissions = new PermissionsState(permissionsState);
716 permissionsState.reset();
717 } else {
718 // We need to know only about runtime permission changes since the
719 // calling code always writes the install permissions state but
720 // the runtime ones are written only if changed. The only cases of
721 // changed runtime permissions here are promotion of an install to
722 // runtime and revocation of a runtime from a shared user.
723 synchronized (mLock) {
724 updatedUserIds = revokeUnusedSharedUserPermissionsLocked(
725 ps.getSharedUser(), UserManagerService.getInstance().getUserIds());
726 if (!ArrayUtils.isEmpty(updatedUserIds)) {
727 runtimePermissionsRevoked = true;
728 }
729 }
730 }
731 }
732
733 permissionsState.setGlobalGids(mGlobalGids);
734
735 synchronized (mLock) {
736 final int N = pkg.requestedPermissions.size();
737 for (int i = 0; i < N; i++) {
738 final String permName = pkg.requestedPermissions.get(i);
739 final BasePermission bp = mSettings.getPermissionLocked(permName);
740 final boolean appSupportsRuntimePermissions =
741 pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M;
742
743 if (DEBUG_INSTALL) {
744 Log.i(TAG, "Package " + pkg.packageName + " checking " + permName + ": " + bp);
745 }
746
747 if (bp == null || bp.getSourcePackageSetting() == null) {
748 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
749 if (DEBUG_PERMISSIONS) {
750 Slog.i(TAG, "Unknown permission " + permName
751 + " in package " + pkg.packageName);
752 }
753 }
754 continue;
755 }
756
757 // Limit ephemeral apps to ephemeral allowed permissions.
758 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
759 if (DEBUG_PERMISSIONS) {
760 Log.i(TAG, "Denying non-ephemeral permission " + bp.getName()
761 + " for package " + pkg.packageName);
762 }
763 continue;
764 }
765
766 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
767 if (DEBUG_PERMISSIONS) {
768 Log.i(TAG, "Denying runtime-only permission " + bp.getName()
769 + " for package " + pkg.packageName);
770 }
771 continue;
772 }
773
774 final String perm = bp.getName();
775 boolean allowedSig = false;
776 int grant = GRANT_DENIED;
777
778 // Keep track of app op permissions.
779 if (bp.isAppOp()) {
780 mSettings.addAppOpPackage(perm, pkg.packageName);
781 }
782
783 if (bp.isNormal()) {
784 // For all apps normal permissions are install time ones.
785 grant = GRANT_INSTALL;
786 } else if (bp.isRuntime()) {
787 // If a permission review is required for legacy apps we represent
788 // their permissions as always granted runtime ones since we need
789 // to keep the review required permission flag per user while an
790 // install permission's state is shared across all users.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700791 if (origPermissions.hasInstallPermission(bp.getName())) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700792 // For legacy apps that became modern, install becomes runtime.
793 grant = GRANT_UPGRADE;
794 } else if (isLegacySystemApp) {
795 // For legacy system apps, install becomes runtime.
796 // We cannot check hasInstallPermission() for system apps since those
797 // permissions were granted implicitly and not persisted pre-M.
798 grant = GRANT_UPGRADE;
799 } else {
800 // For modern apps keep runtime permissions unchanged.
801 grant = GRANT_RUNTIME;
802 }
803 } else if (bp.isSignature()) {
804 // For all apps signature permissions are install time ones.
805 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
806 if (allowedSig) {
807 grant = GRANT_INSTALL;
808 }
809 }
810
811 if (DEBUG_PERMISSIONS) {
812 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
813 }
814
815 if (grant != GRANT_DENIED) {
816 if (!ps.isSystem() && ps.areInstallPermissionsFixed()) {
817 // If this is an existing, non-system package, then
818 // we can't add any new permissions to it.
819 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
820 // Except... if this is a permission that was added
821 // to the platform (note: need to only do this when
822 // updating the platform).
823 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
824 grant = GRANT_DENIED;
825 }
826 }
827 }
828
829 switch (grant) {
830 case GRANT_INSTALL: {
831 // Revoke this as runtime permission to handle the case of
832 // a runtime permission being downgraded to an install one.
833 // Also in permission review mode we keep dangerous permissions
834 // for legacy apps
835 for (int userId : UserManagerService.getInstance().getUserIds()) {
836 if (origPermissions.getRuntimePermissionState(
837 perm, userId) != null) {
838 // Revoke the runtime permission and clear the flags.
839 origPermissions.revokeRuntimePermission(bp, userId);
840 origPermissions.updatePermissionFlags(bp, userId,
841 PackageManager.MASK_PERMISSION_FLAGS, 0);
842 // If we revoked a permission permission, we have to write.
843 updatedUserIds = ArrayUtils.appendInt(
844 updatedUserIds, userId);
845 }
846 }
847 // Grant an install permission.
848 if (permissionsState.grantInstallPermission(bp) !=
849 PermissionsState.PERMISSION_OPERATION_FAILURE) {
850 changedInstallPermission = true;
851 }
852 } break;
853
854 case GRANT_RUNTIME: {
855 // Grant previously granted runtime permissions.
856 for (int userId : UserManagerService.getInstance().getUserIds()) {
857 final PermissionState permissionState = origPermissions
858 .getRuntimePermissionState(perm, userId);
859 int flags = permissionState != null
860 ? permissionState.getFlags() : 0;
861 if (origPermissions.hasRuntimePermission(perm, userId)) {
862 // Don't propagate the permission in a permission review
863 // mode if the former was revoked, i.e. marked to not
864 // propagate on upgrade. Note that in a permission review
865 // mode install permissions are represented as constantly
866 // granted runtime ones since we need to keep a per user
867 // state associated with the permission. Also the revoke
868 // on upgrade flag is no longer applicable and is reset.
869 final boolean revokeOnUpgrade = (flags & PackageManager
870 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
871 if (revokeOnUpgrade) {
872 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
873 // Since we changed the flags, we have to write.
874 updatedUserIds = ArrayUtils.appendInt(
875 updatedUserIds, userId);
876 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700877 if (!revokeOnUpgrade) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700878 if (permissionsState.grantRuntimePermission(bp, userId) ==
879 PermissionsState.PERMISSION_OPERATION_FAILURE) {
880 // If we cannot put the permission as it was,
881 // we have to write.
882 updatedUserIds = ArrayUtils.appendInt(
883 updatedUserIds, userId);
884 }
885 }
886
887 // If the app supports runtime permissions no need for a review.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700888 if (appSupportsRuntimePermissions
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700889 && (flags & PackageManager
890 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
891 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
892 // Since we changed the flags, we have to write.
893 updatedUserIds = ArrayUtils.appendInt(
894 updatedUserIds, userId);
895 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700896 } else if (!appSupportsRuntimePermissions) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -0700897 // For legacy apps that need a permission review, every new
898 // runtime permission is granted but it is pending a review.
899 // We also need to review only platform defined runtime
900 // permissions as these are the only ones the platform knows
901 // how to disable the API to simulate revocation as legacy
902 // apps don't expect to run with revoked permissions.
903 if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
904 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
905 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
906 // We changed the flags, hence have to write.
907 updatedUserIds = ArrayUtils.appendInt(
908 updatedUserIds, userId);
909 }
910 }
911 if (permissionsState.grantRuntimePermission(bp, userId)
912 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
913 // We changed the permission, hence have to write.
914 updatedUserIds = ArrayUtils.appendInt(
915 updatedUserIds, userId);
916 }
917 }
918 // Propagate the permission flags.
919 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
920 }
921 } break;
922
923 case GRANT_UPGRADE: {
924 // Grant runtime permissions for a previously held install permission.
925 final PermissionState permissionState = origPermissions
926 .getInstallPermissionState(perm);
927 final int flags =
928 (permissionState != null) ? permissionState.getFlags() : 0;
929
930 if (origPermissions.revokeInstallPermission(bp)
931 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
932 // We will be transferring the permission flags, so clear them.
933 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
934 PackageManager.MASK_PERMISSION_FLAGS, 0);
935 changedInstallPermission = true;
936 }
937
938 // If the permission is not to be promoted to runtime we ignore it and
939 // also its other flags as they are not applicable to install permissions.
940 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
941 for (int userId : currentUserIds) {
942 if (permissionsState.grantRuntimePermission(bp, userId) !=
943 PermissionsState.PERMISSION_OPERATION_FAILURE) {
944 // Transfer the permission flags.
945 permissionsState.updatePermissionFlags(bp, userId,
946 flags, flags);
947 // If we granted the permission, we have to write.
948 updatedUserIds = ArrayUtils.appendInt(
949 updatedUserIds, userId);
950 }
951 }
952 }
953 } break;
954
955 default: {
956 if (packageOfInterest == null
957 || packageOfInterest.equals(pkg.packageName)) {
958 if (DEBUG_PERMISSIONS) {
959 Slog.i(TAG, "Not granting permission " + perm
960 + " to package " + pkg.packageName
961 + " because it was previously installed without");
962 }
963 }
964 } break;
965 }
966 } else {
967 if (permissionsState.revokeInstallPermission(bp) !=
968 PermissionsState.PERMISSION_OPERATION_FAILURE) {
969 // Also drop the permission flags.
970 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
971 PackageManager.MASK_PERMISSION_FLAGS, 0);
972 changedInstallPermission = true;
973 Slog.i(TAG, "Un-granting permission " + perm
974 + " from package " + pkg.packageName
975 + " (protectionLevel=" + bp.getProtectionLevel()
976 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
977 + ")");
978 } else if (bp.isAppOp()) {
979 // Don't print warning for app op permissions, since it is fine for them
980 // not to be granted, there is a UI for the user to decide.
981 if (DEBUG_PERMISSIONS
982 && (packageOfInterest == null
983 || packageOfInterest.equals(pkg.packageName))) {
984 Slog.i(TAG, "Not granting permission " + perm
985 + " to package " + pkg.packageName
986 + " (protectionLevel=" + bp.getProtectionLevel()
987 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
988 + ")");
989 }
990 }
991 }
992 }
993
994 if ((changedInstallPermission || replace) && !ps.areInstallPermissionsFixed() &&
995 !ps.isSystem() || ps.isUpdatedSystem()) {
996 // This is the first that we have heard about this package, so the
997 // permissions we have now selected are fixed until explicitly
998 // changed.
999 ps.setInstallPermissionsFixed(true);
1000 }
1001 }
1002
1003 // Persist the runtime permissions state for users with changes. If permissions
1004 // were revoked because no app in the shared user declares them we have to
1005 // write synchronously to avoid losing runtime permissions state.
1006 if (callback != null) {
1007 callback.onPermissionUpdated(updatedUserIds, runtimePermissionsRevoked);
1008 }
1009 }
1010
1011 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
1012 boolean allowed = false;
1013 final int NP = PackageParser.NEW_PERMISSIONS.length;
1014 for (int ip=0; ip<NP; ip++) {
1015 final PackageParser.NewPermissionInfo npi
1016 = PackageParser.NEW_PERMISSIONS[ip];
1017 if (npi.name.equals(perm)
1018 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
1019 allowed = true;
1020 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
1021 + pkg.packageName);
1022 break;
1023 }
1024 }
1025 return allowed;
1026 }
1027
1028 /**
1029 * Determines whether a package is whitelisted for a particular privapp permission.
1030 *
1031 * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
1032 *
1033 * <p>This handles parent/child apps.
1034 */
1035 private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
Jaekyun Seok1713d9e2018-01-12 21:47:26 +09001036 ArraySet<String> wlPermissions = null;
1037 if (pkg.isVendor()) {
1038 wlPermissions =
1039 SystemConfig.getInstance().getVendorPrivAppPermissions(pkg.packageName);
1040 } else if (pkg.isProduct()) {
1041 wlPermissions =
1042 SystemConfig.getInstance().getProductPrivAppPermissions(pkg.packageName);
Dario Freni2bef1762018-06-01 14:02:08 +01001043 } else if (pkg.isProductServices()) {
1044 wlPermissions =
1045 SystemConfig.getInstance().getProductServicesPrivAppPermissions(
1046 pkg.packageName);
Jaekyun Seok1713d9e2018-01-12 21:47:26 +09001047 } else {
1048 wlPermissions = SystemConfig.getInstance().getPrivAppPermissions(pkg.packageName);
1049 }
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001050 // Let's check if this package is whitelisted...
1051 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
1052 // If it's not, we'll also tail-recurse to the parent.
1053 return whitelisted ||
1054 pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
1055 }
1056
1057 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
1058 BasePermission bp, PermissionsState origPermissions) {
1059 boolean oemPermission = bp.isOEM();
Jiyong Park002fdbd2017-02-13 20:50:31 +09001060 boolean vendorPrivilegedPermission = bp.isVendorPrivileged();
1061 boolean privilegedPermission = bp.isPrivileged() || bp.isVendorPrivileged();
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001062 boolean privappPermissionsDisable =
1063 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
1064 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
1065 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
1066 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivileged()
1067 && !platformPackage && platformPermission) {
1068 if (!hasPrivappWhitelistEntry(perm, pkg)) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001069 // Only report violations for apps on system image
1070 if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
1071 // it's only a reportable violation if the permission isn't explicitly denied
Jaekyun Seok1713d9e2018-01-12 21:47:26 +09001072 ArraySet<String> deniedPermissions = null;
1073 if (pkg.isVendor()) {
1074 deniedPermissions = SystemConfig.getInstance()
1075 .getVendorPrivAppDenyPermissions(pkg.packageName);
1076 } else if (pkg.isProduct()) {
1077 deniedPermissions = SystemConfig.getInstance()
1078 .getProductPrivAppDenyPermissions(pkg.packageName);
Dario Freni2bef1762018-06-01 14:02:08 +01001079 } else if (pkg.isProductServices()) {
1080 deniedPermissions = SystemConfig.getInstance()
1081 .getProductServicesPrivAppDenyPermissions(pkg.packageName);
Jaekyun Seok1713d9e2018-01-12 21:47:26 +09001082 } else {
1083 deniedPermissions = SystemConfig.getInstance()
1084 .getPrivAppDenyPermissions(pkg.packageName);
1085 }
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001086 final boolean permissionViolation =
1087 deniedPermissions == null || !deniedPermissions.contains(perm);
Fyodor Kupolovf5e600d2017-10-25 17:03:50 -07001088 if (permissionViolation) {
1089 Slog.w(TAG, "Privileged permission " + perm + " for package "
1090 + pkg.packageName + " - not in privapp-permissions whitelist");
1091
1092 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
1093 if (mPrivappPermissionsViolations == null) {
1094 mPrivappPermissionsViolations = new ArraySet<>();
1095 }
1096 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001097 }
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001098 } else {
1099 return false;
1100 }
1101 }
1102 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
1103 return false;
1104 }
1105 }
1106 }
1107 final String systemPackageName = mPackageManagerInt.getKnownPackageName(
1108 PackageManagerInternal.PACKAGE_SYSTEM, UserHandle.USER_SYSTEM);
1109 final PackageParser.Package systemPackage =
1110 mPackageManagerInt.getPackage(systemPackageName);
Dan Cashman1dbe6d02018-01-23 11:18:28 -08001111
1112 // check if the package is allow to use this signature permission. A package is allowed to
1113 // use a signature permission if:
1114 // - it has the same set of signing certificates as the source package
1115 // - or its signing certificate was rotated from the source package's certificate
1116 // - or its signing certificate is a previous signing certificate of the defining
1117 // package, and the defining package still trusts the old certificate for permissions
1118 // - or it shares the above relationships with the system package
1119 boolean allowed =
1120 pkg.mSigningDetails.hasAncestorOrSelf(
1121 bp.getSourcePackageSetting().getSigningDetails())
1122 || bp.getSourcePackageSetting().getSigningDetails().checkCapability(
1123 pkg.mSigningDetails,
1124 PackageParser.SigningDetails.CertCapabilities.PERMISSION)
1125 || pkg.mSigningDetails.hasAncestorOrSelf(systemPackage.mSigningDetails)
1126 || systemPackage.mSigningDetails.checkCapability(
1127 pkg.mSigningDetails,
1128 PackageParser.SigningDetails.CertCapabilities.PERMISSION);
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001129 if (!allowed && (privilegedPermission || oemPermission)) {
1130 if (pkg.isSystem()) {
1131 // For updated system applications, a privileged/oem permission
1132 // is granted only if it had been defined by the original application.
1133 if (pkg.isUpdatedSystemApp()) {
1134 final PackageParser.Package disabledPkg =
Philip P. Moltmannb0be05c2018-09-19 02:46:56 +00001135 mPackageManagerInt.getDisabledSystemPackage(pkg.packageName);
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001136 final PackageSetting disabledPs =
1137 (disabledPkg != null) ? (PackageSetting) disabledPkg.mExtras : null;
1138 if (disabledPs != null
1139 && disabledPs.getPermissionsState().hasInstallPermission(perm)) {
1140 // If the original was granted this permission, we take
1141 // that grant decision as read and propagate it to the
1142 // update.
1143 if ((privilegedPermission && disabledPs.isPrivileged())
1144 || (oemPermission && disabledPs.isOem()
1145 && canGrantOemPermission(disabledPs, perm))) {
1146 allowed = true;
1147 }
1148 } else {
1149 // The system apk may have been updated with an older
1150 // version of the one on the data partition, but which
1151 // granted a new system permission that it didn't have
1152 // before. In this case we do want to allow the app to
1153 // now get the new permission if the ancestral apk is
1154 // privileged to get it.
Todd Kennedy1efb8332017-10-25 15:51:36 -07001155 if (disabledPs != null && disabledPkg != null
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001156 && isPackageRequestingPermission(disabledPkg, perm)
1157 && ((privilegedPermission && disabledPs.isPrivileged())
1158 || (oemPermission && disabledPs.isOem()
1159 && canGrantOemPermission(disabledPs, perm)))) {
1160 allowed = true;
1161 }
1162 // Also if a privileged parent package on the system image or any of
1163 // its children requested a privileged/oem permission, the updated child
1164 // packages can also get the permission.
1165 if (pkg.parentPackage != null) {
1166 final PackageParser.Package disabledParentPkg = mPackageManagerInt
Philip P. Moltmannb0be05c2018-09-19 02:46:56 +00001167 .getDisabledSystemPackage(pkg.parentPackage.packageName);
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001168 final PackageSetting disabledParentPs = (disabledParentPkg != null)
1169 ? (PackageSetting) disabledParentPkg.mExtras : null;
1170 if (disabledParentPkg != null
1171 && ((privilegedPermission && disabledParentPs.isPrivileged())
1172 || (oemPermission && disabledParentPs.isOem()))) {
1173 if (isPackageRequestingPermission(disabledParentPkg, perm)
1174 && canGrantOemPermission(disabledParentPs, perm)) {
1175 allowed = true;
1176 } else if (disabledParentPkg.childPackages != null) {
1177 for (PackageParser.Package disabledChildPkg
1178 : disabledParentPkg.childPackages) {
1179 final PackageSetting disabledChildPs =
1180 (disabledChildPkg != null)
1181 ? (PackageSetting) disabledChildPkg.mExtras
1182 : null;
1183 if (isPackageRequestingPermission(disabledChildPkg, perm)
1184 && canGrantOemPermission(
1185 disabledChildPs, perm)) {
1186 allowed = true;
1187 break;
1188 }
1189 }
1190 }
1191 }
1192 }
1193 }
1194 } else {
1195 final PackageSetting ps = (PackageSetting) pkg.mExtras;
1196 allowed = (privilegedPermission && pkg.isPrivileged())
1197 || (oemPermission && pkg.isOem()
1198 && canGrantOemPermission(ps, perm));
1199 }
Jiyong Park002fdbd2017-02-13 20:50:31 +09001200 // In any case, don't grant a privileged permission to privileged vendor apps, if
1201 // the permission's protectionLevel does not have the extra 'vendorPrivileged'
1202 // flag.
1203 if (allowed && privilegedPermission &&
1204 !vendorPrivilegedPermission && pkg.isVendor()) {
1205 Slog.w(TAG, "Permission " + perm + " cannot be granted to privileged vendor apk "
1206 + pkg.packageName + " because it isn't a 'vendorPrivileged' permission.");
1207 allowed = false;
1208 }
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001209 }
1210 }
1211 if (!allowed) {
1212 if (!allowed
1213 && bp.isPre23()
1214 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
1215 // If this was a previously normal/dangerous permission that got moved
1216 // to a system permission as part of the runtime permission redesign, then
1217 // we still want to blindly grant it to old apps.
1218 allowed = true;
1219 }
Philip P. Moltmann8943ad62018-07-25 12:12:30 -07001220 // TODO (moltmann): The installer now shares the platforms signature. Hence it does not
1221 // need a separate flag anymore. Hence we need to check which
1222 // permissions are needed by the permission controller
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001223 if (!allowed && bp.isInstaller()
Philip P. Moltmann8943ad62018-07-25 12:12:30 -07001224 && (pkg.packageName.equals(mPackageManagerInt.getKnownPackageName(
1225 PackageManagerInternal.PACKAGE_INSTALLER, UserHandle.USER_SYSTEM))
1226 || pkg.packageName.equals(mPackageManagerInt.getKnownPackageName(
1227 PackageManagerInternal.PACKAGE_PERMISSION_CONTROLLER,
1228 UserHandle.USER_SYSTEM)))) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001229 // If this permission is to be granted to the system installer and
1230 // this app is an installer, then it gets the permission.
1231 allowed = true;
1232 }
1233 if (!allowed && bp.isVerifier()
1234 && pkg.packageName.equals(mPackageManagerInt.getKnownPackageName(
1235 PackageManagerInternal.PACKAGE_VERIFIER, UserHandle.USER_SYSTEM))) {
1236 // If this permission is to be granted to the system verifier and
1237 // this app is a verifier, then it gets the permission.
1238 allowed = true;
1239 }
1240 if (!allowed && bp.isPreInstalled()
1241 && pkg.isSystem()) {
1242 // Any pre-installed system app is allowed to get this permission.
1243 allowed = true;
1244 }
1245 if (!allowed && bp.isDevelopment()) {
1246 // For development permissions, a development permission
1247 // is granted only if it was already granted.
1248 allowed = origPermissions.hasInstallPermission(perm);
1249 }
1250 if (!allowed && bp.isSetup()
1251 && pkg.packageName.equals(mPackageManagerInt.getKnownPackageName(
1252 PackageManagerInternal.PACKAGE_SETUP_WIZARD, UserHandle.USER_SYSTEM))) {
1253 // If this permission is to be granted to the system setup wizard and
1254 // this app is a setup wizard, then it gets the permission.
1255 allowed = true;
1256 }
Makoto Onuki700feef2018-02-15 10:59:41 -08001257 if (!allowed && bp.isSystemTextClassifier()
1258 && pkg.packageName.equals(mPackageManagerInt.getKnownPackageName(
1259 PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER,
1260 UserHandle.USER_SYSTEM))) {
1261 // Special permissions for the system default text classifier.
1262 allowed = true;
1263 }
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001264 }
1265 return allowed;
1266 }
1267
1268 private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
1269 if (!ps.isOem()) {
1270 return false;
1271 }
1272 // all oem permissions must explicitly be granted or denied
1273 final Boolean granted =
1274 SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
1275 if (granted == null) {
1276 throw new IllegalStateException("OEM permission" + permission + " requested by package "
1277 + ps.name + " must be explicitly declared granted or not");
1278 }
1279 return Boolean.TRUE == granted;
1280 }
1281
1282 private boolean isPermissionsReviewRequired(PackageParser.Package pkg, int userId) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001283 // Permission review applies only to apps not supporting the new permission model.
1284 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
1285 return false;
1286 }
1287
1288 // Legacy apps have the permission and get user consent on launch.
1289 if (pkg == null || pkg.mExtras == null) {
1290 return false;
1291 }
1292 final PackageSetting ps = (PackageSetting) pkg.mExtras;
1293 final PermissionsState permissionsState = ps.getPermissionsState();
1294 return permissionsState.isPermissionReviewRequired(userId);
1295 }
1296
1297 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
1298 final int permCount = pkg.requestedPermissions.size();
1299 for (int j = 0; j < permCount; j++) {
1300 String requestedPermission = pkg.requestedPermissions.get(j);
1301 if (permission.equals(requestedPermission)) {
1302 return true;
1303 }
1304 }
1305 return false;
1306 }
1307
Andreas Gampea36dc622018-02-05 17:19:22 -08001308 @GuardedBy("mLock")
Todd Kennedy0eb97382017-10-03 16:57:22 -07001309 private void grantRuntimePermissionsGrantedToDisabledPackageLocked(
1310 PackageParser.Package pkg, int callingUid, PermissionCallback callback) {
1311 if (pkg.parentPackage == null) {
1312 return;
1313 }
1314 if (pkg.requestedPermissions == null) {
1315 return;
1316 }
1317 final PackageParser.Package disabledPkg =
Philip P. Moltmannb0be05c2018-09-19 02:46:56 +00001318 mPackageManagerInt.getDisabledSystemPackage(pkg.parentPackage.packageName);
Todd Kennedy0eb97382017-10-03 16:57:22 -07001319 if (disabledPkg == null || disabledPkg.mExtras == null) {
1320 return;
1321 }
1322 final PackageSetting disabledPs = (PackageSetting) disabledPkg.mExtras;
1323 if (!disabledPs.isPrivileged() || disabledPs.hasChildPackages()) {
1324 return;
1325 }
1326 final int permCount = pkg.requestedPermissions.size();
1327 for (int i = 0; i < permCount; i++) {
1328 String permission = pkg.requestedPermissions.get(i);
1329 BasePermission bp = mSettings.getPermissionLocked(permission);
1330 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1331 continue;
1332 }
1333 for (int userId : mUserManagerInt.getUserIds()) {
1334 if (disabledPs.getPermissionsState().hasRuntimePermission(permission, userId)) {
1335 grantRuntimePermission(
1336 permission, pkg.packageName, false, callingUid, userId, callback);
1337 }
1338 }
1339 }
1340 }
1341
1342 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1343 String[] grantedPermissions, int callingUid, PermissionCallback callback) {
1344 for (int userId : userIds) {
1345 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions, callingUid,
1346 callback);
1347 }
1348 }
1349
1350 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1351 String[] grantedPermissions, int callingUid, PermissionCallback callback) {
1352 PackageSetting ps = (PackageSetting) pkg.mExtras;
1353 if (ps == null) {
1354 return;
1355 }
1356
1357 PermissionsState permissionsState = ps.getPermissionsState();
1358
1359 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1360 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1361
1362 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
1363 >= Build.VERSION_CODES.M;
1364
1365 final boolean instantApp = mPackageManagerInt.isInstantApp(pkg.packageName, userId);
1366
1367 for (String permission : pkg.requestedPermissions) {
1368 final BasePermission bp;
1369 synchronized (mLock) {
1370 bp = mSettings.getPermissionLocked(permission);
1371 }
1372 if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1373 && (!instantApp || bp.isInstant())
1374 && (supportsRuntimePermissions || !bp.isRuntimeOnly())
1375 && (grantedPermissions == null
1376 || ArrayUtils.contains(grantedPermissions, permission))) {
1377 final int flags = permissionsState.getPermissionFlags(permission, userId);
1378 if (supportsRuntimePermissions) {
1379 // Installer cannot change immutable permissions.
1380 if ((flags & immutableFlags) == 0) {
1381 grantRuntimePermission(permission, pkg.packageName, false, callingUid,
1382 userId, callback);
1383 }
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001384 } else {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001385 // In permission review mode we clear the review flag when we
1386 // are asked to install the app with all permissions granted.
1387 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
1388 updatePermissionFlags(permission, pkg.packageName,
1389 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, callingUid,
1390 userId, callback);
1391 }
1392 }
1393 }
1394 }
1395 }
1396
1397 private void grantRuntimePermission(String permName, String packageName, boolean overridePolicy,
1398 int callingUid, final int userId, PermissionCallback callback) {
1399 if (!mUserManagerInt.exists(userId)) {
1400 Log.e(TAG, "No such user:" + userId);
1401 return;
1402 }
1403
1404 mContext.enforceCallingOrSelfPermission(
1405 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
1406 "grantRuntimePermission");
1407
1408 enforceCrossUserPermission(callingUid, userId,
Todd Kennedyef9acb62018-05-29 15:18:06 -07001409 true, // requireFullPermission
1410 true, // checkShell
1411 false, // requirePermissionWhenSameUser
Todd Kennedy0eb97382017-10-03 16:57:22 -07001412 "grantRuntimePermission");
1413
1414 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
1415 if (pkg == null || pkg.mExtras == null) {
1416 throw new IllegalArgumentException("Unknown package: " + packageName);
1417 }
1418 final BasePermission bp;
1419 synchronized(mLock) {
1420 bp = mSettings.getPermissionLocked(permName);
1421 }
1422 if (bp == null) {
1423 throw new IllegalArgumentException("Unknown permission: " + permName);
1424 }
1425 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) {
1426 throw new IllegalArgumentException("Unknown package: " + packageName);
1427 }
1428
1429 bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg);
1430
1431 // If a permission review is required for legacy apps we represent
1432 // their permissions as always granted runtime ones since we need
1433 // to keep the review required permission flag per user while an
1434 // install permission's state is shared across all users.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001435 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
Todd Kennedy0eb97382017-10-03 16:57:22 -07001436 && bp.isRuntime()) {
1437 return;
1438 }
1439
1440 final int uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
1441
1442 final PackageSetting ps = (PackageSetting) pkg.mExtras;
1443 final PermissionsState permissionsState = ps.getPermissionsState();
1444
1445 final int flags = permissionsState.getPermissionFlags(permName, userId);
1446 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
1447 throw new SecurityException("Cannot grant system fixed permission "
1448 + permName + " for package " + packageName);
1449 }
1450 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
1451 throw new SecurityException("Cannot grant policy fixed permission "
1452 + permName + " for package " + packageName);
1453 }
1454
1455 if (bp.isDevelopment()) {
1456 // Development permissions must be handled specially, since they are not
1457 // normal runtime permissions. For now they apply to all users.
1458 if (permissionsState.grantInstallPermission(bp) !=
1459 PermissionsState.PERMISSION_OPERATION_FAILURE) {
1460 if (callback != null) {
1461 callback.onInstallPermissionGranted();
1462 }
1463 }
1464 return;
1465 }
1466
1467 if (ps.getInstantApp(userId) && !bp.isInstant()) {
1468 throw new SecurityException("Cannot grant non-ephemeral permission"
1469 + permName + " for package " + packageName);
1470 }
1471
1472 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
1473 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
1474 return;
1475 }
1476
1477 final int result = permissionsState.grantRuntimePermission(bp, userId);
1478 switch (result) {
1479 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
1480 return;
1481 }
1482
1483 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
1484 if (callback != null) {
1485 callback.onGidsChanged(UserHandle.getAppId(pkg.applicationInfo.uid), userId);
1486 }
1487 }
1488 break;
1489 }
1490
1491 if (bp.isRuntime()) {
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -07001492 logPermission(MetricsEvent.ACTION_PERMISSION_GRANTED, permName, packageName);
Todd Kennedy0eb97382017-10-03 16:57:22 -07001493 }
1494
1495 if (callback != null) {
1496 callback.onPermissionGranted(uid, userId);
1497 }
1498
1499 // Only need to do this if user is initialized. Otherwise it's a new user
1500 // and there are no processes running as the user yet and there's no need
1501 // to make an expensive call to remount processes for the changed permissions.
1502 if (READ_EXTERNAL_STORAGE.equals(permName)
1503 || WRITE_EXTERNAL_STORAGE.equals(permName)) {
1504 final long token = Binder.clearCallingIdentity();
1505 try {
1506 if (mUserManagerInt.isUserInitialized(userId)) {
1507 StorageManagerInternal storageManagerInternal = LocalServices.getService(
1508 StorageManagerInternal.class);
1509 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
1510 }
1511 } finally {
1512 Binder.restoreCallingIdentity(token);
1513 }
1514 }
1515
1516 }
Hongming Jinae750fb2018-09-27 23:00:20 +00001517
1518 private void revokeRuntimePermission(String permName, String packageName,
1519 boolean overridePolicy, int callingUid, int userId, PermissionCallback callback) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001520 if (!mUserManagerInt.exists(userId)) {
1521 Log.e(TAG, "No such user:" + userId);
1522 return;
1523 }
1524
1525 mContext.enforceCallingOrSelfPermission(
1526 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
1527 "revokeRuntimePermission");
1528
1529 enforceCrossUserPermission(Binder.getCallingUid(), userId,
Todd Kennedyef9acb62018-05-29 15:18:06 -07001530 true, // requireFullPermission
1531 true, // checkShell
1532 false, // requirePermissionWhenSameUser
Todd Kennedy0eb97382017-10-03 16:57:22 -07001533 "revokeRuntimePermission");
1534
1535 final int appId;
1536
1537 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
1538 if (pkg == null || pkg.mExtras == null) {
1539 throw new IllegalArgumentException("Unknown package: " + packageName);
1540 }
1541 if (mPackageManagerInt.filterAppAccess(pkg, Binder.getCallingUid(), userId)) {
1542 throw new IllegalArgumentException("Unknown package: " + packageName);
1543 }
Hongming Jinae750fb2018-09-27 23:00:20 +00001544 final BasePermission bp = mSettings.getPermissionLocked(permName);
Todd Kennedy0eb97382017-10-03 16:57:22 -07001545 if (bp == null) {
1546 throw new IllegalArgumentException("Unknown permission: " + permName);
1547 }
1548
1549 bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg);
1550
1551 // If a permission review is required for legacy apps we represent
1552 // their permissions as always granted runtime ones since we need
1553 // to keep the review required permission flag per user while an
1554 // install permission's state is shared across all users.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001555 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
Todd Kennedy0eb97382017-10-03 16:57:22 -07001556 && bp.isRuntime()) {
1557 return;
1558 }
1559
1560 final PackageSetting ps = (PackageSetting) pkg.mExtras;
1561 final PermissionsState permissionsState = ps.getPermissionsState();
1562
1563 final int flags = permissionsState.getPermissionFlags(permName, userId);
Nathan Haroldd66b9f32018-03-14 19:55:38 -07001564 // Only the system may revoke SYSTEM_FIXED permissions.
1565 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0
1566 && UserHandle.getCallingAppId() != Process.SYSTEM_UID) {
1567 throw new SecurityException("Non-System UID cannot revoke system fixed permission "
Todd Kennedy0eb97382017-10-03 16:57:22 -07001568 + permName + " for package " + packageName);
1569 }
1570 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
1571 throw new SecurityException("Cannot revoke policy fixed permission "
1572 + permName + " for package " + packageName);
1573 }
1574
1575 if (bp.isDevelopment()) {
1576 // Development permissions must be handled specially, since they are not
1577 // normal runtime permissions. For now they apply to all users.
1578 if (permissionsState.revokeInstallPermission(bp) !=
1579 PermissionsState.PERMISSION_OPERATION_FAILURE) {
1580 if (callback != null) {
1581 callback.onInstallPermissionRevoked();
1582 }
1583 }
1584 return;
1585 }
1586
1587 if (permissionsState.revokeRuntimePermission(bp, userId) ==
1588 PermissionsState.PERMISSION_OPERATION_FAILURE) {
1589 return;
1590 }
1591
1592 if (bp.isRuntime()) {
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -07001593 logPermission(MetricsEvent.ACTION_PERMISSION_REVOKED, permName, packageName);
Todd Kennedy0eb97382017-10-03 16:57:22 -07001594 }
1595
1596 if (callback != null) {
1597 final int uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
1598 callback.onPermissionRevoked(pkg.applicationInfo.uid, userId);
1599 }
1600 }
1601
Andreas Gampea36dc622018-02-05 17:19:22 -08001602 @GuardedBy("mLock")
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001603 private int[] revokeUnusedSharedUserPermissionsLocked(
1604 SharedUserSetting suSetting, int[] allUserIds) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001605 // Collect all used permissions in the UID
1606 final ArraySet<String> usedPermissions = new ArraySet<>();
1607 final List<PackageParser.Package> pkgList = suSetting.getPackages();
1608 if (pkgList == null || pkgList.size() == 0) {
1609 return EmptyArray.INT;
1610 }
1611 for (PackageParser.Package pkg : pkgList) {
Svet Ganovd8308072018-03-24 00:04:38 -07001612 if (pkg.requestedPermissions == null) {
1613 continue;
1614 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07001615 final int requestedPermCount = pkg.requestedPermissions.size();
1616 for (int j = 0; j < requestedPermCount; j++) {
1617 String permission = pkg.requestedPermissions.get(j);
1618 BasePermission bp = mSettings.getPermissionLocked(permission);
1619 if (bp != null) {
1620 usedPermissions.add(permission);
1621 }
1622 }
1623 }
1624
1625 PermissionsState permissionsState = suSetting.getPermissionsState();
1626 // Prune install permissions
1627 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
1628 final int installPermCount = installPermStates.size();
1629 for (int i = installPermCount - 1; i >= 0; i--) {
1630 PermissionState permissionState = installPermStates.get(i);
1631 if (!usedPermissions.contains(permissionState.getName())) {
1632 BasePermission bp = mSettings.getPermissionLocked(permissionState.getName());
1633 if (bp != null) {
1634 permissionsState.revokeInstallPermission(bp);
1635 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
1636 PackageManager.MASK_PERMISSION_FLAGS, 0);
1637 }
1638 }
1639 }
1640
1641 int[] runtimePermissionChangedUserIds = EmptyArray.INT;
1642
1643 // Prune runtime permissions
1644 for (int userId : allUserIds) {
1645 List<PermissionState> runtimePermStates = permissionsState
1646 .getRuntimePermissionStates(userId);
1647 final int runtimePermCount = runtimePermStates.size();
1648 for (int i = runtimePermCount - 1; i >= 0; i--) {
1649 PermissionState permissionState = runtimePermStates.get(i);
1650 if (!usedPermissions.contains(permissionState.getName())) {
1651 BasePermission bp = mSettings.getPermissionLocked(permissionState.getName());
1652 if (bp != null) {
1653 permissionsState.revokeRuntimePermission(bp, userId);
1654 permissionsState.updatePermissionFlags(bp, userId,
1655 PackageManager.MASK_PERMISSION_FLAGS, 0);
1656 runtimePermissionChangedUserIds = ArrayUtils.appendInt(
1657 runtimePermissionChangedUserIds, userId);
1658 }
1659 }
1660 }
1661 }
1662
1663 return runtimePermissionChangedUserIds;
1664 }
1665
Todd Kennedyc8423932017-10-05 08:58:36 -07001666 private String[] getAppOpPermissionPackages(String permName) {
1667 if (mPackageManagerInt.getInstantAppPackageName(Binder.getCallingUid()) != null) {
1668 return null;
1669 }
1670 synchronized (mLock) {
1671 final ArraySet<String> pkgs = mSettings.mAppOpPermissionPackages.get(permName);
1672 if (pkgs == null) {
1673 return null;
1674 }
1675 return pkgs.toArray(new String[pkgs.size()]);
1676 }
1677 }
1678
1679 private int getPermissionFlags(
1680 String permName, String packageName, int callingUid, int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001681 if (!mUserManagerInt.exists(userId)) {
1682 return 0;
1683 }
1684
1685 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
1686
1687 enforceCrossUserPermission(callingUid, userId,
Todd Kennedyef9acb62018-05-29 15:18:06 -07001688 true, // requireFullPermission
1689 false, // checkShell
1690 false, // requirePermissionWhenSameUser
Todd Kennedy0eb97382017-10-03 16:57:22 -07001691 "getPermissionFlags");
1692
1693 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
1694 if (pkg == null || pkg.mExtras == null) {
1695 return 0;
1696 }
1697 synchronized (mLock) {
1698 if (mSettings.getPermissionLocked(permName) == null) {
1699 return 0;
1700 }
1701 }
1702 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) {
1703 return 0;
1704 }
1705 final PackageSetting ps = (PackageSetting) pkg.mExtras;
1706 PermissionsState permissionsState = ps.getPermissionsState();
1707 return permissionsState.getPermissionFlags(permName, userId);
1708 }
1709
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001710 private static final int UPDATE_PERMISSIONS_ALL = 1<<0;
1711 private static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
1712 private static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
1713
1714 private void updatePermissions(String packageName, PackageParser.Package pkg,
1715 boolean replaceGrant, Collection<PackageParser.Package> allPackages,
1716 PermissionCallback callback) {
1717 final int flags = (pkg != null ? UPDATE_PERMISSIONS_ALL : 0) |
1718 (replaceGrant ? UPDATE_PERMISSIONS_REPLACE_PKG : 0);
1719 updatePermissions(
1720 packageName, pkg, getVolumeUuidForPackage(pkg), flags, allPackages, callback);
1721 if (pkg != null && pkg.childPackages != null) {
1722 for (PackageParser.Package childPkg : pkg.childPackages) {
1723 updatePermissions(childPkg.packageName, childPkg,
1724 getVolumeUuidForPackage(childPkg), flags, allPackages, callback);
1725 }
1726 }
1727 }
1728
1729 private void updateAllPermissions(String volumeUuid, boolean sdkUpdated,
1730 Collection<PackageParser.Package> allPackages, PermissionCallback callback) {
1731 final int flags = UPDATE_PERMISSIONS_ALL |
1732 (sdkUpdated
1733 ? UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL
1734 : 0);
1735 updatePermissions(null, null, volumeUuid, flags, allPackages, callback);
1736 }
1737
1738 private void updatePermissions(String changingPkgName, PackageParser.Package changingPkg,
1739 String replaceVolumeUuid, int flags, Collection<PackageParser.Package> allPackages,
1740 PermissionCallback callback) {
1741 // TODO: Most of the methods exposing BasePermission internals [source package name,
1742 // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
1743 // have package settings, we should make note of it elsewhere [map between
1744 // source package name and BasePermission] and cycle through that here. Then we
1745 // define a single method on BasePermission that takes a PackageSetting, changing
1746 // package name and a package.
1747 // NOTE: With this approach, we also don't need to tree trees differently than
1748 // normal permissions. Today, we need two separate loops because these BasePermission
1749 // objects are stored separately.
1750 // Make sure there are no dangling permission trees.
1751 flags = updatePermissionTrees(changingPkgName, changingPkg, flags);
1752
1753 // Make sure all dynamic permissions have been assigned to a package,
1754 // and make sure there are no dangling permissions.
1755 flags = updatePermissions(changingPkgName, changingPkg, flags);
1756
1757 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
1758 // Now update the permissions for all packages, in particular
1759 // replace the granted permissions of the system packages.
1760 if ((flags & UPDATE_PERMISSIONS_ALL) != 0) {
1761 for (PackageParser.Package pkg : allPackages) {
1762 if (pkg != changingPkg) {
1763 // Only replace for packages on requested volume
1764 final String volumeUuid = getVolumeUuidForPackage(pkg);
1765 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
1766 && Objects.equals(replaceVolumeUuid, volumeUuid);
1767 grantPermissions(pkg, replace, changingPkgName, callback);
1768 }
1769 }
1770 }
1771
1772 if (changingPkg != null) {
1773 // Only replace for packages on requested volume
1774 final String volumeUuid = getVolumeUuidForPackage(changingPkg);
1775 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
1776 && Objects.equals(replaceVolumeUuid, volumeUuid);
1777 grantPermissions(changingPkg, replace, changingPkgName, callback);
1778 }
1779 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1780 }
1781
1782 private int updatePermissions(String packageName, PackageParser.Package pkg, int flags) {
Todd Kennedyc8423932017-10-05 08:58:36 -07001783 Set<BasePermission> needsUpdate = null;
1784 synchronized (mLock) {
1785 final Iterator<BasePermission> it = mSettings.mPermissions.values().iterator();
1786 while (it.hasNext()) {
1787 final BasePermission bp = it.next();
1788 if (bp.isDynamic()) {
1789 bp.updateDynamicPermission(mSettings.mPermissionTrees.values());
1790 }
1791 if (bp.getSourcePackageSetting() != null) {
1792 if (packageName != null && packageName.equals(bp.getSourcePackageName())
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001793 && (pkg == null || !hasPermission(pkg, bp.getName()))) {
Todd Kennedyc8423932017-10-05 08:58:36 -07001794 Slog.i(TAG, "Removing old permission tree: " + bp.getName()
1795 + " from package " + bp.getSourcePackageName());
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001796 flags |= UPDATE_PERMISSIONS_ALL;
Todd Kennedyc8423932017-10-05 08:58:36 -07001797 it.remove();
1798 }
1799 continue;
1800 }
1801 if (needsUpdate == null) {
1802 needsUpdate = new ArraySet<>(mSettings.mPermissions.size());
1803 }
1804 needsUpdate.add(bp);
1805 }
1806 }
1807 if (needsUpdate != null) {
1808 for (final BasePermission bp : needsUpdate) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001809 final PackageParser.Package sourcePkg =
Todd Kennedyc8423932017-10-05 08:58:36 -07001810 mPackageManagerInt.getPackage(bp.getSourcePackageName());
1811 synchronized (mLock) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001812 if (sourcePkg != null && sourcePkg.mExtras != null) {
1813 final PackageSetting sourcePs = (PackageSetting) sourcePkg.mExtras;
Todd Kennedyc8423932017-10-05 08:58:36 -07001814 if (bp.getSourcePackageSetting() == null) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001815 bp.setSourcePackageSetting(sourcePs);
Todd Kennedyc8423932017-10-05 08:58:36 -07001816 }
1817 continue;
1818 }
1819 Slog.w(TAG, "Removing dangling permission: " + bp.getName()
1820 + " from package " + bp.getSourcePackageName());
1821 mSettings.removePermissionLocked(bp.getName());
1822 }
1823 }
1824 }
1825 return flags;
1826 }
1827
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001828 private int updatePermissionTrees(String packageName, PackageParser.Package pkg,
Todd Kennedyc8423932017-10-05 08:58:36 -07001829 int flags) {
1830 Set<BasePermission> needsUpdate = null;
1831 synchronized (mLock) {
1832 final Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
1833 while (it.hasNext()) {
1834 final BasePermission bp = it.next();
1835 if (bp.getSourcePackageSetting() != null) {
1836 if (packageName != null && packageName.equals(bp.getSourcePackageName())
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001837 && (pkg == null || !hasPermission(pkg, bp.getName()))) {
Todd Kennedyc8423932017-10-05 08:58:36 -07001838 Slog.i(TAG, "Removing old permission tree: " + bp.getName()
1839 + " from package " + bp.getSourcePackageName());
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001840 flags |= UPDATE_PERMISSIONS_ALL;
Todd Kennedyc8423932017-10-05 08:58:36 -07001841 it.remove();
1842 }
1843 continue;
1844 }
1845 if (needsUpdate == null) {
1846 needsUpdate = new ArraySet<>(mSettings.mPermissionTrees.size());
1847 }
1848 needsUpdate.add(bp);
1849 }
1850 }
1851 if (needsUpdate != null) {
1852 for (final BasePermission bp : needsUpdate) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001853 final PackageParser.Package sourcePkg =
Todd Kennedyc8423932017-10-05 08:58:36 -07001854 mPackageManagerInt.getPackage(bp.getSourcePackageName());
1855 synchronized (mLock) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001856 if (sourcePkg != null && sourcePkg.mExtras != null) {
1857 final PackageSetting sourcePs = (PackageSetting) sourcePkg.mExtras;
Todd Kennedyc8423932017-10-05 08:58:36 -07001858 if (bp.getSourcePackageSetting() == null) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001859 bp.setSourcePackageSetting(sourcePs);
Todd Kennedyc8423932017-10-05 08:58:36 -07001860 }
1861 continue;
1862 }
1863 Slog.w(TAG, "Removing dangling permission tree: " + bp.getName()
1864 + " from package " + bp.getSourcePackageName());
1865 mSettings.removePermissionLocked(bp.getName());
1866 }
1867 }
1868 }
1869 return flags;
1870 }
1871
Todd Kennedy0eb97382017-10-03 16:57:22 -07001872 private void updatePermissionFlags(String permName, String packageName, int flagMask,
1873 int flagValues, int callingUid, int userId, PermissionCallback callback) {
1874 if (!mUserManagerInt.exists(userId)) {
1875 return;
1876 }
1877
1878 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
1879
1880 enforceCrossUserPermission(callingUid, userId,
Todd Kennedyef9acb62018-05-29 15:18:06 -07001881 true, // requireFullPermission
1882 true, // checkShell
1883 false, // requirePermissionWhenSameUser
Todd Kennedy0eb97382017-10-03 16:57:22 -07001884 "updatePermissionFlags");
1885
1886 // Only the system can change these flags and nothing else.
1887 if (callingUid != Process.SYSTEM_UID) {
1888 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
1889 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
1890 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1891 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1892 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
1893 }
1894
1895 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
1896 if (pkg == null || pkg.mExtras == null) {
1897 throw new IllegalArgumentException("Unknown package: " + packageName);
1898 }
1899 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) {
1900 throw new IllegalArgumentException("Unknown package: " + packageName);
1901 }
1902
1903 final BasePermission bp;
1904 synchronized (mLock) {
1905 bp = mSettings.getPermissionLocked(permName);
1906 }
1907 if (bp == null) {
1908 throw new IllegalArgumentException("Unknown permission: " + permName);
1909 }
1910
1911 final PackageSetting ps = (PackageSetting) pkg.mExtras;
1912 final PermissionsState permissionsState = ps.getPermissionsState();
1913 final boolean hadState =
1914 permissionsState.getRuntimePermissionState(permName, userId) != null;
1915 final boolean permissionUpdated =
1916 permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues);
1917 if (permissionUpdated && callback != null) {
1918 // Install and runtime permissions are stored in different places,
1919 // so figure out what permission changed and persist the change.
1920 if (permissionsState.getInstallPermissionState(permName) != null) {
1921 callback.onInstallPermissionUpdated();
1922 } else if (permissionsState.getRuntimePermissionState(permName, userId) != null
1923 || hadState) {
Todd Kennedyc29b11a2017-10-23 15:55:59 -07001924 callback.onPermissionUpdated(new int[] { userId }, false);
Todd Kennedy0eb97382017-10-03 16:57:22 -07001925 }
1926 }
1927 }
1928
1929 private boolean updatePermissionFlagsForAllApps(int flagMask, int flagValues, int callingUid,
1930 int userId, Collection<Package> packages, PermissionCallback callback) {
1931 if (!mUserManagerInt.exists(userId)) {
1932 return false;
1933 }
1934
1935 enforceGrantRevokeRuntimePermissionPermissions(
1936 "updatePermissionFlagsForAllApps");
1937 enforceCrossUserPermission(callingUid, userId,
Todd Kennedyef9acb62018-05-29 15:18:06 -07001938 true, // requireFullPermission
1939 true, // checkShell
1940 false, // requirePermissionWhenSameUser
Todd Kennedy0eb97382017-10-03 16:57:22 -07001941 "updatePermissionFlagsForAllApps");
1942
1943 // Only the system can change system fixed flags.
1944 if (callingUid != Process.SYSTEM_UID) {
1945 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
1946 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
1947 }
1948
1949 boolean changed = false;
1950 for (PackageParser.Package pkg : packages) {
1951 final PackageSetting ps = (PackageSetting) pkg.mExtras;
1952 if (ps == null) {
1953 continue;
1954 }
1955 PermissionsState permissionsState = ps.getPermissionsState();
1956 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
1957 userId, flagMask, flagValues);
1958 }
1959 return changed;
1960 }
1961
1962 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
1963 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
1964 != PackageManager.PERMISSION_GRANTED
1965 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
1966 != PackageManager.PERMISSION_GRANTED) {
1967 throw new SecurityException(message + " requires "
1968 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
1969 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
1970 }
1971 }
1972
1973 /**
1974 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
1975 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
1976 * @param checkShell whether to prevent shell from access if there's a debugging restriction
1977 * @param message the message to log on security exception
1978 */
1979 private void enforceCrossUserPermission(int callingUid, int userId,
Todd Kennedyef9acb62018-05-29 15:18:06 -07001980 boolean requireFullPermission, boolean checkShell,
1981 boolean requirePermissionWhenSameUser, String message) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001982 if (userId < 0) {
1983 throw new IllegalArgumentException("Invalid userId " + userId);
1984 }
1985 if (checkShell) {
1986 PackageManagerServiceUtils.enforceShellRestriction(
1987 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
1988 }
Todd Kennedyef9acb62018-05-29 15:18:06 -07001989 if (!requirePermissionWhenSameUser && userId == UserHandle.getUserId(callingUid)) return;
Suprabh Shukla151b21b2018-04-27 19:30:30 -07001990 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07001991 if (requireFullPermission) {
1992 mContext.enforceCallingOrSelfPermission(
1993 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
1994 } else {
1995 try {
1996 mContext.enforceCallingOrSelfPermission(
1997 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
1998 } catch (SecurityException se) {
1999 mContext.enforceCallingOrSelfPermission(
2000 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2001 }
2002 }
2003 }
2004 }
2005
Andreas Gampea71bee82018-07-20 12:55:36 -07002006 @GuardedBy({"mSettings.mLock", "mLock"})
Todd Kennedy0eb97382017-10-03 16:57:22 -07002007 private int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2008 int size = 0;
Todd Kennedyc8423932017-10-05 08:58:36 -07002009 for (BasePermission perm : mSettings.mPermissions.values()) {
Todd Kennedy0eb97382017-10-03 16:57:22 -07002010 size += tree.calculateFootprint(perm);
2011 }
2012 return size;
2013 }
2014
Andreas Gampea71bee82018-07-20 12:55:36 -07002015 @GuardedBy({"mSettings.mLock", "mLock"})
Todd Kennedy0eb97382017-10-03 16:57:22 -07002016 private void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2017 // We calculate the max size of permissions defined by this uid and throw
2018 // if that plus the size of 'info' would exceed our stated maximum.
2019 if (tree.getUid() != Process.SYSTEM_UID) {
2020 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2021 if (curTreeSize + info.calculateFootprint() > MAX_PERMISSION_TREE_FOOTPRINT) {
2022 throw new SecurityException("Permission tree size cap exceeded");
2023 }
2024 }
2025 }
2026
Todd Kennedyc29b11a2017-10-23 15:55:59 -07002027 private void systemReady() {
2028 mSystemReady = true;
2029 if (mPrivappPermissionsViolations != null) {
2030 throw new IllegalStateException("Signature|privileged permissions not in "
2031 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
2032 }
2033 }
2034
2035 private static String getVolumeUuidForPackage(PackageParser.Package pkg) {
2036 if (pkg == null) {
2037 return StorageManager.UUID_PRIVATE_INTERNAL;
2038 }
2039 if (pkg.isExternal()) {
2040 if (TextUtils.isEmpty(pkg.volumeUuid)) {
2041 return StorageManager.UUID_PRIMARY_PHYSICAL;
2042 } else {
2043 return pkg.volumeUuid;
2044 }
2045 } else {
2046 return StorageManager.UUID_PRIVATE_INTERNAL;
2047 }
2048 }
2049
Todd Kennedyc8423932017-10-05 08:58:36 -07002050 private static boolean hasPermission(PackageParser.Package pkgInfo, String permName) {
2051 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
2052 if (pkgInfo.permissions.get(i).info.name.equals(permName)) {
2053 return true;
2054 }
2055 }
2056 return false;
2057 }
2058
Todd Kennedy0eb97382017-10-03 16:57:22 -07002059 /**
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -07002060 * Log that a permission request was granted/revoked.
Todd Kennedy0eb97382017-10-03 16:57:22 -07002061 *
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -07002062 * @param action the action performed
Todd Kennedy0eb97382017-10-03 16:57:22 -07002063 * @param name name of the permission
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -07002064 * @param packageName package permission is for
Todd Kennedy0eb97382017-10-03 16:57:22 -07002065 */
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -07002066 private void logPermission(int action, @NonNull String name, @NonNull String packageName) {
2067 final LogMaker log = new LogMaker(action);
2068 log.setPackageName(packageName);
2069 log.addTaggedData(MetricsEvent.FIELD_PERMISSION, name);
Todd Kennedy0eb97382017-10-03 16:57:22 -07002070
Philip P. Moltmann8cff8b92017-10-25 14:32:41 -07002071 mMetricsLogger.write(log);
Todd Kennedy0eb97382017-10-03 16:57:22 -07002072 }
2073
2074 private class PermissionManagerInternalImpl extends PermissionManagerInternal {
2075 @Override
Todd Kennedyc29b11a2017-10-23 15:55:59 -07002076 public void systemReady() {
2077 PermissionManagerService.this.systemReady();
2078 }
2079 @Override
2080 public boolean isPermissionsReviewRequired(Package pkg, int userId) {
2081 return PermissionManagerService.this.isPermissionsReviewRequired(pkg, userId);
2082 }
2083 @Override
Philip P. Moltmannfae8a5282018-04-10 12:15:32 -07002084 public void revokeRuntimePermissionsIfGroupChanged(
2085 @NonNull PackageParser.Package newPackage,
2086 @NonNull PackageParser.Package oldPackage,
2087 @NonNull ArrayList<String> allPackageNames,
2088 @NonNull PermissionCallback permissionCallback) {
2089 PermissionManagerService.this.revokeRuntimePermissionsIfGroupChanged(newPackage,
2090 oldPackage, allPackageNames, permissionCallback);
2091 }
2092 @Override
Todd Kennedyc8423932017-10-05 08:58:36 -07002093 public void addAllPermissions(Package pkg, boolean chatty) {
2094 PermissionManagerService.this.addAllPermissions(pkg, chatty);
Todd Kennedy0eb97382017-10-03 16:57:22 -07002095 }
2096 @Override
Todd Kennedy460f28c2017-10-06 13:46:22 -07002097 public void addAllPermissionGroups(Package pkg, boolean chatty) {
2098 PermissionManagerService.this.addAllPermissionGroups(pkg, chatty);
2099 }
2100 @Override
Hongming Jinae750fb2018-09-27 23:00:20 +00002101 public void removeAllPermissions(Package pkg, boolean chatty) {
2102 PermissionManagerService.this.removeAllPermissions(pkg, chatty);
Todd Kennedyc8423932017-10-05 08:58:36 -07002103 }
2104 @Override
2105 public boolean addDynamicPermission(PermissionInfo info, boolean async, int callingUid,
Todd Kennedy0eb97382017-10-03 16:57:22 -07002106 PermissionCallback callback) {
Todd Kennedyc8423932017-10-05 08:58:36 -07002107 return PermissionManagerService.this.addDynamicPermission(info, callingUid, callback);
2108 }
2109 @Override
2110 public void removeDynamicPermission(String permName, int callingUid,
2111 PermissionCallback callback) {
2112 PermissionManagerService.this.removeDynamicPermission(permName, callingUid, callback);
Todd Kennedy0eb97382017-10-03 16:57:22 -07002113 }
2114 @Override
2115 public void grantRuntimePermission(String permName, String packageName,
2116 boolean overridePolicy, int callingUid, int userId,
2117 PermissionCallback callback) {
2118 PermissionManagerService.this.grantRuntimePermission(
2119 permName, packageName, overridePolicy, callingUid, userId, callback);
2120 }
2121 @Override
2122 public void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2123 String[] grantedPermissions, int callingUid, PermissionCallback callback) {
2124 PermissionManagerService.this.grantRequestedRuntimePermissions(
2125 pkg, userIds, grantedPermissions, callingUid, callback);
2126 }
2127 @Override
2128 public void grantRuntimePermissionsGrantedToDisabledPackage(PackageParser.Package pkg,
2129 int callingUid, PermissionCallback callback) {
2130 PermissionManagerService.this.grantRuntimePermissionsGrantedToDisabledPackageLocked(
2131 pkg, callingUid, callback);
2132 }
2133 @Override
2134 public void revokeRuntimePermission(String permName, String packageName,
2135 boolean overridePolicy, int callingUid, int userId,
2136 PermissionCallback callback) {
2137 PermissionManagerService.this.revokeRuntimePermission(permName, packageName,
Hongming Jinae750fb2018-09-27 23:00:20 +00002138 overridePolicy, callingUid, userId, callback);
Todd Kennedy0eb97382017-10-03 16:57:22 -07002139 }
2140 @Override
Todd Kennedyc29b11a2017-10-23 15:55:59 -07002141 public void updatePermissions(String packageName, Package pkg, boolean replaceGrant,
2142 Collection<PackageParser.Package> allPackages, PermissionCallback callback) {
2143 PermissionManagerService.this.updatePermissions(
2144 packageName, pkg, replaceGrant, allPackages, callback);
2145 }
2146 @Override
2147 public void updateAllPermissions(String volumeUuid, boolean sdkUpdated,
2148 Collection<PackageParser.Package> allPackages, PermissionCallback callback) {
2149 PermissionManagerService.this.updateAllPermissions(
2150 volumeUuid, sdkUpdated, allPackages, callback);
Todd Kennedy0eb97382017-10-03 16:57:22 -07002151 }
2152 @Override
Todd Kennedyc8423932017-10-05 08:58:36 -07002153 public String[] getAppOpPermissionPackages(String permName) {
2154 return PermissionManagerService.this.getAppOpPermissionPackages(permName);
2155 }
2156 @Override
Todd Kennedy0eb97382017-10-03 16:57:22 -07002157 public int getPermissionFlags(String permName, String packageName, int callingUid,
2158 int userId) {
2159 return PermissionManagerService.this.getPermissionFlags(permName, packageName,
2160 callingUid, userId);
2161 }
2162 @Override
2163 public void updatePermissionFlags(String permName, String packageName, int flagMask,
2164 int flagValues, int callingUid, int userId, PermissionCallback callback) {
2165 PermissionManagerService.this.updatePermissionFlags(
2166 permName, packageName, flagMask, flagValues, callingUid, userId, callback);
2167 }
2168 @Override
2169 public boolean updatePermissionFlagsForAllApps(int flagMask, int flagValues, int callingUid,
2170 int userId, Collection<Package> packages, PermissionCallback callback) {
2171 return PermissionManagerService.this.updatePermissionFlagsForAllApps(
2172 flagMask, flagValues, callingUid, userId, packages, callback);
2173 }
2174 @Override
2175 public void enforceCrossUserPermission(int callingUid, int userId,
2176 boolean requireFullPermission, boolean checkShell, String message) {
2177 PermissionManagerService.this.enforceCrossUserPermission(callingUid, userId,
Todd Kennedyef9acb62018-05-29 15:18:06 -07002178 requireFullPermission, checkShell, false, message);
2179 }
2180 @Override
2181 public void enforceCrossUserPermission(int callingUid, int userId,
2182 boolean requireFullPermission, boolean checkShell,
2183 boolean requirePermissionWhenSameUser, String message) {
2184 PermissionManagerService.this.enforceCrossUserPermission(callingUid, userId,
2185 requireFullPermission, checkShell, requirePermissionWhenSameUser, message);
Todd Kennedy0eb97382017-10-03 16:57:22 -07002186 }
2187 @Override
2188 public void enforceGrantRevokeRuntimePermissionPermissions(String message) {
2189 PermissionManagerService.this.enforceGrantRevokeRuntimePermissionPermissions(message);
2190 }
2191 @Override
2192 public int checkPermission(String permName, String packageName, int callingUid,
2193 int userId) {
2194 return PermissionManagerService.this.checkPermission(
2195 permName, packageName, callingUid, userId);
2196 }
2197 @Override
Todd Kennedy3c714492017-10-27 09:12:50 -07002198 public int checkUidPermission(String permName, PackageParser.Package pkg, int uid,
2199 int callingUid) {
2200 return PermissionManagerService.this.checkUidPermission(permName, pkg, uid, callingUid);
Todd Kennedy3bc94722017-10-10 09:55:53 -07002201 }
2202 @Override
Todd Kennedy460f28c2017-10-06 13:46:22 -07002203 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags,
2204 int callingUid) {
2205 return PermissionManagerService.this.getPermissionGroupInfo(
2206 groupName, flags, callingUid);
2207 }
2208 @Override
2209 public List<PermissionGroupInfo> getAllPermissionGroups(int flags, int callingUid) {
2210 return PermissionManagerService.this.getAllPermissionGroups(flags, callingUid);
2211 }
2212 @Override
Todd Kennedy0eb97382017-10-03 16:57:22 -07002213 public PermissionInfo getPermissionInfo(String permName, String packageName, int flags,
2214 int callingUid) {
2215 return PermissionManagerService.this.getPermissionInfo(
2216 permName, packageName, flags, callingUid);
2217 }
2218 @Override
2219 public List<PermissionInfo> getPermissionInfoByGroup(String group, int flags,
2220 int callingUid) {
2221 return PermissionManagerService.this.getPermissionInfoByGroup(group, flags, callingUid);
2222 }
2223 @Override
Todd Kennedy0eb97382017-10-03 16:57:22 -07002224 public PermissionSettings getPermissionSettings() {
2225 return mSettings;
2226 }
2227 @Override
2228 public DefaultPermissionGrantPolicy getDefaultPermissionGrantPolicy() {
2229 return mDefaultPermissionGrantPolicy;
2230 }
2231 @Override
2232 public BasePermission getPermissionTEMP(String permName) {
2233 synchronized (PermissionManagerService.this.mLock) {
2234 return mSettings.getPermissionLocked(permName);
2235 }
2236 }
Todd Kennedy0eb97382017-10-03 16:57:22 -07002237 }
2238}