1 /* 2 * Copyright (C) 2020 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.internal.telephony; 18 19 import static android.telephony.CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY; 20 import static android.telephony.SubscriptionManager.INVALID_SIM_SLOT_INDEX; 21 import static android.telephony.TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS; 22 import static android.telephony.TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS; 23 import static android.telephony.TelephonyManager.CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED; 24 import static android.telephony.TelephonyManager.EXTRA_SIM_STATE; 25 import static android.telephony.TelephonyManager.SIM_STATE_ABSENT; 26 import static android.telephony.TelephonyManager.SIM_STATE_LOADED; 27 import static android.telephony.TelephonyManager.SIM_STATE_NOT_READY; 28 import static android.telephony.TelephonyManager.SIM_STATE_READY; 29 import static android.telephony.TelephonyManager.SIM_STATE_UNKNOWN; 30 31 import android.annotation.ElapsedRealtimeLong; 32 import android.annotation.NonNull; 33 import android.annotation.Nullable; 34 import android.app.ActivityManager; 35 import android.content.BroadcastReceiver; 36 import android.content.Context; 37 import android.content.Intent; 38 import android.content.IntentFilter; 39 import android.content.pm.PackageInfo; 40 import android.content.pm.PackageManager; 41 import android.content.pm.PackageManager.NameNotFoundException; 42 import android.content.pm.ResolveInfo; 43 import android.content.pm.Signature; 44 import android.content.pm.UserInfo; 45 import android.net.Uri; 46 import android.os.Bundle; 47 import android.os.Handler; 48 import android.os.Looper; 49 import android.os.Message; 50 import android.os.PersistableBundle; 51 import android.os.Process; 52 import android.os.SystemClock; 53 import android.os.UserHandle; 54 import android.os.UserManager; 55 import android.service.carrier.CarrierService; 56 import android.telephony.Annotation.CarrierPrivilegeStatus; 57 import android.telephony.CarrierConfigManager; 58 import android.telephony.SubscriptionManager; 59 import android.telephony.TelephonyManager; 60 import android.telephony.TelephonyRegistryManager; 61 import android.telephony.UiccAccessRule; 62 import android.text.TextUtils; 63 import android.util.ArrayMap; 64 import android.util.ArraySet; 65 import android.util.LocalLog; 66 import android.util.Pair; 67 68 import com.android.internal.annotations.GuardedBy; 69 import com.android.internal.telephony.uicc.IccUtils; 70 import com.android.internal.telephony.uicc.UiccPort; 71 import com.android.internal.telephony.uicc.UiccProfile; 72 import com.android.telephony.Rlog; 73 74 import java.io.FileDescriptor; 75 import java.io.PrintWriter; 76 import java.util.ArrayList; 77 import java.util.Arrays; 78 import java.util.Collection; 79 import java.util.Collections; 80 import java.util.List; 81 import java.util.Locale; 82 import java.util.Map; 83 import java.util.Objects; 84 import java.util.Set; 85 import java.util.StringJoiner; 86 import java.util.concurrent.TimeUnit; 87 import java.util.concurrent.locks.ReadWriteLock; 88 import java.util.concurrent.locks.ReentrantReadWriteLock; 89 import java.util.function.Function; 90 91 /** 92 * CarrierPrivilegesTracker will track the Carrier Privileges for a specific {@link Phone}. 93 * Registered Telephony entities will receive notifications when the UIDs with these privileges 94 * change. 95 */ 96 public class CarrierPrivilegesTracker extends Handler { 97 private static final String TAG = CarrierPrivilegesTracker.class.getSimpleName(); 98 99 private static final boolean VDBG = false; 100 101 private static final String SHA_1 = "SHA-1"; 102 private static final String SHA_256 = "SHA-256"; 103 104 private static final int PACKAGE_NOT_PRIVILEGED = 0; 105 private static final int PACKAGE_PRIVILEGED_FROM_CARRIER_CONFIG = 1; 106 private static final int PACKAGE_PRIVILEGED_FROM_SIM = 2; 107 private static final int PACKAGE_PRIVILEGED_FROM_CARRIER_SERVICE_TEST_OVERRIDE = 3; 108 109 // TODO(b/232273884): Turn feature on when find solution to handle the inter-carriers switching 110 /** 111 * Time delay to clear UICC rules after UICC is gone. 112 * This introduces the grace period to retain carrier privileges when SIM is removed. 113 * 114 * This feature is off by default due to the security concern during inter-carriers switching. 115 */ 116 private static final long CLEAR_UICC_RULES_DELAY_MILLIS = TimeUnit.SECONDS.toMillis(0); 117 118 /** 119 * PackageManager flags used to query installed packages. 120 * Include DISABLED_UNTIL_USED components. This facilitates cases where a carrier app 121 * is disabled by default, and some other component wants to enable it when it has 122 * gained carrier privileges (as an indication that a matching SIM has been inserted). 123 */ 124 private static final int INSTALLED_PACKAGES_QUERY_FLAGS = 125 PackageManager.GET_SIGNING_CERTIFICATES 126 | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS 127 | PackageManager.MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS; 128 129 /** 130 * Action for tracking when the Phone's SIM state changes. 131 * arg1: slotId that this Action applies to 132 * arg2: simState reported by this Broadcast 133 */ 134 private static final int ACTION_SIM_STATE_UPDATED = 4; 135 136 /** 137 * Action for tracking when a package is installed, replaced or changed (exclude the case 138 * disabled by user) on the device. 139 * obj: String package name that was installed, replaced or changed on the device. 140 */ 141 private static final int ACTION_PACKAGE_ADDED_REPLACED_OR_CHANGED = 5; 142 143 /** 144 * Action for tracking when a package is uninstalled or disabled by user on the device. 145 * obj: String package name that was installed or disabled by user on the device. 146 */ 147 private static final int ACTION_PACKAGE_REMOVED_OR_DISABLED_BY_USER = 6; 148 149 /** 150 * Action used to initialize the state of the Tracker. 151 */ 152 private static final int ACTION_INITIALIZE_TRACKER = 7; 153 154 /** 155 * Action to set the test override rule through {@link TelephonyManager#setCarrierTestOverride}. 156 * obj: String of the carrierPrivilegeRules from method setCarrierTestOverride. 157 */ 158 private static final int ACTION_SET_TEST_OVERRIDE_RULE = 8; 159 160 /** 161 * Action to clear UICC rules. 162 */ 163 private static final int ACTION_CLEAR_UICC_RULES = 9; 164 165 /** 166 * Action to handle the case when UiccAccessRules has been loaded. 167 */ 168 private static final int ACTION_UICC_ACCESS_RULES_LOADED = 10; 169 170 /** 171 * Action to set the test override rule through {@link 172 * TelephonyManager#setCarrierServicePackageOverride}. 173 * 174 * <p>obj: String of the carrierServicePackage from method setCarrierServicePackageOverride. 175 */ 176 private static final int ACTION_SET_TEST_OVERRIDE_CARRIER_SERVICE_PACKAGE = 11; 177 178 private final Context mContext; 179 private final Phone mPhone; 180 private final PackageManager mPackageManager; 181 private final UserManager mUserManager; 182 private final CarrierConfigManager mCarrierConfigManager; 183 private final TelephonyManager mTelephonyManager; 184 private final TelephonyRegistryManager mTelephonyRegistryManager; 185 186 @NonNull private final LocalLog mLocalLog = new LocalLog(64); 187 // Stores rules for Carrier Config-loaded rules 188 @NonNull private final List<UiccAccessRule> mCarrierConfigRules = new ArrayList<>(); 189 // Stores rules for SIM-loaded rules. 190 @NonNull private final List<UiccAccessRule> mUiccRules = new ArrayList<>(); 191 // Stores rule from test override (through TelephonyManager#setCarrierTestOverride). 192 // - Null list indicates no test override (CC and UICC rules are respected) 193 // - Empty list indicates test override to simulate no rules (CC and UICC rules are ignored) 194 // - Non-empty list indicates test override with specific rules (CC and UICC rules are ignored) 195 @Nullable private List<UiccAccessRule> mTestOverrideRules = null; 196 @Nullable private String mTestOverrideCarrierServicePackage = null; 197 // Map of PackageName -> Certificate hashes for that Package 198 @NonNull private final Map<String, Set<String>> mInstalledPackageCerts = new ArrayMap<>(); 199 // Map of PackageName -> UIDs for that Package 200 @NonNull private final Map<String, Set<Integer>> mCachedUids = new ArrayMap<>(); 201 202 // This should be used to guard critical section either with 203 // mPrivilegedPackageInfoLock.readLock() or mPrivilegedPackageInfoLock.writeLock(), but never 204 // with the mPrivilegedPackageInfoLock object itself. 205 @NonNull private final ReadWriteLock mPrivilegedPackageInfoLock = new ReentrantReadWriteLock(); 206 // Package names and UIDs of apps that currently hold carrier privileges. 207 @GuardedBy(anyOf = {"mPrivilegedPackageInfoLock.readLock()", 208 "mPrivilegedPackageInfoLock.writeLock()"}) 209 @NonNull private PrivilegedPackageInfo mPrivilegedPackageInfo = new PrivilegedPackageInfo(); 210 211 // Uptime in millis on when the NEXT clear-up of UiccRules are scheduled 212 @ElapsedRealtimeLong 213 private long mClearUiccRulesUptimeMillis = CLEAR_UICC_RULE_NOT_SCHEDULED; 214 // Constant indicates no schedule to clear UiccRules 215 private static final long CLEAR_UICC_RULE_NOT_SCHEDULED = -1; 216 217 // Indicates SIM has reached SIM_STATE_READY but not SIM_STATE_LOADED yet. During this transient 218 // state, all the information previously loaded from SIM may be updated soon later and thus 219 // unreliable. For security's concern, any carrier privileges check should return 220 // CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED (instead of neither HAS_ACCESS nor NO_ACCESS) until 221 // SIM becomes LOADED again, or grace period specified by CLEAR_UICC_RULES_DELAY_MILLIS expires. 222 @GuardedBy(anyOf = {"mPrivilegedPackageInfoLock.readLock()", 223 "mPrivilegedPackageInfoLock.writeLock()"}) 224 private boolean mSimIsReadyButNotLoaded = false; 225 226 /** Small snapshot to hold package names and UIDs of privileged packages. */ 227 private static final class PrivilegedPackageInfo { 228 @NonNull final Set<String> mPackageNames; 229 @NonNull final Set<Integer> mUids; 230 // The carrier service (packageName, UID) pair 231 @NonNull final Pair<String, Integer> mCarrierService; 232 PrivilegedPackageInfo()233 PrivilegedPackageInfo() { 234 mPackageNames = Collections.emptySet(); 235 mUids = Collections.emptySet(); 236 mCarrierService = new Pair<>(null, Process.INVALID_UID); 237 } 238 PrivilegedPackageInfo(@onNull Set<String> packageNames, @NonNull Set<Integer> uids, @NonNull Pair<String, Integer> carrierService)239 PrivilegedPackageInfo(@NonNull Set<String> packageNames, @NonNull Set<Integer> uids, 240 @NonNull Pair<String, Integer> carrierService) { 241 mPackageNames = packageNames; 242 mUids = uids; 243 mCarrierService = carrierService; 244 } 245 246 @Override toString()247 public String toString() { 248 return "{packageNames=" 249 + getObfuscatedPackages(mPackageNames, pkg -> Rlog.pii(TAG, pkg)) 250 + ", uids=" 251 + mUids 252 + ", carrierServicePackageName=" 253 + Rlog.pii(TAG, mCarrierService.first) 254 + ", carrierServiceUid=" 255 + mCarrierService.second 256 + "}"; 257 } 258 259 @Override equals(Object o)260 public boolean equals(Object o) { 261 if (this == o) { 262 return true; 263 } 264 if (!(o instanceof PrivilegedPackageInfo)) { 265 return false; 266 } 267 PrivilegedPackageInfo other = (PrivilegedPackageInfo) o; 268 return mPackageNames.equals(other.mPackageNames) && mUids.equals(other.mUids) 269 && mCarrierService.equals(other.mCarrierService); 270 } 271 272 @Override hashCode()273 public int hashCode() { 274 return Objects.hash(mPackageNames, mUids, mCarrierService); 275 } 276 } 277 278 private final BroadcastReceiver mIntentReceiver = 279 new BroadcastReceiver() { 280 @Override 281 public void onReceive(Context context, Intent intent) { 282 String action = intent.getAction(); 283 if (action == null) return; 284 285 switch (action) { 286 case TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED: // fall through 287 case TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED: { 288 Bundle extras = intent.getExtras(); 289 int simState = extras.getInt(EXTRA_SIM_STATE, SIM_STATE_UNKNOWN); 290 int slotId = 291 extras.getInt(PhoneConstants.PHONE_KEY, INVALID_SIM_SLOT_INDEX); 292 293 if (simState != SIM_STATE_ABSENT 294 && simState != SIM_STATE_NOT_READY 295 && simState != SIM_STATE_READY 296 && simState != SIM_STATE_LOADED) { 297 return; 298 } 299 300 sendMessage(obtainMessage(ACTION_SIM_STATE_UPDATED, slotId, simState)); 301 break; 302 } 303 case Intent.ACTION_PACKAGE_ADDED: // fall through 304 case Intent.ACTION_PACKAGE_REPLACED: // fall through 305 case Intent.ACTION_PACKAGE_REMOVED: // fall through 306 case Intent.ACTION_PACKAGE_CHANGED: { 307 Uri uri = intent.getData(); 308 String pkgName = (uri != null) ? uri.getSchemeSpecificPart() : null; 309 if (TextUtils.isEmpty(pkgName)) { 310 Rlog.e(TAG, "Failed to get package from Intent"); 311 return; 312 } 313 314 boolean removed = action.equals(Intent.ACTION_PACKAGE_REMOVED); 315 boolean disabledByUser = false; 316 boolean notExist = false; 317 try { 318 disabledByUser = action.equals(Intent.ACTION_PACKAGE_CHANGED) 319 && mPackageManager.getApplicationEnabledSetting(pkgName) 320 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 321 } catch (IllegalArgumentException iae) { 322 // Very rare case when package changed race with package removed 323 Rlog.w(TAG, "Package does not exist: " + pkgName); 324 notExist = true; 325 } 326 // When a package is explicitly disabled by the user or does not exist, 327 // treat them as if it was removed: clear it from the cache 328 int what = (removed || disabledByUser || notExist) 329 ? ACTION_PACKAGE_REMOVED_OR_DISABLED_BY_USER 330 : ACTION_PACKAGE_ADDED_REPLACED_OR_CHANGED; 331 332 sendMessage(obtainMessage(what, pkgName)); 333 break; 334 } 335 } 336 } 337 }; 338 CarrierPrivilegesTracker( @onNull Looper looper, @NonNull Phone phone, @NonNull Context context)339 public CarrierPrivilegesTracker( 340 @NonNull Looper looper, @NonNull Phone phone, @NonNull Context context) { 341 super(looper); 342 mContext = context; 343 mPhone = phone; 344 mPackageManager = mContext.getPackageManager(); 345 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); 346 mCarrierConfigManager = 347 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE); 348 // Callback is executed in handler thread and directly handles carrier config update 349 mCarrierConfigManager.registerCarrierConfigChangeListener(this::post, 350 (slotIndex, subId, carrierId, specificCarrierId) -> handleCarrierConfigUpdated( 351 subId, slotIndex)); 352 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 353 mTelephonyRegistryManager = 354 (TelephonyRegistryManager) 355 mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE); 356 357 IntentFilter certFilter = new IntentFilter(); 358 certFilter.addAction(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED); 359 certFilter.addAction(TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED); 360 mContext.registerReceiver(mIntentReceiver, certFilter); 361 362 IntentFilter packageFilter = new IntentFilter(); 363 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); 364 packageFilter.addAction(Intent.ACTION_PACKAGE_REPLACED); 365 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 366 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED); 367 368 // For package-related broadcasts, specify the data scheme for "package" to receive the 369 // package name along with the broadcast 370 packageFilter.addDataScheme("package"); 371 mContext.registerReceiver(mIntentReceiver, packageFilter); 372 373 sendMessage(obtainMessage(ACTION_INITIALIZE_TRACKER)); 374 } 375 376 @Override handleMessage(Message msg)377 public void handleMessage(Message msg) { 378 switch (msg.what) { 379 case ACTION_SIM_STATE_UPDATED: { 380 handleSimStateChanged(msg.arg1, msg.arg2); 381 break; 382 } 383 case ACTION_PACKAGE_ADDED_REPLACED_OR_CHANGED: { 384 String pkgName = (String) msg.obj; 385 handlePackageAddedReplacedOrChanged(pkgName); 386 break; 387 } 388 case ACTION_PACKAGE_REMOVED_OR_DISABLED_BY_USER: { 389 String pkgName = (String) msg.obj; 390 handlePackageRemovedOrDisabledByUser(pkgName); 391 break; 392 } 393 case ACTION_INITIALIZE_TRACKER: { 394 handleInitializeTracker(); 395 break; 396 } 397 case ACTION_SET_TEST_OVERRIDE_RULE: { 398 String carrierPrivilegeRules = (String) msg.obj; 399 handleSetTestOverrideRules(carrierPrivilegeRules); 400 break; 401 } 402 case ACTION_CLEAR_UICC_RULES: { 403 handleClearUiccRules(); 404 break; 405 } 406 case ACTION_UICC_ACCESS_RULES_LOADED: { 407 handleUiccAccessRulesLoaded(); 408 break; 409 } 410 case ACTION_SET_TEST_OVERRIDE_CARRIER_SERVICE_PACKAGE: { 411 String carrierServicePackage = (String) msg.obj; 412 handleSetTestOverrideCarrierServicePackage(carrierServicePackage); 413 break; 414 } 415 default: { 416 Rlog.e(TAG, "Received unknown msg type: " + msg.what); 417 break; 418 } 419 } 420 } 421 handleCarrierConfigUpdated(int subId, int slotIndex)422 private void handleCarrierConfigUpdated(int subId, int slotIndex) { 423 if (slotIndex != mPhone.getPhoneId()) return; 424 425 List<UiccAccessRule> updatedCarrierConfigRules = Collections.EMPTY_LIST; 426 427 // Carrier Config broadcasts with INVALID_SUBSCRIPTION_ID when the SIM is removed. This is 428 // an expected event. When this happens, clear the certificates from the previous configs. 429 // The rules will be cleared in maybeUpdateRulesAndNotifyRegistrants() below. 430 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) { 431 updatedCarrierConfigRules = getCarrierConfigRules(subId); 432 } 433 434 mLocalLog.log("CarrierConfigUpdated:" 435 + " subId=" + subId 436 + " slotIndex=" + slotIndex 437 + " updated CarrierConfig rules=" + updatedCarrierConfigRules); 438 maybeUpdateRulesAndNotifyRegistrants(mCarrierConfigRules, updatedCarrierConfigRules); 439 } 440 441 @NonNull getCarrierConfigRules(int subId)442 private List<UiccAccessRule> getCarrierConfigRules(int subId) { 443 PersistableBundle carrierConfigs = 444 CarrierConfigManager.getCarrierConfigSubset( 445 mContext, subId, KEY_CARRIER_CERTIFICATE_STRING_ARRAY); 446 // CarrierConfigManager#isConfigForIdentifiedCarrier can handle null or empty bundle 447 if (!mCarrierConfigManager.isConfigForIdentifiedCarrier(carrierConfigs)) { 448 return Collections.EMPTY_LIST; 449 } 450 451 String[] carrierConfigRules = 452 carrierConfigs.getStringArray(KEY_CARRIER_CERTIFICATE_STRING_ARRAY); 453 if (carrierConfigRules == null) { 454 return Collections.EMPTY_LIST; 455 } 456 return Arrays.asList(UiccAccessRule.decodeRulesFromCarrierConfig(carrierConfigRules)); 457 } 458 handleSimStateChanged(int slotId, int simState)459 private void handleSimStateChanged(int slotId, int simState) { 460 if (slotId != mPhone.getPhoneId()) return; 461 462 List<UiccAccessRule> updatedUiccRules = Collections.EMPTY_LIST; 463 464 mPrivilegedPackageInfoLock.writeLock().lock(); 465 try { 466 mSimIsReadyButNotLoaded = simState == SIM_STATE_READY; 467 } finally { 468 mPrivilegedPackageInfoLock.writeLock().unlock(); 469 } 470 471 // Only include the UICC rules if the SIM is fully loaded 472 if (simState == SIM_STATE_LOADED) { 473 mLocalLog.log("SIM fully loaded, handleUiccAccessRulesLoaded."); 474 handleUiccAccessRulesLoaded(); 475 } else { 476 if (!mUiccRules.isEmpty() 477 && mClearUiccRulesUptimeMillis == CLEAR_UICC_RULE_NOT_SCHEDULED) { 478 mClearUiccRulesUptimeMillis = 479 SystemClock.uptimeMillis() + CLEAR_UICC_RULES_DELAY_MILLIS; 480 sendMessageAtTime(obtainMessage(ACTION_CLEAR_UICC_RULES), 481 mClearUiccRulesUptimeMillis); 482 mLocalLog.log("SIM is gone, simState=" + TelephonyManager.simStateToString(simState) 483 + ". Delay " + TimeUnit.MILLISECONDS.toSeconds( 484 CLEAR_UICC_RULES_DELAY_MILLIS) + " seconds to clear UICC rules."); 485 } else { 486 mLocalLog.log( 487 "Ignore SIM gone event while UiccRules is empty or waiting to be emptied."); 488 } 489 } 490 } 491 handleUiccAccessRulesLoaded()492 private void handleUiccAccessRulesLoaded() { 493 mClearUiccRulesUptimeMillis = CLEAR_UICC_RULE_NOT_SCHEDULED; 494 removeMessages(ACTION_CLEAR_UICC_RULES); 495 496 List<UiccAccessRule> updatedUiccRules = getSimRules(); 497 mLocalLog.log("UiccAccessRules loaded:" 498 + " updated SIM-loaded rules=" + updatedUiccRules); 499 maybeUpdateRulesAndNotifyRegistrants(mUiccRules, updatedUiccRules); 500 } 501 502 /** Called when UiccAccessRules has been loaded */ onUiccAccessRulesLoaded()503 public void onUiccAccessRulesLoaded() { 504 sendEmptyMessage(ACTION_UICC_ACCESS_RULES_LOADED); 505 } 506 handleClearUiccRules()507 private void handleClearUiccRules() { 508 mClearUiccRulesUptimeMillis = CLEAR_UICC_RULE_NOT_SCHEDULED; 509 removeMessages(ACTION_CLEAR_UICC_RULES); 510 maybeUpdateRulesAndNotifyRegistrants(mUiccRules, Collections.EMPTY_LIST); 511 } 512 513 @NonNull getSimRules()514 private List<UiccAccessRule> getSimRules() { 515 if (!mTelephonyManager.hasIccCard(mPhone.getPhoneId())) { 516 return Collections.EMPTY_LIST; 517 } 518 519 UiccPort uiccPort = mPhone.getUiccPort(); 520 if (uiccPort == null) { 521 Rlog.w( 522 TAG, 523 "Null UiccPort, but hasIccCard was present for phoneId " + mPhone.getPhoneId()); 524 return Collections.EMPTY_LIST; 525 } 526 527 UiccProfile uiccProfile = uiccPort.getUiccProfile(); 528 if (uiccProfile == null) { 529 Rlog.w( 530 TAG, 531 "Null UiccProfile, but hasIccCard was true for phoneId " + mPhone.getPhoneId()); 532 return Collections.EMPTY_LIST; 533 } 534 return uiccProfile.getCarrierPrivilegeAccessRules(); 535 } 536 handlePackageAddedReplacedOrChanged(@ullable String pkgName)537 private void handlePackageAddedReplacedOrChanged(@Nullable String pkgName) { 538 if (pkgName == null) return; 539 540 PackageInfo pkg; 541 try { 542 pkg = mPackageManager.getPackageInfo(pkgName, INSTALLED_PACKAGES_QUERY_FLAGS); 543 } catch (NameNotFoundException e) { 544 Rlog.e(TAG, "Error getting installed package: " + pkgName, e); 545 return; 546 } 547 548 updateCertsForPackage(pkg); 549 // Invalidate cache because this may be a package already on the device but getting 550 // installed for a user it wasn't installed in before, which means there will be an 551 // additional UID. 552 getUidsForPackage(pkg.packageName, /* invalidateCache= */ true); 553 if (VDBG) { 554 Rlog.d(TAG, "Package added/replaced/changed:" 555 + " pkg=" + Rlog.pii(TAG, pkgName) 556 + " cert hashes=" + mInstalledPackageCerts.get(pkgName)); 557 } 558 559 maybeUpdatePrivilegedPackagesAndNotifyRegistrants(); 560 } 561 updateCertsForPackage(@onNull PackageInfo pkg)562 private void updateCertsForPackage(@NonNull PackageInfo pkg) { 563 Set<String> certs = new ArraySet<>(1); 564 List<Signature> signatures = UiccAccessRule.getSignatures(pkg); 565 for (Signature signature : signatures) { 566 byte[] sha1 = UiccAccessRule.getCertHash(signature, SHA_1); 567 certs.add(IccUtils.bytesToHexString(sha1).toUpperCase(Locale.ROOT)); 568 569 byte[] sha256 = UiccAccessRule.getCertHash(signature, SHA_256); 570 certs.add(IccUtils.bytesToHexString(sha256).toUpperCase(Locale.ROOT)); 571 } 572 573 mInstalledPackageCerts.put(pkg.packageName, certs); 574 } 575 handlePackageRemovedOrDisabledByUser(@ullable String pkgName)576 private void handlePackageRemovedOrDisabledByUser(@Nullable String pkgName) { 577 if (pkgName == null) return; 578 579 if (mInstalledPackageCerts.remove(pkgName) == null || mCachedUids.remove(pkgName) == null) { 580 Rlog.e(TAG, "Unknown package was uninstalled or disabled by user: " + pkgName); 581 return; 582 } 583 584 if (VDBG) { 585 Rlog.d(TAG, "Package removed or disabled by user: pkg=" + Rlog.pii(TAG, pkgName)); 586 } 587 588 maybeUpdatePrivilegedPackagesAndNotifyRegistrants(); 589 } 590 handleInitializeTracker()591 private void handleInitializeTracker() { 592 // Cache CarrierConfig rules 593 mCarrierConfigRules.addAll(getCarrierConfigRules(mPhone.getSubId())); 594 595 // Cache SIM rules 596 mUiccRules.addAll(getSimRules()); 597 598 // Cache all installed packages and their certs 599 refreshInstalledPackageCache(); 600 601 // Okay because no registrants exist yet 602 maybeUpdatePrivilegedPackagesAndNotifyRegistrants(); 603 604 String msg = "Initializing state:" 605 + " CarrierConfig rules=" + mCarrierConfigRules 606 + " SIM-loaded rules=" + mUiccRules; 607 if (VDBG) { 608 msg += 609 " installed pkgs=" 610 + getObfuscatedPackages( 611 mInstalledPackageCerts.entrySet(), 612 e -> "pkg(" + Rlog.pii(TAG, e.getKey()) + ")=" + e.getValue()); 613 } 614 mLocalLog.log(msg); 615 } 616 refreshInstalledPackageCache()617 private void refreshInstalledPackageCache() { 618 List<PackageInfo> installedPackages = 619 mPackageManager.getInstalledPackagesAsUser( 620 INSTALLED_PACKAGES_QUERY_FLAGS, UserHandle.SYSTEM.getIdentifier()); 621 for (PackageInfo pkg : installedPackages) { 622 updateCertsForPackage(pkg); 623 // This may be unnecessary before initialization, but invalidate the cache all the time 624 // just in case to ensure consistency. 625 getUidsForPackage(pkg.packageName, /* invalidateCache= */ true); 626 } 627 } 628 629 @NonNull getObfuscatedPackages( @onNull Collection<T> packageNames, @NonNull Function<T, String> obfuscator)630 private static <T> String getObfuscatedPackages( 631 @NonNull Collection<T> packageNames, @NonNull Function<T, String> obfuscator) { 632 StringJoiner obfuscated = new StringJoiner(", ", "{", "}"); 633 for (T packageName : packageNames) { 634 obfuscated.add(obfuscator.apply(packageName)); 635 } 636 return obfuscated.toString(); 637 } 638 maybeUpdateRulesAndNotifyRegistrants(@onNull List<UiccAccessRule> currentRules, @NonNull List<UiccAccessRule> updatedRules)639 private void maybeUpdateRulesAndNotifyRegistrants(@NonNull List<UiccAccessRule> currentRules, 640 @NonNull List<UiccAccessRule> updatedRules) { 641 if (currentRules.equals(updatedRules)) return; 642 643 currentRules.clear(); 644 currentRules.addAll(updatedRules); 645 646 maybeUpdatePrivilegedPackagesAndNotifyRegistrants(); 647 } 648 maybeUpdatePrivilegedPackagesAndNotifyRegistrants()649 private void maybeUpdatePrivilegedPackagesAndNotifyRegistrants() { 650 PrivilegedPackageInfo currentPrivilegedPackageInfo = 651 getCurrentPrivilegedPackagesForAllUsers(); 652 653 boolean carrierPrivilegesPackageNamesChanged; 654 boolean carrierPrivilegesUidsChanged; 655 boolean carrierServiceChanged; 656 657 mPrivilegedPackageInfoLock.readLock().lock(); 658 try { 659 if (mPrivilegedPackageInfo.equals(currentPrivilegedPackageInfo)) return; 660 661 mLocalLog.log("Privileged packages info changed. New state = " 662 + currentPrivilegedPackageInfo); 663 664 carrierPrivilegesPackageNamesChanged = 665 !currentPrivilegedPackageInfo.mPackageNames.equals( 666 mPrivilegedPackageInfo.mPackageNames); 667 carrierPrivilegesUidsChanged = 668 !currentPrivilegedPackageInfo.mUids.equals(mPrivilegedPackageInfo.mUids); 669 carrierServiceChanged = !currentPrivilegedPackageInfo.mCarrierService.equals( 670 mPrivilegedPackageInfo.mCarrierService); 671 } finally { 672 mPrivilegedPackageInfoLock.readLock().unlock(); 673 } 674 675 mPrivilegedPackageInfoLock.writeLock().lock(); 676 try { 677 mPrivilegedPackageInfo = currentPrivilegedPackageInfo; 678 } finally { 679 mPrivilegedPackageInfoLock.writeLock().unlock(); 680 } 681 682 mPrivilegedPackageInfoLock.readLock().lock(); 683 try { 684 if (carrierPrivilegesPackageNamesChanged || carrierPrivilegesUidsChanged) { 685 mTelephonyRegistryManager.notifyCarrierPrivilegesChanged( 686 mPhone.getPhoneId(), 687 Collections.unmodifiableSet(mPrivilegedPackageInfo.mPackageNames), 688 Collections.unmodifiableSet(mPrivilegedPackageInfo.mUids)); 689 } 690 691 if (carrierServiceChanged) { 692 mTelephonyRegistryManager.notifyCarrierServiceChanged(mPhone.getPhoneId(), 693 mPrivilegedPackageInfo.mCarrierService.first, 694 mPrivilegedPackageInfo.mCarrierService.second); 695 } 696 } finally { 697 mPrivilegedPackageInfoLock.readLock().unlock(); 698 } 699 700 // Update set of enabled carrier apps now that the privilege rules may have changed. 701 ActivityManager am = mContext.getSystemService(ActivityManager.class); 702 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), 703 mTelephonyManager, am.getCurrentUser(), mContext); 704 } 705 706 @NonNull getCurrentPrivilegedPackagesForAllUsers()707 private PrivilegedPackageInfo getCurrentPrivilegedPackagesForAllUsers() { 708 Set<String> carrierServiceEligiblePackages = new ArraySet<>(); 709 Set<String> privilegedPackageNames = new ArraySet<>(); 710 Set<Integer> privilegedUids = new ArraySet<>(); 711 for (Map.Entry<String, Set<String>> e : mInstalledPackageCerts.entrySet()) { 712 final int priv = getPackagePrivilegedStatus(e.getKey(), e.getValue()); 713 switch (priv) { 714 case PACKAGE_PRIVILEGED_FROM_SIM: 715 case PACKAGE_PRIVILEGED_FROM_CARRIER_SERVICE_TEST_OVERRIDE: // fallthrough 716 carrierServiceEligiblePackages.add(e.getKey()); 717 // fallthrough 718 case PACKAGE_PRIVILEGED_FROM_CARRIER_CONFIG: 719 privilegedPackageNames.add(e.getKey()); 720 privilegedUids.addAll( 721 getUidsForPackage(e.getKey(), /* invalidateCache= */ false)); 722 } 723 } 724 725 return new PrivilegedPackageInfo( 726 privilegedPackageNames, 727 privilegedUids, 728 getCarrierService(carrierServiceEligiblePackages)); 729 } 730 731 /** 732 * Returns the privilege status of the provided package. 733 * 734 * <p>Returned privilege status depends on whether a package matches the certificates from 735 * carrier config, from test overrides or from certificates stored on the SIM. 736 */ getPackagePrivilegedStatus(@onNull String pkgName, @NonNull Set<String> certs)737 private int getPackagePrivilegedStatus(@NonNull String pkgName, @NonNull Set<String> certs) { 738 // Double-nested for loops, but each collection should contain at most 2 elements in nearly 739 // every case. 740 // TODO(b/184382310) find a way to speed this up 741 for (String cert : certs) { 742 // Non-null (whether empty or not) test override rule will ignore the UICC and CC rules 743 if (mTestOverrideRules != null) { 744 for (UiccAccessRule rule : mTestOverrideRules) { 745 if (rule.matches(cert, pkgName)) { 746 return PACKAGE_PRIVILEGED_FROM_SIM; 747 } 748 } 749 } else { 750 for (UiccAccessRule rule : mUiccRules) { 751 if (rule.matches(cert, pkgName)) { 752 return PACKAGE_PRIVILEGED_FROM_SIM; 753 } 754 } 755 for (UiccAccessRule rule : mCarrierConfigRules) { 756 if (rule.matches(cert, pkgName)) { 757 return pkgName.equals(mTestOverrideCarrierServicePackage) 758 ? PACKAGE_PRIVILEGED_FROM_CARRIER_SERVICE_TEST_OVERRIDE 759 : PACKAGE_PRIVILEGED_FROM_CARRIER_CONFIG; 760 } 761 } 762 } 763 } 764 return PACKAGE_NOT_PRIVILEGED; 765 } 766 767 @NonNull getUidsForPackage(@onNull String pkgName, boolean invalidateCache)768 private Set<Integer> getUidsForPackage(@NonNull String pkgName, boolean invalidateCache) { 769 if (invalidateCache) { 770 mCachedUids.remove(pkgName); 771 } 772 if (mCachedUids.containsKey(pkgName)) { 773 return mCachedUids.get(pkgName); 774 } 775 776 Set<Integer> uids = new ArraySet<>(1); 777 List<UserInfo> users = mUserManager.getUsers(); 778 for (UserInfo user : users) { 779 int userId = user.getUserHandle().getIdentifier(); 780 try { 781 uids.add(mPackageManager.getPackageUidAsUser(pkgName, userId)); 782 } catch (NameNotFoundException exception) { 783 // Didn't find package. Continue looking at other packages 784 Rlog.e(TAG, "Unable to find uid for package " + pkgName + " and user " + userId); 785 } 786 } 787 mCachedUids.put(pkgName, uids); 788 return uids; 789 } 790 getPackageUid(@ullable String pkgName)791 private int getPackageUid(@Nullable String pkgName) { 792 int uid = Process.INVALID_UID; 793 try { 794 uid = mPackageManager.getPackageUid(pkgName, /* flags= */0); 795 } catch (NameNotFoundException e) { 796 Rlog.e(TAG, "Unable to find uid for package " + pkgName); 797 } 798 return uid; 799 } 800 801 /** 802 * Dump the local log buffer and other internal state of CarrierPrivilegesTracker. 803 */ dump(@onNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args)804 public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) { 805 pw.println("CarrierPrivilegesTracker - phoneId: " + mPhone.getPhoneId()); 806 pw.println("CarrierPrivilegesTracker - Log Begin ----"); 807 mLocalLog.dump(fd, pw, args); 808 pw.println("CarrierPrivilegesTracker - Log End ----"); 809 mPrivilegedPackageInfoLock.readLock().lock(); 810 try { 811 pw.println( 812 "CarrierPrivilegesTracker - Privileged package info: " 813 + mPrivilegedPackageInfo); 814 pw.println("mSimIsReadyButNotLoaded: " + mSimIsReadyButNotLoaded); 815 } finally { 816 mPrivilegedPackageInfoLock.readLock().unlock(); 817 } 818 pw.println("CarrierPrivilegesTracker - Test-override rules: " + mTestOverrideRules); 819 pw.println("CarrierPrivilegesTracker - SIM-loaded rules: " + mUiccRules); 820 pw.println("CarrierPrivilegesTracker - Carrier config rules: " + mCarrierConfigRules); 821 if (VDBG) { 822 pw.println( 823 "CarrierPrivilegesTracker - Obfuscated Pkgs + Certs: " 824 + getObfuscatedPackages( 825 mInstalledPackageCerts.entrySet(), 826 e -> "pkg(" + Rlog.pii(TAG, e.getKey()) + ")=" + e.getValue())); 827 } 828 pw.println("mClearUiccRulesUptimeMillis: " + mClearUiccRulesUptimeMillis); 829 } 830 831 /** 832 * Set test carrier privilege rules which will override the actual rules on both Carrier Config 833 * and SIM. 834 * 835 * <p>{@code carrierPrivilegeRules} can be null, in which case the rules on the Carrier Config 836 * and SIM will be used and any previous overrides will be cleared. 837 * 838 * @see TelephonyManager#setCarrierTestOverride 839 */ setTestOverrideCarrierPrivilegeRules(@ullable String carrierPrivilegeRules)840 public void setTestOverrideCarrierPrivilegeRules(@Nullable String carrierPrivilegeRules) { 841 sendMessage(obtainMessage(ACTION_SET_TEST_OVERRIDE_RULE, carrierPrivilegeRules)); 842 } 843 844 /** 845 * Override the carrier provisioning package, if it exists. 846 * 847 * <p>This API is to be used ONLY for testing, and requires the provided package to be carrier 848 * privileged. While this override is set, ONLY the specified package will be considered 849 * eligible to be bound as the carrier provisioning package, and any existing bindings will be 850 * terminated. 851 * 852 * @param carrierServicePackage the package to be used as the overridden carrier service 853 * package, or {@code null} to reset override 854 * @see TelephonyManager#setCarrierServicePackageOverride 855 */ setTestOverrideCarrierServicePackage(@ullable String carrierServicePackage)856 public void setTestOverrideCarrierServicePackage(@Nullable String carrierServicePackage) { 857 sendMessage(obtainMessage( 858 ACTION_SET_TEST_OVERRIDE_CARRIER_SERVICE_PACKAGE, carrierServicePackage)); 859 } 860 handleSetTestOverrideCarrierServicePackage( @ullable String carrierServicePackage)861 private void handleSetTestOverrideCarrierServicePackage( 862 @Nullable String carrierServicePackage) { 863 mTestOverrideCarrierServicePackage = carrierServicePackage; 864 refreshInstalledPackageCache(); 865 maybeUpdatePrivilegedPackagesAndNotifyRegistrants(); 866 } 867 handleSetTestOverrideRules(@ullable String carrierPrivilegeRules)868 private void handleSetTestOverrideRules(@Nullable String carrierPrivilegeRules) { 869 if (carrierPrivilegeRules == null) { 870 mTestOverrideRules = null; 871 } else if (carrierPrivilegeRules.isEmpty()) { 872 mTestOverrideRules = Collections.emptyList(); 873 } else { 874 mTestOverrideRules = Arrays.asList(UiccAccessRule.decodeRulesFromCarrierConfig( 875 new String[]{carrierPrivilegeRules})); 876 // TODO(b/215239409): remove the additional cache refresh for test override cases. 877 // Test override doesn't respect if the package for the specified cert has been removed 878 // or hidden since initialization. Refresh the cache again to get the pkg/uid with the 879 // best effort. 880 refreshInstalledPackageCache(); 881 } 882 maybeUpdatePrivilegedPackagesAndNotifyRegistrants(); 883 } 884 885 /** Backing of {@link TelephonyManager#checkCarrierPrivilegesForPackage}. */ getCarrierPrivilegeStatusForPackage( @ullable String packageName)886 public @CarrierPrivilegeStatus int getCarrierPrivilegeStatusForPackage( 887 @Nullable String packageName) { 888 if (packageName == null) return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS; 889 890 // TODO(b/205736323) consider if/how we want to account for the RULES_NOT_LOADED and 891 // ERROR_LOADING_RULES constants. Technically those will never be returned today since those 892 // results are only from the SIM rules, but the CC rules' result (which never has these 893 // errors) always supersede them unless something goes super wrong when getting CC. 894 mPrivilegedPackageInfoLock.readLock().lock(); 895 try { 896 if (mSimIsReadyButNotLoaded) { 897 return CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED; 898 } else if (mPrivilegedPackageInfo.mPackageNames.contains(packageName)) { 899 return CARRIER_PRIVILEGE_STATUS_HAS_ACCESS; 900 } else { 901 return CARRIER_PRIVILEGE_STATUS_NO_ACCESS; 902 } 903 } finally { 904 mPrivilegedPackageInfoLock.readLock().unlock(); 905 } 906 } 907 908 /** Backing of {@link TelephonyManager#getPackagesWithCarrierPrivileges}. */ 909 @NonNull getPackagesWithCarrierPrivileges()910 public Set<String> getPackagesWithCarrierPrivileges() { 911 mPrivilegedPackageInfoLock.readLock().lock(); 912 try { 913 return mSimIsReadyButNotLoaded ? Collections.emptySet() : 914 Collections.unmodifiableSet(mPrivilegedPackageInfo.mPackageNames); 915 } finally { 916 mPrivilegedPackageInfoLock.readLock().unlock(); 917 } 918 } 919 920 /** 921 * Backing of {@link TelephonyManager#hasCarrierPrivileges} and {@link 922 * TelephonyManager#getCarrierPrivilegeStatus(int)}. 923 */ getCarrierPrivilegeStatusForUid(int uid)924 public @CarrierPrivilegeStatus int getCarrierPrivilegeStatusForUid(int uid) { 925 // TODO(b/205736323) consider if/how we want to account for the RULES_NOT_LOADED and 926 // ERROR_LOADING_RULES constants. Technically those will never be returned today since those 927 // results are only from the SIM rules, but the CC rules' result (which never has these 928 // errors) always supersede them unless something goes super wrong when getting CC. 929 mPrivilegedPackageInfoLock.readLock().lock(); 930 try { 931 if (mSimIsReadyButNotLoaded) { 932 return CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED; 933 } else if (mPrivilegedPackageInfo.mUids.contains(uid)) { 934 return CARRIER_PRIVILEGE_STATUS_HAS_ACCESS; 935 } else { 936 return CARRIER_PRIVILEGE_STATUS_NO_ACCESS; 937 } 938 } finally { 939 mPrivilegedPackageInfoLock.readLock().unlock(); 940 } 941 } 942 943 /** 944 * Backing of {@link TelephonyManager#getCarrierServicePackageName()} and 945 * {@link TelephonyManager#getCarrierServicePackageNameForLogicalSlot(int)} 946 */ 947 @Nullable getCarrierServicePackageName()948 public String getCarrierServicePackageName() { 949 // Return the cached one if present, it is fast and safe (no IPC call to PackageManager) 950 mPrivilegedPackageInfoLock.readLock().lock(); 951 try { 952 // If SIM is READY but not LOADED, neither the cache nor the queries below are reliable, 953 // we should return null for this transient state for security/privacy's concern. 954 if (mSimIsReadyButNotLoaded) return null; 955 956 return mPrivilegedPackageInfo.mCarrierService.first; 957 } finally { 958 mPrivilegedPackageInfoLock.readLock().unlock(); 959 } 960 // Do NOT query package manager, mPrivilegedPackageInfo.mCarrierService has maintained the 961 // latest CarrierService info. Querying PM will not get better result. 962 } 963 964 /** 965 * @return The UID of carrier service package. {@link Process#INVALID_UID} if not found. 966 */ getCarrierServicePackageUid()967 public int getCarrierServicePackageUid() { 968 mPrivilegedPackageInfoLock.readLock().lock(); 969 try { 970 if (mSimIsReadyButNotLoaded) return Process.INVALID_UID; 971 972 return mPrivilegedPackageInfo.mCarrierService.second; 973 } finally { 974 mPrivilegedPackageInfoLock.readLock().unlock(); 975 } 976 } 977 978 /** 979 * Backing of {@link TelephonyManager#getCarrierPackageNamesForIntent} and {@link 980 * TelephonyManager#getCarrierPackageNamesForIntentAndPhone}. 981 */ 982 @NonNull getCarrierPackageNamesForIntent(@onNull Intent intent)983 public List<String> getCarrierPackageNamesForIntent(@NonNull Intent intent) { 984 mPrivilegedPackageInfoLock.readLock().lock(); 985 try { 986 if (mSimIsReadyButNotLoaded) return Collections.emptyList(); 987 } finally { 988 mPrivilegedPackageInfoLock.readLock().unlock(); 989 } 990 991 // Do the PackageManager queries before we take the lock, as these are the longest-running 992 // pieces of this method and don't depend on the set of carrier apps. 993 List<ResolveInfo> resolveInfos = new ArrayList<>(); 994 resolveInfos.addAll(mPackageManager.queryBroadcastReceivers(intent, 0)); 995 resolveInfos.addAll(mPackageManager.queryIntentActivities(intent, 0)); 996 resolveInfos.addAll(mPackageManager.queryIntentServices(intent, 0)); 997 resolveInfos.addAll(mPackageManager.queryIntentContentProviders(intent, 0)); 998 999 // Now actually check which of the resolved packages have carrier privileges. 1000 mPrivilegedPackageInfoLock.readLock().lock(); 1001 try { 1002 // Check mSimIsReadyButNotLoaded again here since the PackageManager queries above are 1003 // pretty time-consuming, mSimIsReadyButNotLoaded state may change since last check 1004 if (mSimIsReadyButNotLoaded) return Collections.emptyList(); 1005 1006 Set<String> packageNames = new ArraySet<>(); // For deduping purposes 1007 for (ResolveInfo resolveInfo : resolveInfos) { 1008 String packageName = getPackageName(resolveInfo); 1009 if (packageName != null && CARRIER_PRIVILEGE_STATUS_HAS_ACCESS 1010 == getCarrierPrivilegeStatusForPackage(packageName)) { 1011 packageNames.add(packageName); 1012 } 1013 } 1014 return new ArrayList<>(packageNames); 1015 } finally { 1016 mPrivilegedPackageInfoLock.readLock().unlock(); 1017 } 1018 } 1019 1020 @Nullable getPackageName(@onNull ResolveInfo resolveInfo)1021 private static String getPackageName(@NonNull ResolveInfo resolveInfo) { 1022 // Note: activityInfo covers both activities + broadcast receivers 1023 if (resolveInfo.activityInfo != null) return resolveInfo.activityInfo.packageName; 1024 if (resolveInfo.serviceInfo != null) return resolveInfo.serviceInfo.packageName; 1025 if (resolveInfo.providerInfo != null) return resolveInfo.providerInfo.packageName; 1026 return null; 1027 } 1028 1029 @NonNull getCarrierService(@onNull Set<String> simPrivilegedPackages)1030 private Pair<String, Integer> getCarrierService(@NonNull Set<String> simPrivilegedPackages) { 1031 List<ResolveInfo> carrierServiceResolveInfos = mPackageManager.queryIntentServices( 1032 new Intent(CarrierService.CARRIER_SERVICE_INTERFACE), /* flags= */ 0); 1033 String carrierServicePackageName = null; 1034 for (ResolveInfo resolveInfo : carrierServiceResolveInfos) { 1035 String packageName = getPackageName(resolveInfo); 1036 if (mTestOverrideCarrierServicePackage != null 1037 && !mTestOverrideCarrierServicePackage.equals(packageName)) { 1038 continue; 1039 } 1040 1041 if (simPrivilegedPackages.contains(packageName)) { 1042 carrierServicePackageName = packageName; 1043 break; 1044 } 1045 } 1046 return carrierServicePackageName == null 1047 ? new Pair<>(null, Process.INVALID_UID) 1048 : new Pair<>(carrierServicePackageName, getPackageUid(carrierServicePackageName)); 1049 } 1050 } 1051