1 /* 2 * Copyright (C) 2021 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 17 package com.android.server.pm; 18 19 import static android.content.pm.PackageInstaller.SessionParams.MODE_INHERIT_EXISTING; 20 import static android.content.pm.PackageManager.INSTALL_SUCCEEDED; 21 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 22 import static android.content.pm.SigningDetails.SignatureSchemeVersion.SIGNING_BLOCK_V4; 23 import static android.os.PowerWhitelistManager.REASON_PACKAGE_VERIFIER; 24 import static android.os.PowerWhitelistManager.TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED; 25 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 26 27 import static com.android.server.pm.PackageManagerService.CHECK_PENDING_VERIFICATION; 28 import static com.android.server.pm.PackageManagerService.DEBUG_INSTALL; 29 import static com.android.server.pm.PackageManagerService.DEBUG_VERIFY; 30 import static com.android.server.pm.PackageManagerService.DEFAULT_VERIFICATION_RESPONSE; 31 import static com.android.server.pm.PackageManagerService.ENABLE_ROLLBACK_TIMEOUT; 32 import static com.android.server.pm.PackageManagerService.PACKAGE_MIME_TYPE; 33 import static com.android.server.pm.PackageManagerService.TAG; 34 35 import android.annotation.NonNull; 36 import android.annotation.Nullable; 37 import android.app.AppOpsManager; 38 import android.app.BroadcastOptions; 39 import android.content.ComponentName; 40 import android.content.Intent; 41 import android.content.pm.ActivityInfo; 42 import android.content.pm.DataLoaderType; 43 import android.content.pm.Flags; 44 import android.content.pm.IPackageInstallObserver2; 45 import android.content.pm.PackageInfoLite; 46 import android.content.pm.PackageInstaller; 47 import android.content.pm.PackageManager; 48 import android.content.pm.PackageManagerInternal; 49 import android.content.pm.ParceledListSlice; 50 import android.content.pm.ResolveInfo; 51 import android.content.pm.SigningDetails; 52 import android.content.pm.VerifierInfo; 53 import android.content.pm.parsing.PackageLite; 54 import android.net.Uri; 55 import android.os.Bundle; 56 import android.os.Message; 57 import android.os.Process; 58 import android.os.RemoteException; 59 import android.os.SystemProperties; 60 import android.os.Trace; 61 import android.os.UserHandle; 62 import android.os.UserManager; 63 import android.os.incremental.IncrementalManager; 64 import android.provider.DeviceConfig; 65 import android.text.TextUtils; 66 import android.util.Pair; 67 import android.util.Slog; 68 69 import com.android.server.DeviceIdleInternal; 70 import com.android.server.sdksandbox.SdkSandboxManagerLocal; 71 72 import java.io.File; 73 import java.util.ArrayList; 74 import java.util.Arrays; 75 import java.util.List; 76 77 final class VerifyingSession { 78 /** 79 * Whether verification is enabled by default. 80 */ 81 private static final boolean DEFAULT_VERIFY_ENABLE = true; 82 /** 83 * The default maximum time to wait for the integrity verification to return in 84 * milliseconds. 85 */ 86 private static final long DEFAULT_INTEGRITY_VERIFICATION_TIMEOUT = 30 * 1000; 87 /** 88 * Timeout duration in milliseconds for enabling package rollback. If we fail to enable 89 * rollback within that period, the install will proceed without rollback enabled. 90 * 91 * <p>If flag value is negative, the default value will be assigned. 92 * 93 * Flag type: {@code long} 94 * Namespace: NAMESPACE_ROLLBACK 95 */ 96 private static final String PROPERTY_ENABLE_ROLLBACK_TIMEOUT_MILLIS = "enable_rollback_timeout"; 97 /** 98 * The default duration to wait for rollback to be enabled in 99 * milliseconds. 100 */ 101 private static final long DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS = 10 * 1000; 102 103 final OriginInfo mOriginInfo; 104 final IPackageInstallObserver2 mObserver; 105 private final int mInstallFlags; 106 @NonNull 107 private final InstallSource mInstallSource; 108 private final String mPackageAbiOverride; 109 private final VerificationInfo mVerificationInfo; 110 private final SigningDetails mSigningDetails; 111 @Nullable 112 MultiPackageVerifyingSession mParentVerifyingSession; 113 private final long mRequiredInstalledVersionCode; 114 private final int mDataLoaderType; 115 private final int mSessionId; 116 private final boolean mUserActionRequired; 117 private final int mUserActionRequiredType; 118 private boolean mWaitForVerificationToComplete; 119 private boolean mWaitForEnableRollbackToComplete; 120 private int mRet = PackageManager.INSTALL_SUCCEEDED; 121 private String mErrorMessage = null; 122 private final boolean mIsInherit; 123 private final boolean mIsStaged; 124 125 private final PackageLite mPackageLite; 126 private final UserHandle mUser; 127 @NonNull 128 private final PackageManagerService mPm; 129 130 private final int mInstallReason; 131 VerifyingSession(UserHandle user, File stagedDir, IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, InstallSource installSource, int installerUid, SigningDetails signingDetails, int sessionId, PackageLite lite, boolean userActionRequired, PackageManagerService pm)132 VerifyingSession(UserHandle user, File stagedDir, IPackageInstallObserver2 observer, 133 PackageInstaller.SessionParams sessionParams, InstallSource installSource, 134 int installerUid, SigningDetails signingDetails, int sessionId, PackageLite lite, 135 boolean userActionRequired, PackageManagerService pm) { 136 mPm = pm; 137 mUser = user; 138 mOriginInfo = OriginInfo.fromStagedFile(stagedDir); 139 mObserver = observer; 140 mInstallFlags = sessionParams.installFlags; 141 mInstallSource = installSource; 142 mPackageAbiOverride = sessionParams.abiOverride; 143 mVerificationInfo = new VerificationInfo( 144 sessionParams.originatingUri, 145 sessionParams.referrerUri, 146 sessionParams.originatingUid, 147 installerUid 148 ); 149 mSigningDetails = signingDetails; 150 mRequiredInstalledVersionCode = sessionParams.requiredInstalledVersionCode; 151 mDataLoaderType = (sessionParams.dataLoaderParams != null) 152 ? sessionParams.dataLoaderParams.getType() : DataLoaderType.NONE; 153 mSessionId = sessionId; 154 mPackageLite = lite; 155 mUserActionRequired = userActionRequired; 156 mUserActionRequiredType = sessionParams.requireUserAction; 157 mIsInherit = sessionParams.mode == MODE_INHERIT_EXISTING; 158 mIsStaged = sessionParams.isStaged; 159 mInstallReason = sessionParams.installReason; 160 } 161 162 @Override toString()163 public String toString() { 164 return "VerifyingSession{" + Integer.toHexString(System.identityHashCode(this)) 165 + " file=" + mOriginInfo.mFile + "}"; 166 } 167 handleStartVerify()168 public void handleStartVerify() { 169 PackageInfoLite pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mPm.mContext, 170 mPackageLite, mOriginInfo.mResolvedPath, mInstallFlags, mPackageAbiOverride); 171 172 Pair<Integer, String> ret = mPm.verifyReplacingVersionCode( 173 pkgLite, mRequiredInstalledVersionCode, mInstallFlags); 174 setReturnCode(ret.first, ret.second); 175 if (mRet != INSTALL_SUCCEEDED) { 176 return; 177 } 178 179 // Perform package verification and enable rollback (unless we are simply moving the 180 // package). 181 if (!mOriginInfo.mExisting) { 182 final boolean verifyForRollback = !isARollback(); 183 if (!isApex() && !isArchivedInstallation() && verifyForRollback) { 184 // TODO(b/182426975): treat APEX as APK when APK verification is concerned 185 sendApkVerificationRequest(pkgLite); 186 } 187 if ((mInstallFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0) { 188 sendEnableRollbackRequest(); 189 } 190 } 191 } 192 isARollback()193 private boolean isARollback() { 194 return mInstallReason == PackageManager.INSTALL_REASON_ROLLBACK 195 && mInstallSource.mInitiatingPackageName.equals("android"); 196 } 197 sendApkVerificationRequest(PackageInfoLite pkgLite)198 private void sendApkVerificationRequest(PackageInfoLite pkgLite) { 199 final int verificationId = mPm.mPendingVerificationToken++; 200 201 PackageVerificationState verificationState = 202 new PackageVerificationState(this); 203 mPm.mPendingVerification.append(verificationId, verificationState); 204 205 sendPackageVerificationRequest( 206 verificationId, pkgLite, verificationState); 207 208 // If both verifications are skipped, we should remove the state. 209 if (verificationState.areAllVerificationsComplete()) { 210 mPm.mPendingVerification.remove(verificationId); 211 } 212 } 213 sendEnableRollbackRequest()214 void sendEnableRollbackRequest() { 215 final int enableRollbackToken = mPm.mPendingEnableRollbackToken++; 216 Trace.asyncTraceBegin( 217 TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken); 218 mPm.mPendingEnableRollback.append(enableRollbackToken, this); 219 220 Intent enableRollbackIntent = new Intent(Intent.ACTION_PACKAGE_ENABLE_ROLLBACK); 221 enableRollbackIntent.putExtra( 222 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_TOKEN, 223 enableRollbackToken); 224 enableRollbackIntent.putExtra( 225 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_SESSION_ID, 226 mSessionId); 227 enableRollbackIntent.setType(PACKAGE_MIME_TYPE); 228 enableRollbackIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION 229 | Intent.FLAG_RECEIVER_FOREGROUND); 230 231 // Allow the broadcast to be sent before boot complete. 232 // This is needed when committing the apk part of a staged 233 // session in early boot. The rollback manager registers 234 // its receiver early enough during the boot process that 235 // it will not miss the broadcast. 236 enableRollbackIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 237 238 mPm.mContext.sendBroadcastAsUser(enableRollbackIntent, UserHandle.SYSTEM, 239 android.Manifest.permission.PACKAGE_ROLLBACK_AGENT); 240 241 mWaitForEnableRollbackToComplete = true; 242 243 // the duration to wait for rollback to be enabled, in millis 244 long rollbackTimeout = DeviceConfig.getLong( 245 DeviceConfig.NAMESPACE_ROLLBACK, 246 PROPERTY_ENABLE_ROLLBACK_TIMEOUT_MILLIS, 247 DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS); 248 if (rollbackTimeout < 0) { 249 rollbackTimeout = DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS; 250 } 251 final Message msg = mPm.mHandler.obtainMessage(ENABLE_ROLLBACK_TIMEOUT); 252 msg.arg1 = enableRollbackToken; 253 msg.arg2 = mSessionId; 254 mPm.mHandler.sendMessageDelayed(msg, rollbackTimeout); 255 } 256 257 258 /** 259 * Send a request to verifier(s) to verify the package if necessary. 260 */ sendPackageVerificationRequest( int verificationId, PackageInfoLite pkgLite, PackageVerificationState verificationState)261 private void sendPackageVerificationRequest( 262 int verificationId, 263 PackageInfoLite pkgLite, 264 PackageVerificationState verificationState) { 265 266 // Apps installed for "all" users use the current user to verify the app 267 UserHandle verifierUser = getUser(); 268 if (verifierUser == UserHandle.ALL) { 269 verifierUser = UserHandle.of(mPm.mUserManager.getCurrentUserId()); 270 } 271 // TODO(b/300965895): Remove when inconsistencies loading classpaths from apex for 272 // user > 1 are fixed. Tests should cover verifiers from apex classpaths run on 273 // primary user, secondary user and work profile. 274 if (pkgLite.isSdkLibrary) { 275 verifierUser = UserHandle.SYSTEM; 276 } 277 final int verifierUserId = verifierUser.getIdentifier(); 278 279 List<String> requiredVerifierPackages = new ArrayList<>( 280 Arrays.asList(mPm.mRequiredVerifierPackages)); 281 boolean requiredVerifierPackagesOverridden = false; 282 283 // Allow verifier override for ADB installations which could already be unverified using 284 // PackageManager.INSTALL_DISABLE_VERIFICATION flag. 285 if ((mInstallFlags & PackageManager.INSTALL_FROM_ADB) != 0 286 && (mInstallFlags & PackageManager.INSTALL_DISABLE_VERIFICATION) == 0) { 287 String property = SystemProperties.get("debug.pm.adb_verifier_override_packages", ""); 288 if (!TextUtils.isEmpty(property)) { 289 String[] verifierPackages = property.split(";"); 290 List<String> adbVerifierOverridePackages = new ArrayList<>(); 291 for (String verifierPackage : verifierPackages) { 292 if (!TextUtils.isEmpty(verifierPackage) && packageExists(verifierPackage)) { 293 adbVerifierOverridePackages.add(verifierPackage); 294 } 295 } 296 // Check if the package installed. 297 if (adbVerifierOverridePackages.size() > 0) { 298 // Pretend we requested to disable verification from command line. 299 boolean requestedDisableVerification = true; 300 // If this returns false then the caller can already skip verification, so we 301 // are not adding a new way to disable verifications. 302 if (!isAdbVerificationEnabled(pkgLite, verifierUserId, 303 requestedDisableVerification)) { 304 requiredVerifierPackages = adbVerifierOverridePackages; 305 requiredVerifierPackagesOverridden = true; 306 } 307 } 308 } 309 } 310 311 if (mOriginInfo.mExisting || !isVerificationEnabled(pkgLite, verifierUserId, 312 requiredVerifierPackages)) { 313 verificationState.passRequiredVerification(); 314 return; 315 } 316 317 /* 318 * Determine if we have any installed package verifiers. If we 319 * do, then we'll defer to them to verify the packages. 320 */ 321 final Computer snapshot = mPm.snapshotComputer(); 322 323 final int numRequiredVerifierPackages = requiredVerifierPackages.size(); 324 for (int i = numRequiredVerifierPackages - 1; i >= 0; i--) { 325 if (!snapshot.isApplicationEffectivelyEnabled(requiredVerifierPackages.get(i), 326 verifierUser)) { 327 Slog.w(TAG, 328 "Required verifier: " + requiredVerifierPackages.get(i) + " is disabled"); 329 requiredVerifierPackages.remove(i); 330 } 331 } 332 333 for (String requiredVerifierPackage : requiredVerifierPackages) { 334 final int requiredUid = snapshot.getPackageUid(requiredVerifierPackage, 335 MATCH_DEBUG_TRIAGED_MISSING, verifierUserId); 336 verificationState.addRequiredVerifierUid(requiredUid); 337 } 338 339 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 340 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 341 verification.setDataAndType(Uri.fromFile(new File(mOriginInfo.mResolvedPath)), 342 PACKAGE_MIME_TYPE); 343 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 344 345 // Query all live verifiers based on current user state 346 final ParceledListSlice<ResolveInfo> receivers = mPm.queryIntentReceivers(snapshot, 347 verification, PACKAGE_MIME_TYPE, 0, verifierUserId); 348 349 if (DEBUG_VERIFY) { 350 Slog.d(TAG, "Found " + receivers.getList().size() + " verifiers for intent " 351 + verification.toString() + " with " + pkgLite.verifiers.length 352 + " optional verifiers"); 353 } 354 355 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 356 357 verification.putExtra( 358 PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, mInstallFlags); 359 360 verification.putExtra( 361 PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, pkgLite.packageName); 362 363 verification.putExtra( 364 PackageManager.EXTRA_VERIFICATION_VERSION_CODE, pkgLite.versionCode); 365 366 verification.putExtra( 367 PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 368 pkgLite.getLongVersionCode()); 369 370 final String baseCodePath = mPackageLite.getBaseApkPath(); 371 final String[] splitCodePaths = mPackageLite.getSplitApkPaths(); 372 373 final String rootHashString; 374 if (IncrementalManager.isIncrementalPath(baseCodePath)) { 375 rootHashString = PackageManagerServiceUtils.buildVerificationRootHashString( 376 baseCodePath, splitCodePaths); 377 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ROOT_HASH, rootHashString); 378 } else { 379 rootHashString = null; 380 } 381 382 verification.putExtra(PackageInstaller.EXTRA_DATA_LOADER_TYPE, mDataLoaderType); 383 384 verification.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId); 385 386 verification.putExtra(PackageManager.EXTRA_USER_ACTION_REQUIRED, mUserActionRequired); 387 388 populateInstallerExtras(verification); 389 390 // Streaming installation timeout schema is enabled only for: 391 // 1. Incremental installs with v4, 392 // 2. If device/policy allow unverified app installs by default. 393 final boolean streaming = (mDataLoaderType == DataLoaderType.INCREMENTAL) 394 && (mSigningDetails.getSignatureSchemeVersion() == SIGNING_BLOCK_V4) 395 && (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW); 396 397 final long verificationTimeout = VerificationUtils.getVerificationTimeout(mPm.mContext, 398 streaming); 399 400 List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 401 receivers.getList(), verificationState); 402 403 // Add broadcastReceiver Component to verify Sdk before run in Sdk sandbox. 404 if (pkgLite.isSdkLibrary) { 405 if (sufficientVerifiers == null) { 406 sufficientVerifiers = new ArrayList<>(); 407 } 408 ComponentName sdkSandboxComponentName = new ComponentName("android", 409 SdkSandboxManagerLocal.VERIFIER_RECEIVER); 410 sufficientVerifiers.add(sdkSandboxComponentName); 411 412 // Add uid of system_server the same uid for SdkSandboxManagerService 413 verificationState.addSufficientVerifier(Process.myUid()); 414 } 415 416 DeviceIdleInternal idleController = 417 mPm.mInjector.getLocalService(DeviceIdleInternal.class); 418 final BroadcastOptions options = BroadcastOptions.makeBasic(); 419 options.setTemporaryAppAllowlist(verificationTimeout, 420 TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED, 421 REASON_PACKAGE_VERIFIER, ""); 422 423 /* 424 * If any sufficient verifiers were listed in the package 425 * manifest, attempt to ask them. 426 */ 427 if (sufficientVerifiers != null) { 428 final int n = sufficientVerifiers.size(); 429 if (n == 0) { 430 String errorMsg = "Additional verifiers required, but none installed."; 431 Slog.i(TAG, errorMsg); 432 setReturnCode(PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE, errorMsg); 433 } else { 434 for (int i = 0; i < n; i++) { 435 final ComponentName verifierComponent = sufficientVerifiers.get(i); 436 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 437 verifierComponent.getPackageName(), verificationTimeout, 438 verifierUserId, false, 439 REASON_PACKAGE_VERIFIER, "package verifier"); 440 441 final Intent sufficientIntent = new Intent(verification); 442 sufficientIntent.setComponent(verifierComponent); 443 mPm.mContext.sendBroadcastAsUser(sufficientIntent, verifierUser, 444 /* receiverPermission= */ null, 445 options.toBundle()); 446 } 447 } 448 } 449 450 if (requiredVerifierPackages.size() == 0) { 451 Slog.e(TAG, "No required verifiers"); 452 return; 453 } 454 455 final int verificationCodeAtTimeout; 456 // Allows package verification to continue in the event the app being updated is verifying 457 // itself and fails to respond 458 if (Flags.emergencyInstallPermission() && requiredVerifierPackages.contains( 459 pkgLite.packageName)) { 460 verificationCodeAtTimeout = PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT; 461 } else if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 462 verificationCodeAtTimeout = PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT; 463 } else { 464 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 465 } 466 467 for (String requiredVerifierPackage : requiredVerifierPackages) { 468 final int requiredUid = snapshot.getPackageUid(requiredVerifierPackage, 469 MATCH_DEBUG_TRIAGED_MISSING, verifierUserId); 470 471 final Intent requiredIntent; 472 final String receiverPermission; 473 if (!requiredVerifierPackagesOverridden || requiredVerifierPackages.size() == 1) { 474 // Prod code OR test code+single verifier. 475 requiredIntent = new Intent(verification); 476 if (!requiredVerifierPackagesOverridden) { 477 ComponentName requiredVerifierComponent = matchComponentForVerifier( 478 requiredVerifierPackage, receivers.getList()); 479 requiredIntent.setComponent(requiredVerifierComponent); 480 } else { 481 requiredIntent.setPackage(requiredVerifierPackage); 482 } 483 receiverPermission = android.Manifest.permission.PACKAGE_VERIFICATION_AGENT; 484 } else { 485 // Test code+multiple verifiers. 486 // Recreate the intent to contain test-only information. 487 requiredIntent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 488 requiredIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 489 requiredIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 490 requiredIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 491 requiredIntent.setDataAndType(Uri.fromFile(new File(mOriginInfo.mResolvedPath)), 492 PACKAGE_MIME_TYPE); 493 requiredIntent.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId); 494 requiredIntent.putExtra(PackageInstaller.EXTRA_DATA_LOADER_TYPE, mDataLoaderType); 495 if (rootHashString != null) { 496 requiredIntent.putExtra(PackageManager.EXTRA_VERIFICATION_ROOT_HASH, 497 rootHashString); 498 } 499 requiredIntent.setPackage(requiredVerifierPackage); 500 // Negative verification id. 501 requiredIntent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, -verificationId); 502 // OK not to have permission. 503 receiverPermission = null; 504 } 505 506 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), requiredVerifierPackage, 507 verificationTimeout, verifierUserId, false, REASON_PACKAGE_VERIFIER, 508 "package verifier"); 509 510 final PackageVerificationResponse response = new PackageVerificationResponse( 511 verificationCodeAtTimeout, requiredUid); 512 513 startVerificationTimeoutCountdown(verificationId, streaming, response, 514 verificationTimeout); 515 516 // Send the intent to the required verification agent, but only start the 517 // verification timeout after the target BroadcastReceivers have run. 518 mPm.mContext.sendOrderedBroadcastAsUser(requiredIntent, verifierUser, 519 receiverPermission, AppOpsManager.OP_NONE, options.toBundle(), 520 null, null, 0, null, null); 521 } 522 523 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 524 525 /* 526 * We don't want the copy to proceed until verification 527 * succeeds. 528 */ 529 mWaitForVerificationToComplete = true; 530 } 531 startVerificationTimeoutCountdown(int verificationId, boolean streaming, PackageVerificationResponse response, long verificationTimeout)532 private void startVerificationTimeoutCountdown(int verificationId, boolean streaming, 533 PackageVerificationResponse response, long verificationTimeout) { 534 final Message msg = mPm.mHandler.obtainMessage(CHECK_PENDING_VERIFICATION); 535 msg.arg1 = verificationId; 536 msg.arg2 = streaming ? 1 : 0; 537 msg.obj = response; 538 mPm.mHandler.sendMessageDelayed(msg, verificationTimeout); 539 } 540 541 /** 542 * Get the default verification agent response code. 543 * 544 * @return default verification response code 545 */ getDefaultVerificationResponse()546 int getDefaultVerificationResponse() { 547 if (mPm.mUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, 548 getUser().getIdentifier())) { 549 return PackageManager.VERIFICATION_REJECT; 550 } 551 return android.provider.Settings.Global.getInt(mPm.mContext.getContentResolver(), 552 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 553 DEFAULT_VERIFICATION_RESPONSE); 554 } 555 packageExists(String packageName)556 private boolean packageExists(String packageName) { 557 Computer snapshot = mPm.snapshotComputer(); 558 return snapshot.getPackageStateInternal(packageName) != null; 559 } 560 isAdbVerificationEnabled(PackageInfoLite pkgInfoLite, int userId, boolean requestedDisableVerification)561 private boolean isAdbVerificationEnabled(PackageInfoLite pkgInfoLite, int userId, 562 boolean requestedDisableVerification) { 563 boolean verifierIncludeAdb = android.provider.Settings.Global.getInt( 564 mPm.mContext.getContentResolver(), 565 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) != 0; 566 567 if (mPm.isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS)) { 568 if (!verifierIncludeAdb) { 569 Slog.w(TAG, "Force verification of ADB install because of user restriction."); 570 } 571 return true; 572 } 573 574 // Check if the verification disabled globally, first. 575 if (!verifierIncludeAdb) { 576 return false; 577 } 578 579 // Check if the developer wants to skip verification for ADB installs. 580 if (requestedDisableVerification) { 581 if (!packageExists(pkgInfoLite.packageName)) { 582 // Always verify fresh install. 583 return true; 584 } 585 // Only skip when apk is debuggable. 586 return !pkgInfoLite.debuggable; 587 } 588 589 return true; 590 } 591 592 /** 593 * Check whether package verification has been enabled. 594 * 595 * @return true if verification should be performed 596 */ isVerificationEnabled(PackageInfoLite pkgInfoLite, int userId, List<String> requiredVerifierPackages)597 private boolean isVerificationEnabled(PackageInfoLite pkgInfoLite, int userId, 598 List<String> requiredVerifierPackages) { 599 if (!DEFAULT_VERIFY_ENABLE) { 600 return false; 601 } 602 603 final int installerUid = mVerificationInfo == null ? -1 : mVerificationInfo.mInstallerUid; 604 final boolean requestedDisableVerification = 605 (mInstallFlags & PackageManager.INSTALL_DISABLE_VERIFICATION) != 0; 606 607 // Check if installing from ADB 608 if ((mInstallFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 609 return isAdbVerificationEnabled(pkgInfoLite, userId, requestedDisableVerification); 610 } else if (requestedDisableVerification) { 611 // Skip verification for non-adb installs 612 return false; 613 } 614 615 // only when not installed from ADB, skip verification for instant apps when 616 // the installer and verifier are the same. 617 if (isInstant() && mPm.mInstantAppInstallerActivity != null) { 618 String installerPackage = mPm.mInstantAppInstallerActivity.packageName; 619 for (String requiredVerifierPackage : requiredVerifierPackages) { 620 if (installerPackage.equals(requiredVerifierPackage)) { 621 try { 622 mPm.mInjector.getSystemService(AppOpsManager.class) 623 .checkPackage(installerUid, requiredVerifierPackage); 624 if (DEBUG_VERIFY) { 625 Slog.i(TAG, "disable verification for instant app"); 626 } 627 return false; 628 } catch (SecurityException ignore) { 629 } 630 } 631 } 632 } 633 return true; 634 } 635 matchVerifiers(PackageInfoLite pkgInfo, List<ResolveInfo> receivers, final PackageVerificationState verificationState)636 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 637 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 638 if (pkgInfo.verifiers == null || pkgInfo.verifiers.length == 0) { 639 return null; 640 } 641 642 final int n = pkgInfo.verifiers.length; 643 final List<ComponentName> sufficientVerifiers = new ArrayList<>(n + 1); 644 for (int i = 0; i < n; i++) { 645 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 646 647 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 648 receivers); 649 if (comp == null) { 650 continue; 651 } 652 653 final int verifierUid = mPm.getUidForVerifier(verifierInfo); 654 if (verifierUid == -1) { 655 continue; 656 } 657 658 if (DEBUG_VERIFY) { 659 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 660 + " with the correct signature"); 661 } 662 sufficientVerifiers.add(comp); 663 verificationState.addSufficientVerifier(verifierUid); 664 } 665 666 return sufficientVerifiers; 667 } 668 matchComponentForVerifier(String packageName, List<ResolveInfo> receivers)669 private static ComponentName matchComponentForVerifier(String packageName, 670 List<ResolveInfo> receivers) { 671 ActivityInfo targetReceiver = null; 672 673 final int nr = receivers.size(); 674 for (int i = 0; i < nr; i++) { 675 final ResolveInfo info = receivers.get(i); 676 if (info.activityInfo == null) { 677 continue; 678 } 679 680 if (packageName.equals(info.activityInfo.packageName)) { 681 targetReceiver = info.activityInfo; 682 break; 683 } 684 } 685 686 if (targetReceiver == null) { 687 return null; 688 } 689 690 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 691 } 692 populateInstallerExtras(Intent intent)693 void populateInstallerExtras(Intent intent) { 694 intent.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 695 mInstallSource.mInitiatingPackageName); 696 697 if (mVerificationInfo != null) { 698 if (mVerificationInfo.mOriginatingUri != null) { 699 intent.putExtra(Intent.EXTRA_ORIGINATING_URI, 700 mVerificationInfo.mOriginatingUri); 701 } 702 if (mVerificationInfo.mReferrer != null) { 703 intent.putExtra(Intent.EXTRA_REFERRER, 704 mVerificationInfo.mReferrer); 705 } 706 if (mVerificationInfo.mOriginatingUid >= 0) { 707 intent.putExtra(Intent.EXTRA_ORIGINATING_UID, 708 mVerificationInfo.mOriginatingUid); 709 } 710 if (mVerificationInfo.mInstallerUid >= 0) { 711 intent.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 712 mVerificationInfo.mInstallerUid); 713 } 714 } 715 } 716 setReturnCode(int ret, String message)717 void setReturnCode(int ret, String message) { 718 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 719 // Only update mRet if it was previously INSTALL_SUCCEEDED to 720 // ensure we do not overwrite any previous failure results. 721 mRet = ret; 722 mErrorMessage = message; 723 } 724 } 725 handleVerificationFinished()726 void handleVerificationFinished() { 727 mWaitForVerificationToComplete = false; 728 handleReturnCode(); 729 } 730 handleRollbackEnabled()731 void handleRollbackEnabled() { 732 // TODO(b/112431924): Consider halting the install if we 733 // couldn't enable rollback. 734 mWaitForEnableRollbackToComplete = false; 735 handleReturnCode(); 736 } 737 handleReturnCode()738 void handleReturnCode() { 739 if (mWaitForVerificationToComplete 740 || mWaitForEnableRollbackToComplete) { 741 return; 742 } 743 sendVerificationCompleteNotification(); 744 if (mRet != INSTALL_SUCCEEDED) { 745 PackageMetrics.onVerificationFailed(this); 746 } 747 } 748 sendVerificationCompleteNotification()749 private void sendVerificationCompleteNotification() { 750 if (mParentVerifyingSession != null) { 751 mParentVerifyingSession.trySendVerificationCompleteNotification(this); 752 } else { 753 try { 754 mObserver.onPackageInstalled(null, mRet, mErrorMessage, 755 new Bundle()); 756 } catch (RemoteException e) { 757 Slog.i(TAG, "Observer no longer exists."); 758 } 759 } 760 } 761 start()762 private void start() { 763 if (DEBUG_INSTALL) Slog.i(TAG, "start " + mUser + ": " + this); 764 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueVerify", 765 System.identityHashCode(this)); 766 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "start"); 767 handleStartVerify(); 768 handleReturnCode(); 769 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 770 } 771 verifyStage()772 public void verifyStage() { 773 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueVerify", 774 System.identityHashCode(this)); 775 mPm.mHandler.post(this::start); 776 } 777 verifyStage(List<VerifyingSession> children)778 public void verifyStage(List<VerifyingSession> children) 779 throws PackageManagerException { 780 final MultiPackageVerifyingSession multiPackageVerifyingSession = 781 new MultiPackageVerifyingSession(this, children); 782 mPm.mHandler.post(multiPackageVerifyingSession::start); 783 } 784 getRet()785 public int getRet() { 786 return mRet; 787 } getErrorMessage()788 public String getErrorMessage() { 789 return mErrorMessage; 790 } getUser()791 public UserHandle getUser() { 792 return mUser; 793 } getSessionId()794 public int getSessionId() { 795 return mSessionId; 796 } getDataLoaderType()797 public int getDataLoaderType() { 798 return mDataLoaderType; 799 } getUserActionRequiredType()800 public int getUserActionRequiredType() { 801 return mUserActionRequiredType; 802 } isInstant()803 public boolean isInstant() { 804 return (mInstallFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 805 } isInherit()806 public boolean isInherit() { 807 return mIsInherit; 808 } getInstallerPackageUid()809 public int getInstallerPackageUid() { 810 return mInstallSource.mInstallerPackageUid; 811 } isApex()812 public boolean isApex() { 813 return (mInstallFlags & PackageManager.INSTALL_APEX) != 0; 814 } isArchivedInstallation()815 public boolean isArchivedInstallation() { 816 return (mInstallFlags & PackageManager.INSTALL_ARCHIVED) != 0; 817 } isStaged()818 public boolean isStaged() { 819 return mIsStaged; 820 } 821 } 822