PermissionManagerService.java revision f5e600d073e7b3c7a6ba36c904c9d51acfaaf6ff
1/* 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; 21import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 22import static com.android.server.pm.PackageManagerService.DEBUG_INSTALL; 23import static com.android.server.pm.PackageManagerService.DEBUG_PACKAGE_SCANNING; 24import static com.android.server.pm.PackageManagerService.DEBUG_PERMISSIONS; 25import static com.android.server.pm.PackageManagerService.DEBUG_REMOVE; 26import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 27import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 28 29import android.Manifest; 30import android.annotation.NonNull; 31import android.annotation.Nullable; 32import android.app.AppOpsManager; 33import android.content.Context; 34import android.content.pm.PackageManager; 35import android.content.pm.PackageManagerInternal; 36import android.content.pm.PackageParser; 37import android.content.pm.PermissionGroupInfo; 38import android.content.pm.PermissionInfo; 39import android.content.pm.PackageParser.Package; 40import android.os.Binder; 41import android.os.Build; 42import android.os.Handler; 43import android.os.HandlerThread; 44import android.os.Process; 45import android.os.Trace; 46import android.os.UserHandle; 47import android.os.UserManager; 48import android.os.UserManagerInternal; 49import android.os.storage.StorageManager; 50import android.os.storage.StorageManagerInternal; 51import android.text.TextUtils; 52import android.util.ArrayMap; 53import android.util.ArraySet; 54import android.util.Log; 55import android.util.Slog; 56import android.util.SparseArray; 57 58import com.android.internal.R; 59import com.android.internal.annotations.GuardedBy; 60import com.android.internal.logging.MetricsLogger; 61import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 62import com.android.internal.os.RoSystemProperties; 63import com.android.internal.util.ArrayUtils; 64import com.android.server.FgThread; 65import com.android.server.LocalServices; 66import com.android.server.ServiceThread; 67import com.android.server.SystemConfig; 68import com.android.server.Watchdog; 69import com.android.server.pm.PackageManagerService; 70import com.android.server.pm.PackageManagerServiceUtils; 71import com.android.server.pm.PackageSetting; 72import com.android.server.pm.ProcessLoggingHandler; 73import com.android.server.pm.SharedUserSetting; 74import com.android.server.pm.UserManagerService; 75import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 76import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 77import com.android.server.pm.permission.PermissionsState.PermissionState; 78 79import libcore.util.EmptyArray; 80 81import java.util.ArrayList; 82import java.util.Arrays; 83import java.util.Collection; 84import java.util.Iterator; 85import java.util.List; 86import java.util.Objects; 87import java.util.Set; 88 89/** 90 * Manages all permissions and handles permissions related tasks. 91 */ 92public class PermissionManagerService { 93 private static final String TAG = "PackageManager"; 94 95 /** All dangerous permission names in the same order as the events in MetricsEvent */ 96 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 97 Manifest.permission.READ_CALENDAR, 98 Manifest.permission.WRITE_CALENDAR, 99 Manifest.permission.CAMERA, 100 Manifest.permission.READ_CONTACTS, 101 Manifest.permission.WRITE_CONTACTS, 102 Manifest.permission.GET_ACCOUNTS, 103 Manifest.permission.ACCESS_FINE_LOCATION, 104 Manifest.permission.ACCESS_COARSE_LOCATION, 105 Manifest.permission.RECORD_AUDIO, 106 Manifest.permission.READ_PHONE_STATE, 107 Manifest.permission.CALL_PHONE, 108 Manifest.permission.READ_CALL_LOG, 109 Manifest.permission.WRITE_CALL_LOG, 110 Manifest.permission.ADD_VOICEMAIL, 111 Manifest.permission.USE_SIP, 112 Manifest.permission.PROCESS_OUTGOING_CALLS, 113 Manifest.permission.READ_CELL_BROADCASTS, 114 Manifest.permission.BODY_SENSORS, 115 Manifest.permission.SEND_SMS, 116 Manifest.permission.RECEIVE_SMS, 117 Manifest.permission.READ_SMS, 118 Manifest.permission.RECEIVE_WAP_PUSH, 119 Manifest.permission.RECEIVE_MMS, 120 Manifest.permission.READ_EXTERNAL_STORAGE, 121 Manifest.permission.WRITE_EXTERNAL_STORAGE, 122 Manifest.permission.READ_PHONE_NUMBERS, 123 Manifest.permission.ANSWER_PHONE_CALLS); 124 125 /** Permission grant: not grant the permission. */ 126 private static final int GRANT_DENIED = 1; 127 /** Permission grant: grant the permission as an install permission. */ 128 private static final int GRANT_INSTALL = 2; 129 /** Permission grant: grant the permission as a runtime one. */ 130 private static final int GRANT_RUNTIME = 3; 131 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 132 private static final int GRANT_UPGRADE = 4; 133 134 /** Cap the size of permission trees that 3rd party apps can define; in characters of text */ 135 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; 136 /** Empty array to avoid allocations */ 137 private static final int[] EMPTY_INT_ARRAY = new int[0]; 138 139 /** Lock to protect internal data access */ 140 private final Object mLock; 141 142 /** Internal connection to the package manager */ 143 private final PackageManagerInternal mPackageManagerInt; 144 145 /** Internal connection to the user manager */ 146 private final UserManagerInternal mUserManagerInt; 147 148 /** Default permission policy to provide proper behaviour out-of-the-box */ 149 private final DefaultPermissionGrantPolicy mDefaultPermissionGrantPolicy; 150 151 /** 152 * Built-in permissions. Read from system configuration files. Mapping is from 153 * UID to permission name. 154 */ 155 private final SparseArray<ArraySet<String>> mSystemPermissions; 156 157 /** Built-in group IDs given to all packages. Read from system configuration files. */ 158 private final int[] mGlobalGids; 159 160 private final HandlerThread mHandlerThread; 161 private final Handler mHandler; 162 private final Context mContext; 163 164 /** Internal storage for permissions and related settings */ 165 @GuardedBy("mLock") 166 private final PermissionSettings mSettings; 167 168 @GuardedBy("mLock") 169 private ArraySet<String> mPrivappPermissionsViolations; 170 171 @GuardedBy("mLock") 172 private boolean mSystemReady; 173 174 PermissionManagerService(Context context, 175 @Nullable DefaultPermissionGrantedCallback defaultGrantCallback, 176 @NonNull Object externalLock) { 177 mContext = context; 178 mLock = externalLock; 179 mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class); 180 mUserManagerInt = LocalServices.getService(UserManagerInternal.class); 181 mSettings = new PermissionSettings(context, mLock); 182 183 mHandlerThread = new ServiceThread(TAG, 184 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 185 mHandlerThread.start(); 186 mHandler = new Handler(mHandlerThread.getLooper()); 187 Watchdog.getInstance().addThread(mHandler); 188 189 mDefaultPermissionGrantPolicy = new DefaultPermissionGrantPolicy( 190 context, mHandlerThread.getLooper(), defaultGrantCallback, this); 191 SystemConfig systemConfig = SystemConfig.getInstance(); 192 mSystemPermissions = systemConfig.getSystemPermissions(); 193 mGlobalGids = systemConfig.getGlobalGids(); 194 195 // propagate permission configuration 196 final ArrayMap<String, SystemConfig.PermissionEntry> permConfig = 197 SystemConfig.getInstance().getPermissions(); 198 synchronized (mLock) { 199 for (int i=0; i<permConfig.size(); i++) { 200 final SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 201 BasePermission bp = mSettings.getPermissionLocked(perm.name); 202 if (bp == null) { 203 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 204 mSettings.putPermissionLocked(perm.name, bp); 205 } 206 if (perm.gids != null) { 207 bp.setGids(perm.gids, perm.perUser); 208 } 209 } 210 } 211 212 LocalServices.addService( 213 PermissionManagerInternal.class, new PermissionManagerInternalImpl()); 214 } 215 216 /** 217 * Creates and returns an initialized, internal service for use by other components. 218 * <p> 219 * The object returned is identical to the one returned by the LocalServices class using: 220 * {@code LocalServices.getService(PermissionManagerInternal.class);} 221 * <p> 222 * NOTE: The external lock is temporary and should be removed. This needs to be a 223 * lock created by the permission manager itself. 224 */ 225 public static PermissionManagerInternal create(Context context, 226 @Nullable DefaultPermissionGrantedCallback defaultGrantCallback, 227 @NonNull Object externalLock) { 228 final PermissionManagerInternal permMgrInt = 229 LocalServices.getService(PermissionManagerInternal.class); 230 if (permMgrInt != null) { 231 return permMgrInt; 232 } 233 new PermissionManagerService(context, defaultGrantCallback, externalLock); 234 return LocalServices.getService(PermissionManagerInternal.class); 235 } 236 237 @Nullable BasePermission getPermission(String permName) { 238 synchronized (mLock) { 239 return mSettings.getPermissionLocked(permName); 240 } 241 } 242 243 private int checkPermission(String permName, String pkgName, int callingUid, int userId) { 244 if (!mUserManagerInt.exists(userId)) { 245 return PackageManager.PERMISSION_DENIED; 246 } 247 248 final PackageParser.Package pkg = mPackageManagerInt.getPackage(pkgName); 249 if (pkg != null && pkg.mExtras != null) { 250 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) { 251 return PackageManager.PERMISSION_DENIED; 252 } 253 final PackageSetting ps = (PackageSetting) pkg.mExtras; 254 final boolean instantApp = ps.getInstantApp(userId); 255 final PermissionsState permissionsState = ps.getPermissionsState(); 256 if (permissionsState.hasPermission(permName, userId)) { 257 if (instantApp) { 258 synchronized (mLock) { 259 BasePermission bp = mSettings.getPermissionLocked(permName); 260 if (bp != null && bp.isInstant()) { 261 return PackageManager.PERMISSION_GRANTED; 262 } 263 } 264 } else { 265 return PackageManager.PERMISSION_GRANTED; 266 } 267 } 268 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 269 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 270 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 271 return PackageManager.PERMISSION_GRANTED; 272 } 273 } 274 275 return PackageManager.PERMISSION_DENIED; 276 } 277 278 private int checkUidPermission(String permName, int uid, int callingUid) { 279 final int callingUserId = UserHandle.getUserId(callingUid); 280 final boolean isCallerInstantApp = 281 mPackageManagerInt.getInstantAppPackageName(callingUid) != null; 282 final boolean isUidInstantApp = 283 mPackageManagerInt.getInstantAppPackageName(uid) != null; 284 final int userId = UserHandle.getUserId(uid); 285 if (!mUserManagerInt.exists(userId)) { 286 return PackageManager.PERMISSION_DENIED; 287 } 288 289 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid); 290 if (packages != null && packages.length > 0) { 291 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packages[0]); 292 if (pkg.mSharedUserId != null) { 293 if (isCallerInstantApp) { 294 return PackageManager.PERMISSION_DENIED; 295 } 296 } else { 297 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, callingUserId)) { 298 return PackageManager.PERMISSION_DENIED; 299 } 300 } 301 final PermissionsState permissionsState = 302 ((PackageSetting) pkg.mExtras).getPermissionsState(); 303 if (permissionsState.hasPermission(permName, userId)) { 304 if (isUidInstantApp) { 305 if (mSettings.isPermissionInstant(permName)) { 306 return PackageManager.PERMISSION_GRANTED; 307 } 308 } else { 309 return PackageManager.PERMISSION_GRANTED; 310 } 311 } 312 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 313 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 314 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 315 return PackageManager.PERMISSION_GRANTED; 316 } 317 } else { 318 ArraySet<String> perms = mSystemPermissions.get(uid); 319 if (perms != null) { 320 if (perms.contains(permName)) { 321 return PackageManager.PERMISSION_GRANTED; 322 } 323 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 324 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 325 return PackageManager.PERMISSION_GRANTED; 326 } 327 } 328 } 329 return PackageManager.PERMISSION_DENIED; 330 } 331 332 private PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags, 333 int callingUid) { 334 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) { 335 return null; 336 } 337 synchronized (mLock) { 338 return PackageParser.generatePermissionGroupInfo( 339 mSettings.mPermissionGroups.get(groupName), flags); 340 } 341 } 342 343 private List<PermissionGroupInfo> getAllPermissionGroups(int flags, int callingUid) { 344 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) { 345 return null; 346 } 347 synchronized (mLock) { 348 final int N = mSettings.mPermissionGroups.size(); 349 final ArrayList<PermissionGroupInfo> out 350 = new ArrayList<PermissionGroupInfo>(N); 351 for (PackageParser.PermissionGroup pg : mSettings.mPermissionGroups.values()) { 352 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 353 } 354 return out; 355 } 356 } 357 358 private PermissionInfo getPermissionInfo(String permName, String packageName, int flags, 359 int callingUid) { 360 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) { 361 return null; 362 } 363 // reader 364 synchronized (mLock) { 365 final BasePermission bp = mSettings.getPermissionLocked(permName); 366 if (bp == null) { 367 return null; 368 } 369 final int adjustedProtectionLevel = adjustPermissionProtectionFlagsLocked( 370 bp.getProtectionLevel(), packageName, callingUid); 371 return bp.generatePermissionInfo(adjustedProtectionLevel, flags); 372 } 373 } 374 375 private List<PermissionInfo> getPermissionInfoByGroup( 376 String groupName, int flags, int callingUid) { 377 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) { 378 return null; 379 } 380 synchronized (mLock) { 381 if (groupName != null && !mSettings.mPermissionGroups.containsKey(groupName)) { 382 return null; 383 } 384 final ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 385 for (BasePermission bp : mSettings.mPermissions.values()) { 386 final PermissionInfo pi = bp.generatePermissionInfo(groupName, flags); 387 if (pi != null) { 388 out.add(pi); 389 } 390 } 391 return out; 392 } 393 } 394 395 private int adjustPermissionProtectionFlagsLocked( 396 int protectionLevel, String packageName, int uid) { 397 // Signature permission flags area always reported 398 final int protectionLevelMasked = protectionLevel 399 & (PermissionInfo.PROTECTION_NORMAL 400 | PermissionInfo.PROTECTION_DANGEROUS 401 | PermissionInfo.PROTECTION_SIGNATURE); 402 if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) { 403 return protectionLevel; 404 } 405 // System sees all flags. 406 final int appId = UserHandle.getAppId(uid); 407 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID 408 || appId == Process.SHELL_UID) { 409 return protectionLevel; 410 } 411 // Normalize package name to handle renamed packages and static libs 412 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName); 413 if (pkg == null) { 414 return protectionLevel; 415 } 416 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 417 return protectionLevelMasked; 418 } 419 // Apps that target O see flags for all protection levels. 420 final PackageSetting ps = (PackageSetting) pkg.mExtras; 421 if (ps == null) { 422 return protectionLevel; 423 } 424 if (ps.getAppId() != appId) { 425 return protectionLevel; 426 } 427 return protectionLevel; 428 } 429 430 private void addAllPermissions(PackageParser.Package pkg, boolean chatty) { 431 final int N = pkg.permissions.size(); 432 for (int i=0; i<N; i++) { 433 PackageParser.Permission p = pkg.permissions.get(i); 434 435 // Assume by default that we did not install this permission into the system. 436 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 437 438 synchronized (PermissionManagerService.this.mLock) { 439 // Now that permission groups have a special meaning, we ignore permission 440 // groups for legacy apps to prevent unexpected behavior. In particular, 441 // permissions for one app being granted to someone just because they happen 442 // to be in a group defined by another app (before this had no implications). 443 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 444 p.group = mSettings.mPermissionGroups.get(p.info.group); 445 // Warn for a permission in an unknown group. 446 if (DEBUG_PERMISSIONS 447 && p.info.group != null && p.group == null) { 448 Slog.i(TAG, "Permission " + p.info.name + " from package " 449 + p.info.packageName + " in an unknown group " + p.info.group); 450 } 451 } 452 453 if (p.tree) { 454 final BasePermission bp = BasePermission.createOrUpdate( 455 mSettings.getPermissionTreeLocked(p.info.name), p, pkg, 456 mSettings.getAllPermissionTreesLocked(), chatty); 457 mSettings.putPermissionTreeLocked(p.info.name, bp); 458 } else { 459 final BasePermission bp = BasePermission.createOrUpdate( 460 mSettings.getPermissionLocked(p.info.name), 461 p, pkg, mSettings.getAllPermissionTreesLocked(), chatty); 462 mSettings.putPermissionLocked(p.info.name, bp); 463 } 464 } 465 } 466 } 467 468 private void addAllPermissionGroups(PackageParser.Package pkg, boolean chatty) { 469 final int N = pkg.permissionGroups.size(); 470 StringBuilder r = null; 471 for (int i=0; i<N; i++) { 472 final PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 473 final PackageParser.PermissionGroup cur = mSettings.mPermissionGroups.get(pg.info.name); 474 final String curPackageName = (cur == null) ? null : cur.info.packageName; 475 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 476 if (cur == null || isPackageUpdate) { 477 mSettings.mPermissionGroups.put(pg.info.name, pg); 478 if (chatty && DEBUG_PACKAGE_SCANNING) { 479 if (r == null) { 480 r = new StringBuilder(256); 481 } else { 482 r.append(' '); 483 } 484 if (isPackageUpdate) { 485 r.append("UPD:"); 486 } 487 r.append(pg.info.name); 488 } 489 } else { 490 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 491 + pg.info.packageName + " ignored: original from " 492 + cur.info.packageName); 493 if (chatty && DEBUG_PACKAGE_SCANNING) { 494 if (r == null) { 495 r = new StringBuilder(256); 496 } else { 497 r.append(' '); 498 } 499 r.append("DUP:"); 500 r.append(pg.info.name); 501 } 502 } 503 } 504 if (r != null && DEBUG_PACKAGE_SCANNING) { 505 Log.d(TAG, " Permission Groups: " + r); 506 } 507 508 } 509 510 private void removeAllPermissions(PackageParser.Package pkg, boolean chatty) { 511 synchronized (mLock) { 512 int N = pkg.permissions.size(); 513 StringBuilder r = null; 514 for (int i=0; i<N; i++) { 515 PackageParser.Permission p = pkg.permissions.get(i); 516 BasePermission bp = (BasePermission) mSettings.mPermissions.get(p.info.name); 517 if (bp == null) { 518 bp = mSettings.mPermissionTrees.get(p.info.name); 519 } 520 if (bp != null && bp.isPermission(p)) { 521 bp.setPermission(null); 522 if (DEBUG_REMOVE && chatty) { 523 if (r == null) { 524 r = new StringBuilder(256); 525 } else { 526 r.append(' '); 527 } 528 r.append(p.info.name); 529 } 530 } 531 if (p.isAppOp()) { 532 ArraySet<String> appOpPkgs = 533 mSettings.mAppOpPermissionPackages.get(p.info.name); 534 if (appOpPkgs != null) { 535 appOpPkgs.remove(pkg.packageName); 536 } 537 } 538 } 539 if (r != null) { 540 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 541 } 542 543 N = pkg.requestedPermissions.size(); 544 r = null; 545 for (int i=0; i<N; i++) { 546 String perm = pkg.requestedPermissions.get(i); 547 if (mSettings.isPermissionAppOp(perm)) { 548 ArraySet<String> appOpPkgs = mSettings.mAppOpPermissionPackages.get(perm); 549 if (appOpPkgs != null) { 550 appOpPkgs.remove(pkg.packageName); 551 if (appOpPkgs.isEmpty()) { 552 mSettings.mAppOpPermissionPackages.remove(perm); 553 } 554 } 555 } 556 } 557 if (r != null) { 558 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 559 } 560 } 561 } 562 563 private boolean addDynamicPermission( 564 PermissionInfo info, int callingUid, PermissionCallback callback) { 565 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) { 566 throw new SecurityException("Instant apps can't add permissions"); 567 } 568 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 569 throw new SecurityException("Label must be specified in permission"); 570 } 571 final BasePermission tree = mSettings.enforcePermissionTree(info.name, callingUid); 572 final boolean added; 573 final boolean changed; 574 synchronized (mLock) { 575 BasePermission bp = mSettings.getPermissionLocked(info.name); 576 added = bp == null; 577 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 578 if (added) { 579 enforcePermissionCapLocked(info, tree); 580 bp = new BasePermission(info.name, tree.getSourcePackageName(), 581 BasePermission.TYPE_DYNAMIC); 582 } else if (bp.isDynamic()) { 583 // TODO: switch this back to SecurityException 584 Slog.wtf(TAG, "Not allowed to modify non-dynamic permission " 585 + info.name); 586 } 587 changed = bp.addToTree(fixedLevel, info, tree); 588 if (added) { 589 mSettings.putPermissionLocked(info.name, bp); 590 } 591 } 592 if (changed && callback != null) { 593 callback.onPermissionChanged(); 594 } 595 return added; 596 } 597 598 private void removeDynamicPermission( 599 String permName, int callingUid, PermissionCallback callback) { 600 if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) { 601 throw new SecurityException("Instant applications don't have access to this method"); 602 } 603 final BasePermission tree = mSettings.enforcePermissionTree(permName, callingUid); 604 synchronized (mLock) { 605 final BasePermission bp = mSettings.getPermissionLocked(permName); 606 if (bp == null) { 607 return; 608 } 609 if (bp.isDynamic()) { 610 // TODO: switch this back to SecurityException 611 Slog.wtf(TAG, "Not allowed to modify non-dynamic permission " 612 + permName); 613 } 614 mSettings.removePermissionLocked(permName); 615 if (callback != null) { 616 callback.onPermissionRemoved(); 617 } 618 } 619 } 620 621 private void grantPermissions(PackageParser.Package pkg, boolean replace, 622 String packageOfInterest, PermissionCallback callback) { 623 // IMPORTANT: There are two types of permissions: install and runtime. 624 // Install time permissions are granted when the app is installed to 625 // all device users and users added in the future. Runtime permissions 626 // are granted at runtime explicitly to specific users. Normal and signature 627 // protected permissions are install time permissions. Dangerous permissions 628 // are install permissions if the app's target SDK is Lollipop MR1 or older, 629 // otherwise they are runtime permissions. This function does not manage 630 // runtime permissions except for the case an app targeting Lollipop MR1 631 // being upgraded to target a newer SDK, in which case dangerous permissions 632 // are transformed from install time to runtime ones. 633 634 final PackageSetting ps = (PackageSetting) pkg.mExtras; 635 if (ps == null) { 636 return; 637 } 638 final boolean isLegacySystemApp = mPackageManagerInt.isLegacySystemApp(pkg); 639 640 final PermissionsState permissionsState = ps.getPermissionsState(); 641 PermissionsState origPermissions = permissionsState; 642 643 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 644 645 boolean runtimePermissionsRevoked = false; 646 int[] updatedUserIds = EMPTY_INT_ARRAY; 647 648 boolean changedInstallPermission = false; 649 650 if (replace) { 651 ps.setInstallPermissionsFixed(false); 652 if (!ps.isSharedUser()) { 653 origPermissions = new PermissionsState(permissionsState); 654 permissionsState.reset(); 655 } else { 656 // We need to know only about runtime permission changes since the 657 // calling code always writes the install permissions state but 658 // the runtime ones are written only if changed. The only cases of 659 // changed runtime permissions here are promotion of an install to 660 // runtime and revocation of a runtime from a shared user. 661 synchronized (mLock) { 662 updatedUserIds = revokeUnusedSharedUserPermissionsLocked( 663 ps.getSharedUser(), UserManagerService.getInstance().getUserIds()); 664 if (!ArrayUtils.isEmpty(updatedUserIds)) { 665 runtimePermissionsRevoked = true; 666 } 667 } 668 } 669 } 670 671 permissionsState.setGlobalGids(mGlobalGids); 672 673 synchronized (mLock) { 674 final int N = pkg.requestedPermissions.size(); 675 for (int i = 0; i < N; i++) { 676 final String permName = pkg.requestedPermissions.get(i); 677 final BasePermission bp = mSettings.getPermissionLocked(permName); 678 final boolean appSupportsRuntimePermissions = 679 pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M; 680 681 if (DEBUG_INSTALL) { 682 Log.i(TAG, "Package " + pkg.packageName + " checking " + permName + ": " + bp); 683 } 684 685 if (bp == null || bp.getSourcePackageSetting() == null) { 686 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 687 if (DEBUG_PERMISSIONS) { 688 Slog.i(TAG, "Unknown permission " + permName 689 + " in package " + pkg.packageName); 690 } 691 } 692 continue; 693 } 694 695 // Limit ephemeral apps to ephemeral allowed permissions. 696 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 697 if (DEBUG_PERMISSIONS) { 698 Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() 699 + " for package " + pkg.packageName); 700 } 701 continue; 702 } 703 704 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 705 if (DEBUG_PERMISSIONS) { 706 Log.i(TAG, "Denying runtime-only permission " + bp.getName() 707 + " for package " + pkg.packageName); 708 } 709 continue; 710 } 711 712 final String perm = bp.getName(); 713 boolean allowedSig = false; 714 int grant = GRANT_DENIED; 715 716 // Keep track of app op permissions. 717 if (bp.isAppOp()) { 718 mSettings.addAppOpPackage(perm, pkg.packageName); 719 } 720 721 if (bp.isNormal()) { 722 // For all apps normal permissions are install time ones. 723 grant = GRANT_INSTALL; 724 } else if (bp.isRuntime()) { 725 // If a permission review is required for legacy apps we represent 726 // their permissions as always granted runtime ones since we need 727 // to keep the review required permission flag per user while an 728 // install permission's state is shared across all users. 729 if (!appSupportsRuntimePermissions && !mSettings.mPermissionReviewRequired) { 730 // For legacy apps dangerous permissions are install time ones. 731 grant = GRANT_INSTALL; 732 } else if (origPermissions.hasInstallPermission(bp.getName())) { 733 // For legacy apps that became modern, install becomes runtime. 734 grant = GRANT_UPGRADE; 735 } else if (isLegacySystemApp) { 736 // For legacy system apps, install becomes runtime. 737 // We cannot check hasInstallPermission() for system apps since those 738 // permissions were granted implicitly and not persisted pre-M. 739 grant = GRANT_UPGRADE; 740 } else { 741 // For modern apps keep runtime permissions unchanged. 742 grant = GRANT_RUNTIME; 743 } 744 } else if (bp.isSignature()) { 745 // For all apps signature permissions are install time ones. 746 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 747 if (allowedSig) { 748 grant = GRANT_INSTALL; 749 } 750 } 751 752 if (DEBUG_PERMISSIONS) { 753 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName); 754 } 755 756 if (grant != GRANT_DENIED) { 757 if (!ps.isSystem() && ps.areInstallPermissionsFixed()) { 758 // If this is an existing, non-system package, then 759 // we can't add any new permissions to it. 760 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 761 // Except... if this is a permission that was added 762 // to the platform (note: need to only do this when 763 // updating the platform). 764 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 765 grant = GRANT_DENIED; 766 } 767 } 768 } 769 770 switch (grant) { 771 case GRANT_INSTALL: { 772 // Revoke this as runtime permission to handle the case of 773 // a runtime permission being downgraded to an install one. 774 // Also in permission review mode we keep dangerous permissions 775 // for legacy apps 776 for (int userId : UserManagerService.getInstance().getUserIds()) { 777 if (origPermissions.getRuntimePermissionState( 778 perm, userId) != null) { 779 // Revoke the runtime permission and clear the flags. 780 origPermissions.revokeRuntimePermission(bp, userId); 781 origPermissions.updatePermissionFlags(bp, userId, 782 PackageManager.MASK_PERMISSION_FLAGS, 0); 783 // If we revoked a permission permission, we have to write. 784 updatedUserIds = ArrayUtils.appendInt( 785 updatedUserIds, userId); 786 } 787 } 788 // Grant an install permission. 789 if (permissionsState.grantInstallPermission(bp) != 790 PermissionsState.PERMISSION_OPERATION_FAILURE) { 791 changedInstallPermission = true; 792 } 793 } break; 794 795 case GRANT_RUNTIME: { 796 // Grant previously granted runtime permissions. 797 for (int userId : UserManagerService.getInstance().getUserIds()) { 798 final PermissionState permissionState = origPermissions 799 .getRuntimePermissionState(perm, userId); 800 int flags = permissionState != null 801 ? permissionState.getFlags() : 0; 802 if (origPermissions.hasRuntimePermission(perm, userId)) { 803 // Don't propagate the permission in a permission review 804 // mode if the former was revoked, i.e. marked to not 805 // propagate on upgrade. Note that in a permission review 806 // mode install permissions are represented as constantly 807 // granted runtime ones since we need to keep a per user 808 // state associated with the permission. Also the revoke 809 // on upgrade flag is no longer applicable and is reset. 810 final boolean revokeOnUpgrade = (flags & PackageManager 811 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 812 if (revokeOnUpgrade) { 813 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 814 // Since we changed the flags, we have to write. 815 updatedUserIds = ArrayUtils.appendInt( 816 updatedUserIds, userId); 817 } 818 if (!mSettings.mPermissionReviewRequired || !revokeOnUpgrade) { 819 if (permissionsState.grantRuntimePermission(bp, userId) == 820 PermissionsState.PERMISSION_OPERATION_FAILURE) { 821 // If we cannot put the permission as it was, 822 // we have to write. 823 updatedUserIds = ArrayUtils.appendInt( 824 updatedUserIds, userId); 825 } 826 } 827 828 // If the app supports runtime permissions no need for a review. 829 if (mSettings.mPermissionReviewRequired 830 && appSupportsRuntimePermissions 831 && (flags & PackageManager 832 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 833 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 834 // Since we changed the flags, we have to write. 835 updatedUserIds = ArrayUtils.appendInt( 836 updatedUserIds, userId); 837 } 838 } else if (mSettings.mPermissionReviewRequired 839 && !appSupportsRuntimePermissions) { 840 // For legacy apps that need a permission review, every new 841 // runtime permission is granted but it is pending a review. 842 // We also need to review only platform defined runtime 843 // permissions as these are the only ones the platform knows 844 // how to disable the API to simulate revocation as legacy 845 // apps don't expect to run with revoked permissions. 846 if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) { 847 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 848 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 849 // We changed the flags, hence have to write. 850 updatedUserIds = ArrayUtils.appendInt( 851 updatedUserIds, userId); 852 } 853 } 854 if (permissionsState.grantRuntimePermission(bp, userId) 855 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 856 // We changed the permission, hence have to write. 857 updatedUserIds = ArrayUtils.appendInt( 858 updatedUserIds, userId); 859 } 860 } 861 // Propagate the permission flags. 862 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 863 } 864 } break; 865 866 case GRANT_UPGRADE: { 867 // Grant runtime permissions for a previously held install permission. 868 final PermissionState permissionState = origPermissions 869 .getInstallPermissionState(perm); 870 final int flags = 871 (permissionState != null) ? permissionState.getFlags() : 0; 872 873 if (origPermissions.revokeInstallPermission(bp) 874 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 875 // We will be transferring the permission flags, so clear them. 876 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 877 PackageManager.MASK_PERMISSION_FLAGS, 0); 878 changedInstallPermission = true; 879 } 880 881 // If the permission is not to be promoted to runtime we ignore it and 882 // also its other flags as they are not applicable to install permissions. 883 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 884 for (int userId : currentUserIds) { 885 if (permissionsState.grantRuntimePermission(bp, userId) != 886 PermissionsState.PERMISSION_OPERATION_FAILURE) { 887 // Transfer the permission flags. 888 permissionsState.updatePermissionFlags(bp, userId, 889 flags, flags); 890 // If we granted the permission, we have to write. 891 updatedUserIds = ArrayUtils.appendInt( 892 updatedUserIds, userId); 893 } 894 } 895 } 896 } break; 897 898 default: { 899 if (packageOfInterest == null 900 || packageOfInterest.equals(pkg.packageName)) { 901 if (DEBUG_PERMISSIONS) { 902 Slog.i(TAG, "Not granting permission " + perm 903 + " to package " + pkg.packageName 904 + " because it was previously installed without"); 905 } 906 } 907 } break; 908 } 909 } else { 910 if (permissionsState.revokeInstallPermission(bp) != 911 PermissionsState.PERMISSION_OPERATION_FAILURE) { 912 // Also drop the permission flags. 913 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 914 PackageManager.MASK_PERMISSION_FLAGS, 0); 915 changedInstallPermission = true; 916 Slog.i(TAG, "Un-granting permission " + perm 917 + " from package " + pkg.packageName 918 + " (protectionLevel=" + bp.getProtectionLevel() 919 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 920 + ")"); 921 } else if (bp.isAppOp()) { 922 // Don't print warning for app op permissions, since it is fine for them 923 // not to be granted, there is a UI for the user to decide. 924 if (DEBUG_PERMISSIONS 925 && (packageOfInterest == null 926 || packageOfInterest.equals(pkg.packageName))) { 927 Slog.i(TAG, "Not granting permission " + perm 928 + " to package " + pkg.packageName 929 + " (protectionLevel=" + bp.getProtectionLevel() 930 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 931 + ")"); 932 } 933 } 934 } 935 } 936 937 if ((changedInstallPermission || replace) && !ps.areInstallPermissionsFixed() && 938 !ps.isSystem() || ps.isUpdatedSystem()) { 939 // This is the first that we have heard about this package, so the 940 // permissions we have now selected are fixed until explicitly 941 // changed. 942 ps.setInstallPermissionsFixed(true); 943 } 944 } 945 946 // Persist the runtime permissions state for users with changes. If permissions 947 // were revoked because no app in the shared user declares them we have to 948 // write synchronously to avoid losing runtime permissions state. 949 if (callback != null) { 950 callback.onPermissionUpdated(updatedUserIds, runtimePermissionsRevoked); 951 } 952 } 953 954 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 955 boolean allowed = false; 956 final int NP = PackageParser.NEW_PERMISSIONS.length; 957 for (int ip=0; ip<NP; ip++) { 958 final PackageParser.NewPermissionInfo npi 959 = PackageParser.NEW_PERMISSIONS[ip]; 960 if (npi.name.equals(perm) 961 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 962 allowed = true; 963 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 964 + pkg.packageName); 965 break; 966 } 967 } 968 return allowed; 969 } 970 971 /** 972 * Determines whether a package is whitelisted for a particular privapp permission. 973 * 974 * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted. 975 * 976 * <p>This handles parent/child apps. 977 */ 978 private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) { 979 ArraySet<String> wlPermissions = SystemConfig.getInstance() 980 .getPrivAppPermissions(pkg.packageName); 981 // Let's check if this package is whitelisted... 982 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 983 // If it's not, we'll also tail-recurse to the parent. 984 return whitelisted || 985 pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage); 986 } 987 988 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 989 BasePermission bp, PermissionsState origPermissions) { 990 boolean oemPermission = bp.isOEM(); 991 boolean privilegedPermission = bp.isPrivileged(); 992 boolean privappPermissionsDisable = 993 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 994 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName()); 995 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 996 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivileged() 997 && !platformPackage && platformPermission) { 998 if (!hasPrivappWhitelistEntry(perm, pkg)) { 999 // Only report violations for apps on system image 1000 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 1001 // it's only a reportable violation if the permission isn't explicitly denied 1002 final ArraySet<String> deniedPermissions = SystemConfig.getInstance() 1003 .getPrivAppDenyPermissions(pkg.packageName); 1004 final boolean permissionViolation = 1005 deniedPermissions == null || !deniedPermissions.contains(perm); 1006 if (permissionViolation) { 1007 Slog.w(TAG, "Privileged permission " + perm + " for package " 1008 + pkg.packageName + " - not in privapp-permissions whitelist"); 1009 1010 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 1011 if (mPrivappPermissionsViolations == null) { 1012 mPrivappPermissionsViolations = new ArraySet<>(); 1013 } 1014 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 1015 } 1016 } else { 1017 return false; 1018 } 1019 } 1020 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 1021 return false; 1022 } 1023 } 1024 } 1025 final String systemPackageName = mPackageManagerInt.getKnownPackageName( 1026 PackageManagerInternal.PACKAGE_SYSTEM, UserHandle.USER_SYSTEM); 1027 final PackageParser.Package systemPackage = 1028 mPackageManagerInt.getPackage(systemPackageName); 1029 boolean allowed = (PackageManagerService.compareSignatures( 1030 bp.getSourceSignatures(), pkg.mSignatures) 1031 == PackageManager.SIGNATURE_MATCH) 1032 || (PackageManagerService.compareSignatures( 1033 systemPackage.mSignatures, pkg.mSignatures) 1034 == PackageManager.SIGNATURE_MATCH); 1035 if (!allowed && (privilegedPermission || oemPermission)) { 1036 if (pkg.isSystem()) { 1037 // For updated system applications, a privileged/oem permission 1038 // is granted only if it had been defined by the original application. 1039 if (pkg.isUpdatedSystemApp()) { 1040 final PackageParser.Package disabledPkg = 1041 mPackageManagerInt.getDisabledPackage(pkg.packageName); 1042 final PackageSetting disabledPs = 1043 (disabledPkg != null) ? (PackageSetting) disabledPkg.mExtras : null; 1044 if (disabledPs != null 1045 && disabledPs.getPermissionsState().hasInstallPermission(perm)) { 1046 // If the original was granted this permission, we take 1047 // that grant decision as read and propagate it to the 1048 // update. 1049 if ((privilegedPermission && disabledPs.isPrivileged()) 1050 || (oemPermission && disabledPs.isOem() 1051 && canGrantOemPermission(disabledPs, perm))) { 1052 allowed = true; 1053 } 1054 } else { 1055 // The system apk may have been updated with an older 1056 // version of the one on the data partition, but which 1057 // granted a new system permission that it didn't have 1058 // before. In this case we do want to allow the app to 1059 // now get the new permission if the ancestral apk is 1060 // privileged to get it. 1061 if (disabledPkg != null 1062 && isPackageRequestingPermission(disabledPkg, perm) 1063 && ((privilegedPermission && disabledPs.isPrivileged()) 1064 || (oemPermission && disabledPs.isOem() 1065 && canGrantOemPermission(disabledPs, perm)))) { 1066 allowed = true; 1067 } 1068 // Also if a privileged parent package on the system image or any of 1069 // its children requested a privileged/oem permission, the updated child 1070 // packages can also get the permission. 1071 if (pkg.parentPackage != null) { 1072 final PackageParser.Package disabledParentPkg = mPackageManagerInt 1073 .getDisabledPackage(pkg.parentPackage.packageName); 1074 final PackageSetting disabledParentPs = (disabledParentPkg != null) 1075 ? (PackageSetting) disabledParentPkg.mExtras : null; 1076 if (disabledParentPkg != null 1077 && ((privilegedPermission && disabledParentPs.isPrivileged()) 1078 || (oemPermission && disabledParentPs.isOem()))) { 1079 if (isPackageRequestingPermission(disabledParentPkg, perm) 1080 && canGrantOemPermission(disabledParentPs, perm)) { 1081 allowed = true; 1082 } else if (disabledParentPkg.childPackages != null) { 1083 for (PackageParser.Package disabledChildPkg 1084 : disabledParentPkg.childPackages) { 1085 final PackageSetting disabledChildPs = 1086 (disabledChildPkg != null) 1087 ? (PackageSetting) disabledChildPkg.mExtras 1088 : null; 1089 if (isPackageRequestingPermission(disabledChildPkg, perm) 1090 && canGrantOemPermission( 1091 disabledChildPs, perm)) { 1092 allowed = true; 1093 break; 1094 } 1095 } 1096 } 1097 } 1098 } 1099 } 1100 } else { 1101 final PackageSetting ps = (PackageSetting) pkg.mExtras; 1102 allowed = (privilegedPermission && pkg.isPrivileged()) 1103 || (oemPermission && pkg.isOem() 1104 && canGrantOemPermission(ps, perm)); 1105 } 1106 } 1107 } 1108 if (!allowed) { 1109 if (!allowed 1110 && bp.isPre23() 1111 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 1112 // If this was a previously normal/dangerous permission that got moved 1113 // to a system permission as part of the runtime permission redesign, then 1114 // we still want to blindly grant it to old apps. 1115 allowed = true; 1116 } 1117 if (!allowed && bp.isInstaller() 1118 && pkg.packageName.equals(mPackageManagerInt.getKnownPackageName( 1119 PackageManagerInternal.PACKAGE_INSTALLER, UserHandle.USER_SYSTEM))) { 1120 // If this permission is to be granted to the system installer and 1121 // this app is an installer, then it gets the permission. 1122 allowed = true; 1123 } 1124 if (!allowed && bp.isVerifier() 1125 && pkg.packageName.equals(mPackageManagerInt.getKnownPackageName( 1126 PackageManagerInternal.PACKAGE_VERIFIER, UserHandle.USER_SYSTEM))) { 1127 // If this permission is to be granted to the system verifier and 1128 // this app is a verifier, then it gets the permission. 1129 allowed = true; 1130 } 1131 if (!allowed && bp.isPreInstalled() 1132 && pkg.isSystem()) { 1133 // Any pre-installed system app is allowed to get this permission. 1134 allowed = true; 1135 } 1136 if (!allowed && bp.isDevelopment()) { 1137 // For development permissions, a development permission 1138 // is granted only if it was already granted. 1139 allowed = origPermissions.hasInstallPermission(perm); 1140 } 1141 if (!allowed && bp.isSetup() 1142 && pkg.packageName.equals(mPackageManagerInt.getKnownPackageName( 1143 PackageManagerInternal.PACKAGE_SETUP_WIZARD, UserHandle.USER_SYSTEM))) { 1144 // If this permission is to be granted to the system setup wizard and 1145 // this app is a setup wizard, then it gets the permission. 1146 allowed = true; 1147 } 1148 } 1149 return allowed; 1150 } 1151 1152 private static boolean canGrantOemPermission(PackageSetting ps, String permission) { 1153 if (!ps.isOem()) { 1154 return false; 1155 } 1156 // all oem permissions must explicitly be granted or denied 1157 final Boolean granted = 1158 SystemConfig.getInstance().getOemPermissions(ps.name).get(permission); 1159 if (granted == null) { 1160 throw new IllegalStateException("OEM permission" + permission + " requested by package " 1161 + ps.name + " must be explicitly declared granted or not"); 1162 } 1163 return Boolean.TRUE == granted; 1164 } 1165 1166 private boolean isPermissionsReviewRequired(PackageParser.Package pkg, int userId) { 1167 if (!mSettings.mPermissionReviewRequired) { 1168 return false; 1169 } 1170 1171 // Permission review applies only to apps not supporting the new permission model. 1172 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 1173 return false; 1174 } 1175 1176 // Legacy apps have the permission and get user consent on launch. 1177 if (pkg == null || pkg.mExtras == null) { 1178 return false; 1179 } 1180 final PackageSetting ps = (PackageSetting) pkg.mExtras; 1181 final PermissionsState permissionsState = ps.getPermissionsState(); 1182 return permissionsState.isPermissionReviewRequired(userId); 1183 } 1184 1185 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 1186 final int permCount = pkg.requestedPermissions.size(); 1187 for (int j = 0; j < permCount; j++) { 1188 String requestedPermission = pkg.requestedPermissions.get(j); 1189 if (permission.equals(requestedPermission)) { 1190 return true; 1191 } 1192 } 1193 return false; 1194 } 1195 1196 private void grantRuntimePermissionsGrantedToDisabledPackageLocked( 1197 PackageParser.Package pkg, int callingUid, PermissionCallback callback) { 1198 if (pkg.parentPackage == null) { 1199 return; 1200 } 1201 if (pkg.requestedPermissions == null) { 1202 return; 1203 } 1204 final PackageParser.Package disabledPkg = 1205 mPackageManagerInt.getDisabledPackage(pkg.parentPackage.packageName); 1206 if (disabledPkg == null || disabledPkg.mExtras == null) { 1207 return; 1208 } 1209 final PackageSetting disabledPs = (PackageSetting) disabledPkg.mExtras; 1210 if (!disabledPs.isPrivileged() || disabledPs.hasChildPackages()) { 1211 return; 1212 } 1213 final int permCount = pkg.requestedPermissions.size(); 1214 for (int i = 0; i < permCount; i++) { 1215 String permission = pkg.requestedPermissions.get(i); 1216 BasePermission bp = mSettings.getPermissionLocked(permission); 1217 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1218 continue; 1219 } 1220 for (int userId : mUserManagerInt.getUserIds()) { 1221 if (disabledPs.getPermissionsState().hasRuntimePermission(permission, userId)) { 1222 grantRuntimePermission( 1223 permission, pkg.packageName, false, callingUid, userId, callback); 1224 } 1225 } 1226 } 1227 } 1228 1229 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1230 String[] grantedPermissions, int callingUid, PermissionCallback callback) { 1231 for (int userId : userIds) { 1232 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions, callingUid, 1233 callback); 1234 } 1235 } 1236 1237 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1238 String[] grantedPermissions, int callingUid, PermissionCallback callback) { 1239 PackageSetting ps = (PackageSetting) pkg.mExtras; 1240 if (ps == null) { 1241 return; 1242 } 1243 1244 PermissionsState permissionsState = ps.getPermissionsState(); 1245 1246 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1247 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1248 1249 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 1250 >= Build.VERSION_CODES.M; 1251 1252 final boolean instantApp = mPackageManagerInt.isInstantApp(pkg.packageName, userId); 1253 1254 for (String permission : pkg.requestedPermissions) { 1255 final BasePermission bp; 1256 synchronized (mLock) { 1257 bp = mSettings.getPermissionLocked(permission); 1258 } 1259 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1260 && (!instantApp || bp.isInstant()) 1261 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 1262 && (grantedPermissions == null 1263 || ArrayUtils.contains(grantedPermissions, permission))) { 1264 final int flags = permissionsState.getPermissionFlags(permission, userId); 1265 if (supportsRuntimePermissions) { 1266 // Installer cannot change immutable permissions. 1267 if ((flags & immutableFlags) == 0) { 1268 grantRuntimePermission(permission, pkg.packageName, false, callingUid, 1269 userId, callback); 1270 } 1271 } else if (mSettings.mPermissionReviewRequired) { 1272 // In permission review mode we clear the review flag when we 1273 // are asked to install the app with all permissions granted. 1274 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 1275 updatePermissionFlags(permission, pkg.packageName, 1276 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, callingUid, 1277 userId, callback); 1278 } 1279 } 1280 } 1281 } 1282 } 1283 1284 private void grantRuntimePermission(String permName, String packageName, boolean overridePolicy, 1285 int callingUid, final int userId, PermissionCallback callback) { 1286 if (!mUserManagerInt.exists(userId)) { 1287 Log.e(TAG, "No such user:" + userId); 1288 return; 1289 } 1290 1291 mContext.enforceCallingOrSelfPermission( 1292 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 1293 "grantRuntimePermission"); 1294 1295 enforceCrossUserPermission(callingUid, userId, 1296 true /* requireFullPermission */, true /* checkShell */, 1297 "grantRuntimePermission"); 1298 1299 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName); 1300 if (pkg == null || pkg.mExtras == null) { 1301 throw new IllegalArgumentException("Unknown package: " + packageName); 1302 } 1303 final BasePermission bp; 1304 synchronized(mLock) { 1305 bp = mSettings.getPermissionLocked(permName); 1306 } 1307 if (bp == null) { 1308 throw new IllegalArgumentException("Unknown permission: " + permName); 1309 } 1310 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) { 1311 throw new IllegalArgumentException("Unknown package: " + packageName); 1312 } 1313 1314 bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg); 1315 1316 // If a permission review is required for legacy apps we represent 1317 // their permissions as always granted runtime ones since we need 1318 // to keep the review required permission flag per user while an 1319 // install permission's state is shared across all users. 1320 if (mSettings.mPermissionReviewRequired 1321 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 1322 && bp.isRuntime()) { 1323 return; 1324 } 1325 1326 final int uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 1327 1328 final PackageSetting ps = (PackageSetting) pkg.mExtras; 1329 final PermissionsState permissionsState = ps.getPermissionsState(); 1330 1331 final int flags = permissionsState.getPermissionFlags(permName, userId); 1332 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 1333 throw new SecurityException("Cannot grant system fixed permission " 1334 + permName + " for package " + packageName); 1335 } 1336 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 1337 throw new SecurityException("Cannot grant policy fixed permission " 1338 + permName + " for package " + packageName); 1339 } 1340 1341 if (bp.isDevelopment()) { 1342 // Development permissions must be handled specially, since they are not 1343 // normal runtime permissions. For now they apply to all users. 1344 if (permissionsState.grantInstallPermission(bp) != 1345 PermissionsState.PERMISSION_OPERATION_FAILURE) { 1346 if (callback != null) { 1347 callback.onInstallPermissionGranted(); 1348 } 1349 } 1350 return; 1351 } 1352 1353 if (ps.getInstantApp(userId) && !bp.isInstant()) { 1354 throw new SecurityException("Cannot grant non-ephemeral permission" 1355 + permName + " for package " + packageName); 1356 } 1357 1358 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 1359 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 1360 return; 1361 } 1362 1363 final int result = permissionsState.grantRuntimePermission(bp, userId); 1364 switch (result) { 1365 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 1366 return; 1367 } 1368 1369 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 1370 if (callback != null) { 1371 callback.onGidsChanged(UserHandle.getAppId(pkg.applicationInfo.uid), userId); 1372 } 1373 } 1374 break; 1375 } 1376 1377 if (bp.isRuntime()) { 1378 logPermissionGranted(mContext, permName, packageName); 1379 } 1380 1381 if (callback != null) { 1382 callback.onPermissionGranted(uid, userId); 1383 } 1384 1385 // Only need to do this if user is initialized. Otherwise it's a new user 1386 // and there are no processes running as the user yet and there's no need 1387 // to make an expensive call to remount processes for the changed permissions. 1388 if (READ_EXTERNAL_STORAGE.equals(permName) 1389 || WRITE_EXTERNAL_STORAGE.equals(permName)) { 1390 final long token = Binder.clearCallingIdentity(); 1391 try { 1392 if (mUserManagerInt.isUserInitialized(userId)) { 1393 StorageManagerInternal storageManagerInternal = LocalServices.getService( 1394 StorageManagerInternal.class); 1395 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 1396 } 1397 } finally { 1398 Binder.restoreCallingIdentity(token); 1399 } 1400 } 1401 1402 } 1403 1404 private void revokeRuntimePermission(String permName, String packageName, 1405 boolean overridePolicy, int callingUid, int userId, PermissionCallback callback) { 1406 if (!mUserManagerInt.exists(userId)) { 1407 Log.e(TAG, "No such user:" + userId); 1408 return; 1409 } 1410 1411 mContext.enforceCallingOrSelfPermission( 1412 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 1413 "revokeRuntimePermission"); 1414 1415 enforceCrossUserPermission(Binder.getCallingUid(), userId, 1416 true /* requireFullPermission */, true /* checkShell */, 1417 "revokeRuntimePermission"); 1418 1419 final int appId; 1420 1421 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName); 1422 if (pkg == null || pkg.mExtras == null) { 1423 throw new IllegalArgumentException("Unknown package: " + packageName); 1424 } 1425 if (mPackageManagerInt.filterAppAccess(pkg, Binder.getCallingUid(), userId)) { 1426 throw new IllegalArgumentException("Unknown package: " + packageName); 1427 } 1428 final BasePermission bp = mSettings.getPermissionLocked(permName); 1429 if (bp == null) { 1430 throw new IllegalArgumentException("Unknown permission: " + permName); 1431 } 1432 1433 bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg); 1434 1435 // If a permission review is required for legacy apps we represent 1436 // their permissions as always granted runtime ones since we need 1437 // to keep the review required permission flag per user while an 1438 // install permission's state is shared across all users. 1439 if (mSettings.mPermissionReviewRequired 1440 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 1441 && bp.isRuntime()) { 1442 return; 1443 } 1444 1445 final PackageSetting ps = (PackageSetting) pkg.mExtras; 1446 final PermissionsState permissionsState = ps.getPermissionsState(); 1447 1448 final int flags = permissionsState.getPermissionFlags(permName, userId); 1449 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 1450 throw new SecurityException("Cannot revoke system fixed permission " 1451 + permName + " for package " + packageName); 1452 } 1453 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 1454 throw new SecurityException("Cannot revoke policy fixed permission " 1455 + permName + " for package " + packageName); 1456 } 1457 1458 if (bp.isDevelopment()) { 1459 // Development permissions must be handled specially, since they are not 1460 // normal runtime permissions. For now they apply to all users. 1461 if (permissionsState.revokeInstallPermission(bp) != 1462 PermissionsState.PERMISSION_OPERATION_FAILURE) { 1463 if (callback != null) { 1464 callback.onInstallPermissionRevoked(); 1465 } 1466 } 1467 return; 1468 } 1469 1470 if (permissionsState.revokeRuntimePermission(bp, userId) == 1471 PermissionsState.PERMISSION_OPERATION_FAILURE) { 1472 return; 1473 } 1474 1475 if (bp.isRuntime()) { 1476 logPermissionRevoked(mContext, permName, packageName); 1477 } 1478 1479 if (callback != null) { 1480 final int uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 1481 callback.onPermissionRevoked(pkg.applicationInfo.uid, userId); 1482 } 1483 } 1484 1485 private int[] revokeUnusedSharedUserPermissionsLocked( 1486 SharedUserSetting suSetting, int[] allUserIds) { 1487 // Collect all used permissions in the UID 1488 final ArraySet<String> usedPermissions = new ArraySet<>(); 1489 final List<PackageParser.Package> pkgList = suSetting.getPackages(); 1490 if (pkgList == null || pkgList.size() == 0) { 1491 return EmptyArray.INT; 1492 } 1493 for (PackageParser.Package pkg : pkgList) { 1494 final int requestedPermCount = pkg.requestedPermissions.size(); 1495 for (int j = 0; j < requestedPermCount; j++) { 1496 String permission = pkg.requestedPermissions.get(j); 1497 BasePermission bp = mSettings.getPermissionLocked(permission); 1498 if (bp != null) { 1499 usedPermissions.add(permission); 1500 } 1501 } 1502 } 1503 1504 PermissionsState permissionsState = suSetting.getPermissionsState(); 1505 // Prune install permissions 1506 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 1507 final int installPermCount = installPermStates.size(); 1508 for (int i = installPermCount - 1; i >= 0; i--) { 1509 PermissionState permissionState = installPermStates.get(i); 1510 if (!usedPermissions.contains(permissionState.getName())) { 1511 BasePermission bp = mSettings.getPermissionLocked(permissionState.getName()); 1512 if (bp != null) { 1513 permissionsState.revokeInstallPermission(bp); 1514 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 1515 PackageManager.MASK_PERMISSION_FLAGS, 0); 1516 } 1517 } 1518 } 1519 1520 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 1521 1522 // Prune runtime permissions 1523 for (int userId : allUserIds) { 1524 List<PermissionState> runtimePermStates = permissionsState 1525 .getRuntimePermissionStates(userId); 1526 final int runtimePermCount = runtimePermStates.size(); 1527 for (int i = runtimePermCount - 1; i >= 0; i--) { 1528 PermissionState permissionState = runtimePermStates.get(i); 1529 if (!usedPermissions.contains(permissionState.getName())) { 1530 BasePermission bp = mSettings.getPermissionLocked(permissionState.getName()); 1531 if (bp != null) { 1532 permissionsState.revokeRuntimePermission(bp, userId); 1533 permissionsState.updatePermissionFlags(bp, userId, 1534 PackageManager.MASK_PERMISSION_FLAGS, 0); 1535 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 1536 runtimePermissionChangedUserIds, userId); 1537 } 1538 } 1539 } 1540 } 1541 1542 return runtimePermissionChangedUserIds; 1543 } 1544 1545 private String[] getAppOpPermissionPackages(String permName) { 1546 if (mPackageManagerInt.getInstantAppPackageName(Binder.getCallingUid()) != null) { 1547 return null; 1548 } 1549 synchronized (mLock) { 1550 final ArraySet<String> pkgs = mSettings.mAppOpPermissionPackages.get(permName); 1551 if (pkgs == null) { 1552 return null; 1553 } 1554 return pkgs.toArray(new String[pkgs.size()]); 1555 } 1556 } 1557 1558 private int getPermissionFlags( 1559 String permName, String packageName, int callingUid, int userId) { 1560 if (!mUserManagerInt.exists(userId)) { 1561 return 0; 1562 } 1563 1564 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 1565 1566 enforceCrossUserPermission(callingUid, userId, 1567 true /* requireFullPermission */, false /* checkShell */, 1568 "getPermissionFlags"); 1569 1570 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName); 1571 if (pkg == null || pkg.mExtras == null) { 1572 return 0; 1573 } 1574 synchronized (mLock) { 1575 if (mSettings.getPermissionLocked(permName) == null) { 1576 return 0; 1577 } 1578 } 1579 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) { 1580 return 0; 1581 } 1582 final PackageSetting ps = (PackageSetting) pkg.mExtras; 1583 PermissionsState permissionsState = ps.getPermissionsState(); 1584 return permissionsState.getPermissionFlags(permName, userId); 1585 } 1586 1587 private static final int UPDATE_PERMISSIONS_ALL = 1<<0; 1588 private static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 1589 private static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 1590 1591 private void updatePermissions(String packageName, PackageParser.Package pkg, 1592 boolean replaceGrant, Collection<PackageParser.Package> allPackages, 1593 PermissionCallback callback) { 1594 final int flags = (pkg != null ? UPDATE_PERMISSIONS_ALL : 0) | 1595 (replaceGrant ? UPDATE_PERMISSIONS_REPLACE_PKG : 0); 1596 updatePermissions( 1597 packageName, pkg, getVolumeUuidForPackage(pkg), flags, allPackages, callback); 1598 if (pkg != null && pkg.childPackages != null) { 1599 for (PackageParser.Package childPkg : pkg.childPackages) { 1600 updatePermissions(childPkg.packageName, childPkg, 1601 getVolumeUuidForPackage(childPkg), flags, allPackages, callback); 1602 } 1603 } 1604 } 1605 1606 private void updateAllPermissions(String volumeUuid, boolean sdkUpdated, 1607 Collection<PackageParser.Package> allPackages, PermissionCallback callback) { 1608 final int flags = UPDATE_PERMISSIONS_ALL | 1609 (sdkUpdated 1610 ? UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL 1611 : 0); 1612 updatePermissions(null, null, volumeUuid, flags, allPackages, callback); 1613 } 1614 1615 private void updatePermissions(String changingPkgName, PackageParser.Package changingPkg, 1616 String replaceVolumeUuid, int flags, Collection<PackageParser.Package> allPackages, 1617 PermissionCallback callback) { 1618 // TODO: Most of the methods exposing BasePermission internals [source package name, 1619 // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't 1620 // have package settings, we should make note of it elsewhere [map between 1621 // source package name and BasePermission] and cycle through that here. Then we 1622 // define a single method on BasePermission that takes a PackageSetting, changing 1623 // package name and a package. 1624 // NOTE: With this approach, we also don't need to tree trees differently than 1625 // normal permissions. Today, we need two separate loops because these BasePermission 1626 // objects are stored separately. 1627 // Make sure there are no dangling permission trees. 1628 flags = updatePermissionTrees(changingPkgName, changingPkg, flags); 1629 1630 // Make sure all dynamic permissions have been assigned to a package, 1631 // and make sure there are no dangling permissions. 1632 flags = updatePermissions(changingPkgName, changingPkg, flags); 1633 1634 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 1635 // Now update the permissions for all packages, in particular 1636 // replace the granted permissions of the system packages. 1637 if ((flags & UPDATE_PERMISSIONS_ALL) != 0) { 1638 for (PackageParser.Package pkg : allPackages) { 1639 if (pkg != changingPkg) { 1640 // Only replace for packages on requested volume 1641 final String volumeUuid = getVolumeUuidForPackage(pkg); 1642 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 1643 && Objects.equals(replaceVolumeUuid, volumeUuid); 1644 grantPermissions(pkg, replace, changingPkgName, callback); 1645 } 1646 } 1647 } 1648 1649 if (changingPkg != null) { 1650 // Only replace for packages on requested volume 1651 final String volumeUuid = getVolumeUuidForPackage(changingPkg); 1652 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 1653 && Objects.equals(replaceVolumeUuid, volumeUuid); 1654 grantPermissions(changingPkg, replace, changingPkgName, callback); 1655 } 1656 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1657 } 1658 1659 private int updatePermissions(String packageName, PackageParser.Package pkg, int flags) { 1660 Set<BasePermission> needsUpdate = null; 1661 synchronized (mLock) { 1662 final Iterator<BasePermission> it = mSettings.mPermissions.values().iterator(); 1663 while (it.hasNext()) { 1664 final BasePermission bp = it.next(); 1665 if (bp.isDynamic()) { 1666 bp.updateDynamicPermission(mSettings.mPermissionTrees.values()); 1667 } 1668 if (bp.getSourcePackageSetting() != null) { 1669 if (packageName != null && packageName.equals(bp.getSourcePackageName()) 1670 && (pkg == null || !hasPermission(pkg, bp.getName()))) { 1671 Slog.i(TAG, "Removing old permission tree: " + bp.getName() 1672 + " from package " + bp.getSourcePackageName()); 1673 flags |= UPDATE_PERMISSIONS_ALL; 1674 it.remove(); 1675 } 1676 continue; 1677 } 1678 if (needsUpdate == null) { 1679 needsUpdate = new ArraySet<>(mSettings.mPermissions.size()); 1680 } 1681 needsUpdate.add(bp); 1682 } 1683 } 1684 if (needsUpdate != null) { 1685 for (final BasePermission bp : needsUpdate) { 1686 final PackageParser.Package sourcePkg = 1687 mPackageManagerInt.getPackage(bp.getSourcePackageName()); 1688 synchronized (mLock) { 1689 if (sourcePkg != null && sourcePkg.mExtras != null) { 1690 final PackageSetting sourcePs = (PackageSetting) sourcePkg.mExtras; 1691 if (bp.getSourcePackageSetting() == null) { 1692 bp.setSourcePackageSetting(sourcePs); 1693 } 1694 continue; 1695 } 1696 Slog.w(TAG, "Removing dangling permission: " + bp.getName() 1697 + " from package " + bp.getSourcePackageName()); 1698 mSettings.removePermissionLocked(bp.getName()); 1699 } 1700 } 1701 } 1702 return flags; 1703 } 1704 1705 private int updatePermissionTrees(String packageName, PackageParser.Package pkg, 1706 int flags) { 1707 Set<BasePermission> needsUpdate = null; 1708 synchronized (mLock) { 1709 final Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 1710 while (it.hasNext()) { 1711 final BasePermission bp = it.next(); 1712 if (bp.getSourcePackageSetting() != null) { 1713 if (packageName != null && packageName.equals(bp.getSourcePackageName()) 1714 && (pkg == null || !hasPermission(pkg, bp.getName()))) { 1715 Slog.i(TAG, "Removing old permission tree: " + bp.getName() 1716 + " from package " + bp.getSourcePackageName()); 1717 flags |= UPDATE_PERMISSIONS_ALL; 1718 it.remove(); 1719 } 1720 continue; 1721 } 1722 if (needsUpdate == null) { 1723 needsUpdate = new ArraySet<>(mSettings.mPermissionTrees.size()); 1724 } 1725 needsUpdate.add(bp); 1726 } 1727 } 1728 if (needsUpdate != null) { 1729 for (final BasePermission bp : needsUpdate) { 1730 final PackageParser.Package sourcePkg = 1731 mPackageManagerInt.getPackage(bp.getSourcePackageName()); 1732 synchronized (mLock) { 1733 if (sourcePkg != null && sourcePkg.mExtras != null) { 1734 final PackageSetting sourcePs = (PackageSetting) sourcePkg.mExtras; 1735 if (bp.getSourcePackageSetting() == null) { 1736 bp.setSourcePackageSetting(sourcePs); 1737 } 1738 continue; 1739 } 1740 Slog.w(TAG, "Removing dangling permission tree: " + bp.getName() 1741 + " from package " + bp.getSourcePackageName()); 1742 mSettings.removePermissionLocked(bp.getName()); 1743 } 1744 } 1745 } 1746 return flags; 1747 } 1748 1749 private void updatePermissionFlags(String permName, String packageName, int flagMask, 1750 int flagValues, int callingUid, int userId, PermissionCallback callback) { 1751 if (!mUserManagerInt.exists(userId)) { 1752 return; 1753 } 1754 1755 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 1756 1757 enforceCrossUserPermission(callingUid, userId, 1758 true /* requireFullPermission */, true /* checkShell */, 1759 "updatePermissionFlags"); 1760 1761 // Only the system can change these flags and nothing else. 1762 if (callingUid != Process.SYSTEM_UID) { 1763 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 1764 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 1765 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1766 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1767 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 1768 } 1769 1770 final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName); 1771 if (pkg == null || pkg.mExtras == null) { 1772 throw new IllegalArgumentException("Unknown package: " + packageName); 1773 } 1774 if (mPackageManagerInt.filterAppAccess(pkg, callingUid, userId)) { 1775 throw new IllegalArgumentException("Unknown package: " + packageName); 1776 } 1777 1778 final BasePermission bp; 1779 synchronized (mLock) { 1780 bp = mSettings.getPermissionLocked(permName); 1781 } 1782 if (bp == null) { 1783 throw new IllegalArgumentException("Unknown permission: " + permName); 1784 } 1785 1786 final PackageSetting ps = (PackageSetting) pkg.mExtras; 1787 final PermissionsState permissionsState = ps.getPermissionsState(); 1788 final boolean hadState = 1789 permissionsState.getRuntimePermissionState(permName, userId) != null; 1790 final boolean permissionUpdated = 1791 permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues); 1792 if (permissionUpdated && callback != null) { 1793 // Install and runtime permissions are stored in different places, 1794 // so figure out what permission changed and persist the change. 1795 if (permissionsState.getInstallPermissionState(permName) != null) { 1796 callback.onInstallPermissionUpdated(); 1797 } else if (permissionsState.getRuntimePermissionState(permName, userId) != null 1798 || hadState) { 1799 callback.onPermissionUpdated(new int[] { userId }, false); 1800 } 1801 } 1802 } 1803 1804 private boolean updatePermissionFlagsForAllApps(int flagMask, int flagValues, int callingUid, 1805 int userId, Collection<Package> packages, PermissionCallback callback) { 1806 if (!mUserManagerInt.exists(userId)) { 1807 return false; 1808 } 1809 1810 enforceGrantRevokeRuntimePermissionPermissions( 1811 "updatePermissionFlagsForAllApps"); 1812 enforceCrossUserPermission(callingUid, userId, 1813 true /* requireFullPermission */, true /* checkShell */, 1814 "updatePermissionFlagsForAllApps"); 1815 1816 // Only the system can change system fixed flags. 1817 if (callingUid != Process.SYSTEM_UID) { 1818 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 1819 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 1820 } 1821 1822 boolean changed = false; 1823 for (PackageParser.Package pkg : packages) { 1824 final PackageSetting ps = (PackageSetting) pkg.mExtras; 1825 if (ps == null) { 1826 continue; 1827 } 1828 PermissionsState permissionsState = ps.getPermissionsState(); 1829 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 1830 userId, flagMask, flagValues); 1831 } 1832 return changed; 1833 } 1834 1835 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 1836 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 1837 != PackageManager.PERMISSION_GRANTED 1838 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 1839 != PackageManager.PERMISSION_GRANTED) { 1840 throw new SecurityException(message + " requires " 1841 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 1842 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 1843 } 1844 } 1845 1846 /** 1847 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 1848 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 1849 * @param checkShell whether to prevent shell from access if there's a debugging restriction 1850 * @param message the message to log on security exception 1851 */ 1852 private void enforceCrossUserPermission(int callingUid, int userId, 1853 boolean requireFullPermission, boolean checkShell, String message) { 1854 if (userId < 0) { 1855 throw new IllegalArgumentException("Invalid userId " + userId); 1856 } 1857 if (checkShell) { 1858 PackageManagerServiceUtils.enforceShellRestriction( 1859 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 1860 } 1861 if (userId == UserHandle.getUserId(callingUid)) return; 1862 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 1863 if (requireFullPermission) { 1864 mContext.enforceCallingOrSelfPermission( 1865 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 1866 } else { 1867 try { 1868 mContext.enforceCallingOrSelfPermission( 1869 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 1870 } catch (SecurityException se) { 1871 mContext.enforceCallingOrSelfPermission( 1872 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 1873 } 1874 } 1875 } 1876 } 1877 1878 private int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 1879 int size = 0; 1880 for (BasePermission perm : mSettings.mPermissions.values()) { 1881 size += tree.calculateFootprint(perm); 1882 } 1883 return size; 1884 } 1885 1886 private void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 1887 // We calculate the max size of permissions defined by this uid and throw 1888 // if that plus the size of 'info' would exceed our stated maximum. 1889 if (tree.getUid() != Process.SYSTEM_UID) { 1890 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 1891 if (curTreeSize + info.calculateFootprint() > MAX_PERMISSION_TREE_FOOTPRINT) { 1892 throw new SecurityException("Permission tree size cap exceeded"); 1893 } 1894 } 1895 } 1896 1897 private void systemReady() { 1898 mSystemReady = true; 1899 if (mPrivappPermissionsViolations != null) { 1900 throw new IllegalStateException("Signature|privileged permissions not in " 1901 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 1902 } 1903 } 1904 1905 private static String getVolumeUuidForPackage(PackageParser.Package pkg) { 1906 if (pkg == null) { 1907 return StorageManager.UUID_PRIVATE_INTERNAL; 1908 } 1909 if (pkg.isExternal()) { 1910 if (TextUtils.isEmpty(pkg.volumeUuid)) { 1911 return StorageManager.UUID_PRIMARY_PHYSICAL; 1912 } else { 1913 return pkg.volumeUuid; 1914 } 1915 } else { 1916 return StorageManager.UUID_PRIVATE_INTERNAL; 1917 } 1918 } 1919 1920 private static boolean hasPermission(PackageParser.Package pkgInfo, String permName) { 1921 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 1922 if (pkgInfo.permissions.get(i).info.name.equals(permName)) { 1923 return true; 1924 } 1925 } 1926 return false; 1927 } 1928 1929 /** 1930 * Get the first event id for the permission. 1931 * 1932 * <p>There are four events for each permission: <ul> 1933 * <li>Request permission: first id + 0</li> 1934 * <li>Grant permission: first id + 1</li> 1935 * <li>Request for permission denied: first id + 2</li> 1936 * <li>Revoke permission: first id + 3</li> 1937 * </ul></p> 1938 * 1939 * @param name name of the permission 1940 * 1941 * @return The first event id for the permission 1942 */ 1943 private static int getBaseEventId(@NonNull String name) { 1944 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 1945 1946 if (eventIdIndex == -1) { 1947 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 1948 || Build.IS_USER) { 1949 Log.i(TAG, "Unknown permission " + name); 1950 1951 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 1952 } else { 1953 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 1954 // 1955 // Also update 1956 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 1957 // - metrics_constants.proto 1958 throw new IllegalStateException("Unknown permission " + name); 1959 } 1960 } 1961 1962 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 1963 } 1964 1965 /** 1966 * Log that a permission was revoked. 1967 * 1968 * @param context Context of the caller 1969 * @param name name of the permission 1970 * @param packageName package permission if for 1971 */ 1972 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 1973 @NonNull String packageName) { 1974 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 1975 } 1976 1977 /** 1978 * Log that a permission request was granted. 1979 * 1980 * @param context Context of the caller 1981 * @param name name of the permission 1982 * @param packageName package permission if for 1983 */ 1984 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 1985 @NonNull String packageName) { 1986 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 1987 } 1988 1989 private class PermissionManagerInternalImpl extends PermissionManagerInternal { 1990 @Override 1991 public void systemReady() { 1992 PermissionManagerService.this.systemReady(); 1993 } 1994 @Override 1995 public boolean isPermissionsReviewRequired(Package pkg, int userId) { 1996 return PermissionManagerService.this.isPermissionsReviewRequired(pkg, userId); 1997 } 1998 @Override 1999 public void addAllPermissions(Package pkg, boolean chatty) { 2000 PermissionManagerService.this.addAllPermissions(pkg, chatty); 2001 } 2002 @Override 2003 public void addAllPermissionGroups(Package pkg, boolean chatty) { 2004 PermissionManagerService.this.addAllPermissionGroups(pkg, chatty); 2005 } 2006 @Override 2007 public void removeAllPermissions(Package pkg, boolean chatty) { 2008 PermissionManagerService.this.removeAllPermissions(pkg, chatty); 2009 } 2010 @Override 2011 public boolean addDynamicPermission(PermissionInfo info, boolean async, int callingUid, 2012 PermissionCallback callback) { 2013 return PermissionManagerService.this.addDynamicPermission(info, callingUid, callback); 2014 } 2015 @Override 2016 public void removeDynamicPermission(String permName, int callingUid, 2017 PermissionCallback callback) { 2018 PermissionManagerService.this.removeDynamicPermission(permName, callingUid, callback); 2019 } 2020 @Override 2021 public void grantRuntimePermission(String permName, String packageName, 2022 boolean overridePolicy, int callingUid, int userId, 2023 PermissionCallback callback) { 2024 PermissionManagerService.this.grantRuntimePermission( 2025 permName, packageName, overridePolicy, callingUid, userId, callback); 2026 } 2027 @Override 2028 public void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2029 String[] grantedPermissions, int callingUid, PermissionCallback callback) { 2030 PermissionManagerService.this.grantRequestedRuntimePermissions( 2031 pkg, userIds, grantedPermissions, callingUid, callback); 2032 } 2033 @Override 2034 public void grantRuntimePermissionsGrantedToDisabledPackage(PackageParser.Package pkg, 2035 int callingUid, PermissionCallback callback) { 2036 PermissionManagerService.this.grantRuntimePermissionsGrantedToDisabledPackageLocked( 2037 pkg, callingUid, callback); 2038 } 2039 @Override 2040 public void revokeRuntimePermission(String permName, String packageName, 2041 boolean overridePolicy, int callingUid, int userId, 2042 PermissionCallback callback) { 2043 PermissionManagerService.this.revokeRuntimePermission(permName, packageName, 2044 overridePolicy, callingUid, userId, callback); 2045 } 2046 @Override 2047 public void updatePermissions(String packageName, Package pkg, boolean replaceGrant, 2048 Collection<PackageParser.Package> allPackages, PermissionCallback callback) { 2049 PermissionManagerService.this.updatePermissions( 2050 packageName, pkg, replaceGrant, allPackages, callback); 2051 } 2052 @Override 2053 public void updateAllPermissions(String volumeUuid, boolean sdkUpdated, 2054 Collection<PackageParser.Package> allPackages, PermissionCallback callback) { 2055 PermissionManagerService.this.updateAllPermissions( 2056 volumeUuid, sdkUpdated, allPackages, callback); 2057 } 2058 @Override 2059 public String[] getAppOpPermissionPackages(String permName) { 2060 return PermissionManagerService.this.getAppOpPermissionPackages(permName); 2061 } 2062 @Override 2063 public int getPermissionFlags(String permName, String packageName, int callingUid, 2064 int userId) { 2065 return PermissionManagerService.this.getPermissionFlags(permName, packageName, 2066 callingUid, userId); 2067 } 2068 @Override 2069 public void updatePermissionFlags(String permName, String packageName, int flagMask, 2070 int flagValues, int callingUid, int userId, PermissionCallback callback) { 2071 PermissionManagerService.this.updatePermissionFlags( 2072 permName, packageName, flagMask, flagValues, callingUid, userId, callback); 2073 } 2074 @Override 2075 public boolean updatePermissionFlagsForAllApps(int flagMask, int flagValues, int callingUid, 2076 int userId, Collection<Package> packages, PermissionCallback callback) { 2077 return PermissionManagerService.this.updatePermissionFlagsForAllApps( 2078 flagMask, flagValues, callingUid, userId, packages, callback); 2079 } 2080 @Override 2081 public void enforceCrossUserPermission(int callingUid, int userId, 2082 boolean requireFullPermission, boolean checkShell, String message) { 2083 PermissionManagerService.this.enforceCrossUserPermission(callingUid, userId, 2084 requireFullPermission, checkShell, message); 2085 } 2086 @Override 2087 public void enforceGrantRevokeRuntimePermissionPermissions(String message) { 2088 PermissionManagerService.this.enforceGrantRevokeRuntimePermissionPermissions(message); 2089 } 2090 @Override 2091 public int checkPermission(String permName, String packageName, int callingUid, 2092 int userId) { 2093 return PermissionManagerService.this.checkPermission( 2094 permName, packageName, callingUid, userId); 2095 } 2096 @Override 2097 public int checkUidPermission(String permName, int uid, int callingUid) { 2098 return PermissionManagerService.this.checkUidPermission(permName, uid, callingUid); 2099 } 2100 @Override 2101 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags, 2102 int callingUid) { 2103 return PermissionManagerService.this.getPermissionGroupInfo( 2104 groupName, flags, callingUid); 2105 } 2106 @Override 2107 public List<PermissionGroupInfo> getAllPermissionGroups(int flags, int callingUid) { 2108 return PermissionManagerService.this.getAllPermissionGroups(flags, callingUid); 2109 } 2110 @Override 2111 public PermissionInfo getPermissionInfo(String permName, String packageName, int flags, 2112 int callingUid) { 2113 return PermissionManagerService.this.getPermissionInfo( 2114 permName, packageName, flags, callingUid); 2115 } 2116 @Override 2117 public List<PermissionInfo> getPermissionInfoByGroup(String group, int flags, 2118 int callingUid) { 2119 return PermissionManagerService.this.getPermissionInfoByGroup(group, flags, callingUid); 2120 } 2121 @Override 2122 public PermissionSettings getPermissionSettings() { 2123 return mSettings; 2124 } 2125 @Override 2126 public DefaultPermissionGrantPolicy getDefaultPermissionGrantPolicy() { 2127 return mDefaultPermissionGrantPolicy; 2128 } 2129 @Override 2130 public BasePermission getPermissionTEMP(String permName) { 2131 synchronized (PermissionManagerService.this.mLock) { 2132 return mSettings.getPermissionLocked(permName); 2133 } 2134 } 2135 } 2136} 2137