DevicePolicyManagerService.java revision caffa7789c80108c4f2c230c0a26bd8d8a549ec8
1/* 2 * Copyright (C) 2010 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.devicepolicy; 18 19import static android.Manifest.permission.BIND_DEVICE_ADMIN; 20import static android.Manifest.permission.MANAGE_CA_CERTIFICATES; 21import static android.app.ActivityManager.LOCK_TASK_MODE_NONE; 22import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE; 23import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER; 24import static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY; 25import static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED; 26import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE; 27import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED; 28import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER; 29import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED; 30import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED; 31import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS; 32import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER; 33import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT; 34import static android.app.admin.DevicePolicyManager.CODE_OK; 35import static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 36import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER; 37import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER; 38import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING; 39import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED; 40import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS; 41import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL; 42import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL; 43import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP; 44import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE; 45import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES; 46import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS; 47import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT; 48import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO; 49import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI; 50import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID; 51import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL; 52import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED; 53import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME; 54import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW; 55import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 56import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 57import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 58import static android.app.admin.DevicePolicyManager.WIPE_EUICC; 59import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE; 60import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA; 61import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 62 63import static android.provider.Telephony.Carriers.DPC_URI; 64import static android.provider.Telephony.Carriers.ENFORCE_KEY; 65import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI; 66 67import static com.android.internal.logging.nano.MetricsProto.MetricsEvent 68 .PROVISIONING_ENTRY_POINT_ADB; 69import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker 70 .STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW; 71 72import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER; 73import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER; 74 75import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 76import static org.xmlpull.v1.XmlPullParser.END_TAG; 77import static org.xmlpull.v1.XmlPullParser.TEXT; 78 79import android.Manifest.permission; 80import android.accessibilityservice.AccessibilityServiceInfo; 81import android.accounts.Account; 82import android.accounts.AccountManager; 83import android.annotation.NonNull; 84import android.annotation.Nullable; 85import android.annotation.UserIdInt; 86import android.app.Activity; 87import android.app.ActivityManager; 88import android.app.ActivityManagerInternal; 89import android.app.ActivityThread; 90import android.app.AlarmManager; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.IApplicationThread; 94import android.app.IServiceConnection; 95import android.app.Notification; 96import android.app.NotificationManager; 97import android.app.PendingIntent; 98import android.app.StatusBarManager; 99import android.app.admin.DeviceAdminInfo; 100import android.app.admin.DeviceAdminReceiver; 101import android.app.admin.DevicePolicyManager; 102import android.app.admin.DevicePolicyManagerInternal; 103import android.app.admin.NetworkEvent; 104import android.app.admin.PasswordMetrics; 105import android.app.admin.SecurityLog; 106import android.app.admin.SecurityLog.SecurityEvent; 107import android.app.admin.SystemUpdateInfo; 108import android.app.admin.SystemUpdatePolicy; 109import android.app.backup.IBackupManager; 110import android.app.trust.TrustManager; 111import android.app.usage.UsageStatsManagerInternal; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.ContentValues; 115import android.content.Context; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.pm.ActivityInfo; 119import android.content.pm.ApplicationInfo; 120import android.content.pm.IPackageDataObserver; 121import android.content.pm.IPackageManager; 122import android.content.pm.PackageInfo; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.NameNotFoundException; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.ParceledListSlice; 127import android.content.pm.PermissionInfo; 128import android.content.pm.ResolveInfo; 129import android.content.pm.ServiceInfo; 130import android.content.pm.StringParceledListSlice; 131import android.content.pm.UserInfo; 132import android.content.res.Resources; 133import android.database.ContentObserver; 134import android.database.Cursor; 135import android.graphics.Bitmap; 136import android.graphics.Color; 137import android.media.AudioManager; 138import android.media.IAudioService; 139import android.net.ConnectivityManager; 140import android.net.IIpConnectivityMetrics; 141import android.net.ProxyInfo; 142import android.net.Uri; 143import android.net.metrics.IpConnectivityLog; 144import android.net.wifi.WifiInfo; 145import android.net.wifi.WifiManager; 146import android.os.Binder; 147import android.os.Build; 148import android.os.Bundle; 149import android.os.Environment; 150import android.os.FileUtils; 151import android.os.Handler; 152import android.os.IBinder; 153import android.os.Looper; 154import android.os.ParcelFileDescriptor; 155import android.os.PersistableBundle; 156import android.os.PowerManager; 157import android.os.PowerManagerInternal; 158import android.os.Process; 159import android.os.RecoverySystem; 160import android.os.RemoteCallback; 161import android.os.RemoteException; 162import android.os.ServiceManager; 163import android.os.SystemClock; 164import android.os.SystemProperties; 165import android.os.UserHandle; 166import android.os.UserManager; 167import android.os.UserManagerInternal; 168import android.os.UserManagerInternal.UserRestrictionsListener; 169import android.os.storage.StorageManager; 170import android.provider.ContactsContract.QuickContact; 171import android.provider.ContactsInternal; 172import android.provider.Settings; 173import android.provider.Settings.Global; 174import android.security.IKeyChainAliasCallback; 175import android.security.IKeyChainService; 176import android.security.KeyChain; 177import android.security.KeyChain.KeyChainConnection; 178import android.security.KeyStore; 179import android.security.keymaster.KeymasterCertificateChain; 180import android.security.keystore.AttestationUtils; 181import android.security.keystore.KeyGenParameterSpec; 182import android.security.keystore.ParcelableKeyGenParameterSpec; 183import android.service.persistentdata.PersistentDataBlockManager; 184import android.telephony.TelephonyManager; 185import android.telephony.data.ApnSetting; 186import android.text.TextUtils; 187import android.util.ArrayMap; 188import android.util.ArraySet; 189import android.util.AtomicFile; 190import android.util.Log; 191import android.util.Pair; 192import android.util.Slog; 193import android.util.SparseArray; 194import android.util.Xml; 195import android.view.IWindowManager; 196import android.view.accessibility.AccessibilityManager; 197import android.view.accessibility.IAccessibilityManager; 198import android.view.inputmethod.InputMethodInfo; 199import android.view.inputmethod.InputMethodManager; 200 201import com.android.internal.R; 202import com.android.internal.annotations.GuardedBy; 203import com.android.internal.annotations.VisibleForTesting; 204import com.android.internal.logging.MetricsLogger; 205import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 206import com.android.internal.notification.SystemNotificationChannels; 207import com.android.internal.os.BackgroundThread; 208import com.android.internal.statusbar.IStatusBarService; 209import com.android.internal.util.DumpUtils; 210import com.android.internal.util.FastXmlSerializer; 211import com.android.internal.util.FunctionalUtils.ThrowingRunnable; 212import com.android.internal.util.JournaledFile; 213import com.android.internal.util.Preconditions; 214import com.android.internal.util.XmlUtils; 215import com.android.internal.widget.LockPatternUtils; 216import com.android.server.LocalServices; 217import com.android.server.SystemServerInitThreadPool; 218import com.android.server.SystemService; 219import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo; 220import com.android.server.net.NetworkPolicyManagerInternal; 221import com.android.server.pm.UserRestrictionsUtils; 222 223import com.google.android.collect.Sets; 224 225import org.xmlpull.v1.XmlPullParser; 226import org.xmlpull.v1.XmlPullParserException; 227import org.xmlpull.v1.XmlSerializer; 228 229import java.io.File; 230import java.io.FileDescriptor; 231import java.io.FileInputStream; 232import java.io.FileNotFoundException; 233import java.io.FileOutputStream; 234import java.io.IOException; 235import java.io.PrintWriter; 236import java.lang.reflect.Constructor; 237import java.nio.charset.StandardCharsets; 238import java.text.DateFormat; 239import java.time.LocalDate; 240import java.util.ArrayList; 241import java.util.Arrays; 242import java.util.Collection; 243import java.util.Collections; 244import java.util.Date; 245import java.util.HashMap; 246import java.util.List; 247import java.util.Map; 248import java.util.Map.Entry; 249import java.util.Objects; 250import java.util.Set; 251import java.util.concurrent.TimeUnit; 252import java.util.concurrent.atomic.AtomicBoolean; 253import java.util.function.Function; 254 255/** 256 * Implementation of the device policy APIs. 257 */ 258public class DevicePolicyManagerService extends BaseIDevicePolicyManager { 259 260 protected static final String LOG_TAG = "DevicePolicyManager"; 261 262 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE 263 264 private static final String DEVICE_POLICIES_XML = "device_policies.xml"; 265 266 private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML = 267 "transfer-ownership-parameters.xml"; 268 269 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate"; 270 271 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component"; 272 273 private static final String TAG_LOCK_TASK_FEATURES = "lock-task-features"; 274 275 private static final String TAG_STATUS_BAR = "statusbar"; 276 277 private static final String ATTR_DISABLED = "disabled"; 278 279 private static final String ATTR_NAME = "name"; 280 281 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML = 282 "do-not-ask-credentials-on-boot"; 283 284 private static final String TAG_AFFILIATION_ID = "affiliation-id"; 285 286 private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval"; 287 288 private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request"; 289 290 private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval"; 291 292 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending"; 293 294 private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set"; 295 296 private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert"; 297 298 private static final String ATTR_ID = "id"; 299 300 private static final String ATTR_VALUE = "value"; 301 302 private static final String ATTR_ALIAS = "alias"; 303 304 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle"; 305 306 private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token"; 307 308 private static final String TAG_PASSWORD_VALIDITY = "password-validity"; 309 310 private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle"; 311 312 private static final int REQUEST_EXPIRE_PASSWORD = 5571; 313 314 private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1); 315 316 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms 317 318 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION 319 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION"; 320 321 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider"; 322 private static final String ATTR_SETUP_COMPLETE = "setup-complete"; 323 private static final String ATTR_PROVISIONING_STATE = "provisioning-state"; 324 private static final String ATTR_PERMISSION_POLICY = "permission-policy"; 325 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED = 326 "device-provisioning-config-applied"; 327 private static final String ATTR_DEVICE_PAIRED = "device-paired"; 328 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer"; 329 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER 330 = "application-restrictions-manager"; 331 332 private static final String MANAGED_PROVISIONING_PKG = "com.android.managedprovisioning"; 333 334 // Comprehensive list of delegations. 335 private static final String DELEGATIONS[] = { 336 DELEGATION_CERT_INSTALL, 337 DELEGATION_APP_RESTRICTIONS, 338 DELEGATION_BLOCK_UNINSTALL, 339 DELEGATION_ENABLE_SYSTEM_APP, 340 DELEGATION_KEEP_UNINSTALLED_PACKAGES, 341 DELEGATION_PACKAGE_ACCESS, 342 DELEGATION_PERMISSION_GRANT, 343 DELEGATION_INSTALL_EXISTING_PACKAGE, 344 DELEGATION_KEEP_UNINSTALLED_PACKAGES 345 }; 346 347 /** 348 * System property whose value is either "true" or "false", indicating whether 349 * device owner is present. 350 */ 351 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner"; 352 353 private static final int STATUS_BAR_DISABLE_MASK = 354 StatusBarManager.DISABLE_EXPAND | 355 StatusBarManager.DISABLE_NOTIFICATION_ICONS | 356 StatusBarManager.DISABLE_NOTIFICATION_ALERTS | 357 StatusBarManager.DISABLE_SEARCH; 358 359 private static final int STATUS_BAR_DISABLE2_MASK = 360 StatusBarManager.DISABLE2_QUICK_SETTINGS; 361 362 private static final Set<String> SECURE_SETTINGS_WHITELIST; 363 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST; 364 private static final Set<String> GLOBAL_SETTINGS_WHITELIST; 365 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED; 366 private static final Set<String> SYSTEM_SETTINGS_WHITELIST; 367 static { 368 SECURE_SETTINGS_WHITELIST = new ArraySet<>(); 369 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD); 370 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS); 371 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS); 372 373 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>(); 374 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST); 375 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE); 376 377 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>(); 378 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED); 379 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME); 380 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE); 381 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING); 382 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED); 383 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY); 384 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN); 385 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN); 386 387 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>(); 388 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON); 389 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); 390 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER); 391 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE); 392 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON); 393 394 SYSTEM_SETTINGS_WHITELIST = new ArraySet<>(); 395 SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS); 396 SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE); 397 SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_OFF_TIMEOUT); 398 } 399 400 /** 401 * Keyguard features that when set on a profile affect the profile content or challenge only. 402 * These cannot be set on the managed profile's parent DPM instance 403 */ 404 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY = 405 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS; 406 407 /** Keyguard features that are allowed to be set on a managed profile */ 408 private static final int PROFILE_KEYGUARD_FEATURES = 409 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY; 410 411 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000; 412 413 /** 414 * Minimum timeout in milliseconds after which unlocking with weak auth times out, 415 * i.e. the user has to use a strong authentication method like password, PIN or pattern. 416 */ 417 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1); 418 419 /** 420 * Strings logged with {@link 421 * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}. 422 */ 423 private static final String LOG_TAG_PROFILE_OWNER = "profile-owner"; 424 private static final String LOG_TAG_DEVICE_OWNER = "device-owner"; 425 426 final Context mContext; 427 final Injector mInjector; 428 final IPackageManager mIPackageManager; 429 final UserManager mUserManager; 430 final UserManagerInternal mUserManagerInternal; 431 final UsageStatsManagerInternal mUsageStatsManagerInternal; 432 final TelephonyManager mTelephonyManager; 433 private final LockPatternUtils mLockPatternUtils; 434 private final DevicePolicyConstants mConstants; 435 private final DeviceAdminServiceController mDeviceAdminServiceController; 436 private final OverlayPackagesProvider mOverlayPackagesProvider; 437 438 /** 439 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p 440 * is requested for user u. 441 */ 442 private final Set<Pair<String, Integer>> mPackagesToRemove = 443 new ArraySet<Pair<String, Integer>>(); 444 445 final LocalService mLocalService; 446 447 // Stores and loads state on device and profile owners. 448 @VisibleForTesting 449 final Owners mOwners; 450 451 private final Binder mToken = new Binder(); 452 453 /** 454 * Whether or not device admin feature is supported. If it isn't return defaults for all 455 * public methods. 456 */ 457 boolean mHasFeature; 458 459 /** 460 * Whether or not this device is a watch. 461 */ 462 boolean mIsWatch; 463 464 private final CertificateMonitor mCertificateMonitor; 465 private final SecurityLogMonitor mSecurityLogMonitor; 466 private NetworkLogger mNetworkLogger; 467 468 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean(); 469 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean(); 470 471 private SetupContentObserver mSetupContentObserver; 472 473 @VisibleForTesting 474 final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager; 475 476 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() { 477 @Override 478 public void run() { 479 if(mRemoteBugreportServiceIsActive.get()) { 480 onBugreportFailed(); 481 } 482 } 483 }; 484 485 /** Listens only if mHasFeature == true. */ 486 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() { 487 488 @Override 489 public void onReceive(Context context, Intent intent) { 490 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction()) 491 && mRemoteBugreportServiceIsActive.get()) { 492 onBugreportFinished(intent); 493 } 494 } 495 }; 496 497 /** Listens only if mHasFeature == true. */ 498 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() { 499 500 @Override 501 public void onReceive(Context context, Intent intent) { 502 String action = intent.getAction(); 503 mInjector.getNotificationManager().cancel(LOG_TAG, 504 RemoteBugreportUtils.NOTIFICATION_ID); 505 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) { 506 onBugreportSharingAccepted(); 507 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) { 508 onBugreportSharingDeclined(); 509 } 510 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 511 } 512 }; 513 514 public static final class Lifecycle extends SystemService { 515 private BaseIDevicePolicyManager mService; 516 517 public Lifecycle(Context context) { 518 super(context); 519 String dpmsClassName = context.getResources() 520 .getString(R.string.config_deviceSpecificDevicePolicyManagerService); 521 if (TextUtils.isEmpty(dpmsClassName)) { 522 dpmsClassName = DevicePolicyManagerService.class.getName(); 523 } 524 try { 525 Class serviceClass = Class.forName(dpmsClassName); 526 Constructor constructor = serviceClass.getConstructor(Context.class); 527 mService = (BaseIDevicePolicyManager) constructor.newInstance(context); 528 } catch (Exception e) { 529 throw new IllegalStateException( 530 "Failed to instantiate DevicePolicyManagerService with class name: " 531 + dpmsClassName, e); 532 } 533 } 534 535 @Override 536 public void onStart() { 537 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService); 538 } 539 540 @Override 541 public void onBootPhase(int phase) { 542 mService.systemReady(phase); 543 } 544 545 @Override 546 public void onStartUser(int userHandle) { 547 mService.handleStartUser(userHandle); 548 } 549 550 @Override 551 public void onUnlockUser(int userHandle) { 552 mService.handleUnlockUser(userHandle); 553 } 554 555 @Override 556 public void onStopUser(int userHandle) { 557 mService.handleStopUser(userHandle); 558 } 559 } 560 561 public static class DevicePolicyData { 562 @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics(); 563 int mFailedPasswordAttempts = 0; 564 boolean mPasswordStateHasBeenSetSinceBoot = false; 565 boolean mPasswordValidAtLastCheckpoint = false; 566 567 int mUserHandle; 568 int mPasswordOwner = -1; 569 long mLastMaximumTimeToLock = -1; 570 boolean mUserSetupComplete = false; 571 boolean mPaired = false; 572 int mUserProvisioningState; 573 int mPermissionPolicy; 574 575 boolean mDeviceProvisioningConfigApplied = false; 576 577 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>(); 578 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>(); 579 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>(); 580 581 // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead. 582 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>(); 583 584 // This is the list of component allowed to start lock task mode. 585 List<String> mLockTaskPackages = new ArrayList<>(); 586 587 // Bitfield of feature flags to be enabled during LockTask mode. 588 int mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE; 589 590 boolean mStatusBarDisabled = false; 591 592 ComponentName mRestrictionsProvider; 593 594 // Map of delegate package to delegation scopes 595 final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>(); 596 597 boolean doNotAskCredentialsOnBoot = false; 598 599 Set<String> mAffiliationIds = new ArraySet<>(); 600 601 long mLastSecurityLogRetrievalTime = -1; 602 603 long mLastBugReportRequestTime = -1; 604 605 long mLastNetworkLogsRetrievalTime = -1; 606 607 boolean mCurrentInputMethodSet = false; 608 609 // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead. 610 Set<String> mOwnerInstalledCaCerts = new ArraySet<>(); 611 612 // Used for initialization of users created by createAndManageUser. 613 boolean mAdminBroadcastPending = false; 614 PersistableBundle mInitBundle = null; 615 616 long mPasswordTokenHandle = 0; 617 618 public DevicePolicyData(int userHandle) { 619 mUserHandle = userHandle; 620 } 621 } 622 623 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>(); 624 625 final Handler mHandler; 626 final Handler mBackgroundHandler; 627 628 /** Listens only if mHasFeature == true. */ 629 final BroadcastReceiver mReceiver = new BroadcastReceiver() { 630 @Override 631 public void onReceive(Context context, Intent intent) { 632 final String action = intent.getAction(); 633 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 634 getSendingUserId()); 635 636 /* 637 * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(), 638 * however it's too early in the boot process to register with IIpConnectivityMetrics 639 * to listen for events. 640 */ 641 if (Intent.ACTION_USER_STARTED.equals(action) 642 && userHandle == mOwners.getDeviceOwnerUserId()) { 643 synchronized (DevicePolicyManagerService.this) { 644 if (isNetworkLoggingEnabledInternalLocked()) { 645 setNetworkLoggingActiveInternal(true); 646 } 647 } 648 } 649 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 650 && userHandle == mOwners.getDeviceOwnerUserId() 651 && getDeviceOwnerRemoteBugreportUri() != null) { 652 IntentFilter filterConsent = new IntentFilter(); 653 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 654 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 655 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 656 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, 657 RemoteBugreportUtils.NOTIFICATION_ID, 658 RemoteBugreportUtils.buildNotification(mContext, 659 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 660 UserHandle.ALL); 661 } 662 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 663 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) { 664 if (VERBOSE_LOG) { 665 Slog.v(LOG_TAG, "Sending password expiration notifications for action " 666 + action + " for user " + userHandle); 667 } 668 mHandler.post(new Runnable() { 669 @Override 670 public void run() { 671 handlePasswordExpirationNotification(userHandle); 672 } 673 }); 674 } 675 676 if (Intent.ACTION_USER_ADDED.equals(action)) { 677 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle); 678 synchronized (DevicePolicyManagerService.this) { 679 // It might take a while for the user to become affiliated. Make security 680 // and network logging unavailable in the meantime. 681 maybePauseDeviceWideLoggingLocked(); 682 } 683 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 684 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle); 685 synchronized (DevicePolicyManagerService.this) { 686 // Check whether the user is affiliated, *before* removing its data. 687 boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle); 688 removeUserData(userHandle); 689 if (!isRemovedUserAffiliated) { 690 // We discard the logs when unaffiliated users are deleted (so that the 691 // device owner cannot retrieve data about that user after it's gone). 692 discardDeviceWideLogsLocked(); 693 // Resume logging if all remaining users are affiliated. 694 maybeResumeDeviceWideLoggingLocked(); 695 } 696 } 697 } else if (Intent.ACTION_USER_STARTED.equals(action)) { 698 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle); 699 synchronized (DevicePolicyManagerService.this) { 700 maybeSendAdminEnabledBroadcastLocked(userHandle); 701 // Reset the policy data 702 mUserData.remove(userHandle); 703 } 704 handlePackagesChanged(null /* check all admins */, userHandle); 705 } else if (Intent.ACTION_USER_STOPPED.equals(action)) { 706 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle); 707 } else if (Intent.ACTION_USER_SWITCHED.equals(action)) { 708 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle); 709 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) { 710 synchronized (DevicePolicyManagerService.this) { 711 maybeSendAdminEnabledBroadcastLocked(userHandle); 712 } 713 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { 714 handlePackagesChanged(null /* check all admins */, userHandle); 715 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action) 716 || (Intent.ACTION_PACKAGE_ADDED.equals(action) 717 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) { 718 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 719 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action) 720 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 721 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 722 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) { 723 clearWipeProfileNotification(); 724 } else if (Intent.ACTION_DATE_CHANGED.equals(action) 725 || Intent.ACTION_TIME_CHANGED.equals(action)) { 726 // Update freeze period record when clock naturally progresses to the next day 727 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made 728 // (ACTION_TIME_CHANGED) 729 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true); 730 } 731 732 } 733 734 private void sendDeviceOwnerUserCommand(String action, int userHandle) { 735 synchronized (DevicePolicyManagerService.this) { 736 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 737 if (deviceOwner != null) { 738 Bundle extras = new Bundle(); 739 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 740 sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null, 741 /* inForeground */ true); 742 } 743 } 744 } 745 }; 746 747 protected static class RestrictionsListener implements UserRestrictionsListener { 748 private Context mContext; 749 750 public RestrictionsListener(Context context) { 751 mContext = context; 752 } 753 754 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions, 755 Bundle prevRestrictions) { 756 final boolean newlyDisallowed = 757 newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE); 758 final boolean previouslyDisallowed = 759 prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE); 760 final boolean restrictionChanged = (newlyDisallowed != previouslyDisallowed); 761 762 if (restrictionChanged) { 763 // Notify ManagedProvisioning to update the built-in cross profile intent filters. 764 Intent intent = new Intent( 765 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED); 766 intent.setPackage(MANAGED_PROVISIONING_PKG); 767 intent.putExtra(Intent.EXTRA_USER_ID, userId); 768 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 769 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM); 770 } 771 } 772 } 773 774 static class ActiveAdmin { 775 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features"; 776 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin"; 777 private static final String TAG_DISABLE_CAMERA = "disable-camera"; 778 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id"; 779 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search"; 780 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING 781 = "disable-bt-contacts-sharing"; 782 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture"; 783 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management"; 784 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time"; 785 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users"; 786 private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled"; 787 private static final String TAG_ACCOUNT_TYPE = "account-type"; 788 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES 789 = "permitted-accessiblity-services"; 790 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested"; 791 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features"; 792 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options"; 793 private static final String TAG_TRUST_AGENT_COMPONENT = "component"; 794 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date"; 795 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout"; 796 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list"; 797 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec"; 798 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy"; 799 private static final String TAG_PERMITTED_IMES = "permitted-imes"; 800 private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS = 801 "permitted-notification-listeners"; 802 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe"; 803 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock"; 804 private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout"; 805 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter"; 806 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols"; 807 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric"; 808 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters"; 809 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase"; 810 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase"; 811 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length"; 812 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length"; 813 private static final String ATTR_VALUE = "value"; 814 private static final String TAG_PASSWORD_BLACKLIST = "password-blacklist"; 815 private static final String TAG_PASSWORD_QUALITY = "password-quality"; 816 private static final String TAG_POLICIES = "policies"; 817 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS = 818 "cross-profile-widget-providers"; 819 private static final String TAG_PROVIDER = "provider"; 820 private static final String TAG_PACKAGE_LIST_ITEM = "item"; 821 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages"; 822 private static final String TAG_USER_RESTRICTIONS = "user-restrictions"; 823 private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS = 824 "default-enabled-user-restrictions"; 825 private static final String TAG_RESTRICTION = "restriction"; 826 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message"; 827 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message"; 828 private static final String TAG_PARENT_ADMIN = "parent-admin"; 829 private static final String TAG_ORGANIZATION_COLOR = "organization-color"; 830 private static final String TAG_ORGANIZATION_NAME = "organization-name"; 831 private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification"; 832 private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications"; 833 private static final String TAG_IS_LOGOUT_ENABLED = "is_logout_enabled"; 834 private static final String TAG_MANDATORY_BACKUP_TRANSPORT = "mandatory_backup_transport"; 835 private static final String TAG_START_USER_SESSION_MESSAGE = "start_user_session_message"; 836 private static final String TAG_END_USER_SESSION_MESSAGE = "end_user_session_message"; 837 private static final String TAG_METERED_DATA_DISABLED_PACKAGES 838 = "metered_data_disabled_packages"; 839 840 DeviceAdminInfo info; 841 842 843 static final int DEF_PASSWORD_HISTORY_LENGTH = 0; 844 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH; 845 846 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0; 847 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1; 848 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0; 849 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0; 850 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1; 851 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1; 852 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0; 853 @NonNull 854 PasswordMetrics minimumPasswordMetrics = new PasswordMetrics( 855 PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH, 856 DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE, 857 DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC, 858 DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER); 859 860 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0; 861 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK; 862 863 long strongAuthUnlockTimeout = 0; // admin doesn't participate by default 864 865 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0; 866 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE; 867 868 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0; 869 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT; 870 871 static final long DEF_PASSWORD_EXPIRATION_DATE = 0; 872 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE; 873 874 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none 875 876 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED; 877 878 boolean encryptionRequested = false; 879 boolean testOnlyAdmin = false; 880 boolean disableCamera = false; 881 boolean disableCallerId = false; 882 boolean disableContactsSearch = false; 883 boolean disableBluetoothContactSharing = true; 884 boolean disableScreenCapture = false; // Can only be set by a device/profile owner. 885 boolean requireAutoTime = false; // Can only be set by a device owner. 886 boolean forceEphemeralUsers = false; // Can only be set by a device owner. 887 boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner. 888 boolean isLogoutEnabled = false; // Can only be set by a device owner. 889 890 // one notification after enabling + one more after reboots 891 static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2; 892 int numNetworkLoggingNotifications = 0; 893 long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch 894 895 ActiveAdmin parentAdmin; 896 final boolean isParent; 897 898 static class TrustAgentInfo { 899 public PersistableBundle options; 900 TrustAgentInfo(PersistableBundle bundle) { 901 options = bundle; 902 } 903 } 904 905 // The list of packages which are not allowed to use metered data. 906 List<String> meteredDisabledPackages; 907 908 final Set<String> accountTypesWithManagementDisabled = new ArraySet<>(); 909 910 // The list of permitted accessibility services package namesas set by a profile 911 // or device owner. Null means all accessibility services are allowed, empty means 912 // none except system services are allowed. 913 List<String> permittedAccessiblityServices; 914 915 // The list of permitted input methods package names as set by a profile or device owner. 916 // Null means all input methods are allowed, empty means none except system imes are 917 // allowed. 918 List<String> permittedInputMethods; 919 920 // The list of packages allowed to use a NotificationListenerService to receive events for 921 // notifications from this user. Null means that all packages are allowed. Empty list means 922 // that only packages from the system are allowed. 923 List<String> permittedNotificationListeners; 924 925 // List of package names to keep cached. 926 List<String> keepUninstalledPackages; 927 928 // TODO: review implementation decisions with frameworks team 929 boolean specifiesGlobalProxy = false; 930 String globalProxySpec = null; 931 String globalProxyExclusionList = null; 932 933 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>(); 934 935 List<String> crossProfileWidgetProviders; 936 937 Bundle userRestrictions; 938 939 // User restrictions that have already been enabled by default for this admin (either when 940 // setting the device or profile owner, or during a system update if one of those "enabled 941 // by default" restrictions is newly added). 942 final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>(); 943 944 // Support text provided by the admin to display to the user. 945 CharSequence shortSupportMessage = null; 946 CharSequence longSupportMessage = null; 947 948 // Background color of confirm credentials screen. Default: teal. 949 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B"); 950 int organizationColor = DEF_ORGANIZATION_COLOR; 951 952 // Default title of confirm credentials screen 953 String organizationName = null; 954 955 // The blacklist data is stored in a file whose name is stored in the XML 956 String passwordBlacklistFile = null; 957 958 // The component name of the backup transport which has to be used if backups are mandatory 959 // or null if backups are not mandatory. 960 ComponentName mandatoryBackupTransport = null; 961 962 // Message for user switcher 963 String startUserSessionMessage = null; 964 String endUserSessionMessage = null; 965 966 ActiveAdmin(DeviceAdminInfo _info, boolean parent) { 967 info = _info; 968 isParent = parent; 969 } 970 971 ActiveAdmin getParentActiveAdmin() { 972 Preconditions.checkState(!isParent); 973 974 if (parentAdmin == null) { 975 parentAdmin = new ActiveAdmin(info, /* parent */ true); 976 } 977 return parentAdmin; 978 } 979 980 boolean hasParentActiveAdmin() { 981 return parentAdmin != null; 982 } 983 984 int getUid() { return info.getActivityInfo().applicationInfo.uid; } 985 986 public UserHandle getUserHandle() { 987 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid)); 988 } 989 990 void writeToXml(XmlSerializer out) 991 throws IllegalArgumentException, IllegalStateException, IOException { 992 out.startTag(null, TAG_POLICIES); 993 info.writePoliciesToXml(out); 994 out.endTag(null, TAG_POLICIES); 995 if (minimumPasswordMetrics.quality != PASSWORD_QUALITY_UNSPECIFIED) { 996 out.startTag(null, TAG_PASSWORD_QUALITY); 997 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality)); 998 out.endTag(null, TAG_PASSWORD_QUALITY); 999 if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) { 1000 out.startTag(null, TAG_MIN_PASSWORD_LENGTH); 1001 out.attribute( 1002 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length)); 1003 out.endTag(null, TAG_MIN_PASSWORD_LENGTH); 1004 } 1005 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) { 1006 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH); 1007 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength)); 1008 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH); 1009 } 1010 if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) { 1011 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE); 1012 out.attribute( 1013 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase)); 1014 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE); 1015 } 1016 if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) { 1017 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE); 1018 out.attribute( 1019 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase)); 1020 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE); 1021 } 1022 if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) { 1023 out.startTag(null, TAG_MIN_PASSWORD_LETTERS); 1024 out.attribute( 1025 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters)); 1026 out.endTag(null, TAG_MIN_PASSWORD_LETTERS); 1027 } 1028 if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) { 1029 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC); 1030 out.attribute( 1031 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric)); 1032 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC); 1033 } 1034 if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) { 1035 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS); 1036 out.attribute( 1037 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols)); 1038 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS); 1039 } 1040 if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) { 1041 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER); 1042 out.attribute( 1043 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter)); 1044 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER); 1045 } 1046 } 1047 if (passwordBlacklistFile != null) { 1048 out.startTag(null, TAG_PASSWORD_BLACKLIST); 1049 out.attribute(null, ATTR_VALUE, passwordBlacklistFile); 1050 out.endTag(null, TAG_PASSWORD_BLACKLIST); 1051 } 1052 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) { 1053 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK); 1054 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock)); 1055 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK); 1056 } 1057 if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 1058 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT); 1059 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout)); 1060 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT); 1061 } 1062 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 1063 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE); 1064 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe)); 1065 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE); 1066 } 1067 if (specifiesGlobalProxy) { 1068 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY); 1069 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy)); 1070 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY); 1071 if (globalProxySpec != null) { 1072 out.startTag(null, TAG_GLOBAL_PROXY_SPEC); 1073 out.attribute(null, ATTR_VALUE, globalProxySpec); 1074 out.endTag(null, TAG_GLOBAL_PROXY_SPEC); 1075 } 1076 if (globalProxyExclusionList != null) { 1077 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST); 1078 out.attribute(null, ATTR_VALUE, globalProxyExclusionList); 1079 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST); 1080 } 1081 } 1082 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) { 1083 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT); 1084 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout)); 1085 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT); 1086 } 1087 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) { 1088 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE); 1089 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate)); 1090 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE); 1091 } 1092 if (encryptionRequested) { 1093 out.startTag(null, TAG_ENCRYPTION_REQUESTED); 1094 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested)); 1095 out.endTag(null, TAG_ENCRYPTION_REQUESTED); 1096 } 1097 if (testOnlyAdmin) { 1098 out.startTag(null, TAG_TEST_ONLY_ADMIN); 1099 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin)); 1100 out.endTag(null, TAG_TEST_ONLY_ADMIN); 1101 } 1102 if (disableCamera) { 1103 out.startTag(null, TAG_DISABLE_CAMERA); 1104 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera)); 1105 out.endTag(null, TAG_DISABLE_CAMERA); 1106 } 1107 if (disableCallerId) { 1108 out.startTag(null, TAG_DISABLE_CALLER_ID); 1109 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId)); 1110 out.endTag(null, TAG_DISABLE_CALLER_ID); 1111 } 1112 if (disableContactsSearch) { 1113 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH); 1114 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch)); 1115 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH); 1116 } 1117 if (!disableBluetoothContactSharing) { 1118 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING); 1119 out.attribute(null, ATTR_VALUE, 1120 Boolean.toString(disableBluetoothContactSharing)); 1121 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING); 1122 } 1123 if (disableScreenCapture) { 1124 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE); 1125 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture)); 1126 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE); 1127 } 1128 if (requireAutoTime) { 1129 out.startTag(null, TAG_REQUIRE_AUTO_TIME); 1130 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime)); 1131 out.endTag(null, TAG_REQUIRE_AUTO_TIME); 1132 } 1133 if (forceEphemeralUsers) { 1134 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS); 1135 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers)); 1136 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS); 1137 } 1138 if (isNetworkLoggingEnabled) { 1139 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED); 1140 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled)); 1141 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS, 1142 Integer.toString(numNetworkLoggingNotifications)); 1143 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION, 1144 Long.toString(lastNetworkLoggingNotificationTimeMs)); 1145 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED); 1146 } 1147 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) { 1148 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES); 1149 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures)); 1150 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES); 1151 } 1152 if (!accountTypesWithManagementDisabled.isEmpty()) { 1153 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT); 1154 writeAttributeValuesToXml( 1155 out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled); 1156 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT); 1157 } 1158 if (!trustAgentInfos.isEmpty()) { 1159 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet(); 1160 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES); 1161 for (Entry<String, TrustAgentInfo> entry : set) { 1162 TrustAgentInfo trustAgentInfo = entry.getValue(); 1163 out.startTag(null, TAG_TRUST_AGENT_COMPONENT); 1164 out.attribute(null, ATTR_VALUE, entry.getKey()); 1165 if (trustAgentInfo.options != null) { 1166 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS); 1167 try { 1168 trustAgentInfo.options.saveToXml(out); 1169 } catch (XmlPullParserException e) { 1170 Log.e(LOG_TAG, "Failed to save TrustAgent options", e); 1171 } 1172 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS); 1173 } 1174 out.endTag(null, TAG_TRUST_AGENT_COMPONENT); 1175 } 1176 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES); 1177 } 1178 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) { 1179 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS); 1180 writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders); 1181 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS); 1182 } 1183 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES, 1184 permittedAccessiblityServices); 1185 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods); 1186 writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS, 1187 permittedNotificationListeners); 1188 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages); 1189 writePackageListToXml(out, TAG_METERED_DATA_DISABLED_PACKAGES, meteredDisabledPackages); 1190 if (hasUserRestrictions()) { 1191 UserRestrictionsUtils.writeRestrictions( 1192 out, userRestrictions, TAG_USER_RESTRICTIONS); 1193 } 1194 if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) { 1195 out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS); 1196 writeAttributeValuesToXml( 1197 out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet); 1198 out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS); 1199 } 1200 if (!TextUtils.isEmpty(shortSupportMessage)) { 1201 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE); 1202 out.text(shortSupportMessage.toString()); 1203 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE); 1204 } 1205 if (!TextUtils.isEmpty(longSupportMessage)) { 1206 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE); 1207 out.text(longSupportMessage.toString()); 1208 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE); 1209 } 1210 if (parentAdmin != null) { 1211 out.startTag(null, TAG_PARENT_ADMIN); 1212 parentAdmin.writeToXml(out); 1213 out.endTag(null, TAG_PARENT_ADMIN); 1214 } 1215 if (organizationColor != DEF_ORGANIZATION_COLOR) { 1216 out.startTag(null, TAG_ORGANIZATION_COLOR); 1217 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor)); 1218 out.endTag(null, TAG_ORGANIZATION_COLOR); 1219 } 1220 if (organizationName != null) { 1221 out.startTag(null, TAG_ORGANIZATION_NAME); 1222 out.text(organizationName); 1223 out.endTag(null, TAG_ORGANIZATION_NAME); 1224 } 1225 if (isLogoutEnabled) { 1226 out.startTag(null, TAG_IS_LOGOUT_ENABLED); 1227 out.attribute(null, ATTR_VALUE, Boolean.toString(isLogoutEnabled)); 1228 out.endTag(null, TAG_IS_LOGOUT_ENABLED); 1229 } 1230 if (mandatoryBackupTransport != null) { 1231 out.startTag(null, TAG_MANDATORY_BACKUP_TRANSPORT); 1232 out.attribute(null, ATTR_VALUE, mandatoryBackupTransport.flattenToString()); 1233 out.endTag(null, TAG_MANDATORY_BACKUP_TRANSPORT); 1234 } 1235 if (startUserSessionMessage != null) { 1236 out.startTag(null, TAG_START_USER_SESSION_MESSAGE); 1237 out.text(startUserSessionMessage); 1238 out.endTag(null, TAG_START_USER_SESSION_MESSAGE); 1239 } 1240 if (endUserSessionMessage != null) { 1241 out.startTag(null, TAG_END_USER_SESSION_MESSAGE); 1242 out.text(endUserSessionMessage); 1243 out.endTag(null, TAG_END_USER_SESSION_MESSAGE); 1244 } 1245 } 1246 1247 void writePackageListToXml(XmlSerializer out, String outerTag, 1248 List<String> packageList) 1249 throws IllegalArgumentException, IllegalStateException, IOException { 1250 if (packageList == null) { 1251 return; 1252 } 1253 1254 out.startTag(null, outerTag); 1255 writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList); 1256 out.endTag(null, outerTag); 1257 } 1258 1259 void writeAttributeValuesToXml(XmlSerializer out, String tag, 1260 @NonNull Collection<String> values) throws IOException { 1261 for (String value : values) { 1262 out.startTag(null, tag); 1263 out.attribute(null, ATTR_VALUE, value); 1264 out.endTag(null, tag); 1265 } 1266 } 1267 1268 void readFromXml(XmlPullParser parser) 1269 throws XmlPullParserException, IOException { 1270 int outerDepth = parser.getDepth(); 1271 int type; 1272 while ((type=parser.next()) != END_DOCUMENT 1273 && (type != END_TAG || parser.getDepth() > outerDepth)) { 1274 if (type == END_TAG || type == TEXT) { 1275 continue; 1276 } 1277 String tag = parser.getName(); 1278 if (TAG_POLICIES.equals(tag)) { 1279 info.readPoliciesFromXml(parser); 1280 } else if (TAG_PASSWORD_QUALITY.equals(tag)) { 1281 minimumPasswordMetrics.quality = Integer.parseInt( 1282 parser.getAttributeValue(null, ATTR_VALUE)); 1283 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) { 1284 minimumPasswordMetrics.length = Integer.parseInt( 1285 parser.getAttributeValue(null, ATTR_VALUE)); 1286 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) { 1287 passwordHistoryLength = Integer.parseInt( 1288 parser.getAttributeValue(null, ATTR_VALUE)); 1289 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) { 1290 minimumPasswordMetrics.upperCase = Integer.parseInt( 1291 parser.getAttributeValue(null, ATTR_VALUE)); 1292 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) { 1293 minimumPasswordMetrics.lowerCase = Integer.parseInt( 1294 parser.getAttributeValue(null, ATTR_VALUE)); 1295 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) { 1296 minimumPasswordMetrics.letters = Integer.parseInt( 1297 parser.getAttributeValue(null, ATTR_VALUE)); 1298 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) { 1299 minimumPasswordMetrics.numeric = Integer.parseInt( 1300 parser.getAttributeValue(null, ATTR_VALUE)); 1301 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) { 1302 minimumPasswordMetrics.symbols = Integer.parseInt( 1303 parser.getAttributeValue(null, ATTR_VALUE)); 1304 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) { 1305 minimumPasswordMetrics.nonLetter = Integer.parseInt( 1306 parser.getAttributeValue(null, ATTR_VALUE)); 1307 } else if (TAG_PASSWORD_BLACKLIST.equals(tag)) { 1308 passwordBlacklistFile = parser.getAttributeValue(null, ATTR_VALUE); 1309 }else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) { 1310 maximumTimeToUnlock = Long.parseLong( 1311 parser.getAttributeValue(null, ATTR_VALUE)); 1312 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) { 1313 strongAuthUnlockTimeout = Long.parseLong( 1314 parser.getAttributeValue(null, ATTR_VALUE)); 1315 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) { 1316 maximumFailedPasswordsForWipe = Integer.parseInt( 1317 parser.getAttributeValue(null, ATTR_VALUE)); 1318 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) { 1319 specifiesGlobalProxy = Boolean.parseBoolean( 1320 parser.getAttributeValue(null, ATTR_VALUE)); 1321 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) { 1322 globalProxySpec = 1323 parser.getAttributeValue(null, ATTR_VALUE); 1324 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) { 1325 globalProxyExclusionList = 1326 parser.getAttributeValue(null, ATTR_VALUE); 1327 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) { 1328 passwordExpirationTimeout = Long.parseLong( 1329 parser.getAttributeValue(null, ATTR_VALUE)); 1330 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) { 1331 passwordExpirationDate = Long.parseLong( 1332 parser.getAttributeValue(null, ATTR_VALUE)); 1333 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) { 1334 encryptionRequested = Boolean.parseBoolean( 1335 parser.getAttributeValue(null, ATTR_VALUE)); 1336 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) { 1337 testOnlyAdmin = Boolean.parseBoolean( 1338 parser.getAttributeValue(null, ATTR_VALUE)); 1339 } else if (TAG_DISABLE_CAMERA.equals(tag)) { 1340 disableCamera = Boolean.parseBoolean( 1341 parser.getAttributeValue(null, ATTR_VALUE)); 1342 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) { 1343 disableCallerId = Boolean.parseBoolean( 1344 parser.getAttributeValue(null, ATTR_VALUE)); 1345 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) { 1346 disableContactsSearch = Boolean.parseBoolean( 1347 parser.getAttributeValue(null, ATTR_VALUE)); 1348 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) { 1349 disableBluetoothContactSharing = Boolean.parseBoolean(parser 1350 .getAttributeValue(null, ATTR_VALUE)); 1351 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) { 1352 disableScreenCapture = Boolean.parseBoolean( 1353 parser.getAttributeValue(null, ATTR_VALUE)); 1354 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) { 1355 requireAutoTime = Boolean.parseBoolean( 1356 parser.getAttributeValue(null, ATTR_VALUE)); 1357 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) { 1358 forceEphemeralUsers = Boolean.parseBoolean( 1359 parser.getAttributeValue(null, ATTR_VALUE)); 1360 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) { 1361 isNetworkLoggingEnabled = Boolean.parseBoolean( 1362 parser.getAttributeValue(null, ATTR_VALUE)); 1363 lastNetworkLoggingNotificationTimeMs = Long.parseLong( 1364 parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION)); 1365 numNetworkLoggingNotifications = Integer.parseInt( 1366 parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS)); 1367 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) { 1368 disabledKeyguardFeatures = Integer.parseInt( 1369 parser.getAttributeValue(null, ATTR_VALUE)); 1370 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) { 1371 readAttributeValues( 1372 parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled); 1373 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) { 1374 trustAgentInfos = getAllTrustAgentInfos(parser, tag); 1375 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) { 1376 crossProfileWidgetProviders = new ArrayList<>(); 1377 readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders); 1378 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) { 1379 permittedAccessiblityServices = readPackageList(parser, tag); 1380 } else if (TAG_PERMITTED_IMES.equals(tag)) { 1381 permittedInputMethods = readPackageList(parser, tag); 1382 } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) { 1383 permittedNotificationListeners = readPackageList(parser, tag); 1384 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) { 1385 keepUninstalledPackages = readPackageList(parser, tag); 1386 } else if (TAG_METERED_DATA_DISABLED_PACKAGES.equals(tag)) { 1387 meteredDisabledPackages = readPackageList(parser, tag); 1388 } else if (TAG_USER_RESTRICTIONS.equals(tag)) { 1389 userRestrictions = UserRestrictionsUtils.readRestrictions(parser); 1390 } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) { 1391 readAttributeValues( 1392 parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet); 1393 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) { 1394 type = parser.next(); 1395 if (type == XmlPullParser.TEXT) { 1396 shortSupportMessage = parser.getText(); 1397 } else { 1398 Log.w(LOG_TAG, "Missing text when loading short support message"); 1399 } 1400 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) { 1401 type = parser.next(); 1402 if (type == XmlPullParser.TEXT) { 1403 longSupportMessage = parser.getText(); 1404 } else { 1405 Log.w(LOG_TAG, "Missing text when loading long support message"); 1406 } 1407 } else if (TAG_PARENT_ADMIN.equals(tag)) { 1408 Preconditions.checkState(!isParent); 1409 1410 parentAdmin = new ActiveAdmin(info, /* parent */ true); 1411 parentAdmin.readFromXml(parser); 1412 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) { 1413 organizationColor = Integer.parseInt( 1414 parser.getAttributeValue(null, ATTR_VALUE)); 1415 } else if (TAG_ORGANIZATION_NAME.equals(tag)) { 1416 type = parser.next(); 1417 if (type == XmlPullParser.TEXT) { 1418 organizationName = parser.getText(); 1419 } else { 1420 Log.w(LOG_TAG, "Missing text when loading organization name"); 1421 } 1422 } else if (TAG_IS_LOGOUT_ENABLED.equals(tag)) { 1423 isLogoutEnabled = Boolean.parseBoolean( 1424 parser.getAttributeValue(null, ATTR_VALUE)); 1425 } else if (TAG_MANDATORY_BACKUP_TRANSPORT.equals(tag)) { 1426 mandatoryBackupTransport = ComponentName.unflattenFromString( 1427 parser.getAttributeValue(null, ATTR_VALUE)); 1428 } else if (TAG_START_USER_SESSION_MESSAGE.equals(tag)) { 1429 type = parser.next(); 1430 if (type == XmlPullParser.TEXT) { 1431 startUserSessionMessage = parser.getText(); 1432 } else { 1433 Log.w(LOG_TAG, "Missing text when loading start session message"); 1434 } 1435 } else if (TAG_END_USER_SESSION_MESSAGE.equals(tag)) { 1436 type = parser.next(); 1437 if (type == XmlPullParser.TEXT) { 1438 endUserSessionMessage = parser.getText(); 1439 } else { 1440 Log.w(LOG_TAG, "Missing text when loading end session message"); 1441 } 1442 } else { 1443 Slog.w(LOG_TAG, "Unknown admin tag: " + tag); 1444 XmlUtils.skipCurrentTag(parser); 1445 } 1446 } 1447 } 1448 1449 private List<String> readPackageList(XmlPullParser parser, 1450 String tag) throws XmlPullParserException, IOException { 1451 List<String> result = new ArrayList<String>(); 1452 int outerDepth = parser.getDepth(); 1453 int outerType; 1454 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT 1455 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1456 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) { 1457 continue; 1458 } 1459 String outerTag = parser.getName(); 1460 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) { 1461 String packageName = parser.getAttributeValue(null, ATTR_VALUE); 1462 if (packageName != null) { 1463 result.add(packageName); 1464 } else { 1465 Slog.w(LOG_TAG, "Package name missing under " + outerTag); 1466 } 1467 } else { 1468 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag); 1469 } 1470 } 1471 return result; 1472 } 1473 1474 private void readAttributeValues( 1475 XmlPullParser parser, String tag, Collection<String> result) 1476 throws XmlPullParserException, IOException { 1477 result.clear(); 1478 int outerDepthDAM = parser.getDepth(); 1479 int typeDAM; 1480 while ((typeDAM=parser.next()) != END_DOCUMENT 1481 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1482 if (typeDAM == END_TAG || typeDAM == TEXT) { 1483 continue; 1484 } 1485 String tagDAM = parser.getName(); 1486 if (tag.equals(tagDAM)) { 1487 result.add(parser.getAttributeValue(null, ATTR_VALUE)); 1488 } else { 1489 Slog.e(LOG_TAG, "Expected tag " + tag + " but found " + tagDAM); 1490 } 1491 } 1492 } 1493 1494 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos( 1495 XmlPullParser parser, String tag) throws XmlPullParserException, IOException { 1496 int outerDepthDAM = parser.getDepth(); 1497 int typeDAM; 1498 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>(); 1499 while ((typeDAM=parser.next()) != END_DOCUMENT 1500 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1501 if (typeDAM == END_TAG || typeDAM == TEXT) { 1502 continue; 1503 } 1504 String tagDAM = parser.getName(); 1505 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) { 1506 final String component = parser.getAttributeValue(null, ATTR_VALUE); 1507 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag); 1508 result.put(component, trustAgentInfo); 1509 } else { 1510 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 1511 } 1512 } 1513 return result; 1514 } 1515 1516 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag) 1517 throws XmlPullParserException, IOException { 1518 int outerDepthDAM = parser.getDepth(); 1519 int typeDAM; 1520 TrustAgentInfo result = new TrustAgentInfo(null); 1521 while ((typeDAM=parser.next()) != END_DOCUMENT 1522 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1523 if (typeDAM == END_TAG || typeDAM == TEXT) { 1524 continue; 1525 } 1526 String tagDAM = parser.getName(); 1527 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) { 1528 result.options = PersistableBundle.restoreFromXml(parser); 1529 } else { 1530 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 1531 } 1532 } 1533 return result; 1534 } 1535 1536 boolean hasUserRestrictions() { 1537 return userRestrictions != null && userRestrictions.size() > 0; 1538 } 1539 1540 Bundle ensureUserRestrictions() { 1541 if (userRestrictions == null) { 1542 userRestrictions = new Bundle(); 1543 } 1544 return userRestrictions; 1545 } 1546 1547 public void transfer(DeviceAdminInfo deviceAdminInfo) { 1548 if (hasParentActiveAdmin()) { 1549 parentAdmin.info = deviceAdminInfo; 1550 } 1551 info = deviceAdminInfo; 1552 } 1553 1554 void dump(String prefix, PrintWriter pw) { 1555 pw.print(prefix); pw.print("uid="); pw.println(getUid()); 1556 pw.print(prefix); pw.print("testOnlyAdmin="); 1557 pw.println(testOnlyAdmin); 1558 pw.print(prefix); pw.println("policies:"); 1559 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies(); 1560 if (pols != null) { 1561 for (int i=0; i<pols.size(); i++) { 1562 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag); 1563 } 1564 } 1565 pw.print(prefix); pw.print("passwordQuality=0x"); 1566 pw.println(Integer.toHexString(minimumPasswordMetrics.quality)); 1567 pw.print(prefix); pw.print("minimumPasswordLength="); 1568 pw.println(minimumPasswordMetrics.length); 1569 pw.print(prefix); pw.print("passwordHistoryLength="); 1570 pw.println(passwordHistoryLength); 1571 pw.print(prefix); pw.print("minimumPasswordUpperCase="); 1572 pw.println(minimumPasswordMetrics.upperCase); 1573 pw.print(prefix); pw.print("minimumPasswordLowerCase="); 1574 pw.println(minimumPasswordMetrics.lowerCase); 1575 pw.print(prefix); pw.print("minimumPasswordLetters="); 1576 pw.println(minimumPasswordMetrics.letters); 1577 pw.print(prefix); pw.print("minimumPasswordNumeric="); 1578 pw.println(minimumPasswordMetrics.numeric); 1579 pw.print(prefix); pw.print("minimumPasswordSymbols="); 1580 pw.println(minimumPasswordMetrics.symbols); 1581 pw.print(prefix); pw.print("minimumPasswordNonLetter="); 1582 pw.println(minimumPasswordMetrics.nonLetter); 1583 pw.print(prefix); pw.print("passwordBlacklist="); 1584 pw.println(passwordBlacklistFile != null); 1585 pw.print(prefix); pw.print("maximumTimeToUnlock="); 1586 pw.println(maximumTimeToUnlock); 1587 pw.print(prefix); pw.print("strongAuthUnlockTimeout="); 1588 pw.println(strongAuthUnlockTimeout); 1589 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe="); 1590 pw.println(maximumFailedPasswordsForWipe); 1591 pw.print(prefix); pw.print("specifiesGlobalProxy="); 1592 pw.println(specifiesGlobalProxy); 1593 pw.print(prefix); pw.print("passwordExpirationTimeout="); 1594 pw.println(passwordExpirationTimeout); 1595 pw.print(prefix); pw.print("passwordExpirationDate="); 1596 pw.println(passwordExpirationDate); 1597 if (globalProxySpec != null) { 1598 pw.print(prefix); pw.print("globalProxySpec="); 1599 pw.println(globalProxySpec); 1600 } 1601 if (globalProxyExclusionList != null) { 1602 pw.print(prefix); pw.print("globalProxyEclusionList="); 1603 pw.println(globalProxyExclusionList); 1604 } 1605 pw.print(prefix); pw.print("encryptionRequested="); 1606 pw.println(encryptionRequested); 1607 pw.print(prefix); pw.print("disableCamera="); 1608 pw.println(disableCamera); 1609 pw.print(prefix); pw.print("disableCallerId="); 1610 pw.println(disableCallerId); 1611 pw.print(prefix); pw.print("disableContactsSearch="); 1612 pw.println(disableContactsSearch); 1613 pw.print(prefix); pw.print("disableBluetoothContactSharing="); 1614 pw.println(disableBluetoothContactSharing); 1615 pw.print(prefix); pw.print("disableScreenCapture="); 1616 pw.println(disableScreenCapture); 1617 pw.print(prefix); pw.print("requireAutoTime="); 1618 pw.println(requireAutoTime); 1619 pw.print(prefix); pw.print("forceEphemeralUsers="); 1620 pw.println(forceEphemeralUsers); 1621 pw.print(prefix); pw.print("isNetworkLoggingEnabled="); 1622 pw.println(isNetworkLoggingEnabled); 1623 pw.print(prefix); pw.print("disabledKeyguardFeatures="); 1624 pw.println(disabledKeyguardFeatures); 1625 pw.print(prefix); pw.print("crossProfileWidgetProviders="); 1626 pw.println(crossProfileWidgetProviders); 1627 if (permittedAccessiblityServices != null) { 1628 pw.print(prefix); pw.print("permittedAccessibilityServices="); 1629 pw.println(permittedAccessiblityServices); 1630 } 1631 if (permittedInputMethods != null) { 1632 pw.print(prefix); pw.print("permittedInputMethods="); 1633 pw.println(permittedInputMethods); 1634 } 1635 if (permittedNotificationListeners != null) { 1636 pw.print(prefix); pw.print("permittedNotificationListeners="); 1637 pw.println(permittedNotificationListeners); 1638 } 1639 if (keepUninstalledPackages != null) { 1640 pw.print(prefix); pw.print("keepUninstalledPackages="); 1641 pw.println(keepUninstalledPackages); 1642 } 1643 pw.print(prefix); pw.print("organizationColor="); 1644 pw.println(organizationColor); 1645 if (organizationName != null) { 1646 pw.print(prefix); pw.print("organizationName="); 1647 pw.println(organizationName); 1648 } 1649 pw.print(prefix); pw.println("userRestrictions:"); 1650 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions); 1651 pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet="); 1652 pw.println(defaultEnabledRestrictionsAlreadySet); 1653 pw.print(prefix); pw.print("isParent="); 1654 pw.println(isParent); 1655 if (parentAdmin != null) { 1656 pw.print(prefix); pw.println("parentAdmin:"); 1657 parentAdmin.dump(prefix + " ", pw); 1658 } 1659 } 1660 } 1661 1662 private void handlePackagesChanged(@Nullable String packageName, int userHandle) { 1663 boolean removedAdmin = false; 1664 if (VERBOSE_LOG) { 1665 Slog.d(LOG_TAG, "Handling package changes package " + packageName 1666 + " for user " + userHandle); 1667 } 1668 DevicePolicyData policy = getUserData(userHandle); 1669 synchronized (this) { 1670 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 1671 ActiveAdmin aa = policy.mAdminList.get(i); 1672 try { 1673 // If we're checking all packages or if the specific one we're checking matches, 1674 // then check if the package and receiver still exist. 1675 final String adminPackage = aa.info.getPackageName(); 1676 if (packageName == null || packageName.equals(adminPackage)) { 1677 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null 1678 || mIPackageManager.getReceiverInfo(aa.info.getComponent(), 1679 PackageManager.MATCH_DIRECT_BOOT_AWARE 1680 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 1681 userHandle) == null) { 1682 removedAdmin = true; 1683 policy.mAdminList.remove(i); 1684 policy.mAdminMap.remove(aa.info.getComponent()); 1685 pushActiveAdminPackagesLocked(userHandle); 1686 pushMeteredDisabledPackagesLocked(userHandle); 1687 } 1688 } 1689 } catch (RemoteException re) { 1690 // Shouldn't happen. 1691 } 1692 } 1693 if (removedAdmin) { 1694 validatePasswordOwnerLocked(policy); 1695 } 1696 1697 boolean removedDelegate = false; 1698 1699 // Check if a delegate was removed. 1700 for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) { 1701 final String delegatePackage = policy.mDelegationMap.keyAt(i); 1702 if (isRemovedPackage(packageName, delegatePackage, userHandle)) { 1703 policy.mDelegationMap.removeAt(i); 1704 removedDelegate = true; 1705 } 1706 } 1707 1708 // If it's an owner package, we may need to refresh the bound connection. 1709 final ComponentName owner = getOwnerComponent(userHandle); 1710 if ((packageName != null) && (owner != null) 1711 && (owner.getPackageName().equals(packageName))) { 1712 startOwnerService(userHandle, "package-broadcast"); 1713 } 1714 1715 // Persist updates if the removed package was an admin or delegate. 1716 if (removedAdmin || removedDelegate) { 1717 saveSettingsLocked(policy.mUserHandle); 1718 } 1719 } 1720 if (removedAdmin) { 1721 // The removed admin might have disabled camera, so update user restrictions. 1722 pushUserRestrictions(userHandle); 1723 } 1724 } 1725 1726 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) { 1727 try { 1728 return targetPackage != null 1729 && (changedPackage == null || changedPackage.equals(targetPackage)) 1730 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null; 1731 } catch (RemoteException e) { 1732 // Shouldn't happen 1733 } 1734 1735 return false; 1736 } 1737 1738 /** 1739 * Unit test will subclass it to inject mocks. 1740 */ 1741 @VisibleForTesting 1742 static class Injector { 1743 1744 public final Context mContext; 1745 1746 Injector(Context context) { 1747 mContext = context; 1748 } 1749 1750 public boolean hasFeature() { 1751 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN); 1752 } 1753 1754 Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException { 1755 final String packageName = mContext.getPackageName(); 1756 return mContext.createPackageContextAsUser(packageName, 0, user); 1757 } 1758 1759 Resources getResources() { 1760 return mContext.getResources(); 1761 } 1762 1763 Owners newOwners() { 1764 return new Owners(getUserManager(), getUserManagerInternal(), 1765 getPackageManagerInternal()); 1766 } 1767 1768 UserManager getUserManager() { 1769 return UserManager.get(mContext); 1770 } 1771 1772 UserManagerInternal getUserManagerInternal() { 1773 return LocalServices.getService(UserManagerInternal.class); 1774 } 1775 1776 PackageManagerInternal getPackageManagerInternal() { 1777 return LocalServices.getService(PackageManagerInternal.class); 1778 } 1779 1780 UsageStatsManagerInternal getUsageStatsManagerInternal() { 1781 return LocalServices.getService(UsageStatsManagerInternal.class); 1782 } 1783 1784 NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() { 1785 return LocalServices.getService(NetworkPolicyManagerInternal.class); 1786 } 1787 1788 NotificationManager getNotificationManager() { 1789 return mContext.getSystemService(NotificationManager.class); 1790 } 1791 1792 IIpConnectivityMetrics getIIpConnectivityMetrics() { 1793 return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface( 1794 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME)); 1795 } 1796 1797 PackageManager getPackageManager() { 1798 return mContext.getPackageManager(); 1799 } 1800 1801 PowerManagerInternal getPowerManagerInternal() { 1802 return LocalServices.getService(PowerManagerInternal.class); 1803 } 1804 1805 TelephonyManager getTelephonyManager() { 1806 return TelephonyManager.from(mContext); 1807 } 1808 1809 TrustManager getTrustManager() { 1810 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE); 1811 } 1812 1813 AlarmManager getAlarmManager() { 1814 return (AlarmManager) mContext.getSystemService(AlarmManager.class); 1815 } 1816 1817 IWindowManager getIWindowManager() { 1818 return IWindowManager.Stub 1819 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)); 1820 } 1821 1822 IActivityManager getIActivityManager() { 1823 return ActivityManager.getService(); 1824 } 1825 1826 ActivityManagerInternal getActivityManagerInternal() { 1827 return LocalServices.getService(ActivityManagerInternal.class); 1828 } 1829 1830 IPackageManager getIPackageManager() { 1831 return AppGlobals.getPackageManager(); 1832 } 1833 1834 IBackupManager getIBackupManager() { 1835 return IBackupManager.Stub.asInterface( 1836 ServiceManager.getService(Context.BACKUP_SERVICE)); 1837 } 1838 1839 IAudioService getIAudioService() { 1840 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE)); 1841 } 1842 1843 boolean isBuildDebuggable() { 1844 return Build.IS_DEBUGGABLE; 1845 } 1846 1847 LockPatternUtils newLockPatternUtils() { 1848 return new LockPatternUtils(mContext); 1849 } 1850 1851 PasswordBlacklist newPasswordBlacklist(File file) { 1852 return new PasswordBlacklist(file); 1853 } 1854 1855 boolean storageManagerIsFileBasedEncryptionEnabled() { 1856 return StorageManager.isFileEncryptedNativeOnly(); 1857 } 1858 1859 boolean storageManagerIsNonDefaultBlockEncrypted() { 1860 long identity = Binder.clearCallingIdentity(); 1861 try { 1862 return StorageManager.isNonDefaultBlockEncrypted(); 1863 } finally { 1864 Binder.restoreCallingIdentity(identity); 1865 } 1866 } 1867 1868 boolean storageManagerIsEncrypted() { 1869 return StorageManager.isEncrypted(); 1870 } 1871 1872 boolean storageManagerIsEncryptable() { 1873 return StorageManager.isEncryptable(); 1874 } 1875 1876 Looper getMyLooper() { 1877 return Looper.myLooper(); 1878 } 1879 1880 WifiManager getWifiManager() { 1881 return mContext.getSystemService(WifiManager.class); 1882 } 1883 1884 long binderClearCallingIdentity() { 1885 return Binder.clearCallingIdentity(); 1886 } 1887 1888 void binderRestoreCallingIdentity(long token) { 1889 Binder.restoreCallingIdentity(token); 1890 } 1891 1892 int binderGetCallingUid() { 1893 return Binder.getCallingUid(); 1894 } 1895 1896 int binderGetCallingPid() { 1897 return Binder.getCallingPid(); 1898 } 1899 1900 UserHandle binderGetCallingUserHandle() { 1901 return Binder.getCallingUserHandle(); 1902 } 1903 1904 boolean binderIsCallingUidMyUid() { 1905 return getCallingUid() == Process.myUid(); 1906 } 1907 1908 void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) { 1909 Binder.withCleanCallingIdentity(action); 1910 } 1911 1912 final int userHandleGetCallingUserId() { 1913 return UserHandle.getUserId(binderGetCallingUid()); 1914 } 1915 1916 File environmentGetUserSystemDirectory(int userId) { 1917 return Environment.getUserSystemDirectory(userId); 1918 } 1919 1920 void powerManagerGoToSleep(long time, int reason, int flags) { 1921 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags); 1922 } 1923 1924 void powerManagerReboot(String reason) { 1925 mContext.getSystemService(PowerManager.class).reboot(reason); 1926 } 1927 1928 void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, 1929 boolean wipeEuicc) throws IOException { 1930 RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc); 1931 } 1932 1933 boolean systemPropertiesGetBoolean(String key, boolean def) { 1934 return SystemProperties.getBoolean(key, def); 1935 } 1936 1937 long systemPropertiesGetLong(String key, long def) { 1938 return SystemProperties.getLong(key, def); 1939 } 1940 1941 String systemPropertiesGet(String key, String def) { 1942 return SystemProperties.get(key, def); 1943 } 1944 1945 String systemPropertiesGet(String key) { 1946 return SystemProperties.get(key); 1947 } 1948 1949 void systemPropertiesSet(String key, String value) { 1950 SystemProperties.set(key, value); 1951 } 1952 1953 boolean userManagerIsSplitSystemUser() { 1954 return UserManager.isSplitSystemUser(); 1955 } 1956 1957 String getDevicePolicyFilePathForSystemUser() { 1958 return "/data/system/"; 1959 } 1960 1961 PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode, 1962 @NonNull Intent intent, int flags, Bundle options, UserHandle user) { 1963 return PendingIntent.getActivityAsUser( 1964 context, requestCode, intent, flags, options, user); 1965 } 1966 1967 void registerContentObserver(Uri uri, boolean notifyForDescendents, 1968 ContentObserver observer, int userHandle) { 1969 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents, 1970 observer, userHandle); 1971 } 1972 1973 int settingsSecureGetIntForUser(String name, int def, int userHandle) { 1974 return Settings.Secure.getIntForUser(mContext.getContentResolver(), 1975 name, def, userHandle); 1976 } 1977 1978 String settingsSecureGetStringForUser(String name, int userHandle) { 1979 return Settings.Secure.getStringForUser(mContext.getContentResolver(), name, 1980 userHandle); 1981 } 1982 1983 void settingsSecurePutIntForUser(String name, int value, int userHandle) { 1984 Settings.Secure.putIntForUser(mContext.getContentResolver(), 1985 name, value, userHandle); 1986 } 1987 1988 void settingsSecurePutStringForUser(String name, String value, int userHandle) { 1989 Settings.Secure.putStringForUser(mContext.getContentResolver(), 1990 name, value, userHandle); 1991 } 1992 1993 void settingsGlobalPutStringForUser(String name, String value, int userHandle) { 1994 Settings.Global.putStringForUser(mContext.getContentResolver(), 1995 name, value, userHandle); 1996 } 1997 1998 void settingsSecurePutInt(String name, int value) { 1999 Settings.Secure.putInt(mContext.getContentResolver(), name, value); 2000 } 2001 2002 int settingsGlobalGetInt(String name, int def) { 2003 return Settings.Global.getInt(mContext.getContentResolver(), name, def); 2004 } 2005 2006 String settingsGlobalGetString(String name) { 2007 return Settings.Global.getString(mContext.getContentResolver(), name); 2008 } 2009 2010 void settingsGlobalPutInt(String name, int value) { 2011 Settings.Global.putInt(mContext.getContentResolver(), name, value); 2012 } 2013 2014 void settingsSecurePutString(String name, String value) { 2015 Settings.Secure.putString(mContext.getContentResolver(), name, value); 2016 } 2017 2018 void settingsGlobalPutString(String name, String value) { 2019 Settings.Global.putString(mContext.getContentResolver(), name, value); 2020 } 2021 2022 void settingsSystemPutString(String name, String value) { 2023 Settings.System.putString(mContext.getContentResolver(), name, value); 2024 } 2025 2026 void securityLogSetLoggingEnabledProperty(boolean enabled) { 2027 SecurityLog.setLoggingEnabledProperty(enabled); 2028 } 2029 2030 boolean securityLogGetLoggingEnabledProperty() { 2031 return SecurityLog.getLoggingEnabledProperty(); 2032 } 2033 2034 boolean securityLogIsLoggingEnabled() { 2035 return SecurityLog.isLoggingEnabled(); 2036 } 2037 2038 KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException { 2039 return KeyChain.bindAsUser(mContext, user); 2040 } 2041 2042 void postOnSystemServerInitThreadPool(Runnable runnable) { 2043 SystemServerInitThreadPool.get().submit(runnable, LOG_TAG); 2044 } 2045 2046 public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() { 2047 return new TransferOwnershipMetadataManager(); 2048 } 2049 2050 public void runCryptoSelfTest() { 2051 CryptoTestHelper.runAndLogSelfTest(); 2052 } 2053 } 2054 2055 /** 2056 * Instantiates the service. 2057 */ 2058 public DevicePolicyManagerService(Context context) { 2059 this(new Injector(context)); 2060 } 2061 2062 @VisibleForTesting 2063 DevicePolicyManagerService(Injector injector) { 2064 mInjector = injector; 2065 mContext = Preconditions.checkNotNull(injector.mContext); 2066 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper())); 2067 mConstants = DevicePolicyConstants.loadFromString( 2068 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS)); 2069 2070 mOwners = Preconditions.checkNotNull(injector.newOwners()); 2071 2072 mUserManager = Preconditions.checkNotNull(injector.getUserManager()); 2073 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal()); 2074 mUsageStatsManagerInternal = Preconditions.checkNotNull( 2075 injector.getUsageStatsManagerInternal()); 2076 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager()); 2077 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager()); 2078 2079 mLocalService = new LocalService(); 2080 mLockPatternUtils = injector.newLockPatternUtils(); 2081 2082 // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false? 2083 mSecurityLogMonitor = new SecurityLogMonitor(this); 2084 2085 mHasFeature = mInjector.hasFeature(); 2086 mIsWatch = mInjector.getPackageManager() 2087 .hasSystemFeature(PackageManager.FEATURE_WATCH); 2088 mBackgroundHandler = BackgroundThread.getHandler(); 2089 2090 // Needed when mHasFeature == false, because it controls the certificate warning text. 2091 mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler); 2092 2093 mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants); 2094 2095 mOverlayPackagesProvider = new OverlayPackagesProvider(mContext); 2096 2097 mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager(); 2098 2099 if (!mHasFeature) { 2100 // Skip the rest of the initialization 2101 return; 2102 } 2103 2104 IntentFilter filter = new IntentFilter(); 2105 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 2106 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION); 2107 filter.addAction(Intent.ACTION_USER_ADDED); 2108 filter.addAction(Intent.ACTION_USER_REMOVED); 2109 filter.addAction(Intent.ACTION_USER_STARTED); 2110 filter.addAction(Intent.ACTION_USER_STOPPED); 2111 filter.addAction(Intent.ACTION_USER_SWITCHED); 2112 filter.addAction(Intent.ACTION_USER_UNLOCKED); 2113 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 2114 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 2115 filter = new IntentFilter(); 2116 filter.addAction(Intent.ACTION_PACKAGE_CHANGED); 2117 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 2118 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 2119 filter.addAction(Intent.ACTION_PACKAGE_ADDED); 2120 filter.addDataScheme("package"); 2121 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 2122 filter = new IntentFilter(); 2123 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED); 2124 filter.addAction(Intent.ACTION_TIME_CHANGED); 2125 filter.addAction(Intent.ACTION_DATE_CHANGED); 2126 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 2127 2128 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService); 2129 2130 mSetupContentObserver = new SetupContentObserver(mHandler); 2131 2132 mUserManagerInternal.addUserRestrictionsListener(new RestrictionsListener(mContext)); 2133 } 2134 2135 /** 2136 * Creates and loads the policy data from xml. 2137 * @param userHandle the user for whom to load the policy data 2138 * @return 2139 */ 2140 @NonNull 2141 DevicePolicyData getUserData(int userHandle) { 2142 synchronized (this) { 2143 DevicePolicyData policy = mUserData.get(userHandle); 2144 if (policy == null) { 2145 policy = new DevicePolicyData(userHandle); 2146 mUserData.append(userHandle, policy); 2147 loadSettingsLocked(policy, userHandle); 2148 } 2149 return policy; 2150 } 2151 } 2152 2153 /** 2154 * Creates and loads the policy data from xml for data that is shared between 2155 * various profiles of a user. In contrast to {@link #getUserData(int)} 2156 * it allows access to data of users other than the calling user. 2157 * 2158 * This function should only be used for shared data, e.g. everything regarding 2159 * passwords and should be removed once multiple screen locks are present. 2160 * @param userHandle the user for whom to load the policy data 2161 * @return 2162 */ 2163 DevicePolicyData getUserDataUnchecked(int userHandle) { 2164 long ident = mInjector.binderClearCallingIdentity(); 2165 try { 2166 return getUserData(userHandle); 2167 } finally { 2168 mInjector.binderRestoreCallingIdentity(ident); 2169 } 2170 } 2171 2172 void removeUserData(int userHandle) { 2173 synchronized (this) { 2174 if (userHandle == UserHandle.USER_SYSTEM) { 2175 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring."); 2176 return; 2177 } 2178 mOwners.removeProfileOwner(userHandle); 2179 mOwners.writeProfileOwner(userHandle); 2180 2181 DevicePolicyData policy = mUserData.get(userHandle); 2182 if (policy != null) { 2183 mUserData.remove(userHandle); 2184 } 2185 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle), 2186 DEVICE_POLICIES_XML); 2187 policyFile.delete(); 2188 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath()); 2189 } 2190 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */); 2191 } 2192 2193 void loadOwners() { 2194 synchronized (this) { 2195 mOwners.load(); 2196 setDeviceOwnerSystemPropertyLocked(); 2197 findOwnerComponentIfNecessaryLocked(); 2198 migrateUserRestrictionsIfNecessaryLocked(); 2199 maybeSetDefaultDeviceOwnerUserRestrictionsLocked(); 2200 2201 // TODO PO may not have a class name either due to b/17652534. Address that too. 2202 2203 updateDeviceOwnerLocked(); 2204 } 2205 } 2206 2207 /** Apply default restrictions that haven't been applied to device owners yet. */ 2208 private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() { 2209 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 2210 if (deviceOwner != null) { 2211 maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(), 2212 deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner()); 2213 } 2214 } 2215 2216 /** Apply default restrictions that haven't been applied to profile owners yet. */ 2217 private void maybeSetDefaultProfileOwnerUserRestrictions() { 2218 synchronized (this) { 2219 for (final int userId : mOwners.getProfileOwnerKeys()) { 2220 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 2221 // The following restrictions used to be applied to managed profiles by different 2222 // means (via Settings or by disabling components). Now they are proper user 2223 // restrictions so we apply them to managed profile owners. Non-managed secondary 2224 // users didn't have those restrictions so we skip them to keep existing behavior. 2225 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) { 2226 continue; 2227 } 2228 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner, 2229 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 2230 ensureUnknownSourcesRestrictionForProfileOwnerLocked( 2231 userId, profileOwner, false /* newOwner */); 2232 } 2233 } 2234 } 2235 2236 /** 2237 * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the 2238 * set of restrictions for this profile owner. 2239 */ 2240 private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, 2241 ActiveAdmin profileOwner, boolean newOwner) { 2242 if (newOwner || mInjector.settingsSecureGetIntForUser( 2243 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) { 2244 profileOwner.ensureUserRestrictions().putBoolean( 2245 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true); 2246 saveUserRestrictionsLocked(userId); 2247 mInjector.settingsSecurePutIntForUser( 2248 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId); 2249 } 2250 } 2251 2252 /** 2253 * Apply default restrictions that haven't been applied to a given admin yet. 2254 */ 2255 private void maybeSetDefaultRestrictionsForAdminLocked( 2256 int userId, ActiveAdmin admin, Set<String> defaultRestrictions) { 2257 if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) { 2258 return; // The same set of default restrictions has been already applied. 2259 } 2260 Slog.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId); 2261 2262 if (VERBOSE_LOG) { 2263 Slog.d(LOG_TAG,"Default enabled restrictions: " 2264 + defaultRestrictions 2265 + ". Restrictions already enabled: " 2266 + admin.defaultEnabledRestrictionsAlreadySet); 2267 } 2268 2269 final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions); 2270 restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet); 2271 if (!restrictionsToSet.isEmpty()) { 2272 for (final String restriction : restrictionsToSet) { 2273 admin.ensureUserRestrictions().putBoolean(restriction, true); 2274 } 2275 admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet); 2276 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet); 2277 saveUserRestrictionsLocked(userId); 2278 } 2279 } 2280 2281 private void setDeviceOwnerSystemPropertyLocked() { 2282 final boolean deviceProvisioned = 2283 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0; 2284 final boolean hasDeviceOwner = mOwners.hasDeviceOwner(); 2285 // If the device is not provisioned and there is currently no device owner, do not set the 2286 // read-only system property yet, since Device owner may still be provisioned. 2287 if (!hasDeviceOwner && !deviceProvisioned) { 2288 return; 2289 } 2290 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is 2291 // always false at this point. 2292 if (StorageManager.inCryptKeeperBounce()) { 2293 return; 2294 } 2295 2296 if (!mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT, "").isEmpty()) { 2297 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?"); 2298 } else { 2299 final String value = Boolean.toString(hasDeviceOwner); 2300 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, value); 2301 Slog.i(LOG_TAG, "Set ro.device_owner property to " + value); 2302 2303 if (hasDeviceOwner && mInjector.securityLogGetLoggingEnabledProperty()) { 2304 mSecurityLogMonitor.start(); 2305 mInjector.runCryptoSelfTest(); 2306 maybePauseDeviceWideLoggingLocked(); 2307 } 2308 } 2309 } 2310 2311 private void findOwnerComponentIfNecessaryLocked() { 2312 if (!mOwners.hasDeviceOwner()) { 2313 return; 2314 } 2315 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent(); 2316 2317 if (!TextUtils.isEmpty(doComponentName.getClassName())) { 2318 return; // Already a full component name. 2319 } 2320 2321 final ComponentName doComponent = findAdminComponentWithPackageLocked( 2322 doComponentName.getPackageName(), 2323 mOwners.getDeviceOwnerUserId()); 2324 if (doComponent == null) { 2325 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin"); 2326 } else { 2327 mOwners.setDeviceOwnerWithRestrictionsMigrated( 2328 doComponent, 2329 mOwners.getDeviceOwnerName(), 2330 mOwners.getDeviceOwnerUserId(), 2331 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()); 2332 mOwners.writeDeviceOwner(); 2333 if (VERBOSE_LOG) { 2334 Log.v(LOG_TAG, "Device owner component filled in"); 2335 } 2336 } 2337 } 2338 2339 /** 2340 * We didn't use to persist user restrictions for each owners but only persisted in user 2341 * manager. 2342 */ 2343 private void migrateUserRestrictionsIfNecessaryLocked() { 2344 boolean migrated = false; 2345 // Migrate for the DO. Basically all restrictions should be considered to be set by DO, 2346 // except for the "system controlled" ones. 2347 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) { 2348 if (VERBOSE_LOG) { 2349 Log.v(LOG_TAG, "Migrating DO user restrictions"); 2350 } 2351 migrated = true; 2352 2353 // Migrate user 0 restrictions to DO. 2354 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 2355 2356 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin, 2357 /* exceptionList =*/ null, /* isDeviceOwner =*/ true); 2358 2359 // Push DO user restrictions to user manager. 2360 pushUserRestrictions(UserHandle.USER_SYSTEM); 2361 2362 mOwners.setDeviceOwnerUserRestrictionsMigrated(); 2363 } 2364 2365 // Migrate for POs. 2366 2367 // The following restrictions can be set on secondary users by the device owner, so we 2368 // assume they're not from the PO. 2369 final Set<String> secondaryUserExceptionList = Sets.newArraySet( 2370 UserManager.DISALLOW_OUTGOING_CALLS, 2371 UserManager.DISALLOW_SMS); 2372 2373 for (UserInfo ui : mUserManager.getUsers()) { 2374 final int userId = ui.id; 2375 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) { 2376 if (VERBOSE_LOG) { 2377 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId); 2378 } 2379 migrated = true; 2380 2381 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId); 2382 2383 final Set<String> exceptionList = 2384 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList; 2385 2386 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin, 2387 exceptionList, /* isDeviceOwner =*/ false); 2388 2389 // Note if a secondary user has no PO but has a DA that disables camera, we 2390 // don't get here and won't push the camera user restriction to UserManager 2391 // here. That's okay because we'll push user restrictions anyway when a user 2392 // starts. But we still do it because we want to let user manager persist 2393 // upon migration. 2394 pushUserRestrictions(userId); 2395 2396 mOwners.setProfileOwnerUserRestrictionsMigrated(userId); 2397 } 2398 } 2399 if (VERBOSE_LOG && migrated) { 2400 Log.v(LOG_TAG, "User restrictions migrated."); 2401 } 2402 } 2403 2404 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, 2405 Set<String> exceptionList, boolean isDeviceOwner) { 2406 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions( 2407 user.getIdentifier()); 2408 2409 final Bundle newBaseRestrictions = new Bundle(); 2410 final Bundle newOwnerRestrictions = new Bundle(); 2411 2412 for (String key : origRestrictions.keySet()) { 2413 if (!origRestrictions.getBoolean(key)) { 2414 continue; 2415 } 2416 final boolean canOwnerChange = isDeviceOwner 2417 ? UserRestrictionsUtils.canDeviceOwnerChange(key) 2418 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier()); 2419 2420 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) { 2421 newBaseRestrictions.putBoolean(key, true); 2422 } else { 2423 newOwnerRestrictions.putBoolean(key, true); 2424 } 2425 } 2426 2427 if (VERBOSE_LOG) { 2428 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions); 2429 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions); 2430 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions); 2431 } 2432 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(), 2433 newBaseRestrictions); 2434 2435 if (admin != null) { 2436 admin.ensureUserRestrictions().clear(); 2437 admin.ensureUserRestrictions().putAll(newOwnerRestrictions); 2438 } else { 2439 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier()); 2440 } 2441 saveSettingsLocked(user.getIdentifier()); 2442 } 2443 2444 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) { 2445 final DevicePolicyData policy = getUserData(userId); 2446 final int n = policy.mAdminList.size(); 2447 ComponentName found = null; 2448 int nFound = 0; 2449 for (int i = 0; i < n; i++) { 2450 final ActiveAdmin admin = policy.mAdminList.get(i); 2451 if (packageName.equals(admin.info.getPackageName())) { 2452 // Found! 2453 if (nFound == 0) { 2454 found = admin.info.getComponent(); 2455 } 2456 nFound++; 2457 } 2458 } 2459 if (nFound > 1) { 2460 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO."); 2461 } 2462 return found; 2463 } 2464 2465 /** 2466 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration 2467 * reminders. Clears alarm if no expirations are configured. 2468 */ 2469 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) { 2470 final long expiration = getPasswordExpirationLocked(null, userHandle, parent); 2471 final long now = System.currentTimeMillis(); 2472 final long timeToExpire = expiration - now; 2473 final long alarmTime; 2474 if (expiration == 0) { 2475 // No expirations are currently configured: Cancel alarm. 2476 alarmTime = 0; 2477 } else if (timeToExpire <= 0) { 2478 // The password has already expired: Repeat every 24 hours. 2479 alarmTime = now + MS_PER_DAY; 2480 } else { 2481 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before 2482 // the expiration time. 2483 long alarmInterval = timeToExpire % MS_PER_DAY; 2484 if (alarmInterval == 0) { 2485 alarmInterval = MS_PER_DAY; 2486 } 2487 alarmTime = now + alarmInterval; 2488 } 2489 2490 long token = mInjector.binderClearCallingIdentity(); 2491 try { 2492 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle; 2493 AlarmManager am = mInjector.getAlarmManager(); 2494 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD, 2495 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION), 2496 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT, 2497 UserHandle.of(affectedUserHandle)); 2498 am.cancel(pi); 2499 if (alarmTime != 0) { 2500 am.set(AlarmManager.RTC, alarmTime, pi); 2501 } 2502 } finally { 2503 mInjector.binderRestoreCallingIdentity(token); 2504 } 2505 } 2506 2507 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) { 2508 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who); 2509 if (admin != null 2510 && who.getPackageName().equals(admin.info.getActivityInfo().packageName) 2511 && who.getClassName().equals(admin.info.getActivityInfo().name)) { 2512 return admin; 2513 } 2514 return null; 2515 } 2516 2517 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) { 2518 if (parent) { 2519 enforceManagedProfile(userHandle, "call APIs on the parent profile"); 2520 } 2521 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2522 if (admin != null && parent) { 2523 admin = admin.getParentActiveAdmin(); 2524 } 2525 return admin; 2526 } 2527 2528 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy) 2529 throws SecurityException { 2530 final int callingUid = mInjector.binderGetCallingUid(); 2531 2532 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid); 2533 if (result != null) { 2534 return result; 2535 } 2536 2537 if (who != null) { 2538 final int userId = UserHandle.getUserId(callingUid); 2539 final DevicePolicyData policy = getUserData(userId); 2540 ActiveAdmin admin = policy.mAdminMap.get(who); 2541 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) { 2542 throw new SecurityException("Admin " + admin.info.getComponent() 2543 + " does not own the device"); 2544 } 2545 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) { 2546 throw new SecurityException("Admin " + admin.info.getComponent() 2547 + " does not own the profile"); 2548 } 2549 throw new SecurityException("Admin " + admin.info.getComponent() 2550 + " did not specify uses-policy for: " 2551 + admin.info.getTagForPolicy(reqPolicy)); 2552 } else { 2553 throw new SecurityException("No active admin owned by uid " 2554 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy); 2555 } 2556 } 2557 2558 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent) 2559 throws SecurityException { 2560 if (parent) { 2561 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), 2562 "call APIs on the parent profile"); 2563 } 2564 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy); 2565 return parent ? admin.getParentActiveAdmin() : admin; 2566 } 2567 /** 2568 * Find the admin for the component and userId bit of the uid, then check 2569 * the admin's uid matches the uid. 2570 */ 2571 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) { 2572 final int userId = UserHandle.getUserId(uid); 2573 final DevicePolicyData policy = getUserData(userId); 2574 ActiveAdmin admin = policy.mAdminMap.get(who); 2575 if (admin == null) { 2576 throw new SecurityException("No active admin " + who); 2577 } 2578 if (admin.getUid() != uid) { 2579 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2580 } 2581 return admin; 2582 } 2583 2584 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, 2585 int uid) { 2586 // Try to find an admin which can use reqPolicy 2587 final int userId = UserHandle.getUserId(uid); 2588 final DevicePolicyData policy = getUserData(userId); 2589 if (who != null) { 2590 ActiveAdmin admin = policy.mAdminMap.get(who); 2591 if (admin == null) { 2592 throw new SecurityException("No active admin " + who); 2593 } 2594 if (admin.getUid() != uid) { 2595 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2596 } 2597 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) { 2598 return admin; 2599 } 2600 } else { 2601 for (ActiveAdmin admin : policy.mAdminList) { 2602 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, 2603 userId)) { 2604 return admin; 2605 } 2606 } 2607 } 2608 2609 return null; 2610 } 2611 2612 @VisibleForTesting 2613 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, 2614 int userId) { 2615 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId); 2616 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId); 2617 2618 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) { 2619 return ownsDevice; 2620 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) { 2621 // DO always has the PO power. 2622 return ownsDevice || ownsProfile; 2623 } else { 2624 return admin.info.usesPolicy(reqPolicy); 2625 } 2626 } 2627 2628 void sendAdminCommandLocked(ActiveAdmin admin, String action) { 2629 sendAdminCommandLocked(admin, action, null); 2630 } 2631 2632 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) { 2633 sendAdminCommandLocked(admin, action, null, result); 2634 } 2635 2636 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2637 BroadcastReceiver result) { 2638 sendAdminCommandLocked(admin, action, adminExtras, result, false); 2639 } 2640 2641 /** 2642 * Send an update to one specific admin, get notified when that admin returns a result. 2643 * 2644 * @return whether the broadcast was successfully sent 2645 */ 2646 boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2647 BroadcastReceiver result, boolean inForeground) { 2648 Intent intent = new Intent(action); 2649 intent.setComponent(admin.info.getComponent()); 2650 if (UserManager.isDeviceInDemoMode(mContext)) { 2651 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2652 } 2653 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) { 2654 intent.putExtra("expiration", admin.passwordExpirationDate); 2655 } 2656 if (inForeground) { 2657 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2658 } 2659 if (adminExtras != null) { 2660 intent.putExtras(adminExtras); 2661 } 2662 if (mInjector.getPackageManager().queryBroadcastReceiversAsUser( 2663 intent, 2664 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, 2665 admin.getUserHandle()).isEmpty()) { 2666 return false; 2667 } 2668 if (result != null) { 2669 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(), 2670 null, result, mHandler, Activity.RESULT_OK, null, null); 2671 } else { 2672 mContext.sendBroadcastAsUser(intent, admin.getUserHandle()); 2673 } 2674 return true; 2675 } 2676 2677 /** 2678 * Send an update to all admins of a user that enforce a specified policy. 2679 */ 2680 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) { 2681 final DevicePolicyData policy = getUserData(userHandle); 2682 final int count = policy.mAdminList.size(); 2683 for (int i = 0; i < count; i++) { 2684 final ActiveAdmin admin = policy.mAdminList.get(i); 2685 if (admin.info.usesPolicy(reqPolicy)) { 2686 sendAdminCommandLocked(admin, action, adminExtras, null); 2687 } 2688 } 2689 } 2690 2691 /** 2692 * Send an update intent to all admins of a user and its profiles. Only send to admins that 2693 * enforce a specified policy. 2694 */ 2695 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy, 2696 int userHandle, Bundle adminExtras) { 2697 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle); 2698 for (int profileId : profileIds) { 2699 sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras); 2700 } 2701 } 2702 2703 /** 2704 * Sends a broadcast to each profile that share the password unlock with the given user id. 2705 */ 2706 private void sendAdminCommandForLockscreenPoliciesLocked( 2707 String action, int reqPolicy, int userHandle) { 2708 final Bundle extras = new Bundle(); 2709 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 2710 if (isSeparateProfileChallengeEnabled(userHandle)) { 2711 sendAdminCommandLocked(action, reqPolicy, userHandle, extras); 2712 } else { 2713 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras); 2714 } 2715 } 2716 2717 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) { 2718 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 2719 DevicePolicyData policy = getUserData(userHandle); 2720 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) { 2721 policy.mRemovingAdmins.add(adminReceiver); 2722 sendAdminCommandLocked(admin, 2723 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED, 2724 new BroadcastReceiver() { 2725 @Override 2726 public void onReceive(Context context, Intent intent) { 2727 removeAdminArtifacts(adminReceiver, userHandle); 2728 removePackageIfRequired(adminReceiver.getPackageName(), userHandle); 2729 } 2730 }); 2731 } 2732 } 2733 2734 2735 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle, 2736 boolean throwForMissingPermission) { 2737 if (!mHasFeature) { 2738 return null; 2739 } 2740 enforceFullCrossUsersPermission(userHandle); 2741 ActivityInfo ai = null; 2742 try { 2743 ai = mIPackageManager.getReceiverInfo(adminName, 2744 PackageManager.GET_META_DATA | 2745 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS | 2746 PackageManager.MATCH_DIRECT_BOOT_AWARE | 2747 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle); 2748 } catch (RemoteException e) { 2749 // shouldn't happen. 2750 } 2751 if (ai == null) { 2752 throw new IllegalArgumentException("Unknown admin: " + adminName); 2753 } 2754 2755 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) { 2756 final String message = "DeviceAdminReceiver " + adminName + " must be protected with " 2757 + permission.BIND_DEVICE_ADMIN; 2758 Slog.w(LOG_TAG, message); 2759 if (throwForMissingPermission && 2760 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) { 2761 throw new IllegalArgumentException(message); 2762 } 2763 } 2764 2765 try { 2766 return new DeviceAdminInfo(mContext, ai); 2767 } catch (XmlPullParserException | IOException e) { 2768 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName, 2769 e); 2770 return null; 2771 } 2772 } 2773 2774 private File getPolicyFileDirectory(@UserIdInt int userId) { 2775 return userId == UserHandle.USER_SYSTEM 2776 ? new File(mInjector.getDevicePolicyFilePathForSystemUser()) 2777 : mInjector.environmentGetUserSystemDirectory(userId); 2778 } 2779 2780 private JournaledFile makeJournaledFile(@UserIdInt int userId) { 2781 final String base = new File(getPolicyFileDirectory(userId), DEVICE_POLICIES_XML) 2782 .getAbsolutePath(); 2783 if (VERBOSE_LOG) { 2784 Log.v(LOG_TAG, "Opening " + base); 2785 } 2786 return new JournaledFile(new File(base), new File(base + ".tmp")); 2787 } 2788 2789 private void saveSettingsLocked(int userHandle) { 2790 DevicePolicyData policy = getUserData(userHandle); 2791 JournaledFile journal = makeJournaledFile(userHandle); 2792 FileOutputStream stream = null; 2793 try { 2794 stream = new FileOutputStream(journal.chooseForWrite(), false); 2795 XmlSerializer out = new FastXmlSerializer(); 2796 out.setOutput(stream, StandardCharsets.UTF_8.name()); 2797 out.startDocument(null, true); 2798 2799 out.startTag(null, "policies"); 2800 if (policy.mRestrictionsProvider != null) { 2801 out.attribute(null, ATTR_PERMISSION_PROVIDER, 2802 policy.mRestrictionsProvider.flattenToString()); 2803 } 2804 if (policy.mUserSetupComplete) { 2805 out.attribute(null, ATTR_SETUP_COMPLETE, 2806 Boolean.toString(true)); 2807 } 2808 if (policy.mPaired) { 2809 out.attribute(null, ATTR_DEVICE_PAIRED, 2810 Boolean.toString(true)); 2811 } 2812 if (policy.mDeviceProvisioningConfigApplied) { 2813 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED, 2814 Boolean.toString(true)); 2815 } 2816 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) { 2817 out.attribute(null, ATTR_PROVISIONING_STATE, 2818 Integer.toString(policy.mUserProvisioningState)); 2819 } 2820 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) { 2821 out.attribute(null, ATTR_PERMISSION_POLICY, 2822 Integer.toString(policy.mPermissionPolicy)); 2823 } 2824 2825 // Serialize delegations. 2826 for (int i = 0; i < policy.mDelegationMap.size(); ++i) { 2827 final String delegatePackage = policy.mDelegationMap.keyAt(i); 2828 final List<String> scopes = policy.mDelegationMap.valueAt(i); 2829 2830 // Every "delegation" tag serializes the information of one delegate-scope pair. 2831 for (String scope : scopes) { 2832 out.startTag(null, "delegation"); 2833 out.attribute(null, "delegatePackage", delegatePackage); 2834 out.attribute(null, "scope", scope); 2835 out.endTag(null, "delegation"); 2836 } 2837 } 2838 2839 final int N = policy.mAdminList.size(); 2840 for (int i=0; i<N; i++) { 2841 ActiveAdmin ap = policy.mAdminList.get(i); 2842 if (ap != null) { 2843 out.startTag(null, "admin"); 2844 out.attribute(null, "name", ap.info.getComponent().flattenToString()); 2845 ap.writeToXml(out); 2846 out.endTag(null, "admin"); 2847 } 2848 } 2849 2850 if (policy.mPasswordOwner >= 0) { 2851 out.startTag(null, "password-owner"); 2852 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner)); 2853 out.endTag(null, "password-owner"); 2854 } 2855 2856 if (policy.mFailedPasswordAttempts != 0) { 2857 out.startTag(null, "failed-password-attempts"); 2858 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts)); 2859 out.endTag(null, "failed-password-attempts"); 2860 } 2861 2862 // For FDE devices only, we save this flag so we can report on password sufficiency 2863 // before the user enters their password for the first time after a reboot. For 2864 // security reasons, we don't want to store the full set of active password metrics. 2865 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 2866 out.startTag(null, TAG_PASSWORD_VALIDITY); 2867 out.attribute(null, ATTR_VALUE, 2868 Boolean.toString(policy.mPasswordValidAtLastCheckpoint)); 2869 out.endTag(null, TAG_PASSWORD_VALIDITY); 2870 } 2871 2872 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) { 2873 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 2874 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i)); 2875 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 2876 } 2877 2878 for (int i=0; i<policy.mLockTaskPackages.size(); i++) { 2879 String component = policy.mLockTaskPackages.get(i); 2880 out.startTag(null, TAG_LOCK_TASK_COMPONENTS); 2881 out.attribute(null, "name", component); 2882 out.endTag(null, TAG_LOCK_TASK_COMPONENTS); 2883 } 2884 2885 if (policy.mLockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) { 2886 out.startTag(null, TAG_LOCK_TASK_FEATURES); 2887 out.attribute(null, ATTR_VALUE, Integer.toString(policy.mLockTaskFeatures)); 2888 out.endTag(null, TAG_LOCK_TASK_FEATURES); 2889 } 2890 2891 if (policy.mStatusBarDisabled) { 2892 out.startTag(null, TAG_STATUS_BAR); 2893 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled)); 2894 out.endTag(null, TAG_STATUS_BAR); 2895 } 2896 2897 if (policy.doNotAskCredentialsOnBoot) { 2898 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 2899 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 2900 } 2901 2902 for (String id : policy.mAffiliationIds) { 2903 out.startTag(null, TAG_AFFILIATION_ID); 2904 out.attribute(null, ATTR_ID, id); 2905 out.endTag(null, TAG_AFFILIATION_ID); 2906 } 2907 2908 if (policy.mLastSecurityLogRetrievalTime >= 0) { 2909 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 2910 out.attribute(null, ATTR_VALUE, 2911 Long.toString(policy.mLastSecurityLogRetrievalTime)); 2912 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 2913 } 2914 2915 if (policy.mLastBugReportRequestTime >= 0) { 2916 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST); 2917 out.attribute(null, ATTR_VALUE, 2918 Long.toString(policy.mLastBugReportRequestTime)); 2919 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST); 2920 } 2921 2922 if (policy.mLastNetworkLogsRetrievalTime >= 0) { 2923 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 2924 out.attribute(null, ATTR_VALUE, 2925 Long.toString(policy.mLastNetworkLogsRetrievalTime)); 2926 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 2927 } 2928 2929 if (policy.mAdminBroadcastPending) { 2930 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING); 2931 out.attribute(null, ATTR_VALUE, 2932 Boolean.toString(policy.mAdminBroadcastPending)); 2933 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING); 2934 } 2935 2936 if (policy.mInitBundle != null) { 2937 out.startTag(null, TAG_INITIALIZATION_BUNDLE); 2938 policy.mInitBundle.saveToXml(out); 2939 out.endTag(null, TAG_INITIALIZATION_BUNDLE); 2940 } 2941 2942 if (policy.mPasswordTokenHandle != 0) { 2943 out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE); 2944 out.attribute(null, ATTR_VALUE, 2945 Long.toString(policy.mPasswordTokenHandle)); 2946 out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE); 2947 } 2948 2949 if (policy.mCurrentInputMethodSet) { 2950 out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET); 2951 out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET); 2952 } 2953 2954 for (final String cert : policy.mOwnerInstalledCaCerts) { 2955 out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT); 2956 out.attribute(null, ATTR_ALIAS, cert); 2957 out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT); 2958 } 2959 2960 out.endTag(null, "policies"); 2961 2962 out.endDocument(); 2963 stream.flush(); 2964 FileUtils.sync(stream); 2965 stream.close(); 2966 journal.commit(); 2967 sendChangedNotification(userHandle); 2968 } catch (XmlPullParserException | IOException e) { 2969 Slog.w(LOG_TAG, "failed writing file", e); 2970 try { 2971 if (stream != null) { 2972 stream.close(); 2973 } 2974 } catch (IOException ex) { 2975 // Ignore 2976 } 2977 journal.rollback(); 2978 } 2979 } 2980 2981 private void sendChangedNotification(int userHandle) { 2982 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 2983 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 2984 long ident = mInjector.binderClearCallingIdentity(); 2985 try { 2986 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle)); 2987 } finally { 2988 mInjector.binderRestoreCallingIdentity(ident); 2989 } 2990 } 2991 2992 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) { 2993 JournaledFile journal = makeJournaledFile(userHandle); 2994 FileInputStream stream = null; 2995 File file = journal.chooseForRead(); 2996 boolean needsRewrite = false; 2997 try { 2998 stream = new FileInputStream(file); 2999 XmlPullParser parser = Xml.newPullParser(); 3000 parser.setInput(stream, StandardCharsets.UTF_8.name()); 3001 3002 int type; 3003 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 3004 && type != XmlPullParser.START_TAG) { 3005 } 3006 String tag = parser.getName(); 3007 if (!"policies".equals(tag)) { 3008 throw new XmlPullParserException( 3009 "Settings do not start with policies tag: found " + tag); 3010 } 3011 3012 // Extract the permission provider component name if available 3013 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER); 3014 if (permissionProvider != null) { 3015 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider); 3016 } 3017 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE); 3018 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) { 3019 policy.mUserSetupComplete = true; 3020 } 3021 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED); 3022 if (paired != null && Boolean.toString(true).equals(paired)) { 3023 policy.mPaired = true; 3024 } 3025 String deviceProvisioningConfigApplied = parser.getAttributeValue(null, 3026 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED); 3027 if (deviceProvisioningConfigApplied != null 3028 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) { 3029 policy.mDeviceProvisioningConfigApplied = true; 3030 } 3031 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE); 3032 if (!TextUtils.isEmpty(provisioningState)) { 3033 policy.mUserProvisioningState = Integer.parseInt(provisioningState); 3034 } 3035 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY); 3036 if (!TextUtils.isEmpty(permissionPolicy)) { 3037 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy); 3038 } 3039 // Check for delegation compatibility with pre-O. 3040 // TODO(edmanp) remove in P. 3041 { 3042 final String certDelegate = parser.getAttributeValue(null, 3043 ATTR_DELEGATED_CERT_INSTALLER); 3044 if (certDelegate != null) { 3045 List<String> scopes = policy.mDelegationMap.get(certDelegate); 3046 if (scopes == null) { 3047 scopes = new ArrayList<>(); 3048 policy.mDelegationMap.put(certDelegate, scopes); 3049 } 3050 if (!scopes.contains(DELEGATION_CERT_INSTALL)) { 3051 scopes.add(DELEGATION_CERT_INSTALL); 3052 needsRewrite = true; 3053 } 3054 } 3055 final String appRestrictionsDelegate = parser.getAttributeValue(null, 3056 ATTR_APPLICATION_RESTRICTIONS_MANAGER); 3057 if (appRestrictionsDelegate != null) { 3058 List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate); 3059 if (scopes == null) { 3060 scopes = new ArrayList<>(); 3061 policy.mDelegationMap.put(appRestrictionsDelegate, scopes); 3062 } 3063 if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) { 3064 scopes.add(DELEGATION_APP_RESTRICTIONS); 3065 needsRewrite = true; 3066 } 3067 } 3068 } 3069 3070 type = parser.next(); 3071 int outerDepth = parser.getDepth(); 3072 policy.mLockTaskPackages.clear(); 3073 policy.mAdminList.clear(); 3074 policy.mAdminMap.clear(); 3075 policy.mAffiliationIds.clear(); 3076 policy.mOwnerInstalledCaCerts.clear(); 3077 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 3078 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 3079 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 3080 continue; 3081 } 3082 tag = parser.getName(); 3083 if ("admin".equals(tag)) { 3084 String name = parser.getAttributeValue(null, "name"); 3085 try { 3086 DeviceAdminInfo dai = findAdmin( 3087 ComponentName.unflattenFromString(name), userHandle, 3088 /* throwForMissingPermission= */ false); 3089 if (VERBOSE_LOG 3090 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid) 3091 != userHandle)) { 3092 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid " 3093 + dai.getActivityInfo().applicationInfo.uid + " for user " 3094 + userHandle); 3095 } 3096 if (dai != null) { 3097 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false); 3098 ap.readFromXml(parser); 3099 policy.mAdminMap.put(ap.info.getComponent(), ap); 3100 } 3101 } catch (RuntimeException e) { 3102 Slog.w(LOG_TAG, "Failed loading admin " + name, e); 3103 } 3104 } else if ("delegation".equals(tag)) { 3105 // Parse delegation info. 3106 final String delegatePackage = parser.getAttributeValue(null, 3107 "delegatePackage"); 3108 final String scope = parser.getAttributeValue(null, "scope"); 3109 3110 // Get a reference to the scopes list for the delegatePackage. 3111 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 3112 // Or make a new list if none was found. 3113 if (scopes == null) { 3114 scopes = new ArrayList<>(); 3115 policy.mDelegationMap.put(delegatePackage, scopes); 3116 } 3117 // Add the new scope to the list of delegatePackage if it's not already there. 3118 if (!scopes.contains(scope)) { 3119 scopes.add(scope); 3120 } 3121 } else if ("failed-password-attempts".equals(tag)) { 3122 policy.mFailedPasswordAttempts = Integer.parseInt( 3123 parser.getAttributeValue(null, "value")); 3124 } else if ("password-owner".equals(tag)) { 3125 policy.mPasswordOwner = Integer.parseInt( 3126 parser.getAttributeValue(null, "value")); 3127 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) { 3128 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME)); 3129 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) { 3130 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name")); 3131 } else if (TAG_LOCK_TASK_FEATURES.equals(tag)) { 3132 policy.mLockTaskFeatures = Integer.parseInt( 3133 parser.getAttributeValue(null, ATTR_VALUE)); 3134 } else if (TAG_STATUS_BAR.equals(tag)) { 3135 policy.mStatusBarDisabled = Boolean.parseBoolean( 3136 parser.getAttributeValue(null, ATTR_DISABLED)); 3137 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) { 3138 policy.doNotAskCredentialsOnBoot = true; 3139 } else if (TAG_AFFILIATION_ID.equals(tag)) { 3140 policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID)); 3141 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) { 3142 policy.mLastSecurityLogRetrievalTime = Long.parseLong( 3143 parser.getAttributeValue(null, ATTR_VALUE)); 3144 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) { 3145 policy.mLastBugReportRequestTime = Long.parseLong( 3146 parser.getAttributeValue(null, ATTR_VALUE)); 3147 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) { 3148 policy.mLastNetworkLogsRetrievalTime = Long.parseLong( 3149 parser.getAttributeValue(null, ATTR_VALUE)); 3150 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) { 3151 String pending = parser.getAttributeValue(null, ATTR_VALUE); 3152 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending); 3153 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) { 3154 policy.mInitBundle = PersistableBundle.restoreFromXml(parser); 3155 } else if ("active-password".equals(tag)) { 3156 // Remove password metrics from saved settings, as we no longer wish to store 3157 // these on disk 3158 needsRewrite = true; 3159 } else if (TAG_PASSWORD_VALIDITY.equals(tag)) { 3160 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 3161 // This flag is only used for FDE devices 3162 policy.mPasswordValidAtLastCheckpoint = Boolean.parseBoolean( 3163 parser.getAttributeValue(null, ATTR_VALUE)); 3164 } 3165 } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) { 3166 policy.mPasswordTokenHandle = Long.parseLong( 3167 parser.getAttributeValue(null, ATTR_VALUE)); 3168 } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) { 3169 policy.mCurrentInputMethodSet = true; 3170 } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) { 3171 policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS)); 3172 } else { 3173 Slog.w(LOG_TAG, "Unknown tag: " + tag); 3174 XmlUtils.skipCurrentTag(parser); 3175 } 3176 } 3177 } catch (FileNotFoundException e) { 3178 // Don't be noisy, this is normal if we haven't defined any policies. 3179 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException 3180 | IndexOutOfBoundsException e) { 3181 Slog.w(LOG_TAG, "failed parsing " + file, e); 3182 } 3183 try { 3184 if (stream != null) { 3185 stream.close(); 3186 } 3187 } catch (IOException e) { 3188 // Ignore 3189 } 3190 3191 // Generate a list of admins from the admin map 3192 policy.mAdminList.addAll(policy.mAdminMap.values()); 3193 3194 // Might need to upgrade the file by rewriting it 3195 if (needsRewrite) { 3196 saveSettingsLocked(userHandle); 3197 } 3198 3199 validatePasswordOwnerLocked(policy); 3200 updateMaximumTimeToLockLocked(userHandle); 3201 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle); 3202 updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle); 3203 if (policy.mStatusBarDisabled) { 3204 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle); 3205 } 3206 } 3207 3208 private void updateLockTaskPackagesLocked(List<String> packages, int userId) { 3209 long ident = mInjector.binderClearCallingIdentity(); 3210 try { 3211 mInjector.getIActivityManager() 3212 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()])); 3213 } catch (RemoteException e) { 3214 // Not gonna happen. 3215 } finally { 3216 mInjector.binderRestoreCallingIdentity(ident); 3217 } 3218 } 3219 3220 private void updateLockTaskFeaturesLocked(int flags, int userId) { 3221 long ident = mInjector.binderClearCallingIdentity(); 3222 try { 3223 mInjector.getIActivityManager() 3224 .updateLockTaskFeatures(userId, flags); 3225 } catch (RemoteException e) { 3226 // Not gonna happen. 3227 } finally { 3228 mInjector.binderRestoreCallingIdentity(ident); 3229 } 3230 } 3231 3232 private void updateDeviceOwnerLocked() { 3233 long ident = mInjector.binderClearCallingIdentity(); 3234 try { 3235 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the 3236 // user id and also protect all other DAs too. 3237 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 3238 if (deviceOwnerComponent != null) { 3239 mInjector.getIActivityManager() 3240 .updateDeviceOwner(deviceOwnerComponent.getPackageName()); 3241 } 3242 } catch (RemoteException e) { 3243 // Not gonna happen. 3244 } finally { 3245 mInjector.binderRestoreCallingIdentity(ident); 3246 } 3247 } 3248 3249 static void validateQualityConstant(int quality) { 3250 switch (quality) { 3251 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED: 3252 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK: 3253 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: 3254 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: 3255 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX: 3256 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: 3257 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: 3258 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX: 3259 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED: 3260 return; 3261 } 3262 throw new IllegalArgumentException("Invalid quality constant: 0x" 3263 + Integer.toHexString(quality)); 3264 } 3265 3266 void validatePasswordOwnerLocked(DevicePolicyData policy) { 3267 if (policy.mPasswordOwner >= 0) { 3268 boolean haveOwner = false; 3269 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 3270 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) { 3271 haveOwner = true; 3272 break; 3273 } 3274 } 3275 if (!haveOwner) { 3276 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner 3277 + " no longer active; disabling"); 3278 policy.mPasswordOwner = -1; 3279 } 3280 } 3281 } 3282 3283 @VisibleForTesting 3284 @Override 3285 void systemReady(int phase) { 3286 if (!mHasFeature) { 3287 return; 3288 } 3289 switch (phase) { 3290 case SystemService.PHASE_LOCK_SETTINGS_READY: 3291 onLockSettingsReady(); 3292 loadAdminDataAsync(); 3293 break; 3294 case SystemService.PHASE_BOOT_COMPLETED: 3295 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this. 3296 break; 3297 } 3298 } 3299 3300 private void onLockSettingsReady() { 3301 getUserData(UserHandle.USER_SYSTEM); 3302 loadOwners(); 3303 cleanUpOldUsers(); 3304 maybeSetDefaultProfileOwnerUserRestrictions(); 3305 handleStartUser(UserHandle.USER_SYSTEM); 3306 maybeLogStart(); 3307 3308 // Register an observer for watching for user setup complete and settings changes. 3309 mSetupContentObserver.register(); 3310 // Initialize the user setup state, to handle the upgrade case. 3311 updateUserSetupCompleteAndPaired(); 3312 3313 List<String> packageList; 3314 synchronized (this) { 3315 packageList = getKeepUninstalledPackagesLocked(); 3316 } 3317 if (packageList != null) { 3318 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 3319 } 3320 3321 synchronized (this) { 3322 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 3323 if (deviceOwner != null) { 3324 // Push the force-ephemeral-users policy to the user manager. 3325 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers); 3326 3327 // Update user switcher message to activity manager. 3328 ActivityManagerInternal activityManagerInternal = 3329 mInjector.getActivityManagerInternal(); 3330 activityManagerInternal.setSwitchingFromSystemUserMessage( 3331 deviceOwner.startUserSessionMessage); 3332 activityManagerInternal.setSwitchingToSystemUserMessage( 3333 deviceOwner.endUserSessionMessage); 3334 } 3335 3336 revertTransferOwnershipIfNecessaryLocked(); 3337 } 3338 } 3339 3340 private void revertTransferOwnershipIfNecessaryLocked() { 3341 if (!mTransferOwnershipMetadataManager.metadataFileExists()) { 3342 return; 3343 } 3344 Slog.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer."); 3345 final TransferOwnershipMetadataManager.Metadata metadata = 3346 mTransferOwnershipMetadataManager.loadMetadataFile(); 3347 // Revert transfer 3348 if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) { 3349 transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent, 3350 metadata.userId); 3351 deleteTransferOwnershipMetadataFileLocked(); 3352 deleteTransferOwnershipBundleLocked(metadata.userId); 3353 } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) { 3354 transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent, 3355 metadata.userId); 3356 deleteTransferOwnershipMetadataFileLocked(); 3357 deleteTransferOwnershipBundleLocked(metadata.userId); 3358 } 3359 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true); 3360 } 3361 3362 private void maybeLogStart() { 3363 if (!SecurityLog.isLoggingEnabled()) { 3364 return; 3365 } 3366 final String verifiedBootState = 3367 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate"); 3368 final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode"); 3369 SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode); 3370 } 3371 3372 private void ensureDeviceOwnerUserStarted() { 3373 final int userId; 3374 synchronized (this) { 3375 if (!mOwners.hasDeviceOwner()) { 3376 return; 3377 } 3378 userId = mOwners.getDeviceOwnerUserId(); 3379 } 3380 if (VERBOSE_LOG) { 3381 Log.v(LOG_TAG, "Starting non-system DO user: " + userId); 3382 } 3383 if (userId != UserHandle.USER_SYSTEM) { 3384 try { 3385 mInjector.getIActivityManager().startUserInBackground(userId); 3386 3387 // STOPSHIP Prevent the DO user from being killed. 3388 3389 } catch (RemoteException e) { 3390 Slog.w(LOG_TAG, "Exception starting user", e); 3391 } 3392 } 3393 } 3394 3395 @Override 3396 void handleStartUser(int userId) { 3397 updateScreenCaptureDisabledInWindowManager(userId, 3398 getScreenCaptureDisabled(null, userId)); 3399 pushUserRestrictions(userId); 3400 3401 startOwnerService(userId, "start-user"); 3402 } 3403 3404 @Override 3405 void handleUnlockUser(int userId) { 3406 startOwnerService(userId, "unlock-user"); 3407 } 3408 3409 @Override 3410 void handleStopUser(int userId) { 3411 stopOwnerService(userId, "stop-user"); 3412 } 3413 3414 private void startOwnerService(int userId, String actionForLog) { 3415 final ComponentName owner = getOwnerComponent(userId); 3416 if (owner != null) { 3417 mDeviceAdminServiceController.startServiceForOwner( 3418 owner.getPackageName(), userId, actionForLog); 3419 } 3420 } 3421 3422 private void stopOwnerService(int userId, String actionForLog) { 3423 mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog); 3424 } 3425 3426 private void cleanUpOldUsers() { 3427 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled 3428 // before reboot 3429 Set<Integer> usersWithProfileOwners; 3430 Set<Integer> usersWithData; 3431 synchronized(this) { 3432 usersWithProfileOwners = mOwners.getProfileOwnerKeys(); 3433 usersWithData = new ArraySet<>(); 3434 for (int i = 0; i < mUserData.size(); i++) { 3435 usersWithData.add(mUserData.keyAt(i)); 3436 } 3437 } 3438 List<UserInfo> allUsers = mUserManager.getUsers(); 3439 3440 Set<Integer> deletedUsers = new ArraySet<>(); 3441 deletedUsers.addAll(usersWithProfileOwners); 3442 deletedUsers.addAll(usersWithData); 3443 for (UserInfo userInfo : allUsers) { 3444 deletedUsers.remove(userInfo.id); 3445 } 3446 for (Integer userId : deletedUsers) { 3447 removeUserData(userId); 3448 } 3449 } 3450 3451 private void handlePasswordExpirationNotification(int userHandle) { 3452 final Bundle adminExtras = new Bundle(); 3453 adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 3454 3455 synchronized (this) { 3456 final long now = System.currentTimeMillis(); 3457 3458 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 3459 userHandle, /* parent */ false); 3460 final int N = admins.size(); 3461 for (int i = 0; i < N; i++) { 3462 ActiveAdmin admin = admins.get(i); 3463 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD) 3464 && admin.passwordExpirationTimeout > 0L 3465 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS 3466 && admin.passwordExpirationDate > 0L) { 3467 sendAdminCommandLocked(admin, 3468 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null); 3469 } 3470 } 3471 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false); 3472 } 3473 } 3474 3475 /** 3476 * Clean up internal state when the set of installed trusted CA certificates changes. 3477 * 3478 * @param userHandle user to check for. This must be a real user and not, for example, 3479 * {@link UserHandle#ALL}. 3480 * @param installedCertificates the full set of certificate authorities currently installed for 3481 * {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will 3482 * correspond to some subset of this. 3483 */ 3484 protected void onInstalledCertificatesChanged(final UserHandle userHandle, 3485 final @NonNull Collection<String> installedCertificates) { 3486 if (!mHasFeature) { 3487 return; 3488 } 3489 enforceManageUsers(); 3490 3491 synchronized (this) { 3492 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3493 3494 boolean changed = false; 3495 changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates); 3496 changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates); 3497 if (changed) { 3498 saveSettingsLocked(userHandle.getIdentifier()); 3499 } 3500 } 3501 } 3502 3503 /** 3504 * Internal method used by {@link CertificateMonitor}. 3505 */ 3506 protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) { 3507 if (!mHasFeature) { 3508 return Collections.<String> emptySet(); 3509 } 3510 synchronized (this) { 3511 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3512 return policy.mAcceptedCaCertificates; 3513 } 3514 } 3515 3516 /** 3517 * @param adminReceiver The admin to add 3518 * @param refreshing true = update an active admin, no error 3519 */ 3520 @Override 3521 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) { 3522 if (!mHasFeature) { 3523 return; 3524 } 3525 setActiveAdmin(adminReceiver, refreshing, userHandle, null); 3526 } 3527 3528 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, 3529 Bundle onEnableData) { 3530 mContext.enforceCallingOrSelfPermission( 3531 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 3532 enforceFullCrossUsersPermission(userHandle); 3533 3534 DevicePolicyData policy = getUserData(userHandle); 3535 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle, 3536 /* throwForMissingPermission= */ true); 3537 synchronized (this) { 3538 checkActiveAdminPrecondition(adminReceiver, info, policy); 3539 long ident = mInjector.binderClearCallingIdentity(); 3540 try { 3541 final ActiveAdmin existingAdmin 3542 = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3543 if (!refreshing && existingAdmin != null) { 3544 throw new IllegalArgumentException("Admin is already added"); 3545 } 3546 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false); 3547 newAdmin.testOnlyAdmin = 3548 (existingAdmin != null) ? existingAdmin.testOnlyAdmin 3549 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle); 3550 policy.mAdminMap.put(adminReceiver, newAdmin); 3551 int replaceIndex = -1; 3552 final int N = policy.mAdminList.size(); 3553 for (int i=0; i < N; i++) { 3554 ActiveAdmin oldAdmin = policy.mAdminList.get(i); 3555 if (oldAdmin.info.getComponent().equals(adminReceiver)) { 3556 replaceIndex = i; 3557 break; 3558 } 3559 } 3560 if (replaceIndex == -1) { 3561 policy.mAdminList.add(newAdmin); 3562 enableIfNecessary(info.getPackageName(), userHandle); 3563 mUsageStatsManagerInternal.onActiveAdminAdded( 3564 adminReceiver.getPackageName(), userHandle); 3565 } else { 3566 policy.mAdminList.set(replaceIndex, newAdmin); 3567 } 3568 saveSettingsLocked(userHandle); 3569 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3570 onEnableData, null); 3571 } finally { 3572 mInjector.binderRestoreCallingIdentity(ident); 3573 } 3574 } 3575 } 3576 3577 private void loadAdminDataAsync() { 3578 mInjector.postOnSystemServerInitThreadPool(() -> { 3579 pushActiveAdminPackages(); 3580 mUsageStatsManagerInternal.onAdminDataAvailable(); 3581 pushAllMeteredRestrictedPackages(); 3582 mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable(); 3583 }); 3584 } 3585 3586 private void pushActiveAdminPackages() { 3587 synchronized (this) { 3588 final List<UserInfo> users = mUserManager.getUsers(); 3589 for (int i = users.size() - 1; i >= 0; --i) { 3590 final int userId = users.get(i).id; 3591 mUsageStatsManagerInternal.setActiveAdminApps( 3592 getActiveAdminPackagesLocked(userId), userId); 3593 } 3594 } 3595 } 3596 3597 private void pushAllMeteredRestrictedPackages() { 3598 synchronized (this) { 3599 final List<UserInfo> users = mUserManager.getUsers(); 3600 for (int i = users.size() - 1; i >= 0; --i) { 3601 final int userId = users.get(i).id; 3602 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync( 3603 getMeteredDisabledPackagesLocked(userId), userId); 3604 } 3605 } 3606 } 3607 3608 private void pushActiveAdminPackagesLocked(int userId) { 3609 mUsageStatsManagerInternal.setActiveAdminApps( 3610 getActiveAdminPackagesLocked(userId), userId); 3611 } 3612 3613 private Set<String> getActiveAdminPackagesLocked(int userId) { 3614 final DevicePolicyData policy = getUserData(userId); 3615 Set<String> adminPkgs = null; 3616 for (int i = policy.mAdminList.size() - 1; i >= 0; --i) { 3617 final String pkgName = policy.mAdminList.get(i).info.getPackageName(); 3618 if (adminPkgs == null) { 3619 adminPkgs = new ArraySet<>(); 3620 } 3621 adminPkgs.add(pkgName); 3622 } 3623 return adminPkgs; 3624 } 3625 3626 private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver, 3627 ComponentName outgoingReceiver, int userHandle) { 3628 final DevicePolicyData policy = getUserData(userHandle); 3629 if (!policy.mAdminMap.containsKey(outgoingReceiver) 3630 && policy.mAdminMap.containsKey(incomingReceiver)) { 3631 // Nothing to transfer - the incoming receiver is already the active admin. 3632 return; 3633 } 3634 final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle, 3635 /* throwForMissingPermission= */ true); 3636 final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver); 3637 final int oldAdminUid = adminToTransfer.getUid(); 3638 3639 adminToTransfer.transfer(incomingDeviceInfo); 3640 policy.mAdminMap.remove(outgoingReceiver); 3641 policy.mAdminMap.put(incomingReceiver, adminToTransfer); 3642 if (policy.mPasswordOwner == oldAdminUid) { 3643 policy.mPasswordOwner = adminToTransfer.getUid(); 3644 } 3645 3646 saveSettingsLocked(userHandle); 3647 sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3648 null, null); 3649 } 3650 3651 private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info, 3652 DevicePolicyData policy) { 3653 if (info == null) { 3654 throw new IllegalArgumentException("Bad admin: " + adminReceiver); 3655 } 3656 if (!info.getActivityInfo().applicationInfo.isInternal()) { 3657 throw new IllegalArgumentException("Only apps in internal storage can be active admin: " 3658 + adminReceiver); 3659 } 3660 if (info.getActivityInfo().applicationInfo.isInstantApp()) { 3661 throw new IllegalArgumentException("Instant apps cannot be device admins: " 3662 + adminReceiver); 3663 } 3664 if (policy.mRemovingAdmins.contains(adminReceiver)) { 3665 throw new IllegalArgumentException( 3666 "Trying to set an admin which is being removed"); 3667 } 3668 } 3669 3670 @Override 3671 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) { 3672 if (!mHasFeature) { 3673 return false; 3674 } 3675 enforceFullCrossUsersPermission(userHandle); 3676 synchronized (this) { 3677 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null; 3678 } 3679 } 3680 3681 @Override 3682 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) { 3683 if (!mHasFeature) { 3684 return false; 3685 } 3686 enforceFullCrossUsersPermission(userHandle); 3687 synchronized (this) { 3688 DevicePolicyData policyData = getUserData(userHandle); 3689 return policyData.mRemovingAdmins.contains(adminReceiver); 3690 } 3691 } 3692 3693 @Override 3694 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) { 3695 if (!mHasFeature) { 3696 return false; 3697 } 3698 enforceFullCrossUsersPermission(userHandle); 3699 synchronized (this) { 3700 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3701 if (administrator == null) { 3702 throw new SecurityException("No active admin " + adminReceiver); 3703 } 3704 return administrator.info.usesPolicy(policyId); 3705 } 3706 } 3707 3708 @Override 3709 @SuppressWarnings("unchecked") 3710 public List<ComponentName> getActiveAdmins(int userHandle) { 3711 if (!mHasFeature) { 3712 return Collections.EMPTY_LIST; 3713 } 3714 3715 enforceFullCrossUsersPermission(userHandle); 3716 synchronized (this) { 3717 DevicePolicyData policy = getUserData(userHandle); 3718 final int N = policy.mAdminList.size(); 3719 if (N <= 0) { 3720 return null; 3721 } 3722 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N); 3723 for (int i=0; i<N; i++) { 3724 res.add(policy.mAdminList.get(i).info.getComponent()); 3725 } 3726 return res; 3727 } 3728 } 3729 3730 @Override 3731 public boolean packageHasActiveAdmins(String packageName, int userHandle) { 3732 if (!mHasFeature) { 3733 return false; 3734 } 3735 enforceFullCrossUsersPermission(userHandle); 3736 synchronized (this) { 3737 DevicePolicyData policy = getUserData(userHandle); 3738 final int N = policy.mAdminList.size(); 3739 for (int i=0; i<N; i++) { 3740 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) { 3741 return true; 3742 } 3743 } 3744 return false; 3745 } 3746 } 3747 3748 @Override 3749 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) { 3750 if (!mHasFeature) { 3751 return; 3752 } 3753 Preconditions.checkNotNull(adminReceiver, "ComponentName is null"); 3754 enforceShell("forceRemoveActiveAdmin"); 3755 long ident = mInjector.binderClearCallingIdentity(); 3756 try { 3757 synchronized (this) { 3758 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) { 3759 throw new SecurityException("Attempt to remove non-test admin " 3760 + adminReceiver + " " + userHandle); 3761 } 3762 3763 // If admin is a device or profile owner tidy that up first. 3764 if (isDeviceOwner(adminReceiver, userHandle)) { 3765 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle); 3766 } 3767 if (isProfileOwner(adminReceiver, userHandle)) { 3768 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, 3769 userHandle, /* parent */ false); 3770 clearProfileOwnerLocked(admin, userHandle); 3771 } 3772 } 3773 // Remove the admin skipping sending the broadcast. 3774 removeAdminArtifacts(adminReceiver, userHandle); 3775 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle); 3776 } finally { 3777 mInjector.binderRestoreCallingIdentity(ident); 3778 } 3779 } 3780 3781 private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) { 3782 // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state 3783 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) { 3784 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle); 3785 } 3786 } 3787 3788 /** 3789 * Return if a given package has testOnly="true", in which case we'll relax certain rules 3790 * for CTS. 3791 * 3792 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked} 3793 * to check wehter an active admin is test-only or not. 3794 * 3795 * The system allows this flag to be changed when an app is updated, which is not good 3796 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed, 3797 * and used the persisted version in actual checks. (See b/31382361 and b/28928996) 3798 */ 3799 private boolean isPackageTestOnly(String packageName, int userHandle) { 3800 final ApplicationInfo ai; 3801 try { 3802 ai = mInjector.getIPackageManager().getApplicationInfo(packageName, 3803 (PackageManager.MATCH_DIRECT_BOOT_AWARE 3804 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle); 3805 } catch (RemoteException e) { 3806 throw new IllegalStateException(e); 3807 } 3808 if (ai == null) { 3809 throw new IllegalStateException("Couldn't find package: " 3810 + packageName + " on user " + userHandle); 3811 } 3812 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0; 3813 } 3814 3815 /** 3816 * See {@link #isPackageTestOnly}. 3817 */ 3818 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) { 3819 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3820 return (admin != null) && admin.testOnlyAdmin; 3821 } 3822 3823 private void enforceShell(String method) { 3824 final int callingUid = mInjector.binderGetCallingUid(); 3825 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) { 3826 throw new SecurityException("Non-shell user attempted to call " + method); 3827 } 3828 } 3829 3830 @Override 3831 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) { 3832 if (!mHasFeature) { 3833 return; 3834 } 3835 enforceFullCrossUsersPermission(userHandle); 3836 enforceUserUnlocked(userHandle); 3837 synchronized (this) { 3838 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3839 if (admin == null) { 3840 return; 3841 } 3842 // Active device/profile owners must remain active admins. 3843 if (isDeviceOwner(adminReceiver, userHandle) 3844 || isProfileOwner(adminReceiver, userHandle)) { 3845 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" + 3846 adminReceiver); 3847 return; 3848 } 3849 if (admin.getUid() != mInjector.binderGetCallingUid()) { 3850 mContext.enforceCallingOrSelfPermission( 3851 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 3852 } 3853 long ident = mInjector.binderClearCallingIdentity(); 3854 try { 3855 removeActiveAdminLocked(adminReceiver, userHandle); 3856 } finally { 3857 mInjector.binderRestoreCallingIdentity(ident); 3858 } 3859 } 3860 } 3861 3862 @Override 3863 public boolean isSeparateProfileChallengeAllowed(int userHandle) { 3864 ComponentName profileOwner = getProfileOwner(userHandle); 3865 // Profile challenge is supported on N or newer release. 3866 return profileOwner != null && 3867 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M; 3868 } 3869 3870 @Override 3871 public void setPasswordQuality(ComponentName who, int quality, boolean parent) { 3872 if (!mHasFeature) { 3873 return; 3874 } 3875 Preconditions.checkNotNull(who, "ComponentName is null"); 3876 validateQualityConstant(quality); 3877 3878 final int userId = mInjector.userHandleGetCallingUserId(); 3879 synchronized (this) { 3880 ActiveAdmin ap = getActiveAdminForCallerLocked( 3881 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3882 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 3883 if (metrics.quality != quality) { 3884 metrics.quality = quality; 3885 updatePasswordValidityCheckpointLocked(userId); 3886 saveSettingsLocked(userId); 3887 } 3888 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 3889 } 3890 } 3891 3892 /** 3893 * Updates flag in memory that tells us whether the user's password currently satisfies the 3894 * requirements set by all of the user's active admins. This should be called before 3895 * {@link #saveSettingsLocked} whenever the password or the admin policies have changed. 3896 */ 3897 @GuardedBy("DevicePolicyManagerService.this") 3898 private void updatePasswordValidityCheckpointLocked(int userHandle) { 3899 DevicePolicyData policy = getUserData(userHandle); 3900 policy.mPasswordValidAtLastCheckpoint = isActivePasswordSufficientForUserLocked( 3901 policy, policy.mUserHandle, false); 3902 } 3903 3904 @Override 3905 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) { 3906 if (!mHasFeature) { 3907 return PASSWORD_QUALITY_UNSPECIFIED; 3908 } 3909 enforceFullCrossUsersPermission(userHandle); 3910 synchronized (this) { 3911 int mode = PASSWORD_QUALITY_UNSPECIFIED; 3912 3913 if (who != null) { 3914 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3915 return admin != null ? admin.minimumPasswordMetrics.quality : mode; 3916 } 3917 3918 // Return the strictest policy across all participating admins. 3919 List<ActiveAdmin> admins = 3920 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3921 final int N = admins.size(); 3922 for (int i = 0; i < N; i++) { 3923 ActiveAdmin admin = admins.get(i); 3924 if (mode < admin.minimumPasswordMetrics.quality) { 3925 mode = admin.minimumPasswordMetrics.quality; 3926 } 3927 } 3928 return mode; 3929 } 3930 } 3931 3932 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked( 3933 int userHandle, boolean parent) { 3934 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) { 3935 // If this user has a separate challenge, only return its restrictions. 3936 return getUserDataUnchecked(userHandle).mAdminList; 3937 } else { 3938 // Return all admins for this user and the profiles that are visible from this 3939 // user that do not use a separate work challenge. 3940 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>(); 3941 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 3942 DevicePolicyData policy = getUserData(userInfo.id); 3943 if (!userInfo.isManagedProfile()) { 3944 admins.addAll(policy.mAdminList); 3945 } else { 3946 // For managed profiles, we always include the policies set on the parent 3947 // profile. Additionally, we include the ones set on the managed profile 3948 // if no separate challenge is in place. 3949 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id); 3950 final int N = policy.mAdminList.size(); 3951 for (int i = 0; i < N; i++) { 3952 ActiveAdmin admin = policy.mAdminList.get(i); 3953 if (admin.hasParentActiveAdmin()) { 3954 admins.add(admin.getParentActiveAdmin()); 3955 } 3956 if (!hasSeparateChallenge) { 3957 admins.add(admin); 3958 } 3959 } 3960 } 3961 } 3962 return admins; 3963 } 3964 } 3965 3966 private boolean isSeparateProfileChallengeEnabled(int userHandle) { 3967 long ident = mInjector.binderClearCallingIdentity(); 3968 try { 3969 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle); 3970 } finally { 3971 mInjector.binderRestoreCallingIdentity(ident); 3972 } 3973 } 3974 3975 @Override 3976 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) { 3977 if (!mHasFeature) { 3978 return; 3979 } 3980 Preconditions.checkNotNull(who, "ComponentName is null"); 3981 final int userId = mInjector.userHandleGetCallingUserId(); 3982 synchronized (this) { 3983 ActiveAdmin ap = getActiveAdminForCallerLocked( 3984 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3985 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 3986 if (metrics.length != length) { 3987 metrics.length = length; 3988 updatePasswordValidityCheckpointLocked(userId); 3989 saveSettingsLocked(userId); 3990 } 3991 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 3992 } 3993 } 3994 3995 @Override 3996 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) { 3997 return getStrictestPasswordRequirement(who, userHandle, parent, 3998 admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_UNSPECIFIED); 3999 } 4000 4001 @Override 4002 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) { 4003 if (!mHasFeature) { 4004 return; 4005 } 4006 Preconditions.checkNotNull(who, "ComponentName is null"); 4007 final int userId = mInjector.userHandleGetCallingUserId(); 4008 synchronized (this) { 4009 ActiveAdmin ap = getActiveAdminForCallerLocked( 4010 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4011 if (ap.passwordHistoryLength != length) { 4012 ap.passwordHistoryLength = length; 4013 updatePasswordValidityCheckpointLocked(userId); 4014 saveSettingsLocked(userId); 4015 } 4016 } 4017 if (SecurityLog.isLoggingEnabled()) { 4018 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4019 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET, 4020 who.getPackageName(), userId, affectedUserId, length); 4021 } 4022 } 4023 4024 @Override 4025 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) { 4026 return getStrictestPasswordRequirement(who, userHandle, parent, 4027 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED); 4028 } 4029 4030 @Override 4031 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) { 4032 if (!mHasFeature) { 4033 return; 4034 } 4035 Preconditions.checkNotNull(who, "ComponentName is null"); 4036 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms"); 4037 final int userHandle = mInjector.userHandleGetCallingUserId(); 4038 synchronized (this) { 4039 ActiveAdmin ap = getActiveAdminForCallerLocked( 4040 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent); 4041 // Calling this API automatically bumps the expiration date 4042 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 4043 ap.passwordExpirationDate = expiration; 4044 ap.passwordExpirationTimeout = timeout; 4045 if (timeout > 0L) { 4046 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 4047 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 4048 .format(new Date(expiration))); 4049 } 4050 saveSettingsLocked(userHandle); 4051 4052 // in case this is the first one, set the alarm on the appropriate user. 4053 setExpirationAlarmCheckLocked(mContext, userHandle, parent); 4054 } 4055 if (SecurityLog.isLoggingEnabled()) { 4056 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 4057 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(), 4058 userHandle, affectedUserId, timeout); 4059 } 4060 } 4061 4062 /** 4063 * Return a single admin's expiration cycle time, or the min of all cycle times. 4064 * Returns 0 if not configured. 4065 */ 4066 @Override 4067 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) { 4068 if (!mHasFeature) { 4069 return 0L; 4070 } 4071 enforceFullCrossUsersPermission(userHandle); 4072 synchronized (this) { 4073 long timeout = 0L; 4074 4075 if (who != null) { 4076 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4077 return admin != null ? admin.passwordExpirationTimeout : timeout; 4078 } 4079 4080 // Return the strictest policy across all participating admins. 4081 List<ActiveAdmin> admins = 4082 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4083 final int N = admins.size(); 4084 for (int i = 0; i < N; i++) { 4085 ActiveAdmin admin = admins.get(i); 4086 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 4087 && timeout > admin.passwordExpirationTimeout)) { 4088 timeout = admin.passwordExpirationTimeout; 4089 } 4090 } 4091 return timeout; 4092 } 4093 } 4094 4095 @Override 4096 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4097 final int userId = UserHandle.getCallingUserId(); 4098 List<String> changedProviders = null; 4099 4100 synchronized (this) { 4101 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4102 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4103 if (activeAdmin.crossProfileWidgetProviders == null) { 4104 activeAdmin.crossProfileWidgetProviders = new ArrayList<>(); 4105 } 4106 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4107 if (!providers.contains(packageName)) { 4108 providers.add(packageName); 4109 changedProviders = new ArrayList<>(providers); 4110 saveSettingsLocked(userId); 4111 } 4112 } 4113 4114 if (changedProviders != null) { 4115 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 4116 return true; 4117 } 4118 4119 return false; 4120 } 4121 4122 @Override 4123 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4124 final int userId = UserHandle.getCallingUserId(); 4125 List<String> changedProviders = null; 4126 4127 synchronized (this) { 4128 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4129 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4130 if (activeAdmin.crossProfileWidgetProviders == null 4131 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4132 return false; 4133 } 4134 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4135 if (providers.remove(packageName)) { 4136 changedProviders = new ArrayList<>(providers); 4137 saveSettingsLocked(userId); 4138 } 4139 } 4140 4141 if (changedProviders != null) { 4142 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 4143 return true; 4144 } 4145 4146 return false; 4147 } 4148 4149 @Override 4150 public List<String> getCrossProfileWidgetProviders(ComponentName admin) { 4151 synchronized (this) { 4152 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4153 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4154 if (activeAdmin.crossProfileWidgetProviders == null 4155 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4156 return null; 4157 } 4158 if (mInjector.binderIsCallingUidMyUid()) { 4159 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders); 4160 } else { 4161 return activeAdmin.crossProfileWidgetProviders; 4162 } 4163 } 4164 } 4165 4166 /** 4167 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 4168 * Returns 0 if not configured. 4169 */ 4170 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) { 4171 long timeout = 0L; 4172 4173 if (who != null) { 4174 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4175 return admin != null ? admin.passwordExpirationDate : timeout; 4176 } 4177 4178 // Return the strictest policy across all participating admins. 4179 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4180 final int N = admins.size(); 4181 for (int i = 0; i < N; i++) { 4182 ActiveAdmin admin = admins.get(i); 4183 if (timeout == 0L || (admin.passwordExpirationDate != 0 4184 && timeout > admin.passwordExpirationDate)) { 4185 timeout = admin.passwordExpirationDate; 4186 } 4187 } 4188 return timeout; 4189 } 4190 4191 @Override 4192 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) { 4193 if (!mHasFeature) { 4194 return 0L; 4195 } 4196 enforceFullCrossUsersPermission(userHandle); 4197 synchronized (this) { 4198 return getPasswordExpirationLocked(who, userHandle, parent); 4199 } 4200 } 4201 4202 @Override 4203 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) { 4204 if (!mHasFeature) { 4205 return; 4206 } 4207 Preconditions.checkNotNull(who, "ComponentName is null"); 4208 final int userId = mInjector.userHandleGetCallingUserId(); 4209 synchronized (this) { 4210 final ActiveAdmin ap = getActiveAdminForCallerLocked( 4211 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4212 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4213 if (metrics.upperCase != length) { 4214 metrics.upperCase = length; 4215 updatePasswordValidityCheckpointLocked(userId); 4216 saveSettingsLocked(userId); 4217 } 4218 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4219 } 4220 } 4221 4222 @Override 4223 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) { 4224 return getStrictestPasswordRequirement(who, userHandle, parent, 4225 admin -> admin.minimumPasswordMetrics.upperCase, PASSWORD_QUALITY_COMPLEX); 4226 } 4227 4228 @Override 4229 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) { 4230 Preconditions.checkNotNull(who, "ComponentName is null"); 4231 final int userId = mInjector.userHandleGetCallingUserId(); 4232 synchronized (this) { 4233 ActiveAdmin ap = getActiveAdminForCallerLocked( 4234 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4235 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4236 if (metrics.lowerCase != length) { 4237 metrics.lowerCase = length; 4238 updatePasswordValidityCheckpointLocked(userId); 4239 saveSettingsLocked(userId); 4240 } 4241 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4242 } 4243 } 4244 4245 @Override 4246 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) { 4247 return getStrictestPasswordRequirement(who, userHandle, parent, 4248 admin -> admin.minimumPasswordMetrics.lowerCase, PASSWORD_QUALITY_COMPLEX); 4249 } 4250 4251 @Override 4252 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) { 4253 if (!mHasFeature) { 4254 return; 4255 } 4256 Preconditions.checkNotNull(who, "ComponentName is null"); 4257 final int userId = mInjector.userHandleGetCallingUserId(); 4258 synchronized (this) { 4259 ActiveAdmin ap = getActiveAdminForCallerLocked( 4260 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4261 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4262 if (metrics.letters != length) { 4263 metrics.letters = length; 4264 updatePasswordValidityCheckpointLocked(userId); 4265 saveSettingsLocked(userId); 4266 } 4267 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4268 } 4269 } 4270 4271 @Override 4272 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) { 4273 return getStrictestPasswordRequirement(who, userHandle, parent, 4274 admin -> admin.minimumPasswordMetrics.letters, PASSWORD_QUALITY_COMPLEX); 4275 } 4276 4277 @Override 4278 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) { 4279 if (!mHasFeature) { 4280 return; 4281 } 4282 Preconditions.checkNotNull(who, "ComponentName is null"); 4283 final int userId = mInjector.userHandleGetCallingUserId(); 4284 synchronized (this) { 4285 ActiveAdmin ap = getActiveAdminForCallerLocked( 4286 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4287 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4288 if (metrics.numeric != length) { 4289 metrics.numeric = length; 4290 updatePasswordValidityCheckpointLocked(userId); 4291 saveSettingsLocked(userId); 4292 } 4293 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4294 } 4295 } 4296 4297 @Override 4298 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) { 4299 return getStrictestPasswordRequirement(who, userHandle, parent, 4300 admin -> admin.minimumPasswordMetrics.numeric, PASSWORD_QUALITY_COMPLEX); 4301 } 4302 4303 @Override 4304 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) { 4305 if (!mHasFeature) { 4306 return; 4307 } 4308 Preconditions.checkNotNull(who, "ComponentName is null"); 4309 final int userId = mInjector.userHandleGetCallingUserId(); 4310 synchronized (this) { 4311 ActiveAdmin ap = getActiveAdminForCallerLocked( 4312 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4313 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4314 if (metrics.symbols != length) { 4315 ap.minimumPasswordMetrics.symbols = length; 4316 updatePasswordValidityCheckpointLocked(userId); 4317 saveSettingsLocked(userId); 4318 } 4319 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4320 } 4321 } 4322 4323 @Override 4324 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) { 4325 return getStrictestPasswordRequirement(who, userHandle, parent, 4326 admin -> admin.minimumPasswordMetrics.symbols, PASSWORD_QUALITY_COMPLEX); 4327 } 4328 4329 @Override 4330 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) { 4331 if (!mHasFeature) { 4332 return; 4333 } 4334 Preconditions.checkNotNull(who, "ComponentName is null"); 4335 final int userId = mInjector.userHandleGetCallingUserId(); 4336 synchronized (this) { 4337 ActiveAdmin ap = getActiveAdminForCallerLocked( 4338 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4339 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4340 if (metrics.nonLetter != length) { 4341 ap.minimumPasswordMetrics.nonLetter = length; 4342 updatePasswordValidityCheckpointLocked(userId); 4343 saveSettingsLocked(userId); 4344 } 4345 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4346 } 4347 } 4348 4349 @Override 4350 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) { 4351 return getStrictestPasswordRequirement(who, userHandle, parent, 4352 admin -> admin.minimumPasswordMetrics.nonLetter, PASSWORD_QUALITY_COMPLEX); 4353 } 4354 4355 /** 4356 * Calculates strictest (maximum) value for a given password property enforced by admin[s]. 4357 */ 4358 private int getStrictestPasswordRequirement(ComponentName who, int userHandle, 4359 boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) { 4360 if (!mHasFeature) { 4361 return 0; 4362 } 4363 enforceFullCrossUsersPermission(userHandle); 4364 synchronized (this) { 4365 if (who != null) { 4366 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4367 return admin != null ? getter.apply(admin) : 0; 4368 } 4369 4370 int maxValue = 0; 4371 final List<ActiveAdmin> admins = 4372 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4373 final int N = admins.size(); 4374 for (int i = 0; i < N; i++) { 4375 final ActiveAdmin admin = admins.get(i); 4376 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) { 4377 continue; 4378 } 4379 final Integer adminValue = getter.apply(admin); 4380 if (adminValue > maxValue) { 4381 maxValue = adminValue; 4382 } 4383 } 4384 return maxValue; 4385 } 4386 } 4387 4388 /* @return the password blacklist set by the admin or {@code null} if none. */ 4389 PasswordBlacklist getAdminPasswordBlacklistLocked(@NonNull ActiveAdmin admin) { 4390 final int userId = UserHandle.getUserId(admin.getUid()); 4391 return admin.passwordBlacklistFile == null ? null : new PasswordBlacklist( 4392 new File(getPolicyFileDirectory(userId), admin.passwordBlacklistFile)); 4393 } 4394 4395 private static final String PASSWORD_BLACKLIST_FILE_PREFIX = "password-blacklist-"; 4396 private static final String PASSWORD_BLACKLIST_FILE_SUFFIX = ""; 4397 4398 @Override 4399 public boolean setPasswordBlacklist(ComponentName who, String name, List<String> blacklist, 4400 boolean parent) { 4401 if (!mHasFeature) { 4402 return false; 4403 } 4404 Preconditions.checkNotNull(who, "who is null"); 4405 4406 synchronized (this) { 4407 final ActiveAdmin admin = getActiveAdminForCallerLocked( 4408 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent); 4409 final int userId = mInjector.userHandleGetCallingUserId(); 4410 PasswordBlacklist adminBlacklist = getAdminPasswordBlacklistLocked(admin); 4411 4412 if (blacklist == null || blacklist.isEmpty()) { 4413 // Remove the adminBlacklist 4414 admin.passwordBlacklistFile = null; 4415 saveSettingsLocked(userId); 4416 if (adminBlacklist != null) { 4417 adminBlacklist.delete(); 4418 } 4419 return true; 4420 } 4421 4422 // Validate server side 4423 Preconditions.checkNotNull(name, "name is null"); 4424 DevicePolicyManager.enforcePasswordBlacklistSize(blacklist); 4425 4426 // Blacklist is case insensitive so normalize to lower case 4427 final int blacklistSize = blacklist.size(); 4428 for (int i = 0; i < blacklistSize; ++i) { 4429 blacklist.set(i, blacklist.get(i).toLowerCase()); 4430 } 4431 4432 final boolean isNewBlacklist = adminBlacklist == null; 4433 if (isNewBlacklist) { 4434 // Create a new file for the blacklist. There could be multiple admins, each setting 4435 // different blacklists, to restrict a user's credential, for example a managed 4436 // profile can impose restrictions on its parent while the parent is already 4437 // restricted by its own admin. A deterministic naming scheme would be fragile if 4438 // new types of admin are introduced so we generate and save the file name instead. 4439 // This isn't a temporary file but it reuses the name generation logic 4440 final File file; 4441 try { 4442 file = File.createTempFile(PASSWORD_BLACKLIST_FILE_PREFIX, 4443 PASSWORD_BLACKLIST_FILE_SUFFIX, getPolicyFileDirectory(userId)); 4444 } catch (IOException e) { 4445 Slog.e(LOG_TAG, "Failed to make a file for the blacklist", e); 4446 return false; 4447 } 4448 adminBlacklist = mInjector.newPasswordBlacklist(file); 4449 } 4450 4451 if (adminBlacklist.savePasswordBlacklist(name, blacklist)) { 4452 if (isNewBlacklist) { 4453 // The blacklist was saved so point the admin to the file 4454 admin.passwordBlacklistFile = adminBlacklist.getFile().getName(); 4455 saveSettingsLocked(userId); 4456 } 4457 return true; 4458 } 4459 } 4460 4461 return false; 4462 } 4463 4464 @Override 4465 public String getPasswordBlacklistName(ComponentName who, @UserIdInt int userId, 4466 boolean parent) { 4467 if (!mHasFeature) { 4468 return null; 4469 } 4470 Preconditions.checkNotNull(who, "who is null"); 4471 enforceFullCrossUsersPermission(userId); 4472 synchronized (this) { 4473 final ActiveAdmin admin = getActiveAdminForCallerLocked( 4474 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent); 4475 final PasswordBlacklist blacklist = getAdminPasswordBlacklistLocked(admin); 4476 if (blacklist == null) { 4477 return null; 4478 } 4479 return blacklist.getName(); 4480 } 4481 } 4482 4483 @Override 4484 public boolean isPasswordBlacklisted(@UserIdInt int userId, String password) { 4485 if (!mHasFeature) { 4486 return false; 4487 } 4488 mContext.enforceCallingOrSelfPermission( 4489 android.Manifest.permission.TEST_BLACKLISTED_PASSWORD, null); 4490 return isPasswordBlacklistedInternal(userId, password); 4491 } 4492 4493 private boolean isPasswordBlacklistedInternal(@UserIdInt int userId, String password) { 4494 Preconditions.checkNotNull(password, "Password is null"); 4495 enforceFullCrossUsersPermission(userId); 4496 4497 // Normalize to lower case for case insensitive blacklist match 4498 final String lowerCasePassword = password.toLowerCase(); 4499 4500 synchronized (this) { 4501 final List<ActiveAdmin> admins = 4502 getActiveAdminsForLockscreenPoliciesLocked(userId, /* parent */ false); 4503 final int N = admins.size(); 4504 for (int i = 0; i < N; i++) { 4505 final PasswordBlacklist blacklist 4506 = getAdminPasswordBlacklistLocked(admins.get(i)); 4507 if (blacklist != null) { 4508 if (blacklist.isPasswordBlacklisted(lowerCasePassword)) { 4509 return true; 4510 } 4511 } 4512 } 4513 } 4514 4515 return false; 4516 } 4517 4518 @Override 4519 public boolean isActivePasswordSufficient(int userHandle, boolean parent) { 4520 if (!mHasFeature) { 4521 return true; 4522 } 4523 enforceFullCrossUsersPermission(userHandle); 4524 enforceUserUnlocked(userHandle, parent); 4525 4526 synchronized (this) { 4527 // This API can only be called by an active device admin, 4528 // so try to retrieve it to check that the caller is one. 4529 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4530 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4531 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent); 4532 } 4533 } 4534 4535 @Override 4536 public boolean isUsingUnifiedPassword(ComponentName admin) { 4537 if (!mHasFeature) { 4538 return true; 4539 } 4540 final int userId = mInjector.userHandleGetCallingUserId(); 4541 enforceProfileOrDeviceOwner(admin); 4542 enforceManagedProfile(userId, "query unified challenge status"); 4543 return !isSeparateProfileChallengeEnabled(userId); 4544 } 4545 4546 @Override 4547 public boolean isProfileActivePasswordSufficientForParent(int userHandle) { 4548 if (!mHasFeature) { 4549 return true; 4550 } 4551 enforceFullCrossUsersPermission(userHandle); 4552 enforceManagedProfile(userHandle, "call APIs refering to the parent profile"); 4553 4554 synchronized (this) { 4555 final int targetUser = getProfileParentId(userHandle); 4556 enforceUserUnlocked(targetUser, false); 4557 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false)); 4558 return isActivePasswordSufficientForUserLocked(policy, targetUser, false); 4559 } 4560 } 4561 4562 private boolean isActivePasswordSufficientForUserLocked( 4563 DevicePolicyData policy, int userHandle, boolean parent) { 4564 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent); 4565 if (requiredPasswordQuality == PASSWORD_QUALITY_UNSPECIFIED) { 4566 // A special case is when there is no required password quality, then we just return 4567 // true since any password would be sufficient. This is for the scenario when a work 4568 // profile is first created so there is no information about the current password but 4569 // it should be considered sufficient as there is no password requirement either. 4570 // This is useful since it short-circuits the password checkpoint for FDE device below. 4571 return true; 4572 } 4573 4574 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() 4575 && !policy.mPasswordStateHasBeenSetSinceBoot) { 4576 // Before user enters their password for the first time after a reboot, return the 4577 // value of this flag, which tells us whether the password was valid the last time 4578 // settings were saved. If DPC changes password requirements on boot so that the 4579 // current password no longer meets the requirements, this value will be stale until 4580 // the next time the password is entered. 4581 return policy.mPasswordValidAtLastCheckpoint; 4582 } 4583 4584 if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) { 4585 return false; 4586 } 4587 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC 4588 && policy.mActivePasswordMetrics.length < getPasswordMinimumLength( 4589 null, userHandle, parent)) { 4590 return false; 4591 } 4592 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4593 return true; 4594 } 4595 return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase( 4596 null, userHandle, parent) 4597 && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase( 4598 null, userHandle, parent) 4599 && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters( 4600 null, userHandle, parent) 4601 && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric( 4602 null, userHandle, parent) 4603 && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols( 4604 null, userHandle, parent) 4605 && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter( 4606 null, userHandle, parent); 4607 } 4608 4609 @Override 4610 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) { 4611 enforceFullCrossUsersPermission(userHandle); 4612 synchronized (this) { 4613 if (!isCallerWithSystemUid()) { 4614 // This API can only be called by an active device admin, 4615 // so try to retrieve it to check that the caller is one. 4616 getActiveAdminForCallerLocked( 4617 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4618 } 4619 4620 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4621 4622 return policy.mFailedPasswordAttempts; 4623 } 4624 } 4625 4626 @Override 4627 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) { 4628 if (!mHasFeature) { 4629 return; 4630 } 4631 Preconditions.checkNotNull(who, "ComponentName is null"); 4632 final int userId = mInjector.userHandleGetCallingUserId(); 4633 synchronized (this) { 4634 // This API can only be called by an active device admin, 4635 // so try to retrieve it to check that the caller is one. 4636 getActiveAdminForCallerLocked( 4637 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent); 4638 ActiveAdmin ap = getActiveAdminForCallerLocked( 4639 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4640 if (ap.maximumFailedPasswordsForWipe != num) { 4641 ap.maximumFailedPasswordsForWipe = num; 4642 saveSettingsLocked(userId); 4643 } 4644 } 4645 if (SecurityLog.isLoggingEnabled()) { 4646 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4647 SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(), 4648 userId, affectedUserId, num); 4649 } 4650 } 4651 4652 @Override 4653 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) { 4654 if (!mHasFeature) { 4655 return 0; 4656 } 4657 enforceFullCrossUsersPermission(userHandle); 4658 synchronized (this) { 4659 ActiveAdmin admin = (who != null) 4660 ? getActiveAdminUncheckedLocked(who, userHandle, parent) 4661 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent); 4662 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 4663 } 4664 } 4665 4666 @Override 4667 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) { 4668 if (!mHasFeature) { 4669 return UserHandle.USER_NULL; 4670 } 4671 enforceFullCrossUsersPermission(userHandle); 4672 synchronized (this) { 4673 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked( 4674 userHandle, parent); 4675 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL; 4676 } 4677 } 4678 4679 /** 4680 * Returns the admin with the strictest policy on maximum failed passwords for: 4681 * <ul> 4682 * <li>this user if it has a separate profile challenge, or 4683 * <li>this user and all profiles that don't have their own challenge otherwise. 4684 * </ul> 4685 * <p>If the policy for the primary and any other profile are equal, it returns the admin for 4686 * the primary profile. 4687 * Returns {@code null} if no participating admin has that policy set. 4688 */ 4689 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked( 4690 int userHandle, boolean parent) { 4691 int count = 0; 4692 ActiveAdmin strictestAdmin = null; 4693 4694 // Return the strictest policy across all participating admins. 4695 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4696 final int N = admins.size(); 4697 for (int i = 0; i < N; i++) { 4698 ActiveAdmin admin = admins.get(i); 4699 if (admin.maximumFailedPasswordsForWipe == 4700 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 4701 continue; // No max number of failed passwords policy set for this profile. 4702 } 4703 4704 // We always favor the primary profile if several profiles have the same value set. 4705 int userId = admin.getUserHandle().getIdentifier(); 4706 if (count == 0 || 4707 count > admin.maximumFailedPasswordsForWipe || 4708 (count == admin.maximumFailedPasswordsForWipe && 4709 getUserInfo(userId).isPrimary())) { 4710 count = admin.maximumFailedPasswordsForWipe; 4711 strictestAdmin = admin; 4712 } 4713 } 4714 return strictestAdmin; 4715 } 4716 4717 private UserInfo getUserInfo(@UserIdInt int userId) { 4718 final long token = mInjector.binderClearCallingIdentity(); 4719 try { 4720 return mUserManager.getUserInfo(userId); 4721 } finally { 4722 mInjector.binderRestoreCallingIdentity(token); 4723 } 4724 } 4725 4726 private boolean canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId) { 4727 // Only if the admins targets a pre-O SDK 4728 return getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.O; 4729 } 4730 4731 /* PO or DO could do an untrusted reset in certain conditions. */ 4732 private boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) { 4733 synchronized (this) { 4734 // An active DO or PO might be able to fo an untrusted credential reset 4735 for (final ActiveAdmin admin : getUserData(userId).mAdminList) { 4736 if (!isActiveAdminWithPolicyForUserLocked(admin, 4737 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, userId)) { 4738 continue; 4739 } 4740 if (canPOorDOCallResetPassword(admin, userId)) { 4741 return true; 4742 } 4743 } 4744 return false; 4745 } 4746 } 4747 @Override 4748 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException { 4749 final int callingUid = mInjector.binderGetCallingUid(); 4750 final int userHandle = mInjector.userHandleGetCallingUserId(); 4751 4752 String password = passwordOrNull != null ? passwordOrNull : ""; 4753 4754 // Password resetting to empty/null is not allowed for managed profiles. 4755 if (TextUtils.isEmpty(password)) { 4756 enforceNotManagedProfile(userHandle, "clear the active password"); 4757 } 4758 4759 synchronized (this) { 4760 // If caller has PO (or DO) it can change the password, so see if that's the case first. 4761 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked( 4762 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid); 4763 final boolean preN; 4764 if (admin != null) { 4765 if (!canPOorDOCallResetPassword(admin, userHandle)) { 4766 throw new SecurityException("resetPassword() is deprecated for DPC targeting O" 4767 + " or later"); 4768 } 4769 preN = getTargetSdk(admin.info.getPackageName(), 4770 userHandle) <= android.os.Build.VERSION_CODES.M; 4771 } else { 4772 // Otherwise, make sure the caller has any active admin with the right policy. 4773 admin = getActiveAdminForCallerLocked(null, 4774 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD); 4775 preN = getTargetSdk(admin.info.getPackageName(), 4776 userHandle) <= android.os.Build.VERSION_CODES.M; 4777 4778 // As of N, password resetting to empty/null is not allowed anymore. 4779 // TODO Should we allow DO/PO to set an empty password? 4780 if (TextUtils.isEmpty(password)) { 4781 if (!preN) { 4782 throw new SecurityException("Cannot call with null password"); 4783 } else { 4784 Slog.e(LOG_TAG, "Cannot call with null password"); 4785 return false; 4786 } 4787 } 4788 // As of N, password cannot be changed by the admin if it is already set. 4789 if (isLockScreenSecureUnchecked(userHandle)) { 4790 if (!preN) { 4791 throw new SecurityException("Admin cannot change current password"); 4792 } else { 4793 Slog.e(LOG_TAG, "Admin cannot change current password"); 4794 return false; 4795 } 4796 } 4797 } 4798 // Do not allow to reset password when current user has a managed profile 4799 if (!isManagedProfile(userHandle)) { 4800 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4801 if (userInfo.isManagedProfile()) { 4802 if (!preN) { 4803 throw new IllegalStateException( 4804 "Cannot reset password on user has managed profile"); 4805 } else { 4806 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile"); 4807 return false; 4808 } 4809 } 4810 } 4811 } 4812 // Do not allow to reset password when user is locked 4813 if (!mUserManager.isUserUnlocked(userHandle)) { 4814 if (!preN) { 4815 throw new IllegalStateException("Cannot reset password when user is locked"); 4816 } else { 4817 Slog.e(LOG_TAG, "Cannot reset password when user is locked"); 4818 return false; 4819 } 4820 } 4821 } 4822 4823 return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle); 4824 } 4825 4826 private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token, 4827 int flags, int callingUid, int userHandle) { 4828 int quality; 4829 synchronized (this) { 4830 quality = getPasswordQuality(null, userHandle, /* parent */ false); 4831 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) { 4832 quality = PASSWORD_QUALITY_UNSPECIFIED; 4833 } 4834 final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password); 4835 if (quality != PASSWORD_QUALITY_UNSPECIFIED) { 4836 final int realQuality = metrics.quality; 4837 if (realQuality < quality 4838 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4839 Slog.w(LOG_TAG, "resetPassword: password quality 0x" 4840 + Integer.toHexString(realQuality) 4841 + " does not meet required quality 0x" 4842 + Integer.toHexString(quality)); 4843 return false; 4844 } 4845 quality = Math.max(realQuality, quality); 4846 } 4847 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false); 4848 if (password.length() < length) { 4849 Slog.w(LOG_TAG, "resetPassword: password length " + password.length() 4850 + " does not meet required length " + length); 4851 return false; 4852 } 4853 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4854 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false); 4855 if(metrics.letters < neededLetters) { 4856 Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters 4857 + " does not meet required number of letters " + neededLetters); 4858 return false; 4859 } 4860 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false); 4861 if (metrics.numeric < neededNumeric) { 4862 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric 4863 + " does not meet required number of numerical digits " 4864 + neededNumeric); 4865 return false; 4866 } 4867 int neededLowerCase = getPasswordMinimumLowerCase( 4868 null, userHandle, /* parent */ false); 4869 if (metrics.lowerCase < neededLowerCase) { 4870 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " 4871 + metrics.lowerCase 4872 + " does not meet required number of lowercase letters " 4873 + neededLowerCase); 4874 return false; 4875 } 4876 int neededUpperCase = getPasswordMinimumUpperCase( 4877 null, userHandle, /* parent */ false); 4878 if (metrics.upperCase < neededUpperCase) { 4879 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " 4880 + metrics.upperCase 4881 + " does not meet required number of uppercase letters " 4882 + neededUpperCase); 4883 return false; 4884 } 4885 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false); 4886 if (metrics.symbols < neededSymbols) { 4887 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols 4888 + " does not meet required number of special symbols " + neededSymbols); 4889 return false; 4890 } 4891 int neededNonLetter = getPasswordMinimumNonLetter( 4892 null, userHandle, /* parent */ false); 4893 if (metrics.nonLetter < neededNonLetter) { 4894 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " 4895 + metrics.nonLetter 4896 + " does not meet required number of non-letter characters " 4897 + neededNonLetter); 4898 return false; 4899 } 4900 } 4901 4902 if (isPasswordBlacklistedInternal(userHandle, password)) { 4903 Slog.w(LOG_TAG, "resetPassword: the password is blacklisted"); 4904 return false; 4905 } 4906 } 4907 4908 DevicePolicyData policy = getUserData(userHandle); 4909 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 4910 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 4911 return false; 4912 } 4913 4914 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid); 4915 boolean doNotAskCredentialsOnBoot = 4916 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 4917 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 4918 setDoNotAskCredentialsOnBoot(); 4919 } 4920 4921 // Don't do this with the lock held, because it is going to call 4922 // back in to the service. 4923 final long ident = mInjector.binderClearCallingIdentity(); 4924 final boolean result; 4925 try { 4926 if (token == null) { 4927 if (!TextUtils.isEmpty(password)) { 4928 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle); 4929 } else { 4930 mLockPatternUtils.clearLock(null, userHandle); 4931 } 4932 result = true; 4933 } else { 4934 result = mLockPatternUtils.setLockCredentialWithToken(password, 4935 TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE 4936 : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 4937 quality, tokenHandle, token, userHandle); 4938 } 4939 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 4940 if (requireEntry) { 4941 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, 4942 UserHandle.USER_ALL); 4943 } 4944 synchronized (this) { 4945 int newOwner = requireEntry ? callingUid : -1; 4946 if (policy.mPasswordOwner != newOwner) { 4947 policy.mPasswordOwner = newOwner; 4948 saveSettingsLocked(userHandle); 4949 } 4950 } 4951 } finally { 4952 mInjector.binderRestoreCallingIdentity(ident); 4953 } 4954 return result; 4955 } 4956 4957 private boolean isLockScreenSecureUnchecked(int userId) { 4958 long ident = mInjector.binderClearCallingIdentity(); 4959 try { 4960 return mLockPatternUtils.isSecure(userId); 4961 } finally { 4962 mInjector.binderRestoreCallingIdentity(ident); 4963 } 4964 } 4965 4966 private void setDoNotAskCredentialsOnBoot() { 4967 synchronized (this) { 4968 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4969 if (!policyData.doNotAskCredentialsOnBoot) { 4970 policyData.doNotAskCredentialsOnBoot = true; 4971 saveSettingsLocked(UserHandle.USER_SYSTEM); 4972 } 4973 } 4974 } 4975 4976 @Override 4977 public boolean getDoNotAskCredentialsOnBoot() { 4978 mContext.enforceCallingOrSelfPermission( 4979 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null); 4980 synchronized (this) { 4981 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4982 return policyData.doNotAskCredentialsOnBoot; 4983 } 4984 } 4985 4986 @Override 4987 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) { 4988 if (!mHasFeature) { 4989 return; 4990 } 4991 Preconditions.checkNotNull(who, "ComponentName is null"); 4992 final int userHandle = mInjector.userHandleGetCallingUserId(); 4993 synchronized (this) { 4994 ActiveAdmin ap = getActiveAdminForCallerLocked( 4995 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 4996 if (ap.maximumTimeToUnlock != timeMs) { 4997 ap.maximumTimeToUnlock = timeMs; 4998 saveSettingsLocked(userHandle); 4999 updateMaximumTimeToLockLocked(userHandle); 5000 } 5001 } 5002 if (SecurityLog.isLoggingEnabled()) { 5003 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 5004 SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET, 5005 who.getPackageName(), userHandle, affectedUserId, timeMs); 5006 } 5007 } 5008 5009 private void updateMaximumTimeToLockLocked(@UserIdInt int userId) { 5010 // Update the profile's timeout 5011 if (isManagedProfile(userId)) { 5012 updateProfileLockTimeoutLocked(userId); 5013 } 5014 5015 final long timeMs; 5016 final long ident = mInjector.binderClearCallingIdentity(); 5017 try { 5018 // Update the device timeout 5019 final int parentId = getProfileParentId(userId); 5020 timeMs = getMaximumTimeToLockPolicyFromAdmins( 5021 getActiveAdminsForLockscreenPoliciesLocked(parentId, false)); 5022 5023 final DevicePolicyData policy = getUserDataUnchecked(parentId); 5024 if (policy.mLastMaximumTimeToLock == timeMs) { 5025 return; 5026 } 5027 policy.mLastMaximumTimeToLock = timeMs; 5028 5029 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) { 5030 // Make sure KEEP_SCREEN_ON is disabled, since that 5031 // would allow bypassing of the maximum time to lock. 5032 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 5033 } 5034 } finally { 5035 mInjector.binderRestoreCallingIdentity(ident); 5036 } 5037 5038 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5039 UserHandle.USER_SYSTEM, timeMs); 5040 } 5041 5042 private void updateProfileLockTimeoutLocked(@UserIdInt int userId) { 5043 final long timeMs; 5044 if (isSeparateProfileChallengeEnabled(userId)) { 5045 timeMs = getMaximumTimeToLockPolicyFromAdmins( 5046 getActiveAdminsForLockscreenPoliciesLocked(userId, false /* parent */)); 5047 } else { 5048 timeMs = Long.MAX_VALUE; 5049 } 5050 5051 final DevicePolicyData policy = getUserDataUnchecked(userId); 5052 if (policy.mLastMaximumTimeToLock == timeMs) { 5053 return; 5054 } 5055 policy.mLastMaximumTimeToLock = timeMs; 5056 5057 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5058 userId, policy.mLastMaximumTimeToLock); 5059 } 5060 5061 @Override 5062 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) { 5063 if (!mHasFeature) { 5064 return 0; 5065 } 5066 enforceFullCrossUsersPermission(userHandle); 5067 synchronized (this) { 5068 if (who != null) { 5069 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 5070 return admin != null ? admin.maximumTimeToUnlock : 0; 5071 } 5072 // Return the strictest policy across all participating admins. 5073 final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5074 userHandle, parent); 5075 final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins); 5076 return timeMs == Long.MAX_VALUE ? 0 : timeMs; 5077 } 5078 } 5079 5080 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) { 5081 long time = Long.MAX_VALUE; 5082 for (final ActiveAdmin admin : admins) { 5083 if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) { 5084 time = admin.maximumTimeToUnlock; 5085 } 5086 } 5087 return time; 5088 } 5089 5090 @Override 5091 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, 5092 boolean parent) { 5093 if (!mHasFeature) { 5094 return; 5095 } 5096 Preconditions.checkNotNull(who, "ComponentName is null"); 5097 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number."); 5098 // timeoutMs with value 0 means that the admin doesn't participate 5099 // timeoutMs is clamped to the interval in case the internal constants change in the future 5100 final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs(); 5101 if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) { 5102 timeoutMs = minimumStrongAuthTimeout; 5103 } 5104 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 5105 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5106 } 5107 5108 final int userHandle = mInjector.userHandleGetCallingUserId(); 5109 synchronized (this) { 5110 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5111 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent); 5112 if (ap.strongAuthUnlockTimeout != timeoutMs) { 5113 ap.strongAuthUnlockTimeout = timeoutMs; 5114 saveSettingsLocked(userHandle); 5115 } 5116 } 5117 } 5118 5119 /** 5120 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all 5121 * admins if who is null. 5122 * Returns 0 if not configured for the provided admin. 5123 */ 5124 @Override 5125 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) { 5126 if (!mHasFeature) { 5127 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5128 } 5129 enforceFullCrossUsersPermission(userId); 5130 synchronized (this) { 5131 if (who != null) { 5132 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent); 5133 return admin != null ? admin.strongAuthUnlockTimeout : 0; 5134 } 5135 5136 // Return the strictest policy across all participating admins. 5137 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent); 5138 5139 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5140 for (int i = 0; i < admins.size(); i++) { 5141 final long timeout = admins.get(i).strongAuthUnlockTimeout; 5142 if (timeout != 0) { // take only participating admins into account 5143 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout); 5144 } 5145 } 5146 return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs()); 5147 } 5148 } 5149 5150 private long getMinimumStrongAuthTimeoutMs() { 5151 if (!mInjector.isBuildDebuggable()) { 5152 return MINIMUM_STRONG_AUTH_TIMEOUT_MS; 5153 } 5154 // ideally the property was named persist.sys.min_strong_auth_timeout, but system property 5155 // name cannot be longer than 31 characters 5156 return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo", 5157 MINIMUM_STRONG_AUTH_TIMEOUT_MS), 5158 MINIMUM_STRONG_AUTH_TIMEOUT_MS); 5159 } 5160 5161 @Override 5162 public void lockNow(int flags, boolean parent) { 5163 if (!mHasFeature) { 5164 return; 5165 } 5166 5167 final int callingUserId = mInjector.userHandleGetCallingUserId(); 5168 synchronized (this) { 5169 // This API can only be called by an active device admin, 5170 // so try to retrieve it to check that the caller is one. 5171 final ActiveAdmin admin = getActiveAdminForCallerLocked( 5172 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 5173 5174 final long ident = mInjector.binderClearCallingIdentity(); 5175 try { 5176 final ComponentName adminComponent = admin.info.getComponent(); 5177 // Evict key 5178 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) { 5179 enforceManagedProfile( 5180 callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 5181 if (!isProfileOwner(adminComponent, callingUserId)) { 5182 throw new SecurityException("Only profile owner admins can set " 5183 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 5184 } 5185 if (parent) { 5186 throw new IllegalArgumentException( 5187 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent"); 5188 } 5189 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5190 throw new UnsupportedOperationException( 5191 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices"); 5192 } 5193 mUserManager.evictCredentialEncryptionKey(callingUserId); 5194 } 5195 5196 // Lock all users unless this is a managed profile with a separate challenge 5197 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId) 5198 ? UserHandle.USER_ALL : callingUserId); 5199 mLockPatternUtils.requireStrongAuth( 5200 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock); 5201 5202 // Require authentication for the device or profile 5203 if (userToLock == UserHandle.USER_ALL) { 5204 // Power off the display 5205 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(), 5206 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 5207 mInjector.getIWindowManager().lockNow(null); 5208 } else { 5209 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true); 5210 } 5211 5212 if (SecurityLog.isLoggingEnabled()) { 5213 final int affectedUserId = 5214 parent ? getProfileParentId(callingUserId) : callingUserId; 5215 SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK, 5216 adminComponent.getPackageName(), callingUserId, affectedUserId); 5217 } 5218 } catch (RemoteException e) { 5219 } finally { 5220 mInjector.binderRestoreCallingIdentity(ident); 5221 } 5222 } 5223 } 5224 5225 @Override 5226 public void enforceCanManageCaCerts(ComponentName who, String callerPackage) { 5227 if (who == null) { 5228 if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) { 5229 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 5230 } 5231 } else { 5232 enforceProfileOrDeviceOwner(who); 5233 } 5234 } 5235 5236 private void enforceProfileOrDeviceOwner(ComponentName who) { 5237 synchronized (this) { 5238 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5239 } 5240 } 5241 5242 @Override 5243 public boolean approveCaCert(String alias, int userId, boolean approval) { 5244 enforceManageUsers(); 5245 synchronized (this) { 5246 Set<String> certs = getUserData(userId).mAcceptedCaCertificates; 5247 boolean changed = (approval ? certs.add(alias) : certs.remove(alias)); 5248 if (!changed) { 5249 return false; 5250 } 5251 saveSettingsLocked(userId); 5252 } 5253 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5254 return true; 5255 } 5256 5257 @Override 5258 public boolean isCaCertApproved(String alias, int userId) { 5259 enforceManageUsers(); 5260 synchronized (this) { 5261 return getUserData(userId).mAcceptedCaCertificates.contains(alias); 5262 } 5263 } 5264 5265 private void removeCaApprovalsIfNeeded(int userId) { 5266 for (UserInfo userInfo : mUserManager.getProfiles(userId)) { 5267 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id); 5268 if (userInfo.isManagedProfile()){ 5269 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id)); 5270 } 5271 if (!isSecure) { 5272 synchronized (this) { 5273 getUserData(userInfo.id).mAcceptedCaCertificates.clear(); 5274 saveSettingsLocked(userInfo.id); 5275 } 5276 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5277 } 5278 } 5279 } 5280 5281 @Override 5282 public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) 5283 throws RemoteException { 5284 if (!mHasFeature) { 5285 return false; 5286 } 5287 enforceCanManageCaCerts(admin, callerPackage); 5288 5289 final String alias; 5290 5291 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 5292 final long id = mInjector.binderClearCallingIdentity(); 5293 try { 5294 alias = mCertificateMonitor.installCaCert(userHandle, certBuffer); 5295 if (alias == null) { 5296 Log.w(LOG_TAG, "Problem installing cert"); 5297 return false; 5298 } 5299 } finally { 5300 mInjector.binderRestoreCallingIdentity(id); 5301 } 5302 5303 synchronized (this) { 5304 getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias); 5305 saveSettingsLocked(userHandle.getIdentifier()); 5306 } 5307 return true; 5308 } 5309 5310 @Override 5311 public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) { 5312 if (!mHasFeature) { 5313 return; 5314 } 5315 enforceCanManageCaCerts(admin, callerPackage); 5316 5317 final int userId = mInjector.userHandleGetCallingUserId(); 5318 final long id = mInjector.binderClearCallingIdentity(); 5319 try { 5320 mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases); 5321 } finally { 5322 mInjector.binderRestoreCallingIdentity(id); 5323 } 5324 5325 synchronized (this) { 5326 if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) { 5327 saveSettingsLocked(userId); 5328 } 5329 } 5330 } 5331 5332 @Override 5333 public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey, 5334 byte[] cert, byte[] chain, String alias, boolean requestAccess, 5335 boolean isUserSelectable) { 5336 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5337 DELEGATION_CERT_INSTALL); 5338 5339 5340 final int callingUid = mInjector.binderGetCallingUid(); 5341 final long id = mInjector.binderClearCallingIdentity(); 5342 try { 5343 final KeyChainConnection keyChainConnection = 5344 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid)); 5345 try { 5346 IKeyChainService keyChain = keyChainConnection.getService(); 5347 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) { 5348 return false; 5349 } 5350 if (requestAccess) { 5351 keyChain.setGrant(callingUid, alias, true); 5352 } 5353 keyChain.setUserSelectable(alias, isUserSelectable); 5354 return true; 5355 } catch (RemoteException e) { 5356 Log.e(LOG_TAG, "Installing certificate", e); 5357 } finally { 5358 keyChainConnection.close(); 5359 } 5360 } catch (InterruptedException e) { 5361 Log.w(LOG_TAG, "Interrupted while installing certificate", e); 5362 Thread.currentThread().interrupt(); 5363 } finally { 5364 mInjector.binderRestoreCallingIdentity(id); 5365 } 5366 return false; 5367 } 5368 5369 @Override 5370 public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) { 5371 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5372 DELEGATION_CERT_INSTALL); 5373 5374 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 5375 final long id = Binder.clearCallingIdentity(); 5376 try { 5377 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 5378 try { 5379 IKeyChainService keyChain = keyChainConnection.getService(); 5380 return keyChain.removeKeyPair(alias); 5381 } catch (RemoteException e) { 5382 Log.e(LOG_TAG, "Removing keypair", e); 5383 } finally { 5384 keyChainConnection.close(); 5385 } 5386 } catch (InterruptedException e) { 5387 Log.w(LOG_TAG, "Interrupted while removing keypair", e); 5388 Thread.currentThread().interrupt(); 5389 } finally { 5390 Binder.restoreCallingIdentity(id); 5391 } 5392 return false; 5393 } 5394 5395 private void enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner( 5396 ComponentName who, String callerPackage, int callerUid) throws SecurityException { 5397 if (who == null) { 5398 if (!mOwners.hasDeviceOwner()) { 5399 throw new SecurityException("Not in Device Owner mode."); 5400 } 5401 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 5402 throw new SecurityException("Caller not from device owner user"); 5403 } 5404 if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) { 5405 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() + 5406 "has no permission to generate keys."); 5407 } 5408 } else { 5409 // Caller provided - check it is the device owner. 5410 synchronized (this) { 5411 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5412 } 5413 } 5414 } 5415 5416 @VisibleForTesting 5417 public static int[] translateIdAttestationFlags( 5418 int idAttestationFlags) { 5419 Map<Integer, Integer> idTypeToAttestationFlag = new HashMap(); 5420 idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL); 5421 idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI); 5422 idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID); 5423 5424 int numFlagsSet = Integer.bitCount(idAttestationFlags); 5425 // No flags are set - return null to indicate no device ID attestation information should 5426 // be included in the attestation record. 5427 if (numFlagsSet == 0) { 5428 return null; 5429 } 5430 5431 // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if 5432 // no other flag is set. That will lead to inclusion of general device make data in the 5433 // attestation record, but no specific device identifiers. 5434 if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) { 5435 numFlagsSet -= 1; 5436 idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO); 5437 } 5438 5439 int[] attestationUtilsFlags = new int[numFlagsSet]; 5440 int i = 0; 5441 for (Integer idType: idTypeToAttestationFlag.keySet()) { 5442 if ((idType & idAttestationFlags) != 0) { 5443 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType); 5444 } 5445 } 5446 5447 return attestationUtilsFlags; 5448 } 5449 5450 @Override 5451 public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm, 5452 ParcelableKeyGenParameterSpec parcelableKeySpec, 5453 int idAttestationFlags, 5454 KeymasterCertificateChain attestationChain) { 5455 // Get attestation flags, if any. 5456 final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags); 5457 final boolean deviceIdAttestationRequired = attestationUtilsFlags != null; 5458 final int callingUid = mInjector.binderGetCallingUid(); 5459 5460 if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) { 5461 enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner(who, callerPackage, callingUid); 5462 } else { 5463 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5464 DELEGATION_CERT_INSTALL); 5465 } 5466 final KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec(); 5467 final String alias = keySpec.getKeystoreAlias(); 5468 if (TextUtils.isEmpty(alias)) { 5469 throw new IllegalArgumentException("Empty alias provided."); 5470 } 5471 // As the caller will be granted access to the key, ensure no UID was specified, as 5472 // it will not have the desired effect. 5473 if (keySpec.getUid() != KeyStore.UID_SELF) { 5474 Log.e(LOG_TAG, "Only the caller can be granted access to the generated keypair."); 5475 return false; 5476 } 5477 5478 if (deviceIdAttestationRequired && (keySpec.getAttestationChallenge() == null)) { 5479 throw new IllegalArgumentException( 5480 "Requested Device ID attestation but challenge is empty."); 5481 } 5482 5483 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 5484 final long id = mInjector.binderClearCallingIdentity(); 5485 try { 5486 try (KeyChainConnection keyChainConnection = 5487 KeyChain.bindAsUser(mContext, userHandle)) { 5488 IKeyChainService keyChain = keyChainConnection.getService(); 5489 5490 // Copy the provided keySpec, excluding the attestation challenge, which will be 5491 // used later for requesting key attestation record. 5492 final KeyGenParameterSpec noAttestationSpec = 5493 new KeyGenParameterSpec.Builder(keySpec) 5494 .setAttestationChallenge(null) 5495 .build(); 5496 5497 final boolean generationResult = keyChain.generateKeyPair(algorithm, 5498 new ParcelableKeyGenParameterSpec(noAttestationSpec)); 5499 if (!generationResult) { 5500 Log.e(LOG_TAG, "KeyChain failed to generate a keypair."); 5501 return false; 5502 } 5503 5504 // Set a grant for the caller here so that when the client calls 5505 // requestPrivateKey, it will be able to get the key from Keystore. 5506 // Note the use of the calling UID, since the request for the private 5507 // key will come from the client's process, so the grant has to be for 5508 // that UID. 5509 keyChain.setGrant(callingUid, alias, true); 5510 5511 final byte[] attestationChallenge = keySpec.getAttestationChallenge(); 5512 if (attestationChallenge != null) { 5513 final boolean attestationResult = keyChain.attestKey( 5514 alias, attestationChallenge, attestationUtilsFlags, attestationChain); 5515 if (!attestationResult) { 5516 Log.e(LOG_TAG, String.format( 5517 "Attestation for %s failed, deleting key.", alias)); 5518 keyChain.removeKeyPair(alias); 5519 return false; 5520 } 5521 } 5522 return true; 5523 } 5524 } catch (RemoteException e) { 5525 Log.e(LOG_TAG, "KeyChain error while generating a keypair", e); 5526 } catch (InterruptedException e) { 5527 Log.w(LOG_TAG, "Interrupted while generating keypair", e); 5528 Thread.currentThread().interrupt(); 5529 } finally { 5530 mInjector.binderRestoreCallingIdentity(id); 5531 } 5532 return false; 5533 } 5534 5535 @Override 5536 public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias, 5537 byte[] cert, byte[] chain, boolean isUserSelectable) { 5538 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5539 DELEGATION_CERT_INSTALL); 5540 5541 final int callingUid = mInjector.binderGetCallingUid(); 5542 final long id = mInjector.binderClearCallingIdentity(); 5543 try (final KeyChainConnection keyChainConnection = 5544 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid))) { 5545 IKeyChainService keyChain = keyChainConnection.getService(); 5546 if (!keyChain.setKeyPairCertificate(alias, cert, chain)) { 5547 return false; 5548 } 5549 keyChain.setUserSelectable(alias, isUserSelectable); 5550 return true; 5551 } catch (InterruptedException e) { 5552 Log.w(LOG_TAG, "Interrupted while setting keypair certificate", e); 5553 Thread.currentThread().interrupt(); 5554 } catch (RemoteException e) { 5555 Log.e(LOG_TAG, "Failed setting keypair certificate", e); 5556 } finally { 5557 mInjector.binderRestoreCallingIdentity(id); 5558 } 5559 return false; 5560 } 5561 5562 @Override 5563 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, 5564 final IBinder response) { 5565 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers. 5566 if (!isCallerWithSystemUid()) { 5567 return; 5568 } 5569 5570 final UserHandle caller = mInjector.binderGetCallingUserHandle(); 5571 // If there is a profile owner, redirect to that; otherwise query the device owner. 5572 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier()); 5573 if (aliasChooser == null && caller.isSystem()) { 5574 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 5575 if (deviceOwnerAdmin != null) { 5576 aliasChooser = deviceOwnerAdmin.info.getComponent(); 5577 } 5578 } 5579 if (aliasChooser == null) { 5580 sendPrivateKeyAliasResponse(null, response); 5581 return; 5582 } 5583 5584 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 5585 intent.setComponent(aliasChooser); 5586 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 5587 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri); 5588 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 5589 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 5590 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 5591 5592 final long id = mInjector.binderClearCallingIdentity(); 5593 try { 5594 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() { 5595 @Override 5596 public void onReceive(Context context, Intent intent) { 5597 final String chosenAlias = getResultData(); 5598 sendPrivateKeyAliasResponse(chosenAlias, response); 5599 } 5600 }, null, Activity.RESULT_OK, null, null); 5601 } finally { 5602 mInjector.binderRestoreCallingIdentity(id); 5603 } 5604 } 5605 5606 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 5607 final IKeyChainAliasCallback keyChainAliasResponse = 5608 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 5609 // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback 5610 // is oneway, which means it won't block if the recipient lives in another process. 5611 try { 5612 keyChainAliasResponse.alias(alias); 5613 } catch (Exception e) { 5614 // Caller could throw RuntimeException or RemoteException back across processes. Catch 5615 // everything just to be sure. 5616 Log.e(LOG_TAG, "error while responding to callback", e); 5617 } 5618 } 5619 5620 /** 5621 * Determine whether DPMS should check if a delegate package is already installed before 5622 * granting it new delegations via {@link #setDelegatedScopes}. 5623 */ 5624 private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, 5625 int targetSdk, List<String> scopes) { 5626 // 1) Never skip is installed check from N. 5627 if (targetSdk >= Build.VERSION_CODES.N) { 5628 return true; 5629 } 5630 // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given. 5631 if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) { 5632 return false; 5633 } 5634 // 3) Skip if all previously granted scopes are being cleared. 5635 if (scopes.isEmpty()) { 5636 return false; 5637 } 5638 // Otherwise it should check that delegatePackage is installed. 5639 return true; 5640 } 5641 5642 /** 5643 * Set the scopes of a device owner or profile owner delegate. 5644 * 5645 * @param who the device owner or profile owner. 5646 * @param delegatePackage the name of the delegate package. 5647 * @param scopes the list of delegation scopes to be given to the delegate package. 5648 */ 5649 @Override 5650 public void setDelegatedScopes(ComponentName who, String delegatePackage, 5651 List<String> scopes) throws SecurityException { 5652 Preconditions.checkNotNull(who, "ComponentName is null"); 5653 Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty"); 5654 Preconditions.checkCollectionElementsNotNull(scopes, "Scopes"); 5655 // Remove possible duplicates. 5656 scopes = new ArrayList(new ArraySet(scopes)); 5657 // Ensure given scopes are valid. 5658 if (scopes.retainAll(Arrays.asList(DELEGATIONS))) { 5659 throw new IllegalArgumentException("Unexpected delegation scopes"); 5660 } 5661 5662 // Retrieve the user ID of the calling process. 5663 final int userId = mInjector.userHandleGetCallingUserId(); 5664 synchronized (this) { 5665 // Ensure calling process is device/profile owner. 5666 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5667 // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N). 5668 if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage, 5669 getTargetSdk(who.getPackageName(), userId), scopes)) { 5670 // Throw when the delegate package is not installed. 5671 if (!isPackageInstalledForUser(delegatePackage, userId)) { 5672 throw new IllegalArgumentException("Package " + delegatePackage 5673 + " is not installed on the current user"); 5674 } 5675 } 5676 5677 // Set the new delegate in user policies. 5678 final DevicePolicyData policy = getUserData(userId); 5679 if (!scopes.isEmpty()) { 5680 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes)); 5681 } else { 5682 // Remove any delegation info if the given scopes list is empty. 5683 policy.mDelegationMap.remove(delegatePackage); 5684 } 5685 5686 // Notify delegate package of updates. 5687 final Intent intent = new Intent( 5688 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED); 5689 // Only call receivers registered with Context#registerReceiver (don’t wake delegate). 5690 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 5691 // Limit components this intent resolves to to the delegate package. 5692 intent.setPackage(delegatePackage); 5693 // Include the list of delegated scopes as an extra. 5694 intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, 5695 (ArrayList<String>) scopes); 5696 // Send the broadcast. 5697 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 5698 5699 // Persist updates. 5700 saveSettingsLocked(userId); 5701 } 5702 } 5703 5704 /** 5705 * Get the delegation scopes given to a delegate package by a device owner or profile owner. 5706 * 5707 * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by 5708 * passing in {@code null} as the {@code who} parameter and its own name as the 5709 * {@code delegatepackage}. 5710 * 5711 * @param who the device owner or profile owner, or {@code null} if the caller is 5712 * {@code delegatePackage}. 5713 * @param delegatePackage the name of the delegate package whose scopes are to be retrieved. 5714 * @return a list of the delegation scopes currently given to {@code delegatePackage}. 5715 */ 5716 @Override 5717 @NonNull 5718 public List<String> getDelegatedScopes(ComponentName who, 5719 String delegatePackage) throws SecurityException { 5720 Preconditions.checkNotNull(delegatePackage, "Delegate package is null"); 5721 5722 // Retrieve the user ID of the calling process. 5723 final int callingUid = mInjector.binderGetCallingUid(); 5724 final int userId = UserHandle.getUserId(callingUid); 5725 synchronized (this) { 5726 // Ensure calling process is device/profile owner. 5727 if (who != null) { 5728 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5729 // Or ensure calling process is delegatePackage itself. 5730 } else { 5731 int uid = 0; 5732 try { 5733 uid = mInjector.getPackageManager() 5734 .getPackageUidAsUser(delegatePackage, userId); 5735 } catch(NameNotFoundException e) { 5736 } 5737 if (uid != callingUid) { 5738 throw new SecurityException("Caller with uid " + callingUid + " is not " 5739 + delegatePackage); 5740 } 5741 } 5742 final DevicePolicyData policy = getUserData(userId); 5743 // Retrieve the scopes assigned to delegatePackage, or null if no scope was given. 5744 final List<String> scopes = policy.mDelegationMap.get(delegatePackage); 5745 return scopes == null ? Collections.EMPTY_LIST : scopes; 5746 } 5747 } 5748 5749 /** 5750 * Get a list of packages that were given a specific delegation scopes by a device owner or 5751 * profile owner. 5752 * 5753 * @param who the device owner or profile owner. 5754 * @param scope the scope whose delegates are to be retrieved. 5755 * @return a list of the delegate packages currently given the {@code scope} delegation. 5756 */ 5757 @NonNull 5758 public List<String> getDelegatePackages(ComponentName who, String scope) 5759 throws SecurityException { 5760 Preconditions.checkNotNull(who, "ComponentName is null"); 5761 Preconditions.checkNotNull(scope, "Scope is null"); 5762 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 5763 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 5764 } 5765 5766 // Retrieve the user ID of the calling process. 5767 final int userId = mInjector.userHandleGetCallingUserId(); 5768 synchronized (this) { 5769 // Ensure calling process is device/profile owner. 5770 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5771 final DevicePolicyData policy = getUserData(userId); 5772 5773 // Create a list to hold the resulting delegate packages. 5774 final List<String> delegatePackagesWithScope = new ArrayList<>(); 5775 // Add all delegations containing scope to the result list. 5776 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 5777 if (policy.mDelegationMap.valueAt(i).contains(scope)) { 5778 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i)); 5779 } 5780 } 5781 return delegatePackagesWithScope; 5782 } 5783 } 5784 5785 /** 5786 * Check whether a caller application has been delegated a given scope via 5787 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 5788 * device owner. 5789 * <p> 5790 * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and 5791 * then comparing the calling UID with the UID of {@code callerPackage} as reported by 5792 * {@link PackageManager#getPackageUidAsUser}. 5793 * 5794 * @param callerPackage the name of the package that is trying to invoke a function in the DPMS. 5795 * @param scope the delegation scope to be checked. 5796 * @return {@code true} if the calling process is a delegate of {@code scope}. 5797 */ 5798 private boolean isCallerDelegate(String callerPackage, String scope) { 5799 Preconditions.checkNotNull(callerPackage, "callerPackage is null"); 5800 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 5801 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 5802 } 5803 5804 // Retrieve the UID and user ID of the calling process. 5805 final int callingUid = mInjector.binderGetCallingUid(); 5806 final int userId = UserHandle.getUserId(callingUid); 5807 synchronized (this) { 5808 // Retrieve user policy data. 5809 final DevicePolicyData policy = getUserData(userId); 5810 // Retrieve the list of delegation scopes granted to callerPackage. 5811 final List<String> scopes = policy.mDelegationMap.get(callerPackage); 5812 // Check callingUid only if callerPackage has the required scope delegation. 5813 if (scopes != null && scopes.contains(scope)) { 5814 try { 5815 // Retrieve the expected UID for callerPackage. 5816 final int uid = mInjector.getPackageManager() 5817 .getPackageUidAsUser(callerPackage, userId); 5818 // Return true if the caller is actually callerPackage. 5819 return uid == callingUid; 5820 } catch (NameNotFoundException e) { 5821 // Ignore. 5822 } 5823 } 5824 return false; 5825 } 5826 } 5827 5828 /** 5829 * Throw a security exception if a ComponentName is given and it is not a device/profile owner 5830 * or if the calling process is not a delegate of the given scope. 5831 * 5832 * @param who the device owner of profile owner, or null if {@code callerPackage} is a 5833 * {@code scope} delegate. 5834 * @param callerPackage the name of the calling package. Required if {@code who} is 5835 * {@code null}. 5836 * @param reqPolicy the policy used in the API whose access permission is being checked. 5837 * @param scope the delegation scope corresponding to the API being checked. 5838 * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy}; 5839 * or when {@code who} is {@code null} and {@code callerPackage} is not a delegate 5840 * of {@code scope}. 5841 */ 5842 private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, 5843 String scope) { 5844 // If a ComponentName is given ensure it is a device or profile owner according to policy. 5845 if (who != null) { 5846 synchronized (this) { 5847 getActiveAdminForCallerLocked(who, reqPolicy); 5848 } 5849 // If no ComponentName is given ensure calling process has scope delegation. 5850 } else if (!isCallerDelegate(callerPackage, scope)) { 5851 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() 5852 + " is not a delegate of scope " + scope + "."); 5853 } 5854 } 5855 5856 /** 5857 * Helper function to preserve delegation behavior pre-O when using the deprecated functions 5858 * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}. 5859 */ 5860 private void setDelegatedScopePreO(ComponentName who, 5861 String delegatePackage, String scope) { 5862 Preconditions.checkNotNull(who, "ComponentName is null"); 5863 5864 final int userId = mInjector.userHandleGetCallingUserId(); 5865 synchronized(this) { 5866 // Ensure calling process is device/profile owner. 5867 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5868 final DevicePolicyData policy = getUserData(userId); 5869 5870 if (delegatePackage != null) { 5871 // Set package as a delegate for scope if it is not already one. 5872 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 5873 if (scopes == null) { 5874 scopes = new ArrayList<>(); 5875 } 5876 if (!scopes.contains(scope)) { 5877 scopes.add(scope); 5878 setDelegatedScopes(who, delegatePackage, scopes); 5879 } 5880 } 5881 5882 // Clear any existing scope delegates. 5883 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 5884 final String currentPackage = policy.mDelegationMap.keyAt(i); 5885 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 5886 5887 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) { 5888 final List<String> newScopes = new ArrayList(currentScopes); 5889 newScopes.remove(scope); 5890 setDelegatedScopes(who, currentPackage, newScopes); 5891 } 5892 } 5893 } 5894 } 5895 5896 @Override 5897 public void setCertInstallerPackage(ComponentName who, String installerPackage) 5898 throws SecurityException { 5899 setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL); 5900 } 5901 5902 @Override 5903 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 5904 final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL); 5905 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 5906 } 5907 5908 /** 5909 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is 5910 * not installed and therefore not available. 5911 * 5912 * @throws SecurityException if the caller is not a profile or device owner. 5913 * @throws UnsupportedOperationException if the package does not support being set as always-on. 5914 */ 5915 @Override 5916 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown) 5917 throws SecurityException { 5918 enforceProfileOrDeviceOwner(admin); 5919 5920 final int userId = mInjector.userHandleGetCallingUserId(); 5921 final long token = mInjector.binderClearCallingIdentity(); 5922 try { 5923 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) { 5924 return false; 5925 } 5926 ConnectivityManager connectivityManager = (ConnectivityManager) 5927 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5928 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) { 5929 throw new UnsupportedOperationException(); 5930 } 5931 } finally { 5932 mInjector.binderRestoreCallingIdentity(token); 5933 } 5934 return true; 5935 } 5936 5937 @Override 5938 public String getAlwaysOnVpnPackage(ComponentName admin) 5939 throws SecurityException { 5940 enforceProfileOrDeviceOwner(admin); 5941 5942 final int userId = mInjector.userHandleGetCallingUserId(); 5943 final long token = mInjector.binderClearCallingIdentity(); 5944 try{ 5945 ConnectivityManager connectivityManager = (ConnectivityManager) 5946 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5947 return connectivityManager.getAlwaysOnVpnPackageForUser(userId); 5948 } finally { 5949 mInjector.binderRestoreCallingIdentity(token); 5950 } 5951 } 5952 5953 private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) { 5954 wtfIfInLock(); 5955 5956 if (wipeExtRequested) { 5957 StorageManager sm = (StorageManager) mContext.getSystemService( 5958 Context.STORAGE_SERVICE); 5959 sm.wipeAdoptableDisks(); 5960 } 5961 try { 5962 mInjector.recoverySystemRebootWipeUserData( 5963 /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc); 5964 } catch (IOException | SecurityException e) { 5965 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 5966 } 5967 } 5968 5969 private void forceWipeUser(int userId, String wipeReasonForUser) { 5970 try { 5971 IActivityManager am = mInjector.getIActivityManager(); 5972 if (am.getCurrentUser().id == userId) { 5973 am.switchUser(UserHandle.USER_SYSTEM); 5974 } 5975 5976 boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId); 5977 if (!userRemoved) { 5978 Slog.w(LOG_TAG, "Couldn't remove user " + userId); 5979 } else if (isManagedProfile(userId)) { 5980 sendWipeProfileNotification(wipeReasonForUser); 5981 } 5982 } catch (RemoteException re) { 5983 // Shouldn't happen 5984 } 5985 } 5986 5987 @Override 5988 public void wipeDataWithReason(int flags, String wipeReasonForUser) { 5989 if (!mHasFeature) { 5990 return; 5991 } 5992 Preconditions.checkStringNotEmpty(wipeReasonForUser, "wipeReasonForUser is null or empty"); 5993 enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId()); 5994 5995 final ActiveAdmin admin; 5996 synchronized (this) { 5997 admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA); 5998 } 5999 String internalReason = "DevicePolicyManager.wipeDataWithReason() from " 6000 + admin.info.getComponent().flattenToShortString(); 6001 wipeDataNoLock( 6002 admin.info.getComponent(), flags, internalReason, wipeReasonForUser, 6003 admin.getUserHandle().getIdentifier()); 6004 } 6005 6006 private void wipeDataNoLock(ComponentName admin, int flags, String internalReason, 6007 String wipeReasonForUser, int userId) { 6008 wtfIfInLock(); 6009 6010 long ident = mInjector.binderClearCallingIdentity(); 6011 try { 6012 // First check whether the admin is allowed to wipe the device/user/profile. 6013 final String restriction; 6014 if (userId == UserHandle.USER_SYSTEM) { 6015 restriction = UserManager.DISALLOW_FACTORY_RESET; 6016 } else if (isManagedProfile(userId)) { 6017 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 6018 } else { 6019 restriction = UserManager.DISALLOW_REMOVE_USER; 6020 } 6021 if (isAdminAffectedByRestriction(admin, restriction, userId)) { 6022 throw new SecurityException("Cannot wipe data. " + restriction 6023 + " restriction is set for user " + userId); 6024 } 6025 6026 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 6027 if (!isDeviceOwner(admin, userId)) { 6028 throw new SecurityException( 6029 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA"); 6030 } 6031 PersistentDataBlockManager manager = (PersistentDataBlockManager) 6032 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 6033 if (manager != null) { 6034 manager.wipe(); 6035 } 6036 } 6037 6038 // TODO If split user is enabled and the device owner is set in the primary user 6039 // (rather than system), we should probably trigger factory reset. Current code just 6040 // removes that user (but still clears FRP...) 6041 if (userId == UserHandle.USER_SYSTEM) { 6042 forceWipeDeviceNoLock(/*wipeExtRequested=*/ ( 6043 flags & WIPE_EXTERNAL_STORAGE) != 0, 6044 internalReason, 6045 /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0); 6046 } else { 6047 forceWipeUser(userId, wipeReasonForUser); 6048 } 6049 } finally { 6050 mInjector.binderRestoreCallingIdentity(ident); 6051 } 6052 } 6053 6054 private void sendWipeProfileNotification(String wipeReasonForUser) { 6055 Notification notification = 6056 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 6057 .setSmallIcon(android.R.drawable.stat_sys_warning) 6058 .setContentTitle(mContext.getString(R.string.work_profile_deleted)) 6059 .setContentText(wipeReasonForUser) 6060 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 6061 .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser)) 6062 .build(); 6063 mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification); 6064 } 6065 6066 private void clearWipeProfileNotification() { 6067 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED); 6068 } 6069 6070 @Override 6071 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 6072 if (!mHasFeature) { 6073 return; 6074 } 6075 enforceFullCrossUsersPermission(userHandle); 6076 mContext.enforceCallingOrSelfPermission( 6077 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6078 6079 synchronized (this) { 6080 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 6081 if (admin == null) { 6082 result.sendResult(null); 6083 return; 6084 } 6085 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 6086 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 6087 intent.setComponent(admin.info.getComponent()); 6088 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 6089 null, new BroadcastReceiver() { 6090 @Override 6091 public void onReceive(Context context, Intent intent) { 6092 result.sendResult(getResultExtras(false)); 6093 } 6094 }, null, Activity.RESULT_OK, null, null); 6095 } 6096 } 6097 6098 /** 6099 * Notify DPMS regarding the metric of the current password. This happens when the user changes 6100 * the password, but also when the user just unlocks the keyguard. In comparison, 6101 * reportPasswordChanged() is only called when the user changes the password. 6102 */ 6103 @Override 6104 public void setActivePasswordState(PasswordMetrics metrics, int userHandle) { 6105 if (!mHasFeature) { 6106 return; 6107 } 6108 enforceFullCrossUsersPermission(userHandle); 6109 mContext.enforceCallingOrSelfPermission( 6110 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6111 6112 // If the managed profile doesn't have a separate password, set the metrics to default 6113 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 6114 metrics = new PasswordMetrics(); 6115 } 6116 6117 validateQualityConstant(metrics.quality); 6118 DevicePolicyData policy = getUserData(userHandle); 6119 synchronized (this) { 6120 policy.mActivePasswordMetrics = metrics; 6121 policy.mPasswordStateHasBeenSetSinceBoot = true; 6122 } 6123 } 6124 6125 @Override 6126 public void reportPasswordChanged(@UserIdInt int userId) { 6127 if (!mHasFeature) { 6128 return; 6129 } 6130 enforceFullCrossUsersPermission(userId); 6131 6132 // Managed Profile password can only be changed when it has a separate challenge. 6133 if (!isSeparateProfileChallengeEnabled(userId)) { 6134 enforceNotManagedProfile(userId, "set the active password"); 6135 } 6136 6137 mContext.enforceCallingOrSelfPermission( 6138 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6139 6140 DevicePolicyData policy = getUserData(userId); 6141 6142 long ident = mInjector.binderClearCallingIdentity(); 6143 try { 6144 synchronized (this) { 6145 policy.mFailedPasswordAttempts = 0; 6146 updatePasswordValidityCheckpointLocked(userId); 6147 saveSettingsLocked(userId); 6148 updatePasswordExpirationsLocked(userId); 6149 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 6150 6151 // Send a broadcast to each profile using this password as its primary unlock. 6152 sendAdminCommandForLockscreenPoliciesLocked( 6153 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 6154 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 6155 } 6156 removeCaApprovalsIfNeeded(userId); 6157 } finally { 6158 mInjector.binderRestoreCallingIdentity(ident); 6159 } 6160 } 6161 6162 /** 6163 * Called any time the device password is updated. Resets all password expiration clocks. 6164 */ 6165 private void updatePasswordExpirationsLocked(int userHandle) { 6166 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>(); 6167 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 6168 userHandle, /* parent */ false); 6169 final int N = admins.size(); 6170 for (int i = 0; i < N; i++) { 6171 ActiveAdmin admin = admins.get(i); 6172 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 6173 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 6174 long timeout = admin.passwordExpirationTimeout; 6175 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 6176 admin.passwordExpirationDate = expiration; 6177 } 6178 } 6179 for (int affectedUserId : affectedUserIds) { 6180 saveSettingsLocked(affectedUserId); 6181 } 6182 } 6183 6184 @Override 6185 public void reportFailedPasswordAttempt(int userHandle) { 6186 enforceFullCrossUsersPermission(userHandle); 6187 if (!isSeparateProfileChallengeEnabled(userHandle)) { 6188 enforceNotManagedProfile(userHandle, 6189 "report failed password attempt if separate profile challenge is not in place"); 6190 } 6191 mContext.enforceCallingOrSelfPermission( 6192 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6193 6194 boolean wipeData = false; 6195 ActiveAdmin strictestAdmin = null; 6196 final long ident = mInjector.binderClearCallingIdentity(); 6197 try { 6198 synchronized (this) { 6199 DevicePolicyData policy = getUserData(userHandle); 6200 policy.mFailedPasswordAttempts++; 6201 saveSettingsLocked(userHandle); 6202 if (mHasFeature) { 6203 strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 6204 userHandle, /* parent */ false); 6205 int max = strictestAdmin != null 6206 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 6207 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 6208 wipeData = true; 6209 } 6210 6211 sendAdminCommandForLockscreenPoliciesLocked( 6212 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 6213 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 6214 } 6215 } 6216 } finally { 6217 mInjector.binderRestoreCallingIdentity(ident); 6218 } 6219 6220 if (wipeData && strictestAdmin != null) { 6221 final int userId = strictestAdmin.getUserHandle().getIdentifier(); 6222 Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: " 6223 + strictestAdmin.info.getComponent().flattenToShortString() 6224 + ". Calling wipeData for user " + userId); 6225 6226 // Attempt to wipe the device/user/profile associated with the admin, as if the 6227 // admin had called wipeData(). That way we can check whether the admin is actually 6228 // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the 6229 // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be 6230 // able to do so). 6231 // IMPORTANT: Call without holding the lock to prevent deadlock. 6232 try { 6233 String wipeReasonForUser = mContext.getString( 6234 R.string.work_profile_deleted_reason_maximum_password_failure); 6235 wipeDataNoLock(strictestAdmin.info.getComponent(), 6236 /*flags=*/ 0, 6237 /*reason=*/ "reportFailedPasswordAttempt()", 6238 wipeReasonForUser, 6239 userId); 6240 } catch (SecurityException e) { 6241 Slog.w(LOG_TAG, "Failed to wipe user " + userId 6242 + " after max failed password attempts reached.", e); 6243 } 6244 } 6245 6246 if (mInjector.securityLogIsLoggingEnabled()) { 6247 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, 6248 /*result*/ 0, /*method strength*/ 1); 6249 } 6250 } 6251 6252 @Override 6253 public void reportSuccessfulPasswordAttempt(int userHandle) { 6254 enforceFullCrossUsersPermission(userHandle); 6255 mContext.enforceCallingOrSelfPermission( 6256 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6257 6258 synchronized (this) { 6259 DevicePolicyData policy = getUserData(userHandle); 6260 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 6261 long ident = mInjector.binderClearCallingIdentity(); 6262 try { 6263 policy.mFailedPasswordAttempts = 0; 6264 policy.mPasswordOwner = -1; 6265 saveSettingsLocked(userHandle); 6266 if (mHasFeature) { 6267 sendAdminCommandForLockscreenPoliciesLocked( 6268 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 6269 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 6270 } 6271 } finally { 6272 mInjector.binderRestoreCallingIdentity(ident); 6273 } 6274 } 6275 } 6276 6277 if (mInjector.securityLogIsLoggingEnabled()) { 6278 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 6279 /*method strength*/ 1); 6280 } 6281 } 6282 6283 @Override 6284 public void reportFailedFingerprintAttempt(int userHandle) { 6285 enforceFullCrossUsersPermission(userHandle); 6286 mContext.enforceCallingOrSelfPermission( 6287 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6288 if (mInjector.securityLogIsLoggingEnabled()) { 6289 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 6290 /*method strength*/ 0); 6291 } 6292 } 6293 6294 @Override 6295 public void reportSuccessfulFingerprintAttempt(int userHandle) { 6296 enforceFullCrossUsersPermission(userHandle); 6297 mContext.enforceCallingOrSelfPermission( 6298 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6299 if (mInjector.securityLogIsLoggingEnabled()) { 6300 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 6301 /*method strength*/ 0); 6302 } 6303 } 6304 6305 @Override 6306 public void reportKeyguardDismissed(int userHandle) { 6307 enforceFullCrossUsersPermission(userHandle); 6308 mContext.enforceCallingOrSelfPermission( 6309 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6310 6311 if (mInjector.securityLogIsLoggingEnabled()) { 6312 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 6313 } 6314 } 6315 6316 @Override 6317 public void reportKeyguardSecured(int userHandle) { 6318 enforceFullCrossUsersPermission(userHandle); 6319 mContext.enforceCallingOrSelfPermission( 6320 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6321 6322 if (mInjector.securityLogIsLoggingEnabled()) { 6323 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 6324 } 6325 } 6326 6327 @Override 6328 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 6329 String exclusionList) { 6330 if (!mHasFeature) { 6331 return null; 6332 } 6333 synchronized(this) { 6334 Preconditions.checkNotNull(who, "ComponentName is null"); 6335 6336 // Only check if system user has set global proxy. We don't allow other users to set it. 6337 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6338 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6339 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 6340 6341 // Scan through active admins and find if anyone has already 6342 // set the global proxy. 6343 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 6344 for (ComponentName component : compSet) { 6345 ActiveAdmin ap = policy.mAdminMap.get(component); 6346 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 6347 // Another admin already sets the global proxy 6348 // Return it to the caller. 6349 return component; 6350 } 6351 } 6352 6353 // If the user is not system, don't set the global proxy. Fail silently. 6354 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 6355 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 6356 + UserHandle.getCallingUserId() + " is not permitted."); 6357 return null; 6358 } 6359 if (proxySpec == null) { 6360 admin.specifiesGlobalProxy = false; 6361 admin.globalProxySpec = null; 6362 admin.globalProxyExclusionList = null; 6363 } else { 6364 6365 admin.specifiesGlobalProxy = true; 6366 admin.globalProxySpec = proxySpec; 6367 admin.globalProxyExclusionList = exclusionList; 6368 } 6369 6370 // Reset the global proxy accordingly 6371 // Do this using system permissions, as apps cannot write to secure settings 6372 long origId = mInjector.binderClearCallingIdentity(); 6373 try { 6374 resetGlobalProxyLocked(policy); 6375 } finally { 6376 mInjector.binderRestoreCallingIdentity(origId); 6377 } 6378 return null; 6379 } 6380 } 6381 6382 @Override 6383 public ComponentName getGlobalProxyAdmin(int userHandle) { 6384 if (!mHasFeature) { 6385 return null; 6386 } 6387 enforceFullCrossUsersPermission(userHandle); 6388 synchronized(this) { 6389 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6390 // Scan through active admins and find if anyone has already 6391 // set the global proxy. 6392 final int N = policy.mAdminList.size(); 6393 for (int i = 0; i < N; i++) { 6394 ActiveAdmin ap = policy.mAdminList.get(i); 6395 if (ap.specifiesGlobalProxy) { 6396 // Device admin sets the global proxy 6397 // Return it to the caller. 6398 return ap.info.getComponent(); 6399 } 6400 } 6401 } 6402 // No device admin sets the global proxy. 6403 return null; 6404 } 6405 6406 @Override 6407 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 6408 synchronized (this) { 6409 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6410 } 6411 long token = mInjector.binderClearCallingIdentity(); 6412 try { 6413 ConnectivityManager connectivityManager = (ConnectivityManager) 6414 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 6415 connectivityManager.setGlobalProxy(proxyInfo); 6416 } finally { 6417 mInjector.binderRestoreCallingIdentity(token); 6418 } 6419 } 6420 6421 private void resetGlobalProxyLocked(DevicePolicyData policy) { 6422 final int N = policy.mAdminList.size(); 6423 for (int i = 0; i < N; i++) { 6424 ActiveAdmin ap = policy.mAdminList.get(i); 6425 if (ap.specifiesGlobalProxy) { 6426 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 6427 return; 6428 } 6429 } 6430 // No device admins defining global proxies - reset global proxy settings to none 6431 saveGlobalProxyLocked(null, null); 6432 } 6433 6434 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 6435 if (exclusionList == null) { 6436 exclusionList = ""; 6437 } 6438 if (proxySpec == null) { 6439 proxySpec = ""; 6440 } 6441 // Remove white spaces 6442 proxySpec = proxySpec.trim(); 6443 String data[] = proxySpec.split(":"); 6444 int proxyPort = 8080; 6445 if (data.length > 1) { 6446 try { 6447 proxyPort = Integer.parseInt(data[1]); 6448 } catch (NumberFormatException e) {} 6449 } 6450 exclusionList = exclusionList.trim(); 6451 6452 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 6453 if (!proxyProperties.isValid()) { 6454 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 6455 return; 6456 } 6457 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 6458 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 6459 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 6460 exclusionList); 6461 } 6462 6463 /** 6464 * Set the storage encryption request for a single admin. Returns the new total request 6465 * status (for all admins). 6466 */ 6467 @Override 6468 public int setStorageEncryption(ComponentName who, boolean encrypt) { 6469 if (!mHasFeature) { 6470 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6471 } 6472 Preconditions.checkNotNull(who, "ComponentName is null"); 6473 final int userHandle = UserHandle.getCallingUserId(); 6474 synchronized (this) { 6475 // Check for permissions 6476 // Only system user can set storage encryption 6477 if (userHandle != UserHandle.USER_SYSTEM) { 6478 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User " 6479 + UserHandle.getCallingUserId() + " is not permitted."); 6480 return 0; 6481 } 6482 6483 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 6484 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 6485 6486 // Quick exit: If the filesystem does not support encryption, we can exit early. 6487 if (!isEncryptionSupported()) { 6488 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6489 } 6490 6491 // (1) Record the value for the admin so it's sticky 6492 if (ap.encryptionRequested != encrypt) { 6493 ap.encryptionRequested = encrypt; 6494 saveSettingsLocked(userHandle); 6495 } 6496 6497 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6498 // (2) Compute "max" for all admins 6499 boolean newRequested = false; 6500 final int N = policy.mAdminList.size(); 6501 for (int i = 0; i < N; i++) { 6502 newRequested |= policy.mAdminList.get(i).encryptionRequested; 6503 } 6504 6505 // Notify OS of new request 6506 setEncryptionRequested(newRequested); 6507 6508 // Return the new global request status 6509 return newRequested 6510 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 6511 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 6512 } 6513 } 6514 6515 /** 6516 * Get the current storage encryption request status for a given admin, or aggregate of all 6517 * active admins. 6518 */ 6519 @Override 6520 public boolean getStorageEncryption(ComponentName who, int userHandle) { 6521 if (!mHasFeature) { 6522 return false; 6523 } 6524 enforceFullCrossUsersPermission(userHandle); 6525 synchronized (this) { 6526 // Check for permissions if a particular caller is specified 6527 if (who != null) { 6528 // When checking for a single caller, status is based on caller's request 6529 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 6530 return ap != null ? ap.encryptionRequested : false; 6531 } 6532 6533 // If no particular caller is specified, return the aggregate set of requests. 6534 // This is short circuited by returning true on the first hit. 6535 DevicePolicyData policy = getUserData(userHandle); 6536 final int N = policy.mAdminList.size(); 6537 for (int i = 0; i < N; i++) { 6538 if (policy.mAdminList.get(i).encryptionRequested) { 6539 return true; 6540 } 6541 } 6542 return false; 6543 } 6544 } 6545 6546 /** 6547 * Get the current encryption status of the device. 6548 */ 6549 @Override 6550 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 6551 if (!mHasFeature) { 6552 // Ok to return current status. 6553 } 6554 enforceFullCrossUsersPermission(userHandle); 6555 6556 // It's not critical here, but let's make sure the package name is correct, in case 6557 // we start using it for different purposes. 6558 ensureCallerPackage(callerPackage); 6559 6560 final ApplicationInfo ai; 6561 try { 6562 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 6563 } catch (RemoteException e) { 6564 throw new SecurityException(e); 6565 } 6566 6567 boolean legacyApp = false; 6568 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 6569 legacyApp = true; 6570 } 6571 6572 final int rawStatus = getEncryptionStatus(); 6573 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 6574 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 6575 } 6576 return rawStatus; 6577 } 6578 6579 /** 6580 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 6581 */ 6582 private boolean isEncryptionSupported() { 6583 // Note, this can be implemented as 6584 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6585 // But is provided as a separate internal method if there's a faster way to do a 6586 // simple check for supported-or-not. 6587 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6588 } 6589 6590 /** 6591 * Hook to low-levels: Reporting the current status of encryption. 6592 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 6593 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 6594 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 6595 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or 6596 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 6597 */ 6598 private int getEncryptionStatus() { 6599 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 6600 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 6601 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) { 6602 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 6603 } else if (mInjector.storageManagerIsEncrypted()) { 6604 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 6605 } else if (mInjector.storageManagerIsEncryptable()) { 6606 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 6607 } else { 6608 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6609 } 6610 } 6611 6612 /** 6613 * Hook to low-levels: If needed, record the new admin setting for encryption. 6614 */ 6615 private void setEncryptionRequested(boolean encrypt) { 6616 } 6617 6618 /** 6619 * Set whether the screen capture is disabled for the user managed by the specified admin. 6620 */ 6621 @Override 6622 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) { 6623 if (!mHasFeature) { 6624 return; 6625 } 6626 Preconditions.checkNotNull(who, "ComponentName is null"); 6627 final int userHandle = UserHandle.getCallingUserId(); 6628 synchronized (this) { 6629 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 6630 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6631 if (ap.disableScreenCapture != disabled) { 6632 ap.disableScreenCapture = disabled; 6633 saveSettingsLocked(userHandle); 6634 updateScreenCaptureDisabledInWindowManager(userHandle, disabled); 6635 } 6636 } 6637 } 6638 6639 /** 6640 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 6641 * active admin (if given admin is null). 6642 */ 6643 @Override 6644 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) { 6645 if (!mHasFeature) { 6646 return false; 6647 } 6648 synchronized (this) { 6649 if (who != null) { 6650 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 6651 return (admin != null) ? admin.disableScreenCapture : false; 6652 } 6653 6654 DevicePolicyData policy = getUserData(userHandle); 6655 final int N = policy.mAdminList.size(); 6656 for (int i = 0; i < N; i++) { 6657 ActiveAdmin admin = policy.mAdminList.get(i); 6658 if (admin.disableScreenCapture) { 6659 return true; 6660 } 6661 } 6662 return false; 6663 } 6664 } 6665 6666 private void updateScreenCaptureDisabledInWindowManager(final int userHandle, 6667 final boolean disabled) { 6668 mHandler.post(new Runnable() { 6669 @Override 6670 public void run() { 6671 try { 6672 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled); 6673 } catch (RemoteException e) { 6674 Log.w(LOG_TAG, "Unable to notify WindowManager.", e); 6675 } 6676 } 6677 }); 6678 } 6679 6680 /** 6681 * Set whether auto time is required by the specified admin (must be device or profile owner). 6682 */ 6683 @Override 6684 public void setAutoTimeRequired(ComponentName who, boolean required) { 6685 if (!mHasFeature) { 6686 return; 6687 } 6688 Preconditions.checkNotNull(who, "ComponentName is null"); 6689 final int userHandle = UserHandle.getCallingUserId(); 6690 synchronized (this) { 6691 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6692 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6693 if (admin.requireAutoTime != required) { 6694 admin.requireAutoTime = required; 6695 saveSettingsLocked(userHandle); 6696 } 6697 } 6698 6699 // Turn AUTO_TIME on in settings if it is required 6700 if (required) { 6701 long ident = mInjector.binderClearCallingIdentity(); 6702 try { 6703 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */); 6704 } finally { 6705 mInjector.binderRestoreCallingIdentity(ident); 6706 } 6707 } 6708 } 6709 6710 /** 6711 * Returns whether or not auto time is required by the device owner or any profile owner. 6712 */ 6713 @Override 6714 public boolean getAutoTimeRequired() { 6715 if (!mHasFeature) { 6716 return false; 6717 } 6718 synchronized (this) { 6719 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6720 if (deviceOwner != null && deviceOwner.requireAutoTime) { 6721 // If the device owner enforces auto time, we don't need to check the PO's 6722 return true; 6723 } 6724 6725 // Now check to see if any profile owner on any user enforces auto time 6726 for (Integer userId : mOwners.getProfileOwnerKeys()) { 6727 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 6728 if (profileOwner != null && profileOwner.requireAutoTime) { 6729 return true; 6730 } 6731 } 6732 6733 return false; 6734 } 6735 } 6736 6737 @Override 6738 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 6739 if (!mHasFeature) { 6740 return; 6741 } 6742 Preconditions.checkNotNull(who, "ComponentName is null"); 6743 // Allow setting this policy to true only if there is a split system user. 6744 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) { 6745 throw new UnsupportedOperationException( 6746 "Cannot force ephemeral users on systems without split system user."); 6747 } 6748 boolean removeAllUsers = false; 6749 synchronized (this) { 6750 final ActiveAdmin deviceOwner = 6751 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6752 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) { 6753 deviceOwner.forceEphemeralUsers = forceEphemeralUsers; 6754 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 6755 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers); 6756 removeAllUsers = forceEphemeralUsers; 6757 } 6758 } 6759 if (removeAllUsers) { 6760 long identitity = mInjector.binderClearCallingIdentity(); 6761 try { 6762 mUserManagerInternal.removeAllUsers(); 6763 } finally { 6764 mInjector.binderRestoreCallingIdentity(identitity); 6765 } 6766 } 6767 } 6768 6769 @Override 6770 public boolean getForceEphemeralUsers(ComponentName who) { 6771 if (!mHasFeature) { 6772 return false; 6773 } 6774 Preconditions.checkNotNull(who, "ComponentName is null"); 6775 synchronized (this) { 6776 final ActiveAdmin deviceOwner = 6777 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6778 return deviceOwner.forceEphemeralUsers; 6779 } 6780 } 6781 6782 private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException { 6783 synchronized (this) { 6784 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6785 if (!areAllUsersAffiliatedWithDeviceLocked()) { 6786 throw new SecurityException("Not all users are affiliated."); 6787 } 6788 } 6789 } 6790 6791 @Override 6792 public boolean requestBugreport(ComponentName who) { 6793 if (!mHasFeature) { 6794 return false; 6795 } 6796 Preconditions.checkNotNull(who, "ComponentName is null"); 6797 6798 // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport 6799 // which could still contain data related to that user. Should we disallow that, e.g. until 6800 // next boot? Might not be needed given that this still requires user consent. 6801 ensureDeviceOwnerAndAllUsersAffiliated(who); 6802 6803 if (mRemoteBugreportServiceIsActive.get() 6804 || (getDeviceOwnerRemoteBugreportUri() != null)) { 6805 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running."); 6806 return false; 6807 } 6808 6809 final long currentTime = System.currentTimeMillis(); 6810 synchronized (this) { 6811 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 6812 if (currentTime > policyData.mLastBugReportRequestTime) { 6813 policyData.mLastBugReportRequestTime = currentTime; 6814 saveSettingsLocked(UserHandle.USER_SYSTEM); 6815 } 6816 } 6817 6818 final long callingIdentity = mInjector.binderClearCallingIdentity(); 6819 try { 6820 mInjector.getIActivityManager().requestBugReport( 6821 ActivityManager.BUGREPORT_OPTION_REMOTE); 6822 6823 mRemoteBugreportServiceIsActive.set(true); 6824 mRemoteBugreportSharingAccepted.set(false); 6825 registerRemoteBugreportReceivers(); 6826 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, 6827 RemoteBugreportUtils.NOTIFICATION_ID, 6828 RemoteBugreportUtils.buildNotification(mContext, 6829 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL); 6830 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable, 6831 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS); 6832 return true; 6833 } catch (RemoteException re) { 6834 // should never happen 6835 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re); 6836 return false; 6837 } finally { 6838 mInjector.binderRestoreCallingIdentity(callingIdentity); 6839 } 6840 } 6841 6842 void sendDeviceOwnerCommand(String action, Bundle extras) { 6843 int deviceOwnerUserId; 6844 ComponentName deviceOwnerComponent; 6845 synchronized (this) { 6846 deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 6847 deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 6848 } 6849 sendActiveAdminCommand(action, extras, deviceOwnerUserId, 6850 deviceOwnerComponent); 6851 } 6852 6853 private void sendProfileOwnerCommand(String action, Bundle extras, int userHandle) { 6854 sendActiveAdminCommand(action, extras, userHandle, 6855 mOwners.getProfileOwnerComponent(userHandle)); 6856 } 6857 6858 private void sendActiveAdminCommand(String action, Bundle extras, 6859 int userHandle, ComponentName receiverComponent) { 6860 final Intent intent = new Intent(action); 6861 intent.setComponent(receiverComponent); 6862 if (extras != null) { 6863 intent.putExtras(extras); 6864 } 6865 mContext.sendBroadcastAsUser(intent, UserHandle.of(userHandle)); 6866 } 6867 6868 private void sendOwnerChangedBroadcast(String broadcast, int userId) { 6869 final Intent intent = new Intent(broadcast) 6870 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 6871 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 6872 } 6873 6874 private synchronized String getDeviceOwnerRemoteBugreportUri() { 6875 return mOwners.getDeviceOwnerRemoteBugreportUri(); 6876 } 6877 6878 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, 6879 String bugreportHash) { 6880 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 6881 } 6882 6883 private void registerRemoteBugreportReceivers() { 6884 try { 6885 IntentFilter filterFinished = new IntentFilter( 6886 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH, 6887 RemoteBugreportUtils.BUGREPORT_MIMETYPE); 6888 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished); 6889 } catch (IntentFilter.MalformedMimeTypeException e) { 6890 // should never happen, as setting a constant 6891 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e); 6892 } 6893 IntentFilter filterConsent = new IntentFilter(); 6894 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 6895 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 6896 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 6897 } 6898 6899 private void onBugreportFinished(Intent intent) { 6900 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 6901 mRemoteBugreportServiceIsActive.set(false); 6902 Uri bugreportUri = intent.getData(); 6903 String bugreportUriString = null; 6904 if (bugreportUri != null) { 6905 bugreportUriString = bugreportUri.toString(); 6906 } 6907 String bugreportHash = intent.getStringExtra( 6908 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH); 6909 if (mRemoteBugreportSharingAccepted.get()) { 6910 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 6911 mInjector.getNotificationManager().cancel(LOG_TAG, 6912 RemoteBugreportUtils.NOTIFICATION_ID); 6913 } else { 6914 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash); 6915 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 6916 RemoteBugreportUtils.buildNotification(mContext, 6917 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 6918 UserHandle.ALL); 6919 } 6920 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6921 } 6922 6923 private void onBugreportFailed() { 6924 mRemoteBugreportServiceIsActive.set(false); 6925 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 6926 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 6927 mRemoteBugreportSharingAccepted.set(false); 6928 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6929 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID); 6930 Bundle extras = new Bundle(); 6931 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 6932 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING); 6933 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 6934 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 6935 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6936 } 6937 6938 private void onBugreportSharingAccepted() { 6939 mRemoteBugreportSharingAccepted.set(true); 6940 String bugreportUriString = null; 6941 String bugreportHash = null; 6942 synchronized (this) { 6943 bugreportUriString = getDeviceOwnerRemoteBugreportUri(); 6944 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash(); 6945 } 6946 if (bugreportUriString != null) { 6947 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 6948 } else if (mRemoteBugreportServiceIsActive.get()) { 6949 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 6950 RemoteBugreportUtils.buildNotification(mContext, 6951 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED), 6952 UserHandle.ALL); 6953 } 6954 } 6955 6956 private void onBugreportSharingDeclined() { 6957 if (mRemoteBugreportServiceIsActive.get()) { 6958 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 6959 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 6960 mRemoteBugreportServiceIsActive.set(false); 6961 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 6962 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6963 } 6964 mRemoteBugreportSharingAccepted.set(false); 6965 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6966 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null); 6967 } 6968 6969 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, 6970 String bugreportHash) { 6971 ParcelFileDescriptor pfd = null; 6972 try { 6973 if (bugreportUriString == null) { 6974 throw new FileNotFoundException(); 6975 } 6976 Uri bugreportUri = Uri.parse(bugreportUriString); 6977 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r"); 6978 6979 synchronized (this) { 6980 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 6981 intent.setComponent(mOwners.getDeviceOwnerComponent()); 6982 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE); 6983 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 6984 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6985 6986 LocalServices.getService(ActivityManagerInternal.class) 6987 .grantUriPermissionFromIntent(Process.SHELL_UID, 6988 mOwners.getDeviceOwnerComponent().getPackageName(), 6989 intent, mOwners.getDeviceOwnerUserId()); 6990 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 6991 } 6992 } catch (FileNotFoundException e) { 6993 Bundle extras = new Bundle(); 6994 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 6995 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE); 6996 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 6997 } finally { 6998 try { 6999 if (pfd != null) { 7000 pfd.close(); 7001 } 7002 } catch (IOException ex) { 7003 // Ignore 7004 } 7005 mRemoteBugreportSharingAccepted.set(false); 7006 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 7007 } 7008 } 7009 7010 /** 7011 * Disables all device cameras according to the specified admin. 7012 */ 7013 @Override 7014 public void setCameraDisabled(ComponentName who, boolean disabled) { 7015 if (!mHasFeature) { 7016 return; 7017 } 7018 Preconditions.checkNotNull(who, "ComponentName is null"); 7019 final int userHandle = mInjector.userHandleGetCallingUserId(); 7020 synchronized (this) { 7021 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 7022 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 7023 if (ap.disableCamera != disabled) { 7024 ap.disableCamera = disabled; 7025 saveSettingsLocked(userHandle); 7026 } 7027 } 7028 // Tell the user manager that the restrictions have changed. 7029 pushUserRestrictions(userHandle); 7030 } 7031 7032 /** 7033 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 7034 * active admins. 7035 */ 7036 @Override 7037 public boolean getCameraDisabled(ComponentName who, int userHandle) { 7038 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true); 7039 } 7040 7041 private boolean getCameraDisabled(ComponentName who, int userHandle, 7042 boolean mergeDeviceOwnerRestriction) { 7043 if (!mHasFeature) { 7044 return false; 7045 } 7046 synchronized (this) { 7047 if (who != null) { 7048 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7049 return (admin != null) ? admin.disableCamera : false; 7050 } 7051 // First, see if DO has set it. If so, it's device-wide. 7052 if (mergeDeviceOwnerRestriction) { 7053 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7054 if (deviceOwner != null && deviceOwner.disableCamera) { 7055 return true; 7056 } 7057 } 7058 7059 // Then check each device admin on the user. 7060 DevicePolicyData policy = getUserData(userHandle); 7061 // Determine whether or not the device camera is disabled for any active admins. 7062 final int N = policy.mAdminList.size(); 7063 for (int i = 0; i < N; i++) { 7064 ActiveAdmin admin = policy.mAdminList.get(i); 7065 if (admin.disableCamera) { 7066 return true; 7067 } 7068 } 7069 return false; 7070 } 7071 } 7072 7073 @Override 7074 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 7075 if (!mHasFeature) { 7076 return; 7077 } 7078 Preconditions.checkNotNull(who, "ComponentName is null"); 7079 final int userHandle = mInjector.userHandleGetCallingUserId(); 7080 if (isManagedProfile(userHandle)) { 7081 if (parent) { 7082 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 7083 } else { 7084 which = which & PROFILE_KEYGUARD_FEATURES; 7085 } 7086 } 7087 synchronized (this) { 7088 ActiveAdmin ap = getActiveAdminForCallerLocked( 7089 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 7090 if (ap.disabledKeyguardFeatures != which) { 7091 ap.disabledKeyguardFeatures = which; 7092 saveSettingsLocked(userHandle); 7093 } 7094 } 7095 if (SecurityLog.isLoggingEnabled()) { 7096 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 7097 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET, 7098 who.getPackageName(), userHandle, affectedUserId, which); 7099 } 7100 } 7101 7102 /** 7103 * Gets the disabled state for features in keyguard for the given admin, 7104 * or the aggregate of all active admins if who is null. 7105 */ 7106 @Override 7107 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 7108 if (!mHasFeature) { 7109 return 0; 7110 } 7111 enforceFullCrossUsersPermission(userHandle); 7112 final long ident = mInjector.binderClearCallingIdentity(); 7113 try { 7114 synchronized (this) { 7115 if (who != null) { 7116 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 7117 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 7118 } 7119 7120 final List<ActiveAdmin> admins; 7121 if (!parent && isManagedProfile(userHandle)) { 7122 // If we are being asked about a managed profile, just return keyguard features 7123 // disabled by admins in the profile. 7124 admins = getUserDataUnchecked(userHandle).mAdminList; 7125 } else { 7126 // Otherwise return those set by admins in the user and its profiles. 7127 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 7128 } 7129 7130 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 7131 final int N = admins.size(); 7132 for (int i = 0; i < N; i++) { 7133 ActiveAdmin admin = admins.get(i); 7134 int userId = admin.getUserHandle().getIdentifier(); 7135 boolean isRequestedUser = !parent && (userId == userHandle); 7136 if (isRequestedUser || !isManagedProfile(userId)) { 7137 // If we are being asked explicitly about this user 7138 // return all disabled features even if its a managed profile. 7139 which |= admin.disabledKeyguardFeatures; 7140 } else { 7141 // Otherwise a managed profile is only allowed to disable 7142 // some features on the parent user. 7143 which |= (admin.disabledKeyguardFeatures 7144 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 7145 } 7146 } 7147 return which; 7148 } 7149 } finally { 7150 mInjector.binderRestoreCallingIdentity(ident); 7151 } 7152 } 7153 7154 @Override 7155 public void setKeepUninstalledPackages(ComponentName who, String callerPackage, 7156 List<String> packageList) { 7157 if (!mHasFeature) { 7158 return; 7159 } 7160 Preconditions.checkNotNull(packageList, "packageList is null"); 7161 final int userHandle = UserHandle.getCallingUserId(); 7162 synchronized (this) { 7163 // Ensure the caller is a DO or a keep uninstalled packages delegate. 7164 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7165 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 7166 // Get the device owner 7167 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7168 // Set list of packages to be kept even if uninstalled. 7169 deviceOwner.keepUninstalledPackages = packageList; 7170 // Save settings. 7171 saveSettingsLocked(userHandle); 7172 // Notify package manager. 7173 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 7174 } 7175 } 7176 7177 @Override 7178 public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) { 7179 if (!mHasFeature) { 7180 return null; 7181 } 7182 // TODO In split system user mode, allow apps on user 0 to query the list 7183 synchronized (this) { 7184 // Ensure the caller is a DO or a keep uninstalled packages delegate. 7185 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7186 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 7187 return getKeepUninstalledPackagesLocked(); 7188 } 7189 } 7190 7191 private List<String> getKeepUninstalledPackagesLocked() { 7192 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7193 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 7194 } 7195 7196 @Override 7197 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) { 7198 if (!mHasFeature) { 7199 return false; 7200 } 7201 if (admin == null 7202 || !isPackageInstalledForUser(admin.getPackageName(), userId)) { 7203 throw new IllegalArgumentException("Invalid component " + admin 7204 + " for device owner"); 7205 } 7206 final boolean hasIncompatibleAccountsOrNonAdb = 7207 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin); 7208 synchronized (this) { 7209 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb); 7210 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 7211 if (activeAdmin == null 7212 || getUserData(userId).mRemovingAdmins.contains(admin)) { 7213 throw new IllegalArgumentException("Not active admin: " + admin); 7214 } 7215 7216 // Shutting down backup manager service permanently. 7217 long ident = mInjector.binderClearCallingIdentity(); 7218 try { 7219 if (mInjector.getIBackupManager() != null) { 7220 mInjector.getIBackupManager() 7221 .setBackupServiceActive(UserHandle.USER_SYSTEM, false); 7222 } 7223 } catch (RemoteException e) { 7224 throw new IllegalStateException("Failed deactivating backup service.", e); 7225 } finally { 7226 mInjector.binderRestoreCallingIdentity(ident); 7227 } 7228 7229 if (isAdb()) { 7230 // Log device owner provisioning was started using adb. 7231 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 7232 } 7233 7234 mOwners.setDeviceOwner(admin, ownerName, userId); 7235 mOwners.writeDeviceOwner(); 7236 updateDeviceOwnerLocked(); 7237 setDeviceOwnerSystemPropertyLocked(); 7238 7239 final Set<String> restrictions = 7240 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner(); 7241 if (!restrictions.isEmpty()) { 7242 for (String restriction : restrictions) { 7243 activeAdmin.ensureUserRestrictions().putBoolean(restriction, true); 7244 } 7245 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions); 7246 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions); 7247 7248 saveUserRestrictionsLocked(userId); 7249 } 7250 7251 ident = mInjector.binderClearCallingIdentity(); 7252 try { 7253 // TODO Send to system too? 7254 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId); 7255 } finally { 7256 mInjector.binderRestoreCallingIdentity(ident); 7257 } 7258 mDeviceAdminServiceController.startServiceForOwner( 7259 admin.getPackageName(), userId, "set-device-owner"); 7260 7261 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 7262 return true; 7263 } 7264 } 7265 7266 @Override 7267 public boolean hasDeviceOwner() { 7268 enforceDeviceOwnerOrManageUsers(); 7269 return mOwners.hasDeviceOwner(); 7270 } 7271 7272 boolean isDeviceOwner(ActiveAdmin admin) { 7273 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 7274 } 7275 7276 public boolean isDeviceOwner(ComponentName who, int userId) { 7277 synchronized (this) { 7278 return mOwners.hasDeviceOwner() 7279 && mOwners.getDeviceOwnerUserId() == userId 7280 && mOwners.getDeviceOwnerComponent().equals(who); 7281 } 7282 } 7283 7284 private boolean isDeviceOwnerPackage(String packageName, int userId) { 7285 synchronized (this) { 7286 return mOwners.hasDeviceOwner() 7287 && mOwners.getDeviceOwnerUserId() == userId 7288 && mOwners.getDeviceOwnerPackageName().equals(packageName); 7289 } 7290 } 7291 7292 private boolean isProfileOwnerPackage(String packageName, int userId) { 7293 synchronized (this) { 7294 return mOwners.hasProfileOwner(userId) 7295 && mOwners.getProfileOwnerPackage(userId).equals(packageName); 7296 } 7297 } 7298 7299 public boolean isProfileOwner(ComponentName who, int userId) { 7300 final ComponentName profileOwner = getProfileOwner(userId); 7301 return who != null && who.equals(profileOwner); 7302 } 7303 7304 @Override 7305 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 7306 if (!mHasFeature) { 7307 return null; 7308 } 7309 if (!callingUserOnly) { 7310 enforceManageUsers(); 7311 } 7312 synchronized (this) { 7313 if (!mOwners.hasDeviceOwner()) { 7314 return null; 7315 } 7316 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 7317 mOwners.getDeviceOwnerUserId()) { 7318 return null; 7319 } 7320 return mOwners.getDeviceOwnerComponent(); 7321 } 7322 } 7323 7324 @Override 7325 public int getDeviceOwnerUserId() { 7326 if (!mHasFeature) { 7327 return UserHandle.USER_NULL; 7328 } 7329 enforceManageUsers(); 7330 synchronized (this) { 7331 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 7332 } 7333 } 7334 7335 /** 7336 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 7337 * MANAGE_USERS. 7338 */ 7339 @Override 7340 public String getDeviceOwnerName() { 7341 if (!mHasFeature) { 7342 return null; 7343 } 7344 enforceManageUsers(); 7345 synchronized (this) { 7346 if (!mOwners.hasDeviceOwner()) { 7347 return null; 7348 } 7349 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 7350 // Should setDeviceOwner/ProfileOwner still take a name? 7351 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 7352 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 7353 } 7354 } 7355 7356 /** Returns the active device owner or {@code null} if there is no device owner. */ 7357 @VisibleForTesting 7358 ActiveAdmin getDeviceOwnerAdminLocked() { 7359 ComponentName component = mOwners.getDeviceOwnerComponent(); 7360 if (component == null) { 7361 return null; 7362 } 7363 7364 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 7365 final int n = policy.mAdminList.size(); 7366 for (int i = 0; i < n; i++) { 7367 ActiveAdmin admin = policy.mAdminList.get(i); 7368 if (component.equals(admin.info.getComponent())) { 7369 return admin; 7370 } 7371 } 7372 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 7373 return null; 7374 } 7375 7376 @Override 7377 public void clearDeviceOwner(String packageName) { 7378 Preconditions.checkNotNull(packageName, "packageName is null"); 7379 final int callingUid = mInjector.binderGetCallingUid(); 7380 try { 7381 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 7382 UserHandle.getUserId(callingUid)); 7383 if (uid != callingUid) { 7384 throw new SecurityException("Invalid packageName"); 7385 } 7386 } catch (NameNotFoundException e) { 7387 throw new SecurityException(e); 7388 } 7389 synchronized (this) { 7390 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 7391 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 7392 if (!mOwners.hasDeviceOwner() 7393 || !deviceOwnerComponent.getPackageName().equals(packageName) 7394 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) { 7395 throw new SecurityException( 7396 "clearDeviceOwner can only be called by the device owner"); 7397 } 7398 enforceUserUnlocked(deviceOwnerUserId); 7399 7400 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 7401 long ident = mInjector.binderClearCallingIdentity(); 7402 try { 7403 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 7404 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 7405 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, 7406 deviceOwnerUserId); 7407 } finally { 7408 mInjector.binderRestoreCallingIdentity(ident); 7409 } 7410 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 7411 } 7412 } 7413 7414 private void clearOverrideApnUnchecked() { 7415 // Disable Override APNs and remove them from database. 7416 setOverrideApnsEnabledUnchecked(false); 7417 final List<ApnSetting> apns = getOverrideApnsUnchecked(); 7418 for (int i = 0; i < apns.size(); i ++) { 7419 removeOverrideApnUnchecked(apns.get(i).getId()); 7420 } 7421 } 7422 7423 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 7424 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner"); 7425 7426 if (admin != null) { 7427 admin.disableCamera = false; 7428 admin.userRestrictions = null; 7429 admin.defaultEnabledRestrictionsAlreadySet.clear(); 7430 admin.forceEphemeralUsers = false; 7431 admin.isNetworkLoggingEnabled = false; 7432 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 7433 } 7434 final DevicePolicyData policyData = getUserData(userId); 7435 policyData.mCurrentInputMethodSet = false; 7436 saveSettingsLocked(userId); 7437 final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM); 7438 systemPolicyData.mLastSecurityLogRetrievalTime = -1; 7439 systemPolicyData.mLastBugReportRequestTime = -1; 7440 systemPolicyData.mLastNetworkLogsRetrievalTime = -1; 7441 saveSettingsLocked(UserHandle.USER_SYSTEM); 7442 clearUserPoliciesLocked(userId); 7443 clearOverrideApnUnchecked(); 7444 7445 mOwners.clearDeviceOwner(); 7446 mOwners.writeDeviceOwner(); 7447 updateDeviceOwnerLocked(); 7448 7449 clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId)); 7450 mInjector.securityLogSetLoggingEnabledProperty(false); 7451 mSecurityLogMonitor.stop(); 7452 setNetworkLoggingActiveInternal(false); 7453 deleteTransferOwnershipBundleLocked(userId); 7454 7455 try { 7456 if (mInjector.getIBackupManager() != null) { 7457 // Reactivate backup service. 7458 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true); 7459 } 7460 } catch (RemoteException e) { 7461 throw new IllegalStateException("Failed reactivating backup service.", e); 7462 } 7463 } 7464 7465 @Override 7466 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 7467 if (!mHasFeature) { 7468 return false; 7469 } 7470 if (who == null 7471 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) { 7472 throw new IllegalArgumentException("Component " + who 7473 + " not installed for userId:" + userHandle); 7474 } 7475 final boolean hasIncompatibleAccountsOrNonAdb = 7476 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who); 7477 synchronized (this) { 7478 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb); 7479 7480 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7481 if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) { 7482 throw new IllegalArgumentException("Not active admin: " + who); 7483 } 7484 7485 if (isAdb()) { 7486 // Log profile owner provisioning was started using adb. 7487 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 7488 } 7489 7490 mOwners.setProfileOwner(who, ownerName, userHandle); 7491 mOwners.writeProfileOwner(userHandle); 7492 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 7493 7494 final long id = mInjector.binderClearCallingIdentity(); 7495 try { 7496 if (mUserManager.isManagedProfile(userHandle)) { 7497 maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin, 7498 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 7499 ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin, 7500 true /* newOwner */); 7501 } 7502 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 7503 userHandle); 7504 } finally { 7505 mInjector.binderRestoreCallingIdentity(id); 7506 } 7507 mDeviceAdminServiceController.startServiceForOwner( 7508 who.getPackageName(), userHandle, "set-profile-owner"); 7509 return true; 7510 } 7511 } 7512 7513 @Override 7514 public void clearProfileOwner(ComponentName who) { 7515 if (!mHasFeature) { 7516 return; 7517 } 7518 Preconditions.checkNotNull(who, "ComponentName is null"); 7519 7520 final int userId = mInjector.userHandleGetCallingUserId(); 7521 enforceNotManagedProfile(userId, "clear profile owner"); 7522 enforceUserUnlocked(userId); 7523 synchronized (this) { 7524 // Check if this is the profile owner who is calling 7525 final ActiveAdmin admin = 7526 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7527 7528 final long ident = mInjector.binderClearCallingIdentity(); 7529 try { 7530 clearProfileOwnerLocked(admin, userId); 7531 removeActiveAdminLocked(who, userId); 7532 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 7533 userId); 7534 } finally { 7535 mInjector.binderRestoreCallingIdentity(ident); 7536 } 7537 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 7538 } 7539 } 7540 7541 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 7542 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner"); 7543 7544 if (admin != null) { 7545 admin.disableCamera = false; 7546 admin.userRestrictions = null; 7547 admin.defaultEnabledRestrictionsAlreadySet.clear(); 7548 } 7549 final DevicePolicyData policyData = getUserData(userId); 7550 policyData.mCurrentInputMethodSet = false; 7551 policyData.mOwnerInstalledCaCerts.clear(); 7552 saveSettingsLocked(userId); 7553 clearUserPoliciesLocked(userId); 7554 mOwners.removeProfileOwner(userId); 7555 mOwners.writeProfileOwner(userId); 7556 deleteTransferOwnershipBundleLocked(userId); 7557 } 7558 7559 @Override 7560 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 7561 Preconditions.checkNotNull(who, "ComponentName is null"); 7562 if (!mHasFeature) { 7563 return; 7564 } 7565 7566 synchronized (this) { 7567 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7568 long token = mInjector.binderClearCallingIdentity(); 7569 try { 7570 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null); 7571 } finally { 7572 mInjector.binderRestoreCallingIdentity(token); 7573 } 7574 } 7575 } 7576 7577 @Override 7578 public CharSequence getDeviceOwnerLockScreenInfo() { 7579 return mLockPatternUtils.getDeviceOwnerInfo(); 7580 } 7581 7582 private void clearUserPoliciesLocked(int userId) { 7583 // Reset some of the user-specific policies. 7584 final DevicePolicyData policy = getUserData(userId); 7585 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 7586 // Clear delegations. 7587 policy.mDelegationMap.clear(); 7588 policy.mStatusBarDisabled = false; 7589 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 7590 policy.mAffiliationIds.clear(); 7591 policy.mLockTaskPackages.clear(); 7592 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId); 7593 policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE; 7594 saveSettingsLocked(userId); 7595 7596 try { 7597 mIPackageManager.updatePermissionFlagsForAllApps( 7598 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 7599 0 /* flagValues */, userId); 7600 pushUserRestrictions(userId); 7601 } catch (RemoteException re) { 7602 // Shouldn't happen. 7603 } 7604 } 7605 7606 @Override 7607 public boolean hasUserSetupCompleted() { 7608 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 7609 } 7610 7611 // This checks only if the Setup Wizard has run. Since Wear devices pair before 7612 // completing Setup Wizard, and pairing involves transferring user data, calling 7613 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). 7614 private boolean hasUserSetupCompleted(int userHandle) { 7615 if (!mHasFeature) { 7616 return true; 7617 } 7618 return getUserData(userHandle).mUserSetupComplete; 7619 } 7620 7621 private boolean hasPaired(int userHandle) { 7622 if (!mHasFeature) { 7623 return true; 7624 } 7625 return getUserData(userHandle).mPaired; 7626 } 7627 7628 @Override 7629 public int getUserProvisioningState() { 7630 if (!mHasFeature) { 7631 return DevicePolicyManager.STATE_USER_UNMANAGED; 7632 } 7633 int userHandle = mInjector.userHandleGetCallingUserId(); 7634 return getUserProvisioningState(userHandle); 7635 } 7636 7637 private int getUserProvisioningState(int userHandle) { 7638 return getUserData(userHandle).mUserProvisioningState; 7639 } 7640 7641 @Override 7642 public void setUserProvisioningState(int newState, int userHandle) { 7643 if (!mHasFeature) { 7644 return; 7645 } 7646 7647 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle) 7648 && getManagedUserId(userHandle) == -1) { 7649 // No managed device, user or profile, so setting provisioning state makes no sense. 7650 throw new IllegalStateException("Not allowed to change provisioning state unless a " 7651 + "device or profile owner is set."); 7652 } 7653 7654 synchronized (this) { 7655 boolean transitionCheckNeeded = true; 7656 7657 // Calling identity/permission checks. 7658 if (isAdb()) { 7659 // ADB shell can only move directly from un-managed to finalized as part of directly 7660 // setting profile-owner or device-owner. 7661 if (getUserProvisioningState(userHandle) != 7662 DevicePolicyManager.STATE_USER_UNMANAGED 7663 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 7664 throw new IllegalStateException("Not allowed to change provisioning state " 7665 + "unless current provisioning state is unmanaged, and new state is " 7666 + "finalized."); 7667 } 7668 transitionCheckNeeded = false; 7669 } else { 7670 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS. 7671 enforceCanManageProfileAndDeviceOwners(); 7672 } 7673 7674 final DevicePolicyData policyData = getUserData(userHandle); 7675 if (transitionCheckNeeded) { 7676 // Optional state transition check for non-ADB case. 7677 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState); 7678 } 7679 policyData.mUserProvisioningState = newState; 7680 saveSettingsLocked(userHandle); 7681 } 7682 } 7683 7684 private void checkUserProvisioningStateTransition(int currentState, int newState) { 7685 // Valid transitions for normal use-cases. 7686 switch (currentState) { 7687 case DevicePolicyManager.STATE_USER_UNMANAGED: 7688 // Can move to any state from unmanaged (except itself as an edge case).. 7689 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 7690 return; 7691 } 7692 break; 7693 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 7694 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 7695 // Can only move to finalized from these states. 7696 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 7697 return; 7698 } 7699 break; 7700 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 7701 // Current user has a managed-profile, but current user is not managed, so 7702 // rather than moving to finalized state, go back to unmanaged once 7703 // profile provisioning is complete. 7704 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 7705 return; 7706 } 7707 break; 7708 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED: 7709 // Cannot transition out of finalized. 7710 break; 7711 } 7712 7713 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 7714 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 7715 + "from state [" + currentState + "]"); 7716 } 7717 7718 @Override 7719 public void setProfileEnabled(ComponentName who) { 7720 if (!mHasFeature) { 7721 return; 7722 } 7723 Preconditions.checkNotNull(who, "ComponentName is null"); 7724 synchronized (this) { 7725 // Check if this is the profile owner who is calling 7726 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7727 final int userId = UserHandle.getCallingUserId(); 7728 enforceManagedProfile(userId, "enable the profile"); 7729 // Check if the profile is already enabled. 7730 UserInfo managedProfile = getUserInfo(userId); 7731 if (managedProfile.isEnabled()) { 7732 Slog.e(LOG_TAG, 7733 "setProfileEnabled is called when the profile is already enabled"); 7734 return; 7735 } 7736 long id = mInjector.binderClearCallingIdentity(); 7737 try { 7738 mUserManager.setUserEnabled(userId); 7739 UserInfo parent = mUserManager.getProfileParent(userId); 7740 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 7741 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 7742 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 7743 Intent.FLAG_RECEIVER_FOREGROUND); 7744 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id)); 7745 } finally { 7746 mInjector.binderRestoreCallingIdentity(id); 7747 } 7748 } 7749 } 7750 7751 @Override 7752 public void setProfileName(ComponentName who, String profileName) { 7753 Preconditions.checkNotNull(who, "ComponentName is null"); 7754 int userId = UserHandle.getCallingUserId(); 7755 // Check if this is the profile owner (includes device owner). 7756 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7757 7758 long id = mInjector.binderClearCallingIdentity(); 7759 try { 7760 mUserManager.setUserName(userId, profileName); 7761 } finally { 7762 mInjector.binderRestoreCallingIdentity(id); 7763 } 7764 } 7765 7766 @Override 7767 public ComponentName getProfileOwner(int userHandle) { 7768 if (!mHasFeature) { 7769 return null; 7770 } 7771 7772 synchronized (this) { 7773 return mOwners.getProfileOwnerComponent(userHandle); 7774 } 7775 } 7776 7777 // Returns the active profile owner for this user or null if the current user has no 7778 // profile owner. 7779 @VisibleForTesting 7780 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 7781 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 7782 if (profileOwner == null) { 7783 return null; 7784 } 7785 DevicePolicyData policy = getUserData(userHandle); 7786 final int n = policy.mAdminList.size(); 7787 for (int i = 0; i < n; i++) { 7788 ActiveAdmin admin = policy.mAdminList.get(i); 7789 if (profileOwner.equals(admin.info.getComponent())) { 7790 return admin; 7791 } 7792 } 7793 return null; 7794 } 7795 7796 @Override 7797 public String getProfileOwnerName(int userHandle) { 7798 if (!mHasFeature) { 7799 return null; 7800 } 7801 enforceManageUsers(); 7802 ComponentName profileOwner = getProfileOwner(userHandle); 7803 if (profileOwner == null) { 7804 return null; 7805 } 7806 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 7807 } 7808 7809 /** 7810 * Canonical name for a given package. 7811 */ 7812 private String getApplicationLabel(String packageName, int userHandle) { 7813 long token = mInjector.binderClearCallingIdentity(); 7814 try { 7815 final Context userContext; 7816 try { 7817 UserHandle handle = new UserHandle(userHandle); 7818 userContext = mContext.createPackageContextAsUser(packageName, 0, handle); 7819 } catch (PackageManager.NameNotFoundException nnfe) { 7820 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe); 7821 return null; 7822 } 7823 ApplicationInfo appInfo = userContext.getApplicationInfo(); 7824 CharSequence result = null; 7825 if (appInfo != null) { 7826 PackageManager pm = userContext.getPackageManager(); 7827 result = pm.getApplicationLabel(appInfo); 7828 } 7829 return result != null ? result.toString() : null; 7830 } finally { 7831 mInjector.binderRestoreCallingIdentity(token); 7832 } 7833 } 7834 7835 /** 7836 * Calls wtfStack() if called with the DPMS lock held. 7837 */ 7838 private void wtfIfInLock() { 7839 if (Thread.holdsLock(this)) { 7840 Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held"); 7841 } 7842 } 7843 7844 /** 7845 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 7846 * permission. 7847 * The profile owner can only be set before the user setup phase has completed, 7848 * except for: 7849 * - SYSTEM_UID 7850 * - adb unless hasIncompatibleAccountsOrNonAdb is true. 7851 */ 7852 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle, 7853 boolean hasIncompatibleAccountsOrNonAdb) { 7854 UserInfo info = getUserInfo(userHandle); 7855 if (info == null) { 7856 // User doesn't exist. 7857 throw new IllegalArgumentException( 7858 "Attempted to set profile owner for invalid userId: " + userHandle); 7859 } 7860 if (info.isGuest()) { 7861 throw new IllegalStateException("Cannot set a profile owner on a guest"); 7862 } 7863 if (mOwners.hasProfileOwner(userHandle)) { 7864 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 7865 + "is already set."); 7866 } 7867 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 7868 throw new IllegalStateException("Trying to set the profile owner, but the user " 7869 + "already has a device owner."); 7870 } 7871 if (isAdb()) { 7872 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 7873 && hasIncompatibleAccountsOrNonAdb) { 7874 throw new IllegalStateException("Not allowed to set the profile owner because " 7875 + "there are already some accounts on the profile"); 7876 } 7877 return; 7878 } 7879 enforceCanManageProfileAndDeviceOwners(); 7880 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) { 7881 throw new IllegalStateException("Cannot set the profile owner on a user which is " 7882 + "already set-up"); 7883 } 7884 } 7885 7886 /** 7887 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 7888 * permission. 7889 */ 7890 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId, 7891 boolean hasIncompatibleAccountsOrNonAdb) { 7892 if (!isAdb()) { 7893 enforceCanManageProfileAndDeviceOwners(); 7894 } 7895 7896 final int code = checkDeviceOwnerProvisioningPreConditionLocked( 7897 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb); 7898 switch (code) { 7899 case CODE_OK: 7900 return; 7901 case CODE_HAS_DEVICE_OWNER: 7902 throw new IllegalStateException( 7903 "Trying to set the device owner, but device owner is already set."); 7904 case CODE_USER_HAS_PROFILE_OWNER: 7905 throw new IllegalStateException("Trying to set the device owner, but the user " 7906 + "already has a profile owner."); 7907 case CODE_USER_NOT_RUNNING: 7908 throw new IllegalStateException("User not running: " + userId); 7909 case CODE_NOT_SYSTEM_USER: 7910 throw new IllegalStateException("User is not system user"); 7911 case CODE_USER_SETUP_COMPLETED: 7912 throw new IllegalStateException( 7913 "Cannot set the device owner if the device is already set-up"); 7914 case CODE_NONSYSTEM_USER_EXISTS: 7915 throw new IllegalStateException("Not allowed to set the device owner because there " 7916 + "are already several users on the device"); 7917 case CODE_ACCOUNTS_NOT_EMPTY: 7918 throw new IllegalStateException("Not allowed to set the device owner because there " 7919 + "are already some accounts on the device"); 7920 case CODE_HAS_PAIRED: 7921 throw new IllegalStateException("Not allowed to set the device owner because this " 7922 + "device has already paired"); 7923 default: 7924 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code); 7925 } 7926 } 7927 7928 private void enforceUserUnlocked(int userId) { 7929 // Since we're doing this operation on behalf of an app, we only 7930 // want to use the actual "unlocked" state. 7931 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 7932 "User must be running and unlocked"); 7933 } 7934 7935 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 7936 if (parent) { 7937 enforceUserUnlocked(getProfileParentId(userId)); 7938 } else { 7939 enforceUserUnlocked(userId); 7940 } 7941 } 7942 7943 private void enforceManageUsers() { 7944 final int callingUid = mInjector.binderGetCallingUid(); 7945 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 7946 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7947 } 7948 } 7949 7950 private void enforceFullCrossUsersPermission(int userHandle) { 7951 enforceSystemUserOrPermissionIfCrossUser(userHandle, 7952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 7953 } 7954 7955 private void enforceCrossUsersPermission(int userHandle) { 7956 enforceSystemUserOrPermissionIfCrossUser(userHandle, 7957 android.Manifest.permission.INTERACT_ACROSS_USERS); 7958 } 7959 7960 private void enforceSystemUserOrPermission(String permission) { 7961 if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) { 7962 mContext.enforceCallingOrSelfPermission(permission, 7963 "Must be system or have " + permission + " permission"); 7964 } 7965 } 7966 7967 private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) { 7968 if (userHandle < 0) { 7969 throw new IllegalArgumentException("Invalid userId " + userHandle); 7970 } 7971 if (userHandle == mInjector.userHandleGetCallingUserId()) { 7972 return; 7973 } 7974 enforceSystemUserOrPermission(permission); 7975 } 7976 7977 private void enforceManagedProfile(int userHandle, String message) { 7978 if(!isManagedProfile(userHandle)) { 7979 throw new SecurityException("You can not " + message + " outside a managed profile."); 7980 } 7981 } 7982 7983 private void enforceNotManagedProfile(int userHandle, String message) { 7984 if(isManagedProfile(userHandle)) { 7985 throw new SecurityException("You can not " + message + " for a managed profile."); 7986 } 7987 } 7988 7989 private void enforceDeviceOwnerOrManageUsers() { 7990 synchronized (this) { 7991 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7992 mInjector.binderGetCallingUid()) != null) { 7993 return; 7994 } 7995 } 7996 enforceManageUsers(); 7997 } 7998 7999 private void enforceProfileOwnerOrSystemUser() { 8000 synchronized (this) { 8001 if (getActiveAdminWithPolicyForUidLocked(null, 8002 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 8003 != null) { 8004 return; 8005 } 8006 } 8007 Preconditions.checkState(isCallerWithSystemUid(), 8008 "Only profile owner, device owner and system may call this method."); 8009 } 8010 8011 private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) { 8012 if (userId == mInjector.userHandleGetCallingUserId()) { 8013 synchronized (this) { 8014 if (getActiveAdminWithPolicyForUidLocked(null, 8015 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 8016 != null) { 8017 // Device Owner/Profile Owner may access the user it runs on. 8018 return; 8019 } 8020 } 8021 } 8022 // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required. 8023 enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 8024 } 8025 8026 private boolean canUserUseLockTaskLocked(int userId) { 8027 if (isUserAffiliatedWithDeviceLocked(userId)) { 8028 return true; 8029 } 8030 8031 // Unaffiliated profile owners are not allowed to use lock when there is a device owner. 8032 if (mOwners.hasDeviceOwner()) { 8033 return false; 8034 } 8035 8036 final ComponentName profileOwner = getProfileOwner(userId); 8037 if (profileOwner == null) { 8038 return false; 8039 } 8040 8041 // Managed profiles are not allowed to use lock task 8042 if (isManagedProfile(userId)) { 8043 return false; 8044 } 8045 8046 return true; 8047 } 8048 8049 private void enforceCanCallLockTaskLocked(ComponentName who) { 8050 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8051 final int userId = mInjector.userHandleGetCallingUserId(); 8052 if (!canUserUseLockTaskLocked(userId)) { 8053 throw new SecurityException("User " + userId + " is not allowed to use lock task"); 8054 } 8055 } 8056 8057 private void ensureCallerPackage(@Nullable String packageName) { 8058 if (packageName == null) { 8059 Preconditions.checkState(isCallerWithSystemUid(), 8060 "Only caller can omit package name"); 8061 } else { 8062 final int callingUid = mInjector.binderGetCallingUid(); 8063 final int userId = mInjector.userHandleGetCallingUserId(); 8064 try { 8065 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 8066 packageName, 0, userId); 8067 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name"); 8068 } catch (RemoteException e) { 8069 // Shouldn't happen 8070 } 8071 } 8072 } 8073 8074 private boolean isCallerWithSystemUid() { 8075 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID); 8076 } 8077 8078 protected int getProfileParentId(int userHandle) { 8079 final long ident = mInjector.binderClearCallingIdentity(); 8080 try { 8081 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 8082 return parentUser != null ? parentUser.id : userHandle; 8083 } finally { 8084 mInjector.binderRestoreCallingIdentity(ident); 8085 } 8086 } 8087 8088 private int getCredentialOwner(int userHandle, boolean parent) { 8089 final long ident = mInjector.binderClearCallingIdentity(); 8090 try { 8091 if (parent) { 8092 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 8093 if (parentProfile != null) { 8094 userHandle = parentProfile.id; 8095 } 8096 } 8097 return mUserManager.getCredentialOwnerProfile(userHandle); 8098 } finally { 8099 mInjector.binderRestoreCallingIdentity(ident); 8100 } 8101 } 8102 8103 private boolean isManagedProfile(int userHandle) { 8104 final UserInfo user = getUserInfo(userHandle); 8105 return user != null && user.isManagedProfile(); 8106 } 8107 8108 private void enableIfNecessary(String packageName, int userId) { 8109 try { 8110 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 8111 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId); 8112 if (ai.enabledSetting 8113 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 8114 mIPackageManager.setApplicationEnabledSetting(packageName, 8115 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 8116 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 8117 } 8118 } catch (RemoteException e) { 8119 } 8120 } 8121 8122 @Override 8123 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 8124 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return; 8125 8126 synchronized (this) { 8127 pw.println("Current Device Policy Manager state:"); 8128 8129 mOwners.dump(" ", pw); 8130 mDeviceAdminServiceController.dump(" ", pw); 8131 int userCount = mUserData.size(); 8132 for (int u = 0; u < userCount; u++) { 8133 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 8134 pw.println(); 8135 pw.println(" Enabled Device Admins (User " + policy.mUserHandle 8136 + ", provisioningState: " + policy.mUserProvisioningState + "):"); 8137 final int N = policy.mAdminList.size(); 8138 for (int i=0; i<N; i++) { 8139 ActiveAdmin ap = policy.mAdminList.get(i); 8140 if (ap != null) { 8141 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 8142 pw.println(":"); 8143 ap.dump(" ", pw); 8144 } 8145 } 8146 if (!policy.mRemovingAdmins.isEmpty()) { 8147 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 8148 + policy.mRemovingAdmins); 8149 } 8150 8151 pw.println(" "); 8152 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 8153 } 8154 pw.println(); 8155 mConstants.dump(" ", pw); 8156 pw.println(); 8157 pw.println(" Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 8158 } 8159 } 8160 8161 private String getEncryptionStatusName(int encryptionStatus) { 8162 switch (encryptionStatus) { 8163 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 8164 return "inactive"; 8165 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 8166 return "block default key"; 8167 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 8168 return "block"; 8169 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 8170 return "per-user"; 8171 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 8172 return "unsupported"; 8173 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 8174 return "activating"; 8175 default: 8176 return "unknown"; 8177 } 8178 } 8179 8180 @Override 8181 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 8182 ComponentName activity) { 8183 Preconditions.checkNotNull(who, "ComponentName is null"); 8184 final int userHandle = UserHandle.getCallingUserId(); 8185 synchronized (this) { 8186 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8187 8188 long id = mInjector.binderClearCallingIdentity(); 8189 try { 8190 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 8191 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 8192 } catch (RemoteException re) { 8193 // Shouldn't happen 8194 } finally { 8195 mInjector.binderRestoreCallingIdentity(id); 8196 } 8197 } 8198 } 8199 8200 @Override 8201 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 8202 Preconditions.checkNotNull(who, "ComponentName is null"); 8203 final int userHandle = UserHandle.getCallingUserId(); 8204 synchronized (this) { 8205 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8206 8207 long id = mInjector.binderClearCallingIdentity(); 8208 try { 8209 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 8210 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 8211 } catch (RemoteException re) { 8212 // Shouldn't happen 8213 } finally { 8214 mInjector.binderRestoreCallingIdentity(id); 8215 } 8216 } 8217 } 8218 8219 @Override 8220 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 8221 String packageName) { 8222 try { 8223 setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS); 8224 } catch (IllegalArgumentException e) { 8225 return false; 8226 } 8227 return true; 8228 } 8229 8230 @Override 8231 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 8232 final List<String> delegatePackages = getDelegatePackages(admin, 8233 DELEGATION_APP_RESTRICTIONS); 8234 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 8235 } 8236 8237 @Override 8238 public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) { 8239 return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS); 8240 } 8241 8242 @Override 8243 public void setApplicationRestrictions(ComponentName who, String callerPackage, 8244 String packageName, Bundle settings) { 8245 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8246 DELEGATION_APP_RESTRICTIONS); 8247 8248 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 8249 final long id = mInjector.binderClearCallingIdentity(); 8250 try { 8251 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 8252 } finally { 8253 mInjector.binderRestoreCallingIdentity(id); 8254 } 8255 } 8256 8257 @Override 8258 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 8259 PersistableBundle args, boolean parent) { 8260 if (!mHasFeature) { 8261 return; 8262 } 8263 Preconditions.checkNotNull(admin, "admin is null"); 8264 Preconditions.checkNotNull(agent, "agent is null"); 8265 final int userHandle = UserHandle.getCallingUserId(); 8266 synchronized (this) { 8267 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 8268 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 8269 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 8270 saveSettingsLocked(userHandle); 8271 } 8272 } 8273 8274 @Override 8275 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 8276 ComponentName agent, int userHandle, boolean parent) { 8277 if (!mHasFeature) { 8278 return null; 8279 } 8280 Preconditions.checkNotNull(agent, "agent null"); 8281 enforceFullCrossUsersPermission(userHandle); 8282 8283 synchronized (this) { 8284 final String componentName = agent.flattenToString(); 8285 if (admin != null) { 8286 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 8287 if (ap == null) return null; 8288 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 8289 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 8290 List<PersistableBundle> result = new ArrayList<>(); 8291 result.add(trustAgentInfo.options); 8292 return result; 8293 } 8294 8295 // Return strictest policy for this user and profiles that are visible from this user. 8296 List<PersistableBundle> result = null; 8297 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 8298 // of the options. If any admin doesn't have options, discard options for the rest 8299 // and return null. 8300 List<ActiveAdmin> admins = 8301 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 8302 boolean allAdminsHaveOptions = true; 8303 final int N = admins.size(); 8304 for (int i = 0; i < N; i++) { 8305 final ActiveAdmin active = admins.get(i); 8306 8307 final boolean disablesTrust = (active.disabledKeyguardFeatures 8308 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 8309 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 8310 if (info != null && info.options != null && !info.options.isEmpty()) { 8311 if (disablesTrust) { 8312 if (result == null) { 8313 result = new ArrayList<>(); 8314 } 8315 result.add(info.options); 8316 } else { 8317 Log.w(LOG_TAG, "Ignoring admin " + active.info 8318 + " because it has trust options but doesn't declare " 8319 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 8320 } 8321 } else if (disablesTrust) { 8322 allAdminsHaveOptions = false; 8323 break; 8324 } 8325 } 8326 return allAdminsHaveOptions ? result : null; 8327 } 8328 } 8329 8330 @Override 8331 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 8332 Preconditions.checkNotNull(who, "ComponentName is null"); 8333 synchronized (this) { 8334 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8335 8336 int userHandle = UserHandle.getCallingUserId(); 8337 DevicePolicyData userData = getUserData(userHandle); 8338 userData.mRestrictionsProvider = permissionProvider; 8339 saveSettingsLocked(userHandle); 8340 } 8341 } 8342 8343 @Override 8344 public ComponentName getRestrictionsProvider(int userHandle) { 8345 synchronized (this) { 8346 if (!isCallerWithSystemUid()) { 8347 throw new SecurityException("Only the system can query the permission provider"); 8348 } 8349 DevicePolicyData userData = getUserData(userHandle); 8350 return userData != null ? userData.mRestrictionsProvider : null; 8351 } 8352 } 8353 8354 @Override 8355 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 8356 Preconditions.checkNotNull(who, "ComponentName is null"); 8357 int callingUserId = UserHandle.getCallingUserId(); 8358 synchronized (this) { 8359 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8360 8361 long id = mInjector.binderClearCallingIdentity(); 8362 try { 8363 UserInfo parent = mUserManager.getProfileParent(callingUserId); 8364 if (parent == null) { 8365 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 8366 + "parent"); 8367 return; 8368 } 8369 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 8370 mIPackageManager.addCrossProfileIntentFilter( 8371 filter, who.getPackageName(), callingUserId, parent.id, 0); 8372 } 8373 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 8374 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 8375 parent.id, callingUserId, 0); 8376 } 8377 } catch (RemoteException re) { 8378 // Shouldn't happen 8379 } finally { 8380 mInjector.binderRestoreCallingIdentity(id); 8381 } 8382 } 8383 } 8384 8385 @Override 8386 public void clearCrossProfileIntentFilters(ComponentName who) { 8387 Preconditions.checkNotNull(who, "ComponentName is null"); 8388 int callingUserId = UserHandle.getCallingUserId(); 8389 synchronized (this) { 8390 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8391 long id = mInjector.binderClearCallingIdentity(); 8392 try { 8393 UserInfo parent = mUserManager.getProfileParent(callingUserId); 8394 if (parent == null) { 8395 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 8396 + "parent"); 8397 return; 8398 } 8399 // Removing those that go from the managed profile to the parent. 8400 mIPackageManager.clearCrossProfileIntentFilters( 8401 callingUserId, who.getPackageName()); 8402 // And those that go from the parent to the managed profile. 8403 // If we want to support multiple managed profiles, we will have to only remove 8404 // those that have callingUserId as their target. 8405 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 8406 } catch (RemoteException re) { 8407 // Shouldn't happen 8408 } finally { 8409 mInjector.binderRestoreCallingIdentity(id); 8410 } 8411 } 8412 } 8413 8414 /** 8415 * @return true if all packages in enabledPackages are either in the list 8416 * permittedList or are a system app. 8417 */ 8418 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 8419 List<String> permittedList, int userIdToCheck) { 8420 long id = mInjector.binderClearCallingIdentity(); 8421 try { 8422 // If we have an enabled packages list for a managed profile the packages 8423 // we should check are installed for the parent user. 8424 UserInfo user = getUserInfo(userIdToCheck); 8425 if (user.isManagedProfile()) { 8426 userIdToCheck = user.profileGroupId; 8427 } 8428 8429 for (String enabledPackage : enabledPackages) { 8430 boolean systemService = false; 8431 try { 8432 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 8433 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 8434 userIdToCheck); 8435 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 8436 } catch (RemoteException e) { 8437 Log.i(LOG_TAG, "Can't talk to package managed", e); 8438 } 8439 if (!systemService && !permittedList.contains(enabledPackage)) { 8440 return false; 8441 } 8442 } 8443 } finally { 8444 mInjector.binderRestoreCallingIdentity(id); 8445 } 8446 return true; 8447 } 8448 8449 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 8450 // Not using AccessibilityManager.getInstance because that guesses 8451 // at the user you require based on callingUid and caches for a given 8452 // process. 8453 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 8454 IAccessibilityManager service = iBinder == null 8455 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 8456 return new AccessibilityManager(mContext, service, userId); 8457 } 8458 8459 @Override 8460 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 8461 if (!mHasFeature) { 8462 return false; 8463 } 8464 Preconditions.checkNotNull(who, "ComponentName is null"); 8465 8466 if (packageList != null) { 8467 int userId = UserHandle.getCallingUserId(); 8468 List<AccessibilityServiceInfo> enabledServices = null; 8469 long id = mInjector.binderClearCallingIdentity(); 8470 try { 8471 UserInfo user = getUserInfo(userId); 8472 if (user.isManagedProfile()) { 8473 userId = user.profileGroupId; 8474 } 8475 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 8476 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 8477 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 8478 } finally { 8479 mInjector.binderRestoreCallingIdentity(id); 8480 } 8481 8482 if (enabledServices != null) { 8483 List<String> enabledPackages = new ArrayList<String>(); 8484 for (AccessibilityServiceInfo service : enabledServices) { 8485 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 8486 } 8487 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 8488 userId)) { 8489 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 8490 + "because it contains already enabled accesibility services."); 8491 return false; 8492 } 8493 } 8494 } 8495 8496 synchronized (this) { 8497 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8498 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8499 admin.permittedAccessiblityServices = packageList; 8500 saveSettingsLocked(UserHandle.getCallingUserId()); 8501 } 8502 return true; 8503 } 8504 8505 @Override 8506 public List getPermittedAccessibilityServices(ComponentName who) { 8507 if (!mHasFeature) { 8508 return null; 8509 } 8510 Preconditions.checkNotNull(who, "ComponentName is null"); 8511 8512 synchronized (this) { 8513 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8514 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8515 return admin.permittedAccessiblityServices; 8516 } 8517 } 8518 8519 @Override 8520 public List getPermittedAccessibilityServicesForUser(int userId) { 8521 if (!mHasFeature) { 8522 return null; 8523 } 8524 synchronized (this) { 8525 List<String> result = null; 8526 // If we have multiple profiles we return the intersection of the 8527 // permitted lists. This can happen in cases where we have a device 8528 // and profile owner. 8529 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 8530 for (int profileId : profileIds) { 8531 // Just loop though all admins, only device or profiles 8532 // owners can have permitted lists set. 8533 DevicePolicyData policy = getUserDataUnchecked(profileId); 8534 final int N = policy.mAdminList.size(); 8535 for (int j = 0; j < N; j++) { 8536 ActiveAdmin admin = policy.mAdminList.get(j); 8537 List<String> fromAdmin = admin.permittedAccessiblityServices; 8538 if (fromAdmin != null) { 8539 if (result == null) { 8540 result = new ArrayList<>(fromAdmin); 8541 } else { 8542 result.retainAll(fromAdmin); 8543 } 8544 } 8545 } 8546 } 8547 8548 // If we have a permitted list add all system accessibility services. 8549 if (result != null) { 8550 long id = mInjector.binderClearCallingIdentity(); 8551 try { 8552 UserInfo user = getUserInfo(userId); 8553 if (user.isManagedProfile()) { 8554 userId = user.profileGroupId; 8555 } 8556 AccessibilityManager accessibilityManager = 8557 getAccessibilityManagerForUser(userId); 8558 List<AccessibilityServiceInfo> installedServices = 8559 accessibilityManager.getInstalledAccessibilityServiceList(); 8560 8561 if (installedServices != null) { 8562 for (AccessibilityServiceInfo service : installedServices) { 8563 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 8564 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 8565 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8566 result.add(serviceInfo.packageName); 8567 } 8568 } 8569 } 8570 } finally { 8571 mInjector.binderRestoreCallingIdentity(id); 8572 } 8573 } 8574 8575 return result; 8576 } 8577 } 8578 8579 @Override 8580 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 8581 int userHandle) { 8582 if (!mHasFeature) { 8583 return true; 8584 } 8585 Preconditions.checkNotNull(who, "ComponentName is null"); 8586 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 8587 if (!isCallerWithSystemUid()){ 8588 throw new SecurityException( 8589 "Only the system can query if an accessibility service is disabled by admin"); 8590 } 8591 synchronized (this) { 8592 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 8593 if (admin == null) { 8594 return false; 8595 } 8596 if (admin.permittedAccessiblityServices == null) { 8597 return true; 8598 } 8599 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 8600 admin.permittedAccessiblityServices, userHandle); 8601 } 8602 } 8603 8604 private boolean checkCallerIsCurrentUserOrProfile() { 8605 final int callingUserId = UserHandle.getCallingUserId(); 8606 final long token = mInjector.binderClearCallingIdentity(); 8607 try { 8608 UserInfo currentUser; 8609 UserInfo callingUser = getUserInfo(callingUserId); 8610 try { 8611 currentUser = mInjector.getIActivityManager().getCurrentUser(); 8612 } catch (RemoteException e) { 8613 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 8614 return false; 8615 } 8616 8617 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 8618 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 8619 + "of a user that isn't the foreground user."); 8620 return false; 8621 } 8622 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 8623 Slog.e(LOG_TAG, "Cannot set permitted input methods " 8624 + "of a user that isn't the foreground user."); 8625 return false; 8626 } 8627 } finally { 8628 mInjector.binderRestoreCallingIdentity(token); 8629 } 8630 return true; 8631 } 8632 8633 @Override 8634 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 8635 if (!mHasFeature) { 8636 return false; 8637 } 8638 Preconditions.checkNotNull(who, "ComponentName is null"); 8639 8640 // TODO When InputMethodManager supports per user calls remove 8641 // this restriction. 8642 if (!checkCallerIsCurrentUserOrProfile()) { 8643 return false; 8644 } 8645 8646 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8647 if (packageList != null) { 8648 // InputMethodManager fetches input methods for current user. 8649 // So this can only be set when calling user is the current user 8650 // or parent is current user in case of managed profiles. 8651 InputMethodManager inputMethodManager = 8652 mContext.getSystemService(InputMethodManager.class); 8653 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList(); 8654 8655 if (enabledImes != null) { 8656 List<String> enabledPackages = new ArrayList<String>(); 8657 for (InputMethodInfo ime : enabledImes) { 8658 enabledPackages.add(ime.getPackageName()); 8659 } 8660 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 8661 callingUserId)) { 8662 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 8663 + "because it contains already enabled input method."); 8664 return false; 8665 } 8666 } 8667 } 8668 8669 synchronized (this) { 8670 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8671 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8672 admin.permittedInputMethods = packageList; 8673 saveSettingsLocked(callingUserId); 8674 } 8675 return true; 8676 } 8677 8678 @Override 8679 public List getPermittedInputMethods(ComponentName who) { 8680 if (!mHasFeature) { 8681 return null; 8682 } 8683 Preconditions.checkNotNull(who, "ComponentName is null"); 8684 8685 synchronized (this) { 8686 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8687 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8688 return admin.permittedInputMethods; 8689 } 8690 } 8691 8692 @Override 8693 public List getPermittedInputMethodsForCurrentUser() { 8694 UserInfo currentUser; 8695 try { 8696 currentUser = mInjector.getIActivityManager().getCurrentUser(); 8697 } catch (RemoteException e) { 8698 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e); 8699 // Activity managed is dead, just allow all IMEs 8700 return null; 8701 } 8702 8703 int userId = currentUser.id; 8704 synchronized (this) { 8705 List<String> result = null; 8706 // If we have multiple profiles we return the intersection of the 8707 // permitted lists. This can happen in cases where we have a device 8708 // and profile owner. 8709 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 8710 for (int profileId : profileIds) { 8711 // Just loop though all admins, only device or profiles 8712 // owners can have permitted lists set. 8713 DevicePolicyData policy = getUserDataUnchecked(profileId); 8714 final int N = policy.mAdminList.size(); 8715 for (int j = 0; j < N; j++) { 8716 ActiveAdmin admin = policy.mAdminList.get(j); 8717 List<String> fromAdmin = admin.permittedInputMethods; 8718 if (fromAdmin != null) { 8719 if (result == null) { 8720 result = new ArrayList<String>(fromAdmin); 8721 } else { 8722 result.retainAll(fromAdmin); 8723 } 8724 } 8725 } 8726 } 8727 8728 // If we have a permitted list add all system input methods. 8729 if (result != null) { 8730 InputMethodManager inputMethodManager = 8731 mContext.getSystemService(InputMethodManager.class); 8732 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList(); 8733 long id = mInjector.binderClearCallingIdentity(); 8734 try { 8735 if (imes != null) { 8736 for (InputMethodInfo ime : imes) { 8737 ServiceInfo serviceInfo = ime.getServiceInfo(); 8738 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 8739 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8740 result.add(serviceInfo.packageName); 8741 } 8742 } 8743 } 8744 } finally { 8745 mInjector.binderRestoreCallingIdentity(id); 8746 } 8747 } 8748 return result; 8749 } 8750 } 8751 8752 @Override 8753 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 8754 int userHandle) { 8755 if (!mHasFeature) { 8756 return true; 8757 } 8758 Preconditions.checkNotNull(who, "ComponentName is null"); 8759 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 8760 if (!isCallerWithSystemUid()) { 8761 throw new SecurityException( 8762 "Only the system can query if an input method is disabled by admin"); 8763 } 8764 synchronized (this) { 8765 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 8766 if (admin == null) { 8767 return false; 8768 } 8769 if (admin.permittedInputMethods == null) { 8770 return true; 8771 } 8772 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 8773 admin.permittedInputMethods, userHandle); 8774 } 8775 } 8776 8777 @Override 8778 public boolean setPermittedCrossProfileNotificationListeners( 8779 ComponentName who, List<String> packageList) { 8780 if (!mHasFeature) { 8781 return false; 8782 } 8783 Preconditions.checkNotNull(who, "ComponentName is null"); 8784 8785 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8786 if (!isManagedProfile(callingUserId)) { 8787 return false; 8788 } 8789 8790 synchronized (this) { 8791 ActiveAdmin admin = getActiveAdminForCallerLocked( 8792 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8793 admin.permittedNotificationListeners = packageList; 8794 saveSettingsLocked(callingUserId); 8795 } 8796 return true; 8797 } 8798 8799 @Override 8800 public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) { 8801 if (!mHasFeature) { 8802 return null; 8803 } 8804 Preconditions.checkNotNull(who, "ComponentName is null"); 8805 8806 synchronized (this) { 8807 ActiveAdmin admin = getActiveAdminForCallerLocked( 8808 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8809 return admin.permittedNotificationListeners; 8810 } 8811 } 8812 8813 @Override 8814 public boolean isNotificationListenerServicePermitted(String packageName, int userId) { 8815 if (!mHasFeature) { 8816 return true; 8817 } 8818 8819 Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty"); 8820 if (!isCallerWithSystemUid()) { 8821 throw new SecurityException( 8822 "Only the system can query if a notification listener service is permitted"); 8823 } 8824 synchronized (this) { 8825 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 8826 if (profileOwner == null || profileOwner.permittedNotificationListeners == null) { 8827 return true; 8828 } 8829 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 8830 profileOwner.permittedNotificationListeners, userId); 8831 8832 } 8833 } 8834 8835 private void maybeSendAdminEnabledBroadcastLocked(int userHandle) { 8836 DevicePolicyData policyData = getUserData(userHandle); 8837 if (policyData.mAdminBroadcastPending) { 8838 // Send the initialization data to profile owner and delete the data 8839 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 8840 boolean clearInitBundle = true; 8841 if (admin != null) { 8842 PersistableBundle initBundle = policyData.mInitBundle; 8843 clearInitBundle = sendAdminCommandLocked(admin, 8844 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 8845 initBundle == null ? null : new Bundle(initBundle), 8846 null /* result receiver */, 8847 true /* send in foreground */); 8848 } 8849 if (clearInitBundle) { 8850 // If there's no admin or we've successfully called the admin, clear the init bundle 8851 // otherwise, keep it around 8852 policyData.mInitBundle = null; 8853 policyData.mAdminBroadcastPending = false; 8854 saveSettingsLocked(userHandle); 8855 } 8856 } 8857 } 8858 8859 @Override 8860 public UserHandle createAndManageUser(ComponentName admin, String name, 8861 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 8862 Preconditions.checkNotNull(admin, "admin is null"); 8863 Preconditions.checkNotNull(profileOwner, "profileOwner is null"); 8864 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 8865 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 8866 + admin + " are not in the same package"); 8867 } 8868 // Only allow the system user to use this method 8869 if (!mInjector.binderGetCallingUserHandle().isSystem()) { 8870 throw new SecurityException("createAndManageUser was called from non-system user"); 8871 } 8872 final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0; 8873 final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0 8874 && UserManager.isDeviceInDemoMode(mContext); 8875 final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0; 8876 // Create user. 8877 UserHandle user = null; 8878 synchronized (this) { 8879 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8880 8881 final long id = mInjector.binderClearCallingIdentity(); 8882 try { 8883 int userInfoFlags = 0; 8884 if (ephemeral) { 8885 userInfoFlags |= UserInfo.FLAG_EPHEMERAL; 8886 } 8887 if (demo) { 8888 userInfoFlags |= UserInfo.FLAG_DEMO; 8889 } 8890 String[] disallowedPackages = null; 8891 if (!leaveAllSystemAppsEnabled) { 8892 disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin, 8893 UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray( 8894 new String[0]); 8895 } 8896 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 8897 userInfoFlags, disallowedPackages); 8898 if (userInfo != null) { 8899 user = userInfo.getUserHandle(); 8900 } 8901 } finally { 8902 mInjector.binderRestoreCallingIdentity(id); 8903 } 8904 } 8905 if (user == null) { 8906 return null; 8907 } 8908 8909 final int userHandle = user.getIdentifier(); 8910 final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED) 8911 .putExtra(Intent.EXTRA_USER_HANDLE, userHandle) 8912 .putExtra( 8913 DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED, 8914 leaveAllSystemAppsEnabled) 8915 .setPackage(MANAGED_PROVISIONING_PKG) 8916 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8917 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM); 8918 8919 final long id = mInjector.binderClearCallingIdentity(); 8920 try { 8921 final String adminPkg = admin.getPackageName(); 8922 try { 8923 // Install the profile owner if not present. 8924 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) { 8925 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle, 8926 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 8927 } 8928 } catch (RemoteException e) { 8929 // Does not happen, same process 8930 } 8931 8932 // Set admin. 8933 setActiveAdmin(profileOwner, true, userHandle); 8934 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier()); 8935 setProfileOwner(profileOwner, ownerName, userHandle); 8936 8937 synchronized (this) { 8938 DevicePolicyData policyData = getUserData(userHandle); 8939 policyData.mInitBundle = adminExtras; 8940 policyData.mAdminBroadcastPending = true; 8941 saveSettingsLocked(userHandle); 8942 } 8943 8944 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 8945 Settings.Secure.putIntForUser(mContext.getContentResolver(), 8946 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 8947 } 8948 8949 return user; 8950 } catch (Throwable re) { 8951 mUserManager.removeUser(userHandle); 8952 return null; 8953 } finally { 8954 mInjector.binderRestoreCallingIdentity(id); 8955 } 8956 } 8957 8958 @Override 8959 public boolean removeUser(ComponentName who, UserHandle userHandle) { 8960 Preconditions.checkNotNull(who, "ComponentName is null"); 8961 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 8962 8963 synchronized (this) { 8964 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8965 } 8966 8967 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8968 final long id = mInjector.binderClearCallingIdentity(); 8969 try { 8970 String restriction = isManagedProfile(userHandle.getIdentifier()) 8971 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 8972 : UserManager.DISALLOW_REMOVE_USER; 8973 if (isAdminAffectedByRestriction(who, restriction, callingUserId)) { 8974 Log.w(LOG_TAG, "The device owner cannot remove a user because " 8975 + restriction + " is enabled, and was not set by the device owner"); 8976 return false; 8977 } 8978 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 8979 } finally { 8980 mInjector.binderRestoreCallingIdentity(id); 8981 } 8982 } 8983 8984 private boolean isAdminAffectedByRestriction( 8985 ComponentName admin, String userRestriction, int userId) { 8986 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 8987 case UserManager.RESTRICTION_NOT_SET: 8988 return false; 8989 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 8990 return !isDeviceOwner(admin, userId); 8991 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 8992 return !isProfileOwner(admin, userId); 8993 default: 8994 return true; 8995 } 8996 } 8997 8998 @Override 8999 public boolean switchUser(ComponentName who, UserHandle userHandle) { 9000 Preconditions.checkNotNull(who, "ComponentName is null"); 9001 9002 synchronized (this) { 9003 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9004 9005 long id = mInjector.binderClearCallingIdentity(); 9006 try { 9007 int userId = UserHandle.USER_SYSTEM; 9008 if (userHandle != null) { 9009 userId = userHandle.getIdentifier(); 9010 } 9011 return mInjector.getIActivityManager().switchUser(userId); 9012 } catch (RemoteException e) { 9013 Log.e(LOG_TAG, "Couldn't switch user", e); 9014 return false; 9015 } finally { 9016 mInjector.binderRestoreCallingIdentity(id); 9017 } 9018 } 9019 } 9020 9021 @Override 9022 public int startUserInBackground(ComponentName who, UserHandle userHandle) { 9023 Preconditions.checkNotNull(who, "ComponentName is null"); 9024 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 9025 9026 synchronized (this) { 9027 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9028 } 9029 9030 final int userId = userHandle.getIdentifier(); 9031 if (isManagedProfile(userId)) { 9032 Log.w(LOG_TAG, "Managed profile cannot be started in background"); 9033 return DevicePolicyManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9034 } 9035 9036 final long id = mInjector.binderClearCallingIdentity(); 9037 try { 9038 if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) { 9039 Log.w(LOG_TAG, "Cannot start more users in background"); 9040 return DevicePolicyManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS; 9041 } 9042 9043 if (mInjector.getIActivityManager().startUserInBackground(userId)) { 9044 return DevicePolicyManager.USER_OPERATION_SUCCESS; 9045 } else { 9046 return DevicePolicyManager.USER_OPERATION_ERROR_UNKNOWN; 9047 } 9048 } catch (RemoteException e) { 9049 // Same process, should not happen. 9050 return DevicePolicyManager.USER_OPERATION_ERROR_UNKNOWN; 9051 } finally { 9052 mInjector.binderRestoreCallingIdentity(id); 9053 } 9054 } 9055 9056 @Override 9057 public int stopUser(ComponentName who, UserHandle userHandle) { 9058 Preconditions.checkNotNull(who, "ComponentName is null"); 9059 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 9060 9061 synchronized (this) { 9062 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9063 } 9064 9065 final int userId = userHandle.getIdentifier(); 9066 if (isManagedProfile(userId)) { 9067 Log.w(LOG_TAG, "Managed profile cannot be stopped"); 9068 return DevicePolicyManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9069 } 9070 9071 return stopUserUnchecked(userId); 9072 } 9073 9074 @Override 9075 public int logoutUser(ComponentName who) { 9076 Preconditions.checkNotNull(who, "ComponentName is null"); 9077 9078 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9079 synchronized (this) { 9080 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9081 if (!isUserAffiliatedWithDeviceLocked(callingUserId)) { 9082 throw new SecurityException("Admin " + who + 9083 " is neither the device owner or affiliated user's profile owner."); 9084 } 9085 } 9086 9087 if (isManagedProfile(callingUserId)) { 9088 Log.w(LOG_TAG, "Managed profile cannot be logout"); 9089 return DevicePolicyManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9090 } 9091 9092 final long id = mInjector.binderClearCallingIdentity(); 9093 try { 9094 if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) { 9095 Log.w(LOG_TAG, "Failed to switch to primary user"); 9096 // This should never happen as target user is UserHandle.USER_SYSTEM 9097 return DevicePolicyManager.USER_OPERATION_ERROR_UNKNOWN; 9098 } 9099 } catch (RemoteException e) { 9100 // Same process, should not happen. 9101 return DevicePolicyManager.USER_OPERATION_ERROR_UNKNOWN; 9102 } finally { 9103 mInjector.binderRestoreCallingIdentity(id); 9104 } 9105 9106 return stopUserUnchecked(callingUserId); 9107 } 9108 9109 private int stopUserUnchecked(int userId) { 9110 final long id = mInjector.binderClearCallingIdentity(); 9111 try { 9112 switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) { 9113 case ActivityManager.USER_OP_SUCCESS: 9114 return DevicePolicyManager.USER_OPERATION_SUCCESS; 9115 case ActivityManager.USER_OP_IS_CURRENT: 9116 return DevicePolicyManager.USER_OPERATION_ERROR_CURRENT_USER; 9117 default: 9118 return DevicePolicyManager.USER_OPERATION_ERROR_UNKNOWN; 9119 } 9120 } catch (RemoteException e) { 9121 // Same process, should not happen. 9122 return DevicePolicyManager.USER_OPERATION_ERROR_UNKNOWN; 9123 } finally { 9124 mInjector.binderRestoreCallingIdentity(id); 9125 } 9126 } 9127 9128 @Override 9129 public List<UserHandle> getSecondaryUsers(ComponentName who) { 9130 Preconditions.checkNotNull(who, "ComponentName is null"); 9131 synchronized (this) { 9132 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9133 } 9134 9135 final long id = mInjector.binderClearCallingIdentity(); 9136 try { 9137 final List<UserInfo> userInfos = mInjector.getUserManager().getUsers(true 9138 /*excludeDying*/); 9139 final List<UserHandle> userHandles = new ArrayList<>(); 9140 for (UserInfo userInfo : userInfos) { 9141 UserHandle userHandle = userInfo.getUserHandle(); 9142 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) { 9143 userHandles.add(userInfo.getUserHandle()); 9144 } 9145 } 9146 return userHandles; 9147 } finally { 9148 mInjector.binderRestoreCallingIdentity(id); 9149 } 9150 } 9151 9152 @Override 9153 public boolean isEphemeralUser(ComponentName who) { 9154 Preconditions.checkNotNull(who, "ComponentName is null"); 9155 synchronized (this) { 9156 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9157 } 9158 9159 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9160 final long id = mInjector.binderClearCallingIdentity(); 9161 try { 9162 return mInjector.getUserManager().isUserEphemeral(callingUserId); 9163 } finally { 9164 mInjector.binderRestoreCallingIdentity(id); 9165 } 9166 } 9167 9168 @Override 9169 public Bundle getApplicationRestrictions(ComponentName who, String callerPackage, 9170 String packageName) { 9171 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9172 DELEGATION_APP_RESTRICTIONS); 9173 9174 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 9175 final long id = mInjector.binderClearCallingIdentity(); 9176 try { 9177 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 9178 // if no restrictions were saved, mUserManager.getApplicationRestrictions 9179 // returns null, but DPM method should return an empty Bundle as per JavaDoc 9180 return bundle != null ? bundle : Bundle.EMPTY; 9181 } finally { 9182 mInjector.binderRestoreCallingIdentity(id); 9183 } 9184 } 9185 9186 @Override 9187 public String[] setPackagesSuspended(ComponentName who, String callerPackage, 9188 String[] packageNames, boolean suspended) { 9189 int callingUserId = UserHandle.getCallingUserId(); 9190 synchronized (this) { 9191 // Ensure the caller is a DO/PO or a package access delegate. 9192 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9193 DELEGATION_PACKAGE_ACCESS); 9194 9195 long id = mInjector.binderClearCallingIdentity(); 9196 try { 9197 return mIPackageManager.setPackagesSuspendedAsUser( 9198 packageNames, suspended, callingUserId); 9199 } catch (RemoteException re) { 9200 // Shouldn't happen. 9201 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 9202 } finally { 9203 mInjector.binderRestoreCallingIdentity(id); 9204 } 9205 return packageNames; 9206 } 9207 } 9208 9209 @Override 9210 public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) { 9211 int callingUserId = UserHandle.getCallingUserId(); 9212 synchronized (this) { 9213 // Ensure the caller is a DO/PO or a package access delegate. 9214 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9215 DELEGATION_PACKAGE_ACCESS); 9216 9217 long id = mInjector.binderClearCallingIdentity(); 9218 try { 9219 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId); 9220 } catch (RemoteException re) { 9221 // Shouldn't happen. 9222 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 9223 } finally { 9224 mInjector.binderRestoreCallingIdentity(id); 9225 } 9226 return false; 9227 } 9228 } 9229 9230 @Override 9231 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) { 9232 Preconditions.checkNotNull(who, "ComponentName is null"); 9233 if (!UserRestrictionsUtils.isValidRestriction(key)) { 9234 return; 9235 } 9236 9237 final int userHandle = mInjector.userHandleGetCallingUserId(); 9238 synchronized (this) { 9239 final ActiveAdmin activeAdmin = 9240 getActiveAdminForCallerLocked(who, 9241 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9242 final boolean isDeviceOwner = isDeviceOwner(who, userHandle); 9243 if (isDeviceOwner) { 9244 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 9245 throw new SecurityException("Device owner cannot set user restriction " + key); 9246 } 9247 } else { // profile owner 9248 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) { 9249 throw new SecurityException("Profile owner cannot set user restriction " + key); 9250 } 9251 } 9252 9253 // Save the restriction to ActiveAdmin. 9254 final Bundle restrictions = activeAdmin.ensureUserRestrictions(); 9255 if (enabledFromThisOwner) { 9256 restrictions.putBoolean(key, true); 9257 } else { 9258 restrictions.remove(key); 9259 } 9260 saveUserRestrictionsLocked(userHandle); 9261 } 9262 if (SecurityLog.isLoggingEnabled()) { 9263 final int eventTag = enabledFromThisOwner 9264 ? SecurityLog.TAG_USER_RESTRICTION_ADDED 9265 : SecurityLog.TAG_USER_RESTRICTION_REMOVED; 9266 SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key); 9267 } 9268 } 9269 9270 private void saveUserRestrictionsLocked(int userId) { 9271 saveSettingsLocked(userId); 9272 pushUserRestrictions(userId); 9273 sendChangedNotification(userId); 9274 } 9275 9276 private void pushUserRestrictions(int userId) { 9277 synchronized (this) { 9278 final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId); 9279 final Bundle userRestrictions; 9280 // Whether device owner enforces camera restriction. 9281 boolean disallowCameraGlobally = false; 9282 9283 if (isDeviceOwner) { 9284 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 9285 if (deviceOwner == null) { 9286 return; // Shouldn't happen. 9287 } 9288 userRestrictions = deviceOwner.userRestrictions; 9289 // DO can disable camera globally. 9290 disallowCameraGlobally = deviceOwner.disableCamera; 9291 } else { 9292 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 9293 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null; 9294 } 9295 9296 // Whether any admin enforces camera restriction. 9297 final int cameraRestrictionScope = 9298 getCameraRestrictionScopeLocked(userId, disallowCameraGlobally); 9299 9300 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions, 9301 isDeviceOwner, cameraRestrictionScope); 9302 } 9303 } 9304 9305 /** 9306 * Get the scope of camera restriction for a given user if any. 9307 */ 9308 private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) { 9309 if (disallowCameraGlobally) { 9310 return UserManagerInternal.CAMERA_DISABLED_GLOBALLY; 9311 } else if (getCameraDisabled( 9312 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) { 9313 return UserManagerInternal.CAMERA_DISABLED_LOCALLY; 9314 } 9315 return UserManagerInternal.CAMERA_NOT_DISABLED; 9316 } 9317 9318 @Override 9319 public Bundle getUserRestrictions(ComponentName who) { 9320 if (!mHasFeature) { 9321 return null; 9322 } 9323 Preconditions.checkNotNull(who, "ComponentName is null"); 9324 synchronized (this) { 9325 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who, 9326 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9327 return activeAdmin.userRestrictions; 9328 } 9329 } 9330 9331 @Override 9332 public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName, 9333 boolean hidden) { 9334 int callingUserId = UserHandle.getCallingUserId(); 9335 synchronized (this) { 9336 // Ensure the caller is a DO/PO or a package access delegate. 9337 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9338 DELEGATION_PACKAGE_ACCESS); 9339 9340 long id = mInjector.binderClearCallingIdentity(); 9341 try { 9342 return mIPackageManager.setApplicationHiddenSettingAsUser( 9343 packageName, hidden, callingUserId); 9344 } catch (RemoteException re) { 9345 // shouldn't happen 9346 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 9347 } finally { 9348 mInjector.binderRestoreCallingIdentity(id); 9349 } 9350 return false; 9351 } 9352 } 9353 9354 @Override 9355 public boolean isApplicationHidden(ComponentName who, String callerPackage, 9356 String packageName) { 9357 int callingUserId = UserHandle.getCallingUserId(); 9358 synchronized (this) { 9359 // Ensure the caller is a DO/PO or a package access delegate. 9360 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9361 DELEGATION_PACKAGE_ACCESS); 9362 9363 long id = mInjector.binderClearCallingIdentity(); 9364 try { 9365 return mIPackageManager.getApplicationHiddenSettingAsUser( 9366 packageName, callingUserId); 9367 } catch (RemoteException re) { 9368 // shouldn't happen 9369 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 9370 } finally { 9371 mInjector.binderRestoreCallingIdentity(id); 9372 } 9373 return false; 9374 } 9375 } 9376 9377 @Override 9378 public void enableSystemApp(ComponentName who, String callerPackage, String packageName) { 9379 synchronized (this) { 9380 // Ensure the caller is a DO/PO or an enable system app delegate. 9381 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9382 DELEGATION_ENABLE_SYSTEM_APP); 9383 9384 final boolean isDemo = isCurrentUserDemo(); 9385 9386 int userId = UserHandle.getCallingUserId(); 9387 long id = mInjector.binderClearCallingIdentity(); 9388 9389 try { 9390 if (VERBOSE_LOG) { 9391 Slog.v(LOG_TAG, "installing " + packageName + " for " 9392 + userId); 9393 } 9394 9395 int parentUserId = getProfileParentId(userId); 9396 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) { 9397 throw new IllegalArgumentException("Only system apps can be enabled this way."); 9398 } 9399 9400 // Install the app. 9401 mIPackageManager.installExistingPackageAsUser(packageName, userId, 9402 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 9403 if (isDemo) { 9404 // Ensure the app is also ENABLED for demo users. 9405 mIPackageManager.setApplicationEnabledSetting(packageName, 9406 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 9407 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 9408 } 9409 } catch (RemoteException re) { 9410 // shouldn't happen 9411 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 9412 } finally { 9413 mInjector.binderRestoreCallingIdentity(id); 9414 } 9415 } 9416 } 9417 9418 @Override 9419 public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) { 9420 synchronized (this) { 9421 // Ensure the caller is a DO/PO or an enable system app delegate. 9422 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9423 DELEGATION_ENABLE_SYSTEM_APP); 9424 9425 int userId = UserHandle.getCallingUserId(); 9426 long id = mInjector.binderClearCallingIdentity(); 9427 9428 try { 9429 int parentUserId = getProfileParentId(userId); 9430 List<ResolveInfo> activitiesToEnable = mIPackageManager 9431 .queryIntentActivities(intent, 9432 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 9433 PackageManager.MATCH_DIRECT_BOOT_AWARE 9434 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 9435 parentUserId) 9436 .getList(); 9437 9438 if (VERBOSE_LOG) { 9439 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 9440 } 9441 int numberOfAppsInstalled = 0; 9442 if (activitiesToEnable != null) { 9443 for (ResolveInfo info : activitiesToEnable) { 9444 if (info.activityInfo != null) { 9445 String packageName = info.activityInfo.packageName; 9446 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 9447 numberOfAppsInstalled++; 9448 mIPackageManager.installExistingPackageAsUser(packageName, userId, 9449 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 9450 } else { 9451 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 9452 + " system app"); 9453 } 9454 } 9455 } 9456 } 9457 return numberOfAppsInstalled; 9458 } catch (RemoteException e) { 9459 // shouldn't happen 9460 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 9461 return 0; 9462 } finally { 9463 mInjector.binderRestoreCallingIdentity(id); 9464 } 9465 } 9466 } 9467 9468 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 9469 throws RemoteException { 9470 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 9471 userId); 9472 if (appInfo == null) { 9473 throw new IllegalArgumentException("The application " + packageName + 9474 " is not present on this device"); 9475 } 9476 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9477 } 9478 9479 @Override 9480 public boolean installExistingPackage(ComponentName who, String callerPackage, 9481 String packageName) { 9482 synchronized (this) { 9483 // Ensure the caller is a PO or an install existing package delegate 9484 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9485 DELEGATION_INSTALL_EXISTING_PACKAGE); 9486 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9487 if (!isUserAffiliatedWithDeviceLocked(callingUserId)) { 9488 throw new SecurityException("Admin " + who + 9489 " is neither the device owner or affiliated user's profile owner."); 9490 } 9491 9492 final long id = mInjector.binderClearCallingIdentity(); 9493 try { 9494 if (VERBOSE_LOG) { 9495 Slog.v(LOG_TAG, "installing " + packageName + " for " 9496 + callingUserId); 9497 } 9498 9499 // Install the package. 9500 return mIPackageManager.installExistingPackageAsUser(packageName, callingUserId, 9501 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY) 9502 == PackageManager.INSTALL_SUCCEEDED; 9503 } catch (RemoteException re) { 9504 // shouldn't happen 9505 return false; 9506 } finally { 9507 mInjector.binderRestoreCallingIdentity(id); 9508 } 9509 } 9510 } 9511 9512 @Override 9513 public void setAccountManagementDisabled(ComponentName who, String accountType, 9514 boolean disabled) { 9515 if (!mHasFeature) { 9516 return; 9517 } 9518 Preconditions.checkNotNull(who, "ComponentName is null"); 9519 synchronized (this) { 9520 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 9521 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9522 if (disabled) { 9523 ap.accountTypesWithManagementDisabled.add(accountType); 9524 } else { 9525 ap.accountTypesWithManagementDisabled.remove(accountType); 9526 } 9527 saveSettingsLocked(UserHandle.getCallingUserId()); 9528 } 9529 } 9530 9531 @Override 9532 public String[] getAccountTypesWithManagementDisabled() { 9533 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 9534 } 9535 9536 @Override 9537 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 9538 enforceFullCrossUsersPermission(userId); 9539 if (!mHasFeature) { 9540 return null; 9541 } 9542 synchronized (this) { 9543 DevicePolicyData policy = getUserData(userId); 9544 final int N = policy.mAdminList.size(); 9545 ArraySet<String> resultSet = new ArraySet<>(); 9546 for (int i = 0; i < N; i++) { 9547 ActiveAdmin admin = policy.mAdminList.get(i); 9548 resultSet.addAll(admin.accountTypesWithManagementDisabled); 9549 } 9550 return resultSet.toArray(new String[resultSet.size()]); 9551 } 9552 } 9553 9554 @Override 9555 public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName, 9556 boolean uninstallBlocked) { 9557 final int userId = UserHandle.getCallingUserId(); 9558 synchronized (this) { 9559 // Ensure the caller is a DO/PO or a block uninstall delegate 9560 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9561 DELEGATION_BLOCK_UNINSTALL); 9562 9563 long id = mInjector.binderClearCallingIdentity(); 9564 try { 9565 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 9566 } catch (RemoteException re) { 9567 // Shouldn't happen. 9568 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 9569 } finally { 9570 mInjector.binderRestoreCallingIdentity(id); 9571 } 9572 } 9573 } 9574 9575 @Override 9576 public boolean isUninstallBlocked(ComponentName who, String packageName) { 9577 // This function should return true if and only if the package is blocked by 9578 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 9579 // when the package is a system app, or when it is an active device admin. 9580 final int userId = UserHandle.getCallingUserId(); 9581 9582 synchronized (this) { 9583 if (who != null) { 9584 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9585 } 9586 9587 long id = mInjector.binderClearCallingIdentity(); 9588 try { 9589 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 9590 } catch (RemoteException re) { 9591 // Shouldn't happen. 9592 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 9593 } finally { 9594 mInjector.binderRestoreCallingIdentity(id); 9595 } 9596 } 9597 return false; 9598 } 9599 9600 @Override 9601 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 9602 if (!mHasFeature) { 9603 return; 9604 } 9605 Preconditions.checkNotNull(who, "ComponentName is null"); 9606 synchronized (this) { 9607 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9608 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9609 if (admin.disableCallerId != disabled) { 9610 admin.disableCallerId = disabled; 9611 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 9612 } 9613 } 9614 } 9615 9616 @Override 9617 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 9618 if (!mHasFeature) { 9619 return false; 9620 } 9621 Preconditions.checkNotNull(who, "ComponentName is null"); 9622 synchronized (this) { 9623 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9624 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9625 return admin.disableCallerId; 9626 } 9627 } 9628 9629 @Override 9630 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 9631 enforceCrossUsersPermission(userId); 9632 synchronized (this) { 9633 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9634 return (admin != null) ? admin.disableCallerId : false; 9635 } 9636 } 9637 9638 @Override 9639 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 9640 if (!mHasFeature) { 9641 return; 9642 } 9643 Preconditions.checkNotNull(who, "ComponentName is null"); 9644 synchronized (this) { 9645 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9646 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9647 if (admin.disableContactsSearch != disabled) { 9648 admin.disableContactsSearch = disabled; 9649 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 9650 } 9651 } 9652 } 9653 9654 @Override 9655 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 9656 if (!mHasFeature) { 9657 return false; 9658 } 9659 Preconditions.checkNotNull(who, "ComponentName is null"); 9660 synchronized (this) { 9661 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9662 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9663 return admin.disableContactsSearch; 9664 } 9665 } 9666 9667 @Override 9668 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 9669 enforceCrossUsersPermission(userId); 9670 synchronized (this) { 9671 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9672 return (admin != null) ? admin.disableContactsSearch : false; 9673 } 9674 } 9675 9676 @Override 9677 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 9678 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 9679 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 9680 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 9681 final int callingUserId = UserHandle.getCallingUserId(); 9682 9683 final long ident = mInjector.binderClearCallingIdentity(); 9684 try { 9685 synchronized (this) { 9686 final int managedUserId = getManagedUserId(callingUserId); 9687 if (managedUserId < 0) { 9688 return; 9689 } 9690 if (isCrossProfileQuickContactDisabled(managedUserId)) { 9691 if (VERBOSE_LOG) { 9692 Log.v(LOG_TAG, 9693 "Cross-profile contacts access disabled for user " + managedUserId); 9694 } 9695 return; 9696 } 9697 ContactsInternal.startQuickContactWithErrorToastForUser( 9698 mContext, intent, new UserHandle(managedUserId)); 9699 } 9700 } finally { 9701 mInjector.binderRestoreCallingIdentity(ident); 9702 } 9703 } 9704 9705 /** 9706 * @return true if cross-profile QuickContact is disabled 9707 */ 9708 private boolean isCrossProfileQuickContactDisabled(int userId) { 9709 return getCrossProfileCallerIdDisabledForUser(userId) 9710 && getCrossProfileContactsSearchDisabledForUser(userId); 9711 } 9712 9713 /** 9714 * @return the user ID of the managed user that is linked to the current user, if any. 9715 * Otherwise -1. 9716 */ 9717 public int getManagedUserId(int callingUserId) { 9718 if (VERBOSE_LOG) { 9719 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 9720 } 9721 9722 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 9723 if (ui.id == callingUserId || !ui.isManagedProfile()) { 9724 continue; // Caller user self, or not a managed profile. Skip. 9725 } 9726 if (VERBOSE_LOG) { 9727 Log.v(LOG_TAG, "Managed user=" + ui.id); 9728 } 9729 return ui.id; 9730 } 9731 if (VERBOSE_LOG) { 9732 Log.v(LOG_TAG, "Managed user not found."); 9733 } 9734 return -1; 9735 } 9736 9737 @Override 9738 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 9739 if (!mHasFeature) { 9740 return; 9741 } 9742 Preconditions.checkNotNull(who, "ComponentName is null"); 9743 synchronized (this) { 9744 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9745 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9746 if (admin.disableBluetoothContactSharing != disabled) { 9747 admin.disableBluetoothContactSharing = disabled; 9748 saveSettingsLocked(UserHandle.getCallingUserId()); 9749 } 9750 } 9751 } 9752 9753 @Override 9754 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 9755 if (!mHasFeature) { 9756 return false; 9757 } 9758 Preconditions.checkNotNull(who, "ComponentName is null"); 9759 synchronized (this) { 9760 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9761 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9762 return admin.disableBluetoothContactSharing; 9763 } 9764 } 9765 9766 @Override 9767 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 9768 // TODO: Should there be a check to make sure this relationship is 9769 // within a profile group? 9770 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 9771 synchronized (this) { 9772 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9773 return (admin != null) ? admin.disableBluetoothContactSharing : false; 9774 } 9775 } 9776 9777 @Override 9778 public void setLockTaskPackages(ComponentName who, String[] packages) 9779 throws SecurityException { 9780 Preconditions.checkNotNull(who, "ComponentName is null"); 9781 Preconditions.checkNotNull(packages, "packages is null"); 9782 9783 synchronized (this) { 9784 enforceCanCallLockTaskLocked(who); 9785 final int userHandle = mInjector.userHandleGetCallingUserId(); 9786 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 9787 } 9788 } 9789 9790 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 9791 DevicePolicyData policy = getUserData(userHandle); 9792 policy.mLockTaskPackages = packages; 9793 9794 // Store the settings persistently. 9795 saveSettingsLocked(userHandle); 9796 updateLockTaskPackagesLocked(packages, userHandle); 9797 } 9798 9799 @Override 9800 public String[] getLockTaskPackages(ComponentName who) { 9801 Preconditions.checkNotNull(who, "ComponentName is null"); 9802 9803 final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 9804 synchronized (this) { 9805 enforceCanCallLockTaskLocked(who); 9806 final List<String> packages = getUserData(userHandle).mLockTaskPackages; 9807 return packages.toArray(new String[packages.size()]); 9808 } 9809 } 9810 9811 @Override 9812 public boolean isLockTaskPermitted(String pkg) { 9813 final int userHandle = mInjector.userHandleGetCallingUserId(); 9814 synchronized (this) { 9815 return getUserData(userHandle).mLockTaskPackages.contains(pkg); 9816 } 9817 } 9818 9819 @Override 9820 public void setLockTaskFeatures(ComponentName who, int flags) { 9821 Preconditions.checkNotNull(who, "ComponentName is null"); 9822 9823 // Throw if Overview is used without Home. 9824 boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0; 9825 boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0; 9826 Preconditions.checkArgument(hasHome || !hasOverview, 9827 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME"); 9828 9829 final int userHandle = mInjector.userHandleGetCallingUserId(); 9830 synchronized (this) { 9831 enforceCanCallLockTaskLocked(who); 9832 setLockTaskFeaturesLocked(userHandle, flags); 9833 } 9834 } 9835 9836 private void setLockTaskFeaturesLocked(int userHandle, int flags) { 9837 DevicePolicyData policy = getUserData(userHandle); 9838 policy.mLockTaskFeatures = flags; 9839 saveSettingsLocked(userHandle); 9840 updateLockTaskFeaturesLocked(flags, userHandle); 9841 } 9842 9843 @Override 9844 public int getLockTaskFeatures(ComponentName who) { 9845 Preconditions.checkNotNull(who, "ComponentName is null"); 9846 final int userHandle = mInjector.userHandleGetCallingUserId(); 9847 synchronized (this) { 9848 enforceCanCallLockTaskLocked(who); 9849 return getUserData(userHandle).mLockTaskFeatures; 9850 } 9851 } 9852 9853 private void maybeClearLockTaskPolicyLocked() { 9854 final long ident = mInjector.binderClearCallingIdentity(); 9855 try { 9856 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 9857 for (int i = userInfos.size() - 1; i >= 0; i--) { 9858 int userId = userInfos.get(i).id; 9859 if (canUserUseLockTaskLocked(userId)) { 9860 continue; 9861 } 9862 9863 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages; 9864 if (!lockTaskPackages.isEmpty()) { 9865 Slog.d(LOG_TAG, 9866 "User id " + userId + " not affiliated. Clearing lock task packages"); 9867 setLockTaskPackagesLocked(userId, Collections.<String>emptyList()); 9868 } 9869 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures; 9870 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){ 9871 Slog.d(LOG_TAG, 9872 "User id " + userId + " not affiliated. Clearing lock task features"); 9873 setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE); 9874 } 9875 } 9876 } finally { 9877 mInjector.binderRestoreCallingIdentity(ident); 9878 } 9879 } 9880 9881 @Override 9882 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 9883 if (!isCallerWithSystemUid()) { 9884 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 9885 } 9886 synchronized (this) { 9887 final DevicePolicyData policy = getUserData(userHandle); 9888 9889 if (policy.mStatusBarDisabled) { 9890 // Status bar is managed by LockTaskController during LockTask, so we cancel this 9891 // policy when LockTask starts, and reapply it when LockTask ends 9892 setStatusBarDisabledInternal(!isEnabled, userHandle); 9893 } 9894 9895 Bundle adminExtras = new Bundle(); 9896 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 9897 for (ActiveAdmin admin : policy.mAdminList) { 9898 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 9899 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 9900 if (ownsDevice || ownsProfile) { 9901 if (isEnabled) { 9902 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 9903 adminExtras, null); 9904 } else { 9905 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 9906 } 9907 } 9908 } 9909 } 9910 } 9911 9912 @Override 9913 public void setGlobalSetting(ComponentName who, String setting, String value) { 9914 Preconditions.checkNotNull(who, "ComponentName is null"); 9915 9916 synchronized (this) { 9917 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9918 9919 // Some settings are no supported any more. However we do not want to throw a 9920 // SecurityException to avoid breaking apps. 9921 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 9922 Log.i(LOG_TAG, "Global setting no longer supported: " + setting); 9923 return; 9924 } 9925 9926 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting) 9927 && !UserManager.isDeviceInDemoMode(mContext)) { 9928 throw new SecurityException(String.format( 9929 "Permission denial: device owners cannot update %1$s", setting)); 9930 } 9931 9932 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 9933 // ignore if it contradicts an existing policy 9934 long timeMs = getMaximumTimeToLock( 9935 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 9936 if (timeMs > 0 && timeMs < Long.MAX_VALUE) { 9937 return; 9938 } 9939 } 9940 9941 long id = mInjector.binderClearCallingIdentity(); 9942 try { 9943 mInjector.settingsGlobalPutString(setting, value); 9944 } finally { 9945 mInjector.binderRestoreCallingIdentity(id); 9946 } 9947 } 9948 } 9949 9950 @Override 9951 public void setSystemSetting(ComponentName who, String setting, String value) { 9952 Preconditions.checkNotNull(who, "ComponentName is null"); 9953 Preconditions.checkStringNotEmpty(setting, "String setting is null or empty"); 9954 9955 synchronized (this) { 9956 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9957 9958 if (!SYSTEM_SETTINGS_WHITELIST.contains(setting)) { 9959 throw new SecurityException(String.format( 9960 "Permission denial: device owners cannot update %1$s", setting)); 9961 } 9962 9963 mInjector.binderWithCleanCallingIdentity(() -> mInjector.settingsSystemPutString( 9964 setting, value)); 9965 } 9966 } 9967 9968 @Override 9969 public boolean setTime(ComponentName who, long millis) { 9970 Preconditions.checkNotNull(who, "ComponentName is null in setTime"); 9971 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9972 // Don't allow set time when auto time is on. 9973 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) { 9974 return false; 9975 } 9976 mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis)); 9977 return true; 9978 } 9979 9980 @Override 9981 public boolean setTimeZone(ComponentName who, String timeZone) { 9982 Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone"); 9983 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9984 // Don't allow set timezone when auto timezone is on. 9985 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) { 9986 return false; 9987 } 9988 mInjector.binderWithCleanCallingIdentity(() -> 9989 mInjector.getAlarmManager().setTimeZone(timeZone)); 9990 return true; 9991 } 9992 9993 @Override 9994 public void setSecureSetting(ComponentName who, String setting, String value) { 9995 Preconditions.checkNotNull(who, "ComponentName is null"); 9996 int callingUserId = mInjector.userHandleGetCallingUserId(); 9997 9998 synchronized (this) { 9999 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10000 10001 if (isDeviceOwner(who, callingUserId)) { 10002 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting) 10003 && !isCurrentUserDemo()) { 10004 throw new SecurityException(String.format( 10005 "Permission denial: Device owners cannot update %1$s", setting)); 10006 } 10007 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) { 10008 throw new SecurityException(String.format( 10009 "Permission denial: Profile owners cannot update %1$s", setting)); 10010 } 10011 if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) { 10012 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) { 10013 throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS 10014 + " is deprecated. Please use the user restriction " 10015 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead."); 10016 } 10017 if (!mUserManager.isManagedProfile(callingUserId)) { 10018 Slog.e(LOG_TAG, "Ignoring setSecureSetting request for " 10019 + setting + ". User restriction " 10020 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES 10021 + " should be used instead."); 10022 } else { 10023 try { 10024 setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 10025 (Integer.parseInt(value) == 0) ? true : false); 10026 } catch (NumberFormatException exc) { 10027 Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting); 10028 } 10029 } 10030 return; 10031 } 10032 long id = mInjector.binderClearCallingIdentity(); 10033 try { 10034 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) { 10035 final String currentValue = mInjector.settingsSecureGetStringForUser( 10036 Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId); 10037 if (!TextUtils.equals(currentValue, value)) { 10038 // Tell the content observer that the next change will be due to the owner 10039 // changing the value. There is a small race condition here that we cannot 10040 // avoid: Change notifications are sent asynchronously, so it is possible 10041 // that there are prior notifications queued up before the one we are about 10042 // to trigger. This is a corner case that will have no impact in practice. 10043 mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId); 10044 } 10045 getUserData(callingUserId).mCurrentInputMethodSet = true; 10046 saveSettingsLocked(callingUserId); 10047 } 10048 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 10049 } finally { 10050 mInjector.binderRestoreCallingIdentity(id); 10051 } 10052 } 10053 } 10054 10055 @Override 10056 public void setMasterVolumeMuted(ComponentName who, boolean on) { 10057 Preconditions.checkNotNull(who, "ComponentName is null"); 10058 synchronized (this) { 10059 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10060 setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on); 10061 } 10062 } 10063 10064 @Override 10065 public boolean isMasterVolumeMuted(ComponentName who) { 10066 Preconditions.checkNotNull(who, "ComponentName is null"); 10067 synchronized (this) { 10068 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10069 10070 AudioManager audioManager = 10071 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 10072 return audioManager.isMasterMute(); 10073 } 10074 } 10075 10076 @Override 10077 public void setUserIcon(ComponentName who, Bitmap icon) { 10078 synchronized (this) { 10079 Preconditions.checkNotNull(who, "ComponentName is null"); 10080 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10081 10082 int userId = UserHandle.getCallingUserId(); 10083 long id = mInjector.binderClearCallingIdentity(); 10084 try { 10085 mUserManagerInternal.setUserIcon(userId, icon); 10086 } finally { 10087 mInjector.binderRestoreCallingIdentity(id); 10088 } 10089 } 10090 } 10091 10092 @Override 10093 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 10094 Preconditions.checkNotNull(who, "ComponentName is null"); 10095 final int userId = mInjector.userHandleGetCallingUserId(); 10096 synchronized (this) { 10097 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10098 if (!isUserAffiliatedWithDeviceLocked(userId)) { 10099 throw new SecurityException("Admin " + who + 10100 " is neither the device owner or affiliated user's profile owner."); 10101 } 10102 } 10103 if (isManagedProfile(userId)) { 10104 throw new SecurityException("Managed profile cannot disable keyguard"); 10105 } 10106 10107 long ident = mInjector.binderClearCallingIdentity(); 10108 try { 10109 // disallow disabling the keyguard if a password is currently set 10110 if (disabled && mLockPatternUtils.isSecure(userId)) { 10111 return false; 10112 } 10113 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 10114 mInjector.getIWindowManager().dismissKeyguard(null /* callback */, null /* message */); 10115 } catch (RemoteException e) { 10116 // Same process, does not happen. 10117 } finally { 10118 mInjector.binderRestoreCallingIdentity(ident); 10119 } 10120 return true; 10121 } 10122 10123 @Override 10124 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 10125 int userId = UserHandle.getCallingUserId(); 10126 synchronized (this) { 10127 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10128 if (!isUserAffiliatedWithDeviceLocked(userId)) { 10129 throw new SecurityException("Admin " + who + 10130 " is neither the device owner or affiliated user's profile owner."); 10131 } 10132 if (isManagedProfile(userId)) { 10133 throw new SecurityException("Managed profile cannot disable status bar"); 10134 } 10135 DevicePolicyData policy = getUserData(userId); 10136 if (policy.mStatusBarDisabled != disabled) { 10137 boolean isLockTaskMode = false; 10138 try { 10139 isLockTaskMode = mInjector.getIActivityManager().getLockTaskModeState() 10140 != LOCK_TASK_MODE_NONE; 10141 } catch (RemoteException e) { 10142 Slog.e(LOG_TAG, "Failed to get LockTask mode"); 10143 } 10144 if (!isLockTaskMode) { 10145 if (!setStatusBarDisabledInternal(disabled, userId)) { 10146 return false; 10147 } 10148 } 10149 policy.mStatusBarDisabled = disabled; 10150 saveSettingsLocked(userId); 10151 } 10152 } 10153 return true; 10154 } 10155 10156 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 10157 long ident = mInjector.binderClearCallingIdentity(); 10158 try { 10159 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 10160 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 10161 if (statusBarService != null) { 10162 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 10163 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 10164 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 10165 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 10166 return true; 10167 } 10168 } catch (RemoteException e) { 10169 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 10170 } finally { 10171 mInjector.binderRestoreCallingIdentity(ident); 10172 } 10173 return false; 10174 } 10175 10176 /** 10177 * We need to update the internal state of whether a user has completed setup or a 10178 * device has paired once. After that, we ignore any changes that reset the 10179 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 10180 * as we don't trust any apps that might try to reset them. 10181 * <p> 10182 * Unfortunately, we don't know which user's setup state was changed, so we write all of 10183 * them. 10184 */ 10185 void updateUserSetupCompleteAndPaired() { 10186 List<UserInfo> users = mUserManager.getUsers(true); 10187 final int N = users.size(); 10188 for (int i = 0; i < N; i++) { 10189 int userHandle = users.get(i).id; 10190 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 10191 userHandle) != 0) { 10192 DevicePolicyData policy = getUserData(userHandle); 10193 if (!policy.mUserSetupComplete) { 10194 policy.mUserSetupComplete = true; 10195 synchronized (this) { 10196 saveSettingsLocked(userHandle); 10197 } 10198 } 10199 } 10200 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 10201 userHandle) != 0) { 10202 DevicePolicyData policy = getUserData(userHandle); 10203 if (!policy.mPaired) { 10204 policy.mPaired = true; 10205 synchronized (this) { 10206 saveSettingsLocked(userHandle); 10207 } 10208 } 10209 } 10210 } 10211 } 10212 10213 private class SetupContentObserver extends ContentObserver { 10214 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 10215 Settings.Secure.USER_SETUP_COMPLETE); 10216 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 10217 Settings.Global.DEVICE_PROVISIONED); 10218 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 10219 private final Uri mDefaultImeChanged = Settings.Secure.getUriFor( 10220 Settings.Secure.DEFAULT_INPUT_METHOD); 10221 10222 @GuardedBy("DevicePolicyManagerService.this") 10223 private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>(); 10224 10225 public SetupContentObserver(Handler handler) { 10226 super(handler); 10227 } 10228 10229 void register() { 10230 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 10231 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 10232 if (mIsWatch) { 10233 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 10234 } 10235 mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL); 10236 } 10237 10238 @GuardedBy("DevicePolicyManagerService.this") 10239 private void addPendingChangeByOwnerLocked(int userId) { 10240 mUserIdsWithPendingChangesByOwner.add(userId); 10241 } 10242 10243 @Override 10244 public void onChange(boolean selfChange, Uri uri, int userId) { 10245 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 10246 updateUserSetupCompleteAndPaired(); 10247 } else if (mDeviceProvisioned.equals(uri)) { 10248 synchronized (DevicePolicyManagerService.this) { 10249 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 10250 // is delayed until device is marked as provisioned. 10251 setDeviceOwnerSystemPropertyLocked(); 10252 } 10253 } else if (mDefaultImeChanged.equals(uri)) { 10254 synchronized (DevicePolicyManagerService.this) { 10255 if (mUserIdsWithPendingChangesByOwner.contains(userId)) { 10256 // This change notification was triggered by the owner changing the current 10257 // IME. Ignore it. 10258 mUserIdsWithPendingChangesByOwner.remove(userId); 10259 } else { 10260 // This change notification was triggered by the user manually changing the 10261 // current IME. 10262 getUserData(userId).mCurrentInputMethodSet = false; 10263 saveSettingsLocked(userId); 10264 } 10265 } 10266 } 10267 } 10268 } 10269 10270 @VisibleForTesting 10271 final class LocalService extends DevicePolicyManagerInternal { 10272 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 10273 10274 @Override 10275 public List<String> getCrossProfileWidgetProviders(int profileId) { 10276 synchronized (DevicePolicyManagerService.this) { 10277 if (mOwners == null) { 10278 return Collections.emptyList(); 10279 } 10280 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 10281 if (ownerComponent == null) { 10282 return Collections.emptyList(); 10283 } 10284 10285 DevicePolicyData policy = getUserDataUnchecked(profileId); 10286 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 10287 10288 if (admin == null || admin.crossProfileWidgetProviders == null 10289 || admin.crossProfileWidgetProviders.isEmpty()) { 10290 return Collections.emptyList(); 10291 } 10292 10293 return admin.crossProfileWidgetProviders; 10294 } 10295 } 10296 10297 @Override 10298 public void addOnCrossProfileWidgetProvidersChangeListener( 10299 OnCrossProfileWidgetProvidersChangeListener listener) { 10300 synchronized (DevicePolicyManagerService.this) { 10301 if (mWidgetProviderListeners == null) { 10302 mWidgetProviderListeners = new ArrayList<>(); 10303 } 10304 if (!mWidgetProviderListeners.contains(listener)) { 10305 mWidgetProviderListeners.add(listener); 10306 } 10307 } 10308 } 10309 10310 @Override 10311 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 10312 synchronized(DevicePolicyManagerService.this) { 10313 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 10314 } 10315 } 10316 10317 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 10318 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 10319 synchronized (DevicePolicyManagerService.this) { 10320 listeners = new ArrayList<>(mWidgetProviderListeners); 10321 } 10322 final int listenerCount = listeners.size(); 10323 for (int i = 0; i < listenerCount; i++) { 10324 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 10325 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 10326 } 10327 } 10328 10329 @Override 10330 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 10331 // This method is called from AM with its lock held, so don't take the DPMS lock. 10332 // b/29242568 10333 10334 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 10335 if (profileOwner != null) { 10336 return DevicePolicyManagerService.this 10337 .createShowAdminSupportIntent(profileOwner, userId); 10338 } 10339 10340 final Pair<Integer, ComponentName> deviceOwner = 10341 mOwners.getDeviceOwnerUserIdAndComponent(); 10342 if (deviceOwner != null && deviceOwner.first == userId) { 10343 return DevicePolicyManagerService.this 10344 .createShowAdminSupportIntent(deviceOwner.second, userId); 10345 } 10346 10347 // We're not specifying the device admin because there isn't one. 10348 if (useDefaultIfNoAdmin) { 10349 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 10350 } 10351 return null; 10352 } 10353 10354 @Override 10355 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 10356 int source; 10357 long ident = mInjector.binderClearCallingIdentity(); 10358 try { 10359 source = mUserManager.getUserRestrictionSource(userRestriction, 10360 UserHandle.of(userId)); 10361 } finally { 10362 mInjector.binderRestoreCallingIdentity(ident); 10363 } 10364 if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) { 10365 /* 10366 * In this case, the user restriction is enforced by the system. 10367 * So we won't show an admin support intent, even if it is also 10368 * enforced by a profile/device owner. 10369 */ 10370 return null; 10371 } 10372 boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0; 10373 boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0; 10374 if (enforcedByDo && enforcedByPo) { 10375 // In this case, we'll show an admin support dialog that does not 10376 // specify the admin. 10377 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 10378 } else if (enforcedByPo) { 10379 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 10380 if (profileOwner != null) { 10381 return DevicePolicyManagerService.this 10382 .createShowAdminSupportIntent(profileOwner, userId); 10383 } 10384 // This could happen if another thread has changed the profile owner since we called 10385 // getUserRestrictionSource 10386 return null; 10387 } else if (enforcedByDo) { 10388 final Pair<Integer, ComponentName> deviceOwner 10389 = mOwners.getDeviceOwnerUserIdAndComponent(); 10390 if (deviceOwner != null) { 10391 return DevicePolicyManagerService.this 10392 .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first); 10393 } 10394 // This could happen if another thread has changed the device owner since we called 10395 // getUserRestrictionSource 10396 return null; 10397 } 10398 return null; 10399 } 10400 10401 @Override 10402 public boolean isUserAffiliatedWithDevice(int userId) { 10403 return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId); 10404 } 10405 10406 @Override 10407 public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) { 10408 synchronized (DevicePolicyManagerService.this) { 10409 updateMaximumTimeToLockLocked(userId); 10410 } 10411 } 10412 10413 @Override 10414 public boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) { 10415 return DevicePolicyManagerService.this.canUserHaveUntrustedCredentialReset(userId); 10416 } 10417 10418 @Override 10419 public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) { 10420 synchronized (DevicePolicyManagerService.this) { 10421 DevicePolicyData policy = getUserData(userId); 10422 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING)) { 10423 Log.e(LOG_TAG, "printing is enabled"); 10424 return null; 10425 } 10426 String ownerPackage = mOwners.getProfileOwnerPackage(userId); 10427 if (ownerPackage == null) { 10428 ownerPackage = mOwners.getDeviceOwnerPackageName(); 10429 } 10430 PackageManager pm = mInjector.getPackageManager(); 10431 PackageInfo packageInfo; 10432 try { 10433 packageInfo = pm.getPackageInfo(ownerPackage, 0); 10434 } catch (NameNotFoundException e) { 10435 Log.e(LOG_TAG, "getPackageInfo error", e); 10436 return null; 10437 } 10438 if (packageInfo == null) { 10439 Log.e(LOG_TAG, "packageInfo is inexplicably null"); 10440 return null; 10441 } 10442 ApplicationInfo appInfo = packageInfo.applicationInfo; 10443 if (appInfo == null) { 10444 Log.e(LOG_TAG, "appInfo is inexplicably null"); 10445 return null; 10446 } 10447 CharSequence appLabel = pm.getApplicationLabel(appInfo); 10448 if (appLabel == null) { 10449 Log.e(LOG_TAG, "appLabel is inexplicably null"); 10450 return null; 10451 } 10452 return ((Context) ActivityThread.currentActivityThread().getSystemUiContext()) 10453 .getResources().getString(R.string.printing_disabled_by, appLabel); 10454 } 10455 } 10456 } 10457 10458 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) { 10459 // This method is called with AMS lock held, so don't take DPMS lock 10460 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 10461 intent.putExtra(Intent.EXTRA_USER_ID, userId); 10462 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin); 10463 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 10464 return intent; 10465 } 10466 10467 @Override 10468 public Intent createAdminSupportIntent(String restriction) { 10469 Preconditions.checkNotNull(restriction); 10470 final int uid = mInjector.binderGetCallingUid(); 10471 final int userId = UserHandle.getUserId(uid); 10472 Intent intent = null; 10473 if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) || 10474 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction) || 10475 DevicePolicyManager.POLICY_MANDATORY_BACKUPS.equals(restriction)) { 10476 synchronized(this) { 10477 final DevicePolicyData policy = getUserData(userId); 10478 final int N = policy.mAdminList.size(); 10479 for (int i = 0; i < N; i++) { 10480 final ActiveAdmin admin = policy.mAdminList.get(i); 10481 if ((admin.disableCamera && 10482 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) || 10483 (admin.disableScreenCapture && DevicePolicyManager 10484 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) || 10485 (admin.mandatoryBackupTransport != null && DevicePolicyManager 10486 .POLICY_MANDATORY_BACKUPS.equals(restriction))) { 10487 intent = createShowAdminSupportIntent(admin.info.getComponent(), userId); 10488 break; 10489 } 10490 } 10491 // For the camera, a device owner on a different user can disable it globally, 10492 // so we need an additional check. 10493 if (intent == null 10494 && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) { 10495 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 10496 if (admin != null && admin.disableCamera) { 10497 intent = createShowAdminSupportIntent(admin.info.getComponent(), 10498 mOwners.getDeviceOwnerUserId()); 10499 } 10500 } 10501 } 10502 } else { 10503 // if valid, |restriction| can only be a user restriction 10504 intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction); 10505 } 10506 if (intent != null) { 10507 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction); 10508 } 10509 return intent; 10510 } 10511 10512 /** 10513 * Returns true if specified admin is allowed to limit passwords and has a 10514 * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality} 10515 */ 10516 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 10517 if (admin.minimumPasswordMetrics.quality < minPasswordQuality) { 10518 return false; 10519 } 10520 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 10521 } 10522 10523 @Override 10524 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 10525 if (policy != null) { 10526 // throws exception if policy type is invalid 10527 policy.validateType(); 10528 // throws exception if freeze period is invalid 10529 policy.validateFreezePeriods(); 10530 Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 10531 // throws exception if freeze period is incompatible with previous freeze period record 10532 policy.validateAgainstPreviousFreezePeriod(record.first, record.second, 10533 LocalDate.now()); 10534 } 10535 synchronized (this) { 10536 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10537 if (policy == null) { 10538 mOwners.clearSystemUpdatePolicy(); 10539 } else { 10540 mOwners.setSystemUpdatePolicy(policy); 10541 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false); 10542 } 10543 mOwners.writeDeviceOwner(); 10544 } 10545 mContext.sendBroadcastAsUser( 10546 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 10547 UserHandle.SYSTEM); 10548 } 10549 10550 @Override 10551 public SystemUpdatePolicy getSystemUpdatePolicy() { 10552 synchronized (this) { 10553 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 10554 if (policy != null && !policy.isValid()) { 10555 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 10556 return null; 10557 } 10558 return policy; 10559 } 10560 } 10561 10562 private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) { 10563 return (!date.isBefore(range.first) && !date.isAfter(range.second)); 10564 } 10565 10566 /** 10567 * keeps track of the last continuous period when the system is under OTA freeze. 10568 * 10569 * DPMS keeps track of the previous dates during which OTA was freezed as a result of an 10570 * system update policy with freeze periods in effect. This is needed to make robust 10571 * validation on new system update polices, for example to prevent the OTA from being 10572 * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period 10573 * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting 10574 * a new freeze period after a few days. 10575 * 10576 * @param saveIfChanged whether to persist the result on disk if freeze period record is 10577 * updated. This should only be set to {@code false} if there is a guaranteed 10578 * mOwners.writeDeviceOwner() later in the control flow to reduce the number of 10579 * disk writes. Otherwise you risk inconsistent on-disk state. 10580 * 10581 * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod 10582 */ 10583 private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) { 10584 Slog.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord"); 10585 synchronized (this) { 10586 final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 10587 if (policy == null) { 10588 return; 10589 } 10590 final LocalDate now = LocalDate.now(); 10591 final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now); 10592 if (currentPeriod == null) { 10593 return; 10594 } 10595 final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 10596 final LocalDate start = record.first; 10597 final LocalDate end = record.second; 10598 final boolean changed; 10599 if (end == null || start == null) { 10600 // Start a new period if there is none at the moment 10601 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 10602 } else if (now.equals(end.plusDays(1))) { 10603 // Extend the existing period 10604 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 10605 } else if (now.isAfter(end.plusDays(1))) { 10606 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) { 10607 // The device might be off for some period. If the past freeze record 10608 // is within range of the current freeze period, assume the device was off 10609 // during the period [end, now] and extend the freeze record to [start, now]. 10610 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 10611 } else { 10612 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 10613 } 10614 } else if (now.isBefore(start)) { 10615 // Systm clock was adjusted backwards, restart record 10616 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 10617 } else /* start <= now <= end */ { 10618 changed = false; 10619 } 10620 if (changed && saveIfChanged) { 10621 mOwners.writeDeviceOwner(); 10622 } 10623 } 10624 } 10625 10626 @Override 10627 public void clearSystemUpdatePolicyFreezePeriodRecord() { 10628 enforceShell("clearSystemUpdatePolicyFreezePeriodRecord"); 10629 synchronized (this) { 10630 // Print out current record to help diagnosed CTS failures 10631 Slog.i(LOG_TAG, "Clear freeze period record: " 10632 + mOwners.getSystemUpdateFreezePeriodRecordAsString()); 10633 if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) { 10634 mOwners.writeDeviceOwner(); 10635 } 10636 } 10637 } 10638 10639 /** 10640 * Checks if the caller of the method is the device owner app. 10641 * 10642 * @param callerUid UID of the caller. 10643 * @return true if the caller is the device owner app 10644 */ 10645 @VisibleForTesting 10646 boolean isCallerDeviceOwner(int callerUid) { 10647 synchronized (this) { 10648 if (!mOwners.hasDeviceOwner()) { 10649 return false; 10650 } 10651 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 10652 return false; 10653 } 10654 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 10655 .getPackageName(); 10656 try { 10657 String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid); 10658 for (String pkg : pkgs) { 10659 if (deviceOwnerPackageName.equals(pkg)) { 10660 return true; 10661 } 10662 } 10663 } catch (RemoteException e) { 10664 return false; 10665 } 10666 } 10667 10668 return false; 10669 } 10670 10671 @Override 10672 public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) { 10673 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 10674 "Only the system update service can broadcast update information"); 10675 10676 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 10677 Slog.w(LOG_TAG, "Only the system update service in the system user " + 10678 "can broadcast update information."); 10679 return; 10680 } 10681 10682 if (!mOwners.saveSystemUpdateInfo(info)) { 10683 // Pending system update hasn't changed, don't send duplicate notification. 10684 return; 10685 } 10686 10687 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE) 10688 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 10689 info == null ? -1 : info.getReceivedTime()); 10690 10691 final long ident = mInjector.binderClearCallingIdentity(); 10692 try { 10693 synchronized (this) { 10694 // Broadcast to device owner first if there is one. 10695 if (mOwners.hasDeviceOwner()) { 10696 final UserHandle deviceOwnerUser = 10697 UserHandle.of(mOwners.getDeviceOwnerUserId()); 10698 intent.setComponent(mOwners.getDeviceOwnerComponent()); 10699 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 10700 } 10701 } 10702 // Get running users. 10703 final int runningUserIds[]; 10704 try { 10705 runningUserIds = mInjector.getIActivityManager().getRunningUserIds(); 10706 } catch (RemoteException e) { 10707 // Shouldn't happen. 10708 Log.e(LOG_TAG, "Could not retrieve the list of running users", e); 10709 return; 10710 } 10711 // Send broadcasts to corresponding profile owners if any. 10712 for (final int userId : runningUserIds) { 10713 synchronized (this) { 10714 final ComponentName profileOwnerPackage = 10715 mOwners.getProfileOwnerComponent(userId); 10716 if (profileOwnerPackage != null) { 10717 intent.setComponent(profileOwnerPackage); 10718 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 10719 } 10720 } 10721 } 10722 } finally { 10723 mInjector.binderRestoreCallingIdentity(ident); 10724 } 10725 } 10726 10727 @Override 10728 public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) { 10729 Preconditions.checkNotNull(admin, "ComponentName is null"); 10730 enforceProfileOrDeviceOwner(admin); 10731 10732 return mOwners.getSystemUpdateInfo(); 10733 } 10734 10735 @Override 10736 public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) 10737 throws RemoteException { 10738 int userId = UserHandle.getCallingUserId(); 10739 synchronized (this) { 10740 // Ensure the caller is a DO/PO or a permission grant state delegate. 10741 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10742 DELEGATION_PERMISSION_GRANT); 10743 DevicePolicyData userPolicy = getUserData(userId); 10744 if (userPolicy.mPermissionPolicy != policy) { 10745 userPolicy.mPermissionPolicy = policy; 10746 saveSettingsLocked(userId); 10747 } 10748 } 10749 } 10750 10751 @Override 10752 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 10753 int userId = UserHandle.getCallingUserId(); 10754 synchronized (this) { 10755 DevicePolicyData userPolicy = getUserData(userId); 10756 return userPolicy.mPermissionPolicy; 10757 } 10758 } 10759 10760 @Override 10761 public boolean setPermissionGrantState(ComponentName admin, String callerPackage, 10762 String packageName, String permission, int grantState) throws RemoteException { 10763 UserHandle user = mInjector.binderGetCallingUserHandle(); 10764 synchronized (this) { 10765 // Ensure the caller is a DO/PO or a permission grant state delegate. 10766 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10767 DELEGATION_PERMISSION_GRANT); 10768 long ident = mInjector.binderClearCallingIdentity(); 10769 try { 10770 if (getTargetSdk(packageName, user.getIdentifier()) 10771 < android.os.Build.VERSION_CODES.M) { 10772 return false; 10773 } 10774 if (!isRuntimePermission(permission)) { 10775 return false; 10776 } 10777 final PackageManager packageManager = mInjector.getPackageManager(); 10778 switch (grantState) { 10779 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: { 10780 mInjector.getPackageManagerInternal().grantRuntimePermission(packageName, 10781 permission, user.getIdentifier(), true /* override policy */); 10782 packageManager.updatePermissionFlags(permission, packageName, 10783 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 10784 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 10785 } break; 10786 10787 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: { 10788 mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName, 10789 permission, user.getIdentifier(), true /* override policy */); 10790 packageManager.updatePermissionFlags(permission, packageName, 10791 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 10792 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 10793 } break; 10794 10795 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: { 10796 packageManager.updatePermissionFlags(permission, packageName, 10797 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user); 10798 } break; 10799 } 10800 return true; 10801 } catch (SecurityException se) { 10802 return false; 10803 } catch (NameNotFoundException e) { 10804 return false; 10805 } finally { 10806 mInjector.binderRestoreCallingIdentity(ident); 10807 } 10808 } 10809 } 10810 10811 @Override 10812 public int getPermissionGrantState(ComponentName admin, String callerPackage, 10813 String packageName, String permission) throws RemoteException { 10814 PackageManager packageManager = mInjector.getPackageManager(); 10815 10816 UserHandle user = mInjector.binderGetCallingUserHandle(); 10817 if (!isCallerWithSystemUid()) { 10818 // Ensure the caller is a DO/PO or a permission grant state delegate. 10819 enforceCanManageScope(admin, callerPackage, 10820 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT); 10821 } 10822 synchronized (this) { 10823 long ident = mInjector.binderClearCallingIdentity(); 10824 try { 10825 int granted = mIPackageManager.checkPermission(permission, 10826 packageName, user.getIdentifier()); 10827 int permFlags = packageManager.getPermissionFlags(permission, packageName, user); 10828 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 10829 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 10830 // Not controlled by policy 10831 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 10832 } else { 10833 // Policy controlled so return result based on permission grant state 10834 return granted == PackageManager.PERMISSION_GRANTED 10835 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 10836 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 10837 } 10838 } finally { 10839 mInjector.binderRestoreCallingIdentity(ident); 10840 } 10841 } 10842 } 10843 10844 boolean isPackageInstalledForUser(String packageName, int userHandle) { 10845 try { 10846 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 10847 userHandle); 10848 return (pi != null) && (pi.applicationInfo.flags != 0); 10849 } catch (RemoteException re) { 10850 throw new RuntimeException("Package manager has died", re); 10851 } 10852 } 10853 10854 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException { 10855 final PackageManager packageManager = mInjector.getPackageManager(); 10856 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0); 10857 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 10858 == PermissionInfo.PROTECTION_DANGEROUS; 10859 } 10860 10861 @Override 10862 public boolean isProvisioningAllowed(String action, String packageName) { 10863 Preconditions.checkNotNull(packageName); 10864 10865 final int callingUid = mInjector.binderGetCallingUid(); 10866 final long ident = mInjector.binderClearCallingIdentity(); 10867 try { 10868 final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser( 10869 packageName, UserHandle.getUserId(callingUid)); 10870 Preconditions.checkArgument(callingUid == uidForPackage, 10871 "Caller uid doesn't match the one for the provided package."); 10872 } catch (NameNotFoundException e) { 10873 throw new IllegalArgumentException("Invalid package provided " + packageName, e); 10874 } finally { 10875 mInjector.binderRestoreCallingIdentity(ident); 10876 } 10877 10878 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK; 10879 } 10880 10881 @Override 10882 public int checkProvisioningPreCondition(String action, String packageName) { 10883 Preconditions.checkNotNull(packageName); 10884 enforceCanManageProfileAndDeviceOwners(); 10885 return checkProvisioningPreConditionSkipPermission(action, packageName); 10886 } 10887 10888 private int checkProvisioningPreConditionSkipPermission(String action, String packageName) { 10889 if (!mHasFeature) { 10890 return CODE_DEVICE_ADMIN_NOT_SUPPORTED; 10891 } 10892 10893 final int callingUserId = mInjector.userHandleGetCallingUserId(); 10894 if (action != null) { 10895 switch (action) { 10896 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 10897 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 10898 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 10899 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 10900 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER: 10901 return checkManagedUserProvisioningPreCondition(callingUserId); 10902 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE: 10903 return checkManagedShareableDeviceProvisioningPreCondition(callingUserId); 10904 } 10905 } 10906 throw new IllegalArgumentException("Unknown provisioning action " + action); 10907 } 10908 10909 /** 10910 * The device owner can only be set before the setup phase of the primary user has completed, 10911 * except for adb command if no accounts or additional users are present on the device. 10912 */ 10913 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 10914 int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) { 10915 if (mOwners.hasDeviceOwner()) { 10916 return CODE_HAS_DEVICE_OWNER; 10917 } 10918 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 10919 return CODE_USER_HAS_PROFILE_OWNER; 10920 } 10921 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 10922 return CODE_USER_NOT_RUNNING; 10923 } 10924 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 10925 return CODE_HAS_PAIRED; 10926 } 10927 if (isAdb) { 10928 // if shell command runs after user setup completed check device status. Otherwise, OK. 10929 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 10930 if (!mInjector.userManagerIsSplitSystemUser()) { 10931 if (mUserManager.getUserCount() > 1) { 10932 return CODE_NONSYSTEM_USER_EXISTS; 10933 } 10934 if (hasIncompatibleAccountsOrNonAdb) { 10935 return CODE_ACCOUNTS_NOT_EMPTY; 10936 } 10937 } else { 10938 // STOPSHIP Do proper check in split user mode 10939 } 10940 } 10941 return CODE_OK; 10942 } else { 10943 if (!mInjector.userManagerIsSplitSystemUser()) { 10944 // In non-split user mode, DO has to be user 0 10945 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 10946 return CODE_NOT_SYSTEM_USER; 10947 } 10948 // In non-split user mode, only provision DO before setup wizard completes 10949 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 10950 return CODE_USER_SETUP_COMPLETED; 10951 } 10952 } else { 10953 // STOPSHIP Do proper check in split user mode 10954 } 10955 return CODE_OK; 10956 } 10957 } 10958 10959 private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) { 10960 synchronized (this) { 10961 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb. 10962 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 10963 deviceOwnerUserId, /* isAdb= */ false, 10964 /* hasIncompatibleAccountsOrNonAdb=*/ true); 10965 } 10966 } 10967 10968 private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) { 10969 if (!hasFeatureManagedUsers()) { 10970 return CODE_MANAGED_USERS_NOT_SUPPORTED; 10971 } 10972 if (callingUserId == UserHandle.USER_SYSTEM 10973 && mInjector.userManagerIsSplitSystemUser()) { 10974 // Managed-profiles cannot be setup on the system user. 10975 return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 10976 } 10977 if (getProfileOwner(callingUserId) != null) { 10978 // Managed user cannot have a managed profile. 10979 return CODE_USER_HAS_PROFILE_OWNER; 10980 } 10981 10982 final long ident = mInjector.binderClearCallingIdentity(); 10983 try { 10984 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 10985 final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId); 10986 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, 10987 callingUserHandle)) { 10988 // An admin can initiate provisioning if it has set the restriction. 10989 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 10990 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) { 10991 return CODE_ADD_MANAGED_PROFILE_DISALLOWED; 10992 } 10993 } 10994 boolean canRemoveProfile = true; 10995 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 10996 callingUserHandle)) { 10997 // We can remove a profile if the admin itself has set the restriction. 10998 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 10999 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 11000 callingUserId)) { 11001 canRemoveProfile = false; 11002 } 11003 } 11004 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) { 11005 return CODE_CANNOT_ADD_MANAGED_PROFILE; 11006 } 11007 } finally { 11008 mInjector.binderRestoreCallingIdentity(ident); 11009 } 11010 return CODE_OK; 11011 } 11012 11013 private ComponentName getOwnerComponent(String packageName, int userId) { 11014 if (isDeviceOwnerPackage(packageName, userId)) { 11015 return mOwners.getDeviceOwnerComponent(); 11016 } 11017 if (isProfileOwnerPackage(packageName, userId)) { 11018 return mOwners.getProfileOwnerComponent(userId); 11019 } 11020 return null; 11021 } 11022 11023 /** 11024 * Return device owner or profile owner set on a given user. 11025 */ 11026 private @Nullable ComponentName getOwnerComponent(int userId) { 11027 synchronized (this) { 11028 if (mOwners.getDeviceOwnerUserId() == userId) { 11029 return mOwners.getDeviceOwnerComponent(); 11030 } 11031 if (mOwners.hasProfileOwner(userId)) { 11032 return mOwners.getProfileOwnerComponent(userId); 11033 } 11034 } 11035 return null; 11036 } 11037 11038 private int checkManagedUserProvisioningPreCondition(int callingUserId) { 11039 if (!hasFeatureManagedUsers()) { 11040 return CODE_MANAGED_USERS_NOT_SUPPORTED; 11041 } 11042 if (!mInjector.userManagerIsSplitSystemUser()) { 11043 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems. 11044 return CODE_NOT_SYSTEM_USER_SPLIT; 11045 } 11046 if (callingUserId == UserHandle.USER_SYSTEM) { 11047 // System user cannot be a managed user. 11048 return CODE_SYSTEM_USER; 11049 } 11050 if (hasUserSetupCompleted(callingUserId)) { 11051 return CODE_USER_SETUP_COMPLETED; 11052 } 11053 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 11054 return CODE_HAS_PAIRED; 11055 } 11056 return CODE_OK; 11057 } 11058 11059 private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) { 11060 if (!mInjector.userManagerIsSplitSystemUser()) { 11061 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems. 11062 return CODE_NOT_SYSTEM_USER_SPLIT; 11063 } 11064 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 11065 } 11066 11067 private boolean hasFeatureManagedUsers() { 11068 try { 11069 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 11070 } catch (RemoteException e) { 11071 return false; 11072 } 11073 } 11074 11075 @Override 11076 public String getWifiMacAddress(ComponentName admin) { 11077 // Make sure caller has DO. 11078 synchronized (this) { 11079 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11080 } 11081 11082 final long ident = mInjector.binderClearCallingIdentity(); 11083 try { 11084 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo(); 11085 if (wifiInfo == null) { 11086 return null; 11087 } 11088 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null; 11089 } finally { 11090 mInjector.binderRestoreCallingIdentity(ident); 11091 } 11092 } 11093 11094 /** 11095 * Returns the target sdk version number that the given packageName was built for 11096 * in the given user. 11097 */ 11098 private int getTargetSdk(String packageName, int userId) { 11099 final ApplicationInfo ai; 11100 try { 11101 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 11102 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion; 11103 return targetSdkVersion; 11104 } catch (RemoteException e) { 11105 // Shouldn't happen 11106 return 0; 11107 } 11108 } 11109 11110 @Override 11111 public boolean isManagedProfile(ComponentName admin) { 11112 enforceProfileOrDeviceOwner(admin); 11113 return isManagedProfile(mInjector.userHandleGetCallingUserId()); 11114 } 11115 11116 @Override 11117 public boolean isSystemOnlyUser(ComponentName admin) { 11118 synchronized (this) { 11119 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11120 } 11121 final int callingUserId = mInjector.userHandleGetCallingUserId(); 11122 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM; 11123 } 11124 11125 @Override 11126 public void reboot(ComponentName admin) { 11127 Preconditions.checkNotNull(admin); 11128 // Make sure caller has DO. 11129 synchronized (this) { 11130 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11131 } 11132 long ident = mInjector.binderClearCallingIdentity(); 11133 try { 11134 // Make sure there are no ongoing calls on the device. 11135 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 11136 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 11137 } 11138 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 11139 } finally { 11140 mInjector.binderRestoreCallingIdentity(ident); 11141 } 11142 } 11143 11144 @Override 11145 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 11146 if (!mHasFeature) { 11147 return; 11148 } 11149 Preconditions.checkNotNull(who, "ComponentName is null"); 11150 final int userHandle = mInjector.userHandleGetCallingUserId(); 11151 synchronized (this) { 11152 ActiveAdmin admin = getActiveAdminForUidLocked(who, 11153 mInjector.binderGetCallingUid()); 11154 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 11155 admin.shortSupportMessage = message; 11156 saveSettingsLocked(userHandle); 11157 } 11158 } 11159 } 11160 11161 @Override 11162 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 11163 if (!mHasFeature) { 11164 return null; 11165 } 11166 Preconditions.checkNotNull(who, "ComponentName is null"); 11167 synchronized (this) { 11168 ActiveAdmin admin = getActiveAdminForUidLocked(who, 11169 mInjector.binderGetCallingUid()); 11170 return admin.shortSupportMessage; 11171 } 11172 } 11173 11174 @Override 11175 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 11176 if (!mHasFeature) { 11177 return; 11178 } 11179 Preconditions.checkNotNull(who, "ComponentName is null"); 11180 final int userHandle = mInjector.userHandleGetCallingUserId(); 11181 synchronized (this) { 11182 ActiveAdmin admin = getActiveAdminForUidLocked(who, 11183 mInjector.binderGetCallingUid()); 11184 if (!TextUtils.equals(admin.longSupportMessage, message)) { 11185 admin.longSupportMessage = message; 11186 saveSettingsLocked(userHandle); 11187 } 11188 } 11189 } 11190 11191 @Override 11192 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 11193 if (!mHasFeature) { 11194 return null; 11195 } 11196 Preconditions.checkNotNull(who, "ComponentName is null"); 11197 synchronized (this) { 11198 ActiveAdmin admin = getActiveAdminForUidLocked(who, 11199 mInjector.binderGetCallingUid()); 11200 return admin.longSupportMessage; 11201 } 11202 } 11203 11204 @Override 11205 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 11206 if (!mHasFeature) { 11207 return null; 11208 } 11209 Preconditions.checkNotNull(who, "ComponentName is null"); 11210 if (!isCallerWithSystemUid()) { 11211 throw new SecurityException("Only the system can query support message for user"); 11212 } 11213 synchronized (this) { 11214 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 11215 if (admin != null) { 11216 return admin.shortSupportMessage; 11217 } 11218 } 11219 return null; 11220 } 11221 11222 @Override 11223 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 11224 if (!mHasFeature) { 11225 return null; 11226 } 11227 Preconditions.checkNotNull(who, "ComponentName is null"); 11228 if (!isCallerWithSystemUid()) { 11229 throw new SecurityException("Only the system can query support message for user"); 11230 } 11231 synchronized (this) { 11232 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 11233 if (admin != null) { 11234 return admin.longSupportMessage; 11235 } 11236 } 11237 return null; 11238 } 11239 11240 @Override 11241 public void setOrganizationColor(@NonNull ComponentName who, int color) { 11242 if (!mHasFeature) { 11243 return; 11244 } 11245 Preconditions.checkNotNull(who, "ComponentName is null"); 11246 final int userHandle = mInjector.userHandleGetCallingUserId(); 11247 enforceManagedProfile(userHandle, "set organization color"); 11248 synchronized (this) { 11249 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11250 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11251 admin.organizationColor = color; 11252 saveSettingsLocked(userHandle); 11253 } 11254 } 11255 11256 @Override 11257 public void setOrganizationColorForUser(int color, int userId) { 11258 if (!mHasFeature) { 11259 return; 11260 } 11261 enforceFullCrossUsersPermission(userId); 11262 enforceManageUsers(); 11263 enforceManagedProfile(userId, "set organization color"); 11264 synchronized (this) { 11265 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 11266 admin.organizationColor = color; 11267 saveSettingsLocked(userId); 11268 } 11269 } 11270 11271 @Override 11272 public int getOrganizationColor(@NonNull ComponentName who) { 11273 if (!mHasFeature) { 11274 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 11275 } 11276 Preconditions.checkNotNull(who, "ComponentName is null"); 11277 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color"); 11278 synchronized (this) { 11279 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11280 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11281 return admin.organizationColor; 11282 } 11283 } 11284 11285 @Override 11286 public int getOrganizationColorForUser(int userHandle) { 11287 if (!mHasFeature) { 11288 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 11289 } 11290 enforceFullCrossUsersPermission(userHandle); 11291 enforceManagedProfile(userHandle, "get organization color"); 11292 synchronized (this) { 11293 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 11294 return (profileOwner != null) 11295 ? profileOwner.organizationColor 11296 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 11297 } 11298 } 11299 11300 @Override 11301 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 11302 if (!mHasFeature) { 11303 return; 11304 } 11305 Preconditions.checkNotNull(who, "ComponentName is null"); 11306 final int userHandle = mInjector.userHandleGetCallingUserId(); 11307 11308 synchronized (this) { 11309 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11310 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11311 if (!TextUtils.equals(admin.organizationName, text)) { 11312 admin.organizationName = (text == null || text.length() == 0) 11313 ? null : text.toString(); 11314 saveSettingsLocked(userHandle); 11315 } 11316 } 11317 } 11318 11319 @Override 11320 public CharSequence getOrganizationName(@NonNull ComponentName who) { 11321 if (!mHasFeature) { 11322 return null; 11323 } 11324 Preconditions.checkNotNull(who, "ComponentName is null"); 11325 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name"); 11326 synchronized(this) { 11327 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11328 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11329 return admin.organizationName; 11330 } 11331 } 11332 11333 @Override 11334 public CharSequence getDeviceOwnerOrganizationName() { 11335 if (!mHasFeature) { 11336 return null; 11337 } 11338 enforceDeviceOwnerOrManageUsers(); 11339 synchronized(this) { 11340 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 11341 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 11342 } 11343 } 11344 11345 @Override 11346 public CharSequence getOrganizationNameForUser(int userHandle) { 11347 if (!mHasFeature) { 11348 return null; 11349 } 11350 enforceFullCrossUsersPermission(userHandle); 11351 enforceManagedProfile(userHandle, "get organization name"); 11352 synchronized (this) { 11353 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 11354 return (profileOwner != null) 11355 ? profileOwner.organizationName 11356 : null; 11357 } 11358 } 11359 11360 @Override 11361 public List<String> setMeteredDataDisabled(ComponentName who, List<String> packageNames) { 11362 Preconditions.checkNotNull(who); 11363 Preconditions.checkNotNull(packageNames); 11364 11365 if (!mHasFeature) { 11366 return packageNames; 11367 } 11368 synchronized (this) { 11369 final ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11370 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11371 final int callingUserId = mInjector.userHandleGetCallingUserId(); 11372 final long identity = mInjector.binderClearCallingIdentity(); 11373 try { 11374 final List<String> excludedPkgs 11375 = removeInvalidPkgsForMeteredDataRestriction(callingUserId, packageNames); 11376 admin.meteredDisabledPackages = packageNames; 11377 pushMeteredDisabledPackagesLocked(callingUserId); 11378 saveSettingsLocked(callingUserId); 11379 return excludedPkgs; 11380 } finally { 11381 mInjector.binderRestoreCallingIdentity(identity); 11382 } 11383 } 11384 } 11385 11386 private List<String> removeInvalidPkgsForMeteredDataRestriction( 11387 int userId, List<String> pkgNames) { 11388 final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId); 11389 final List<String> excludedPkgs = new ArrayList<>(); 11390 for (int i = pkgNames.size() - 1; i >= 0; --i) { 11391 final String pkgName = pkgNames.get(i); 11392 // If the package is an active admin, don't restrict it. 11393 if (activeAdmins.contains(pkgName)) { 11394 excludedPkgs.add(pkgName); 11395 continue; 11396 } 11397 // If the package doesn't exist, don't restrict it. 11398 try { 11399 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) { 11400 excludedPkgs.add(pkgName); 11401 } 11402 } catch (RemoteException e) { 11403 // Should not happen 11404 } 11405 } 11406 pkgNames.removeAll(excludedPkgs); 11407 return excludedPkgs; 11408 } 11409 11410 @Override 11411 public List<String> getMeteredDataDisabled(ComponentName who) { 11412 Preconditions.checkNotNull(who); 11413 11414 if (!mHasFeature) { 11415 return new ArrayList<>(); 11416 } 11417 synchronized (this) { 11418 final ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11419 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11420 return admin.meteredDisabledPackages == null 11421 ? new ArrayList<>() : admin.meteredDisabledPackages; 11422 } 11423 } 11424 11425 @Override 11426 public boolean isMeteredDataDisabledForUser(ComponentName who, 11427 String packageName, int userId) { 11428 Preconditions.checkNotNull(who); 11429 11430 if (!mHasFeature) { 11431 return false; 11432 } 11433 if (!isCallerWithSystemUid()) { 11434 throw new SecurityException( 11435 "Only the system can query restricted pkgs for a specific user"); 11436 } 11437 synchronized (this) { 11438 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 11439 if (admin != null && admin.meteredDisabledPackages != null) { 11440 return admin.meteredDisabledPackages.contains(packageName); 11441 } 11442 } 11443 return false; 11444 } 11445 11446 private void pushMeteredDisabledPackagesLocked(int userId) { 11447 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages( 11448 getMeteredDisabledPackagesLocked(userId), userId); 11449 } 11450 11451 private Set<String> getMeteredDisabledPackagesLocked(int userId) { 11452 final ComponentName who = getOwnerComponent(userId); 11453 final Set<String> restrictedPkgs = new ArraySet<>(); 11454 if (who != null) { 11455 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 11456 if (admin != null && admin.meteredDisabledPackages != null) { 11457 restrictedPkgs.addAll(admin.meteredDisabledPackages); 11458 } 11459 } 11460 return restrictedPkgs; 11461 } 11462 11463 @Override 11464 public void setAffiliationIds(ComponentName admin, List<String> ids) { 11465 if (!mHasFeature) { 11466 return; 11467 } 11468 if (ids == null) { 11469 throw new IllegalArgumentException("ids must not be null"); 11470 } 11471 for (String id : ids) { 11472 if (TextUtils.isEmpty(id)) { 11473 throw new IllegalArgumentException("ids must not contain empty string"); 11474 } 11475 } 11476 11477 final Set<String> affiliationIds = new ArraySet<>(ids); 11478 final int callingUserId = mInjector.userHandleGetCallingUserId(); 11479 synchronized (this) { 11480 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11481 getUserData(callingUserId).mAffiliationIds = affiliationIds; 11482 saveSettingsLocked(callingUserId); 11483 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 11484 // Affiliation ids specified by the device owner are additionally stored in 11485 // UserHandle.USER_SYSTEM's DevicePolicyData. 11486 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 11487 saveSettingsLocked(UserHandle.USER_SYSTEM); 11488 } 11489 11490 // Affiliation status for any user, not just the calling user, might have changed. 11491 // The device owner user will still be affiliated after changing its affiliation ids, 11492 // but as a result of that other users might become affiliated or un-affiliated. 11493 maybePauseDeviceWideLoggingLocked(); 11494 maybeResumeDeviceWideLoggingLocked(); 11495 maybeClearLockTaskPolicyLocked(); 11496 } 11497 } 11498 11499 @Override 11500 public List<String> getAffiliationIds(ComponentName admin) { 11501 if (!mHasFeature) { 11502 return Collections.emptyList(); 11503 } 11504 11505 Preconditions.checkNotNull(admin); 11506 synchronized (this) { 11507 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11508 return new ArrayList<String>( 11509 getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds); 11510 } 11511 } 11512 11513 @Override 11514 public boolean isAffiliatedUser() { 11515 if (!mHasFeature) { 11516 return false; 11517 } 11518 11519 synchronized (this) { 11520 return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId()); 11521 } 11522 } 11523 11524 private boolean isUserAffiliatedWithDeviceLocked(int userId) { 11525 if (!mOwners.hasDeviceOwner()) { 11526 return false; 11527 } 11528 if (userId == mOwners.getDeviceOwnerUserId()) { 11529 // The user that the DO is installed on is always affiliated with the device. 11530 return true; 11531 } 11532 if (userId == UserHandle.USER_SYSTEM) { 11533 // The system user is always affiliated in a DO device, even if the DO is set on a 11534 // different user. This could be the case if the DO is set in the primary user 11535 // of a split user device. 11536 return true; 11537 } 11538 11539 final ComponentName profileOwner = getProfileOwner(userId); 11540 if (profileOwner == null) { 11541 return false; 11542 } 11543 11544 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 11545 final Set<String> deviceAffiliationIds = 11546 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 11547 for (String id : userAffiliationIds) { 11548 if (deviceAffiliationIds.contains(id)) { 11549 return true; 11550 } 11551 } 11552 return false; 11553 } 11554 11555 private boolean areAllUsersAffiliatedWithDeviceLocked() { 11556 final long ident = mInjector.binderClearCallingIdentity(); 11557 try { 11558 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 11559 for (int i = 0; i < userInfos.size(); i++) { 11560 int userId = userInfos.get(i).id; 11561 if (!isUserAffiliatedWithDeviceLocked(userId)) { 11562 Slog.d(LOG_TAG, "User id " + userId + " not affiliated."); 11563 return false; 11564 } 11565 } 11566 } finally { 11567 mInjector.binderRestoreCallingIdentity(ident); 11568 } 11569 11570 return true; 11571 } 11572 11573 @Override 11574 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) { 11575 if (!mHasFeature) { 11576 return; 11577 } 11578 Preconditions.checkNotNull(admin); 11579 11580 synchronized (this) { 11581 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11582 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 11583 return; 11584 } 11585 mInjector.securityLogSetLoggingEnabledProperty(enabled); 11586 if (enabled) { 11587 mSecurityLogMonitor.start(); 11588 maybePauseDeviceWideLoggingLocked(); 11589 } else { 11590 mSecurityLogMonitor.stop(); 11591 } 11592 } 11593 } 11594 11595 @Override 11596 public boolean isSecurityLoggingEnabled(ComponentName admin) { 11597 if (!mHasFeature) { 11598 return false; 11599 } 11600 11601 synchronized (this) { 11602 if (!isCallerWithSystemUid()) { 11603 Preconditions.checkNotNull(admin); 11604 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11605 } 11606 return mInjector.securityLogGetLoggingEnabledProperty(); 11607 } 11608 } 11609 11610 private synchronized void recordSecurityLogRetrievalTime() { 11611 final long currentTime = System.currentTimeMillis(); 11612 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 11613 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 11614 policyData.mLastSecurityLogRetrievalTime = currentTime; 11615 saveSettingsLocked(UserHandle.USER_SYSTEM); 11616 } 11617 } 11618 11619 @Override 11620 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) { 11621 if (!mHasFeature) { 11622 return null; 11623 } 11624 11625 Preconditions.checkNotNull(admin); 11626 ensureDeviceOwnerAndAllUsersAffiliated(admin); 11627 11628 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs) 11629 || !mInjector.securityLogGetLoggingEnabledProperty()) { 11630 return null; 11631 } 11632 11633 recordSecurityLogRetrievalTime(); 11634 11635 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 11636 try { 11637 SecurityLog.readPreviousEvents(output); 11638 return new ParceledListSlice<SecurityEvent>(output); 11639 } catch (IOException e) { 11640 Slog.w(LOG_TAG, "Fail to read previous events" , e); 11641 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 11642 } 11643 } 11644 11645 @Override 11646 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) { 11647 if (!mHasFeature) { 11648 return null; 11649 } 11650 11651 Preconditions.checkNotNull(admin); 11652 ensureDeviceOwnerAndAllUsersAffiliated(admin); 11653 11654 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 11655 return null; 11656 } 11657 11658 recordSecurityLogRetrievalTime(); 11659 11660 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 11661 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 11662 } 11663 11664 @Override 11665 public long forceSecurityLogs() { 11666 enforceShell("forceSecurityLogs"); 11667 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 11668 throw new IllegalStateException("logging is not available"); 11669 } 11670 return mSecurityLogMonitor.forceLogs(); 11671 } 11672 11673 private void enforceCanManageDeviceAdmin() { 11674 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS, 11675 null); 11676 } 11677 11678 private void enforceCanManageProfileAndDeviceOwners() { 11679 mContext.enforceCallingOrSelfPermission( 11680 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 11681 } 11682 11683 private void enforceCallerSystemUserHandle() { 11684 final int callingUid = mInjector.binderGetCallingUid(); 11685 final int userId = UserHandle.getUserId(callingUid); 11686 if (userId != UserHandle.USER_SYSTEM) { 11687 throw new SecurityException("Caller has to be in user 0"); 11688 } 11689 } 11690 11691 @Override 11692 public boolean isUninstallInQueue(final String packageName) { 11693 enforceCanManageDeviceAdmin(); 11694 final int userId = mInjector.userHandleGetCallingUserId(); 11695 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 11696 synchronized (this) { 11697 return mPackagesToRemove.contains(packageUserPair); 11698 } 11699 } 11700 11701 @Override 11702 public void uninstallPackageWithActiveAdmins(final String packageName) { 11703 enforceCanManageDeviceAdmin(); 11704 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 11705 11706 final int userId = mInjector.userHandleGetCallingUserId(); 11707 11708 enforceUserUnlocked(userId); 11709 11710 final ComponentName profileOwner = getProfileOwner(userId); 11711 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 11712 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 11713 } 11714 11715 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 11716 if (getDeviceOwnerUserId() == userId && deviceOwner != null 11717 && packageName.equals(deviceOwner.getPackageName())) { 11718 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 11719 } 11720 11721 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 11722 synchronized (this) { 11723 mPackagesToRemove.add(packageUserPair); 11724 } 11725 11726 // All active admins on the user. 11727 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 11728 11729 // Active admins in the target package. 11730 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 11731 if (allActiveAdmins != null) { 11732 for (ComponentName activeAdmin : allActiveAdmins) { 11733 if (packageName.equals(activeAdmin.getPackageName())) { 11734 packageActiveAdmins.add(activeAdmin); 11735 removeActiveAdmin(activeAdmin, userId); 11736 } 11737 } 11738 } 11739 if (packageActiveAdmins.size() == 0) { 11740 startUninstallIntent(packageName, userId); 11741 } else { 11742 mHandler.postDelayed(new Runnable() { 11743 @Override 11744 public void run() { 11745 for (ComponentName activeAdmin : packageActiveAdmins) { 11746 removeAdminArtifacts(activeAdmin, userId); 11747 } 11748 startUninstallIntent(packageName, userId); 11749 } 11750 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 11751 } 11752 } 11753 11754 @Override 11755 public boolean isDeviceProvisioned() { 11756 synchronized (this) { 11757 return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete; 11758 } 11759 } 11760 11761 private boolean isCurrentUserDemo() { 11762 if (UserManager.isDeviceInDemoMode(mContext)) { 11763 final int userId = mInjector.userHandleGetCallingUserId(); 11764 final long callingIdentity = mInjector.binderClearCallingIdentity(); 11765 try { 11766 return mUserManager.getUserInfo(userId).isDemo(); 11767 } finally { 11768 mInjector.binderRestoreCallingIdentity(callingIdentity); 11769 } 11770 } 11771 return false; 11772 } 11773 11774 private void removePackageIfRequired(final String packageName, final int userId) { 11775 if (!packageHasActiveAdmins(packageName, userId)) { 11776 // Will not do anything if uninstall was not requested or was already started. 11777 startUninstallIntent(packageName, userId); 11778 } 11779 } 11780 11781 private void startUninstallIntent(final String packageName, final int userId) { 11782 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 11783 synchronized (this) { 11784 if (!mPackagesToRemove.contains(packageUserPair)) { 11785 // Do nothing if uninstall was not requested or was already started. 11786 return; 11787 } 11788 mPackagesToRemove.remove(packageUserPair); 11789 } 11790 try { 11791 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) { 11792 // Package does not exist. Nothing to do. 11793 return; 11794 } 11795 } catch (RemoteException re) { 11796 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info"); 11797 } 11798 11799 try { // force stop the package before uninstalling 11800 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 11801 } catch (RemoteException re) { 11802 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 11803 } 11804 final Uri packageURI = Uri.parse("package:" + packageName); 11805 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 11806 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 11807 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 11808 } 11809 11810 /** 11811 * Removes the admin from the policy. Ideally called after the admin's 11812 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 11813 * 11814 * @param adminReceiver The admin to remove 11815 * @param userHandle The user for which this admin has to be removed. 11816 */ 11817 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 11818 synchronized (this) { 11819 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 11820 if (admin == null) { 11821 return; 11822 } 11823 final DevicePolicyData policy = getUserData(userHandle); 11824 final boolean doProxyCleanup = admin.info.usesPolicy( 11825 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 11826 policy.mAdminList.remove(admin); 11827 policy.mAdminMap.remove(adminReceiver); 11828 validatePasswordOwnerLocked(policy); 11829 if (doProxyCleanup) { 11830 resetGlobalProxyLocked(policy); 11831 } 11832 pushActiveAdminPackagesLocked(userHandle); 11833 pushMeteredDisabledPackagesLocked(userHandle); 11834 saveSettingsLocked(userHandle); 11835 updateMaximumTimeToLockLocked(userHandle); 11836 policy.mRemovingAdmins.remove(adminReceiver); 11837 11838 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 11839 } 11840 // The removed admin might have disabled camera, so update user 11841 // restrictions. 11842 pushUserRestrictions(userHandle); 11843 } 11844 11845 @Override 11846 public void setDeviceProvisioningConfigApplied() { 11847 enforceManageUsers(); 11848 synchronized (this) { 11849 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 11850 policy.mDeviceProvisioningConfigApplied = true; 11851 saveSettingsLocked(UserHandle.USER_SYSTEM); 11852 } 11853 } 11854 11855 @Override 11856 public boolean isDeviceProvisioningConfigApplied() { 11857 enforceManageUsers(); 11858 synchronized (this) { 11859 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 11860 return policy.mDeviceProvisioningConfigApplied; 11861 } 11862 } 11863 11864 /** 11865 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 11866 * 11867 * It's added for testing only. Please use this API carefully if it's used by other system app 11868 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 11869 * apps. 11870 */ 11871 @Override 11872 public void forceUpdateUserSetupComplete() { 11873 enforceCanManageProfileAndDeviceOwners(); 11874 enforceCallerSystemUserHandle(); 11875 // no effect if it's called from user build 11876 if (!mInjector.isBuildDebuggable()) { 11877 return; 11878 } 11879 final int userId = UserHandle.USER_SYSTEM; 11880 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 11881 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 11882 DevicePolicyData policy = getUserData(userId); 11883 policy.mUserSetupComplete = isUserCompleted; 11884 synchronized (this) { 11885 saveSettingsLocked(userId); 11886 } 11887 } 11888 11889 // TODO(b/22388012): When backup is available for secondary users and profiles, consider 11890 // whether there are any privacy/security implications of enabling the backup service here 11891 // if there are other users or profiles unmanaged or managed by a different entity (i.e. not 11892 // affiliated). 11893 @Override 11894 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 11895 if (!mHasFeature) { 11896 return; 11897 } 11898 Preconditions.checkNotNull(admin); 11899 synchronized (this) { 11900 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked( 11901 admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11902 if (!enabled) { 11903 activeAdmin.mandatoryBackupTransport = null; 11904 saveSettingsLocked(UserHandle.USER_SYSTEM); 11905 } 11906 } 11907 11908 final long ident = mInjector.binderClearCallingIdentity(); 11909 try { 11910 IBackupManager ibm = mInjector.getIBackupManager(); 11911 if (ibm != null) { 11912 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled); 11913 } 11914 } catch (RemoteException e) { 11915 throw new IllegalStateException( 11916 "Failed " + (enabled ? "" : "de") + "activating backup service.", e); 11917 } finally { 11918 mInjector.binderRestoreCallingIdentity(ident); 11919 } 11920 } 11921 11922 @Override 11923 public boolean isBackupServiceEnabled(ComponentName admin) { 11924 Preconditions.checkNotNull(admin); 11925 if (!mHasFeature) { 11926 return true; 11927 } 11928 synchronized (this) { 11929 try { 11930 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11931 IBackupManager ibm = mInjector.getIBackupManager(); 11932 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM); 11933 } catch (RemoteException e) { 11934 throw new IllegalStateException("Failed requesting backup service state.", e); 11935 } 11936 } 11937 } 11938 11939 @Override 11940 public void setMandatoryBackupTransport( 11941 ComponentName admin, ComponentName backupTransportComponent) { 11942 if (!mHasFeature) { 11943 return; 11944 } 11945 Preconditions.checkNotNull(admin); 11946 synchronized (this) { 11947 ActiveAdmin activeAdmin = 11948 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11949 if (!Objects.equals(backupTransportComponent, activeAdmin.mandatoryBackupTransport)) { 11950 activeAdmin.mandatoryBackupTransport = backupTransportComponent; 11951 saveSettingsLocked(UserHandle.USER_SYSTEM); 11952 } 11953 } 11954 final long identity = mInjector.binderClearCallingIdentity(); 11955 try { 11956 IBackupManager ibm = mInjector.getIBackupManager(); 11957 if (ibm != null && backupTransportComponent != null) { 11958 if (!ibm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11959 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, true); 11960 } 11961 ibm.selectBackupTransportAsync(backupTransportComponent, null); 11962 ibm.setBackupEnabled(true); 11963 } 11964 } catch (RemoteException e) { 11965 throw new IllegalStateException("Failed to set mandatory backup transport.", e); 11966 } finally { 11967 mInjector.binderRestoreCallingIdentity(identity); 11968 } 11969 } 11970 11971 @Override 11972 public ComponentName getMandatoryBackupTransport() { 11973 if (!mHasFeature) { 11974 return null; 11975 } 11976 synchronized (this) { 11977 ActiveAdmin activeAdmin = getDeviceOwnerAdminLocked(); 11978 return activeAdmin == null ? null : activeAdmin.mandatoryBackupTransport; 11979 } 11980 } 11981 11982 11983 @Override 11984 public boolean bindDeviceAdminServiceAsUser( 11985 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 11986 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 11987 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 11988 if (!mHasFeature) { 11989 return false; 11990 } 11991 Preconditions.checkNotNull(admin); 11992 Preconditions.checkNotNull(caller); 11993 Preconditions.checkNotNull(serviceIntent); 11994 Preconditions.checkArgument( 11995 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 11996 "Service intent must be explicit (with a package name or component): " 11997 + serviceIntent); 11998 Preconditions.checkNotNull(connection); 11999 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 12000 "target user id must be different from the calling user id"); 12001 12002 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 12003 throw new SecurityException("Not allowed to bind to target user id"); 12004 } 12005 12006 final String targetPackage; 12007 synchronized (this) { 12008 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 12009 } 12010 12011 final long callingIdentity = mInjector.binderClearCallingIdentity(); 12012 try { 12013 // Validate and sanitize the incoming service intent. 12014 final Intent sanitizedIntent = 12015 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 12016 if (sanitizedIntent == null) { 12017 // Fail, cannot lookup the target service. 12018 return false; 12019 } 12020 // Ask ActivityManager to bind it. Notice that we are binding the service with the 12021 // caller app instead of DevicePolicyManagerService. 12022 return mInjector.getIActivityManager().bindService( 12023 caller, activtiyToken, serviceIntent, 12024 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 12025 connection, flags, mContext.getOpPackageName(), 12026 targetUserId) != 0; 12027 } catch (RemoteException ex) { 12028 // Same process, should not happen. 12029 } finally { 12030 mInjector.binderRestoreCallingIdentity(callingIdentity); 12031 } 12032 12033 // Failed to bind. 12034 return false; 12035 } 12036 12037 @Override 12038 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 12039 if (!mHasFeature) { 12040 return Collections.emptyList(); 12041 } 12042 Preconditions.checkNotNull(admin); 12043 12044 synchronized (this) { 12045 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12046 12047 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12048 final long callingIdentity = mInjector.binderClearCallingIdentity(); 12049 try { 12050 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 12051 if (!isDeviceOwner(admin, callingUserId)) { 12052 // Profile owners can only bind to the device owner. 12053 if (canUserBindToDeviceOwnerLocked(callingUserId)) { 12054 targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId())); 12055 } 12056 } else { 12057 // Caller is the device owner: Look for profile owners that it can bind to. 12058 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 12059 for (int i = 0; i < userInfos.size(); i++) { 12060 final int userId = userInfos.get(i).id; 12061 if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) { 12062 targetUsers.add(UserHandle.of(userId)); 12063 } 12064 } 12065 } 12066 12067 return targetUsers; 12068 } finally { 12069 mInjector.binderRestoreCallingIdentity(callingIdentity); 12070 } 12071 } 12072 } 12073 12074 private boolean canUserBindToDeviceOwnerLocked(int userId) { 12075 // There has to be a device owner, under another user id. 12076 if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) { 12077 return false; 12078 } 12079 12080 // The user must have a profile owner that belongs to the same package as the device owner. 12081 if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals( 12082 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) { 12083 return false; 12084 } 12085 12086 // The user must be affiliated. 12087 return isUserAffiliatedWithDeviceLocked(userId); 12088 } 12089 12090 /** 12091 * Return true if a given user has any accounts that'll prevent installing a device or profile 12092 * owner {@code owner}. 12093 * - If the user has no accounts, then return false. 12094 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 12095 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 12096 * ..._DISALLOWED, return true. 12097 * - Otherwise return false. 12098 * 12099 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used 12100 * when the caller is not ADB. 12101 * 12102 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 12103 */ 12104 private boolean hasIncompatibleAccountsOrNonAdbNoLock( 12105 int userId, @Nullable ComponentName owner) { 12106 if (!isAdb()) { 12107 return true; 12108 } 12109 wtfIfInLock(); 12110 12111 final long token = mInjector.binderClearCallingIdentity(); 12112 try { 12113 final AccountManager am = AccountManager.get(mContext); 12114 final Account accounts[] = am.getAccountsAsUser(userId); 12115 if (accounts.length == 0) { 12116 return false; 12117 } 12118 synchronized (this) { 12119 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 12120 Log.w(LOG_TAG, 12121 "Non test-only owner can't be installed with existing accounts."); 12122 return true; 12123 } 12124 } 12125 12126 final String[] feature_allow = 12127 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 12128 final String[] feature_disallow = 12129 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 12130 12131 boolean compatible = true; 12132 for (Account account : accounts) { 12133 if (hasAccountFeatures(am, account, feature_disallow)) { 12134 Log.e(LOG_TAG, account + " has " + feature_disallow[0]); 12135 compatible = false; 12136 break; 12137 } 12138 if (!hasAccountFeatures(am, account, feature_allow)) { 12139 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]); 12140 compatible = false; 12141 break; 12142 } 12143 } 12144 if (compatible) { 12145 Log.w(LOG_TAG, "All accounts are compatible"); 12146 } else { 12147 Log.e(LOG_TAG, "Found incompatible accounts"); 12148 } 12149 return !compatible; 12150 } finally { 12151 mInjector.binderRestoreCallingIdentity(token); 12152 } 12153 } 12154 12155 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 12156 try { 12157 return am.hasFeatures(account, features, null, null).getResult(); 12158 } catch (Exception e) { 12159 Log.w(LOG_TAG, "Failed to get account feature", e); 12160 return false; 12161 } 12162 } 12163 12164 private boolean isAdb() { 12165 final int callingUid = mInjector.binderGetCallingUid(); 12166 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 12167 } 12168 12169 @Override 12170 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) { 12171 if (!mHasFeature) { 12172 return; 12173 } 12174 Preconditions.checkNotNull(admin); 12175 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12176 12177 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 12178 // already in the requested state 12179 return; 12180 } 12181 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 12182 deviceOwner.isNetworkLoggingEnabled = enabled; 12183 if (!enabled) { 12184 deviceOwner.numNetworkLoggingNotifications = 0; 12185 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 12186 } 12187 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 12188 12189 setNetworkLoggingActiveInternal(enabled); 12190 } 12191 12192 private synchronized void setNetworkLoggingActiveInternal(boolean active) { 12193 final long callingIdentity = mInjector.binderClearCallingIdentity(); 12194 try { 12195 if (active) { 12196 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal()); 12197 if (!mNetworkLogger.startNetworkLogging()) { 12198 mNetworkLogger = null; 12199 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging" 12200 + " service not being available yet."); 12201 } 12202 maybePauseDeviceWideLoggingLocked(); 12203 sendNetworkLoggingNotificationLocked(); 12204 } else { 12205 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 12206 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 12207 + " service not being available yet."); 12208 } 12209 mNetworkLogger = null; 12210 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING); 12211 } 12212 } finally { 12213 mInjector.binderRestoreCallingIdentity(callingIdentity); 12214 } 12215 } 12216 12217 /** Pauses security and network logging if there are unaffiliated users on the device */ 12218 private void maybePauseDeviceWideLoggingLocked() { 12219 if (!areAllUsersAffiliatedWithDeviceLocked()) { 12220 Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be " 12221 + "paused if enabled."); 12222 mSecurityLogMonitor.pause(); 12223 if (mNetworkLogger != null) { 12224 mNetworkLogger.pause(); 12225 } 12226 } 12227 } 12228 12229 /** Resumes security and network logging (if they are enabled) if all users are affiliated */ 12230 private void maybeResumeDeviceWideLoggingLocked() { 12231 if (areAllUsersAffiliatedWithDeviceLocked()) { 12232 final long ident = mInjector.binderClearCallingIdentity(); 12233 try { 12234 mSecurityLogMonitor.resume(); 12235 if (mNetworkLogger != null) { 12236 mNetworkLogger.resume(); 12237 } 12238 } finally { 12239 mInjector.binderRestoreCallingIdentity(ident); 12240 } 12241 } 12242 } 12243 12244 /** Deletes any security and network logs that might have been collected so far */ 12245 private void discardDeviceWideLogsLocked() { 12246 mSecurityLogMonitor.discardLogs(); 12247 if (mNetworkLogger != null) { 12248 mNetworkLogger.discardLogs(); 12249 } 12250 // TODO: We should discard pre-boot security logs here too, as otherwise those 12251 // logs (which might contain data from the user just removed) will be 12252 // available after next boot. 12253 } 12254 12255 @Override 12256 public boolean isNetworkLoggingEnabled(ComponentName admin) { 12257 if (!mHasFeature) { 12258 return false; 12259 } 12260 synchronized (this) { 12261 enforceDeviceOwnerOrManageUsers(); 12262 return isNetworkLoggingEnabledInternalLocked(); 12263 } 12264 } 12265 12266 private boolean isNetworkLoggingEnabledInternalLocked() { 12267 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 12268 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled; 12269 } 12270 12271 /* 12272 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 12273 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 12274 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 12275 * 12276 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 12277 */ 12278 @Override 12279 public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) { 12280 if (!mHasFeature) { 12281 return null; 12282 } 12283 Preconditions.checkNotNull(admin); 12284 ensureDeviceOwnerAndAllUsersAffiliated(admin); 12285 12286 synchronized (this) { 12287 if (mNetworkLogger == null 12288 || !isNetworkLoggingEnabledInternalLocked()) { 12289 return null; 12290 } 12291 12292 final long currentTime = System.currentTimeMillis(); 12293 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 12294 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 12295 policyData.mLastNetworkLogsRetrievalTime = currentTime; 12296 saveSettingsLocked(UserHandle.USER_SYSTEM); 12297 } 12298 return mNetworkLogger.retrieveLogs(batchToken); 12299 } 12300 } 12301 12302 private void sendNetworkLoggingNotificationLocked() { 12303 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 12304 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 12305 return; 12306 } 12307 if (deviceOwner.numNetworkLoggingNotifications >= 12308 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 12309 return; 12310 } 12311 final long now = System.currentTimeMillis(); 12312 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 12313 return; 12314 } 12315 deviceOwner.numNetworkLoggingNotifications++; 12316 if (deviceOwner.numNetworkLoggingNotifications 12317 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 12318 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 12319 } else { 12320 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 12321 } 12322 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 12323 intent.setPackage("com.android.systemui"); 12324 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0, 12325 UserHandle.CURRENT); 12326 Notification notification = 12327 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 12328 .setSmallIcon(R.drawable.ic_info_outline) 12329 .setContentTitle(mContext.getString(R.string.network_logging_notification_title)) 12330 .setContentText(mContext.getString(R.string.network_logging_notification_text)) 12331 .setTicker(mContext.getString(R.string.network_logging_notification_title)) 12332 .setShowWhen(true) 12333 .setContentIntent(pendingIntent) 12334 .setStyle(new Notification.BigTextStyle() 12335 .bigText(mContext.getString(R.string.network_logging_notification_text))) 12336 .build(); 12337 mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification); 12338 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 12339 } 12340 12341 /** 12342 * Return the package name of owner in a given user. 12343 */ 12344 private String getOwnerPackageNameForUserLocked(int userId) { 12345 return mOwners.getDeviceOwnerUserId() == userId 12346 ? mOwners.getDeviceOwnerPackageName() 12347 : mOwners.getProfileOwnerPackage(userId); 12348 } 12349 12350 /** 12351 * @param rawIntent Original service intent specified by caller. It must be explicit. 12352 * @param expectedPackageName The expected package name of the resolved service. 12353 * @return Intent that have component explicitly set. {@code null} if no service is resolved 12354 * with the given intent. 12355 * @throws SecurityException if the intent is resolved to an invalid service. 12356 */ 12357 private Intent createCrossUserServiceIntent( 12358 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 12359 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 12360 ResolveInfo info = mIPackageManager.resolveService( 12361 rawIntent, 12362 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 12363 0, // flags 12364 targetUserId); 12365 if (info == null || info.serviceInfo == null) { 12366 Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent 12367 + " or user " + targetUserId + " is not running"); 12368 return null; 12369 } 12370 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 12371 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 12372 } 12373 // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release. 12374 if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) { 12375 throw new SecurityException( 12376 "Service must be protected by BIND_DEVICE_ADMIN permission"); 12377 } 12378 // It is the system server to bind the service, it would be extremely dangerous if it 12379 // can be exploited to bind any service. Set the component explicitly to make sure we 12380 // do not bind anything accidentally. 12381 rawIntent.setComponent(info.serviceInfo.getComponentName()); 12382 return rawIntent; 12383 } 12384 12385 @Override 12386 public long getLastSecurityLogRetrievalTime() { 12387 enforceDeviceOwnerOrManageUsers(); 12388 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 12389 } 12390 12391 @Override 12392 public long getLastBugReportRequestTime() { 12393 enforceDeviceOwnerOrManageUsers(); 12394 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 12395 } 12396 12397 @Override 12398 public long getLastNetworkLogRetrievalTime() { 12399 enforceDeviceOwnerOrManageUsers(); 12400 return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime; 12401 } 12402 12403 @Override 12404 public boolean setResetPasswordToken(ComponentName admin, byte[] token) { 12405 if (!mHasFeature) { 12406 return false; 12407 } 12408 if (token == null || token.length < 32) { 12409 throw new IllegalArgumentException("token must be at least 32-byte long"); 12410 } 12411 synchronized (this) { 12412 final int userHandle = mInjector.userHandleGetCallingUserId(); 12413 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12414 12415 DevicePolicyData policy = getUserData(userHandle); 12416 long ident = mInjector.binderClearCallingIdentity(); 12417 try { 12418 if (policy.mPasswordTokenHandle != 0) { 12419 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle); 12420 } 12421 12422 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle); 12423 saveSettingsLocked(userHandle); 12424 return policy.mPasswordTokenHandle != 0; 12425 } finally { 12426 mInjector.binderRestoreCallingIdentity(ident); 12427 } 12428 } 12429 } 12430 12431 @Override 12432 public boolean clearResetPasswordToken(ComponentName admin) { 12433 if (!mHasFeature) { 12434 return false; 12435 } 12436 synchronized (this) { 12437 final int userHandle = mInjector.userHandleGetCallingUserId(); 12438 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12439 12440 DevicePolicyData policy = getUserData(userHandle); 12441 if (policy.mPasswordTokenHandle != 0) { 12442 long ident = mInjector.binderClearCallingIdentity(); 12443 try { 12444 boolean result = mLockPatternUtils.removeEscrowToken( 12445 policy.mPasswordTokenHandle, userHandle); 12446 policy.mPasswordTokenHandle = 0; 12447 saveSettingsLocked(userHandle); 12448 return result; 12449 } finally { 12450 mInjector.binderRestoreCallingIdentity(ident); 12451 } 12452 } 12453 } 12454 return false; 12455 } 12456 12457 @Override 12458 public boolean isResetPasswordTokenActive(ComponentName admin) { 12459 synchronized (this) { 12460 final int userHandle = mInjector.userHandleGetCallingUserId(); 12461 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12462 12463 DevicePolicyData policy = getUserData(userHandle); 12464 if (policy.mPasswordTokenHandle != 0) { 12465 long ident = mInjector.binderClearCallingIdentity(); 12466 try { 12467 return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle, 12468 userHandle); 12469 } finally { 12470 mInjector.binderRestoreCallingIdentity(ident); 12471 } 12472 } 12473 } 12474 return false; 12475 } 12476 12477 @Override 12478 public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, 12479 int flags) { 12480 Preconditions.checkNotNull(token); 12481 synchronized (this) { 12482 final int userHandle = mInjector.userHandleGetCallingUserId(); 12483 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12484 12485 DevicePolicyData policy = getUserData(userHandle); 12486 if (policy.mPasswordTokenHandle != 0) { 12487 final String password = passwordOrNull != null ? passwordOrNull : ""; 12488 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token, 12489 flags, mInjector.binderGetCallingUid(), userHandle); 12490 } else { 12491 Slog.w(LOG_TAG, "No saved token handle"); 12492 } 12493 } 12494 return false; 12495 } 12496 12497 @Override 12498 public boolean isCurrentInputMethodSetByOwner() { 12499 enforceProfileOwnerOrSystemUser(); 12500 return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet; 12501 } 12502 12503 @Override 12504 public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) { 12505 final int userId = user.getIdentifier(); 12506 enforceProfileOwnerOrFullCrossUsersPermission(userId); 12507 synchronized (this) { 12508 return new StringParceledListSlice( 12509 new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts)); 12510 } 12511 } 12512 12513 @Override 12514 public void clearApplicationUserData(ComponentName admin, String packageName, 12515 IPackageDataObserver callback) { 12516 Preconditions.checkNotNull(admin, "ComponentName is null"); 12517 Preconditions.checkNotNull(packageName, "packageName is null"); 12518 Preconditions.checkNotNull(callback, "callback is null"); 12519 synchronized (this) { 12520 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12521 } 12522 final int userId = UserHandle.getCallingUserId(); 12523 12524 long ident = mInjector.binderClearCallingIdentity(); 12525 try { 12526 ActivityManager.getService().clearApplicationUserData(packageName, false, callback, 12527 userId); 12528 } catch(RemoteException re) { 12529 // Same process, should not happen. 12530 } catch (SecurityException se) { 12531 // This can happen e.g. for device admin packages, do not throw out the exception, 12532 // because callers have no means to know beforehand for which packages this might 12533 // happen. If so, we send back that removal failed. 12534 Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName, 12535 se); 12536 try { 12537 callback.onRemoveCompleted(packageName, false); 12538 } catch (RemoteException re) { 12539 // Caller is no longer available, ignore 12540 } 12541 } finally { 12542 mInjector.binderRestoreCallingIdentity(ident); 12543 } 12544 } 12545 12546 @Override 12547 public synchronized void setLogoutEnabled(ComponentName admin, boolean enabled) { 12548 if (!mHasFeature) { 12549 return; 12550 } 12551 Preconditions.checkNotNull(admin); 12552 12553 synchronized (this) { 12554 ActiveAdmin deviceOwner = 12555 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12556 12557 if (deviceOwner.isLogoutEnabled == enabled) { 12558 // already in the requested state 12559 return; 12560 } 12561 deviceOwner.isLogoutEnabled = enabled; 12562 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 12563 } 12564 } 12565 12566 @Override 12567 public boolean isLogoutEnabled() { 12568 if (!mHasFeature) { 12569 return false; 12570 } 12571 synchronized (this) { 12572 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 12573 return (deviceOwner != null) && deviceOwner.isLogoutEnabled; 12574 } 12575 } 12576 12577 @Override 12578 public List<String> getDisallowedSystemApps(ComponentName admin, int userId, 12579 String provisioningAction) throws RemoteException { 12580 enforceCanManageProfileAndDeviceOwners(); 12581 return new ArrayList<>( 12582 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction)); 12583 } 12584 12585 @Override 12586 public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target, 12587 @Nullable PersistableBundle bundle) { 12588 if (!mHasFeature) { 12589 return; 12590 } 12591 12592 Preconditions.checkNotNull(admin, "Admin cannot be null."); 12593 Preconditions.checkNotNull(target, "Target cannot be null."); 12594 12595 enforceProfileOrDeviceOwner(admin); 12596 12597 if (admin.equals(target)) { 12598 throw new IllegalArgumentException("Provided administrator and target are " 12599 + "the same object."); 12600 } 12601 12602 if (admin.getPackageName().equals(target.getPackageName())) { 12603 throw new IllegalArgumentException("Provided administrator and target have " 12604 + "the same package name."); 12605 } 12606 12607 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12608 final DevicePolicyData policy = getUserData(callingUserId); 12609 final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId, 12610 /* throwForMissingPermission= */ true); 12611 checkActiveAdminPrecondition(target, incomingDeviceInfo, policy); 12612 if (!incomingDeviceInfo.getActivityInfo().metaData 12613 .getBoolean(DeviceAdminReceiver.SUPPORT_TRANSFER_OWNERSHIP_META_DATA, false)) { 12614 throw new IllegalArgumentException("Provided target does not support " 12615 + "ownership transfer."); 12616 } 12617 12618 final long id = mInjector.binderClearCallingIdentity(); 12619 try { 12620 synchronized (this) { 12621 /* 12622 * We must ensure the whole process is atomic to prevent the device from ending up 12623 * in an invalid state (e.g. no active admin). This could happen if the device 12624 * is rebooted or work mode is turned off mid-transfer. 12625 * In order to guarantee atomicity, we: 12626 * 12627 * 1. Save an atomic journal file describing the transfer process 12628 * 2. Perform the transfer itself 12629 * 3. Delete the journal file 12630 * 12631 * That way if the journal file exists on device boot, we know that the transfer 12632 * must be reverted back to the original administrator. This logic is implemented in 12633 * revertTransferOwnershipIfNecessaryLocked. 12634 * */ 12635 if (bundle == null) { 12636 bundle = new PersistableBundle(); 12637 } 12638 if (isProfileOwner(admin, callingUserId)) { 12639 prepareTransfer(admin, target, bundle, callingUserId, 12640 ADMIN_TYPE_PROFILE_OWNER); 12641 transferProfileOwnershipLocked(admin, target, callingUserId); 12642 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 12643 getTransferOwnershipAdminExtras(bundle), callingUserId); 12644 postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId); 12645 if (isUserAffiliatedWithDeviceLocked(callingUserId)) { 12646 notifyAffiliatedProfileTransferOwnershipComplete(callingUserId); 12647 } 12648 } else if (isDeviceOwner(admin, callingUserId)) { 12649 prepareTransfer(admin, target, bundle, callingUserId, 12650 ADMIN_TYPE_DEVICE_OWNER); 12651 transferDeviceOwnershipLocked(admin, target, callingUserId); 12652 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 12653 getTransferOwnershipAdminExtras(bundle)); 12654 postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId); 12655 } 12656 } 12657 } finally { 12658 mInjector.binderRestoreCallingIdentity(id); 12659 } 12660 } 12661 12662 private void prepareTransfer(ComponentName admin, ComponentName target, 12663 PersistableBundle bundle, int callingUserId, String adminType) { 12664 saveTransferOwnershipBundleLocked(bundle, callingUserId); 12665 mTransferOwnershipMetadataManager.saveMetadataFile( 12666 new TransferOwnershipMetadataManager.Metadata(admin, target, 12667 callingUserId, adminType)); 12668 } 12669 12670 private void postTransfer(String broadcast, int callingUserId) { 12671 deleteTransferOwnershipMetadataFileLocked(); 12672 sendOwnerChangedBroadcast(broadcast, callingUserId); 12673 } 12674 12675 private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) { 12676 final Bundle extras = new Bundle(); 12677 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId)); 12678 sendDeviceOwnerCommand( 12679 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras); 12680 } 12681 12682 /** 12683 * Transfers the profile owner for user with id profileOwnerUserId from admin to target. 12684 */ 12685 private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target, 12686 int profileOwnerUserId) { 12687 transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId); 12688 mOwners.transferProfileOwner(target, profileOwnerUserId); 12689 Slog.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId); 12690 mOwners.writeProfileOwner(profileOwnerUserId); 12691 mDeviceAdminServiceController.startServiceForOwner( 12692 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner"); 12693 } 12694 12695 /** 12696 * Transfers the device owner for user with id userId from admin to target. 12697 */ 12698 private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) { 12699 transferActiveAdminUncheckedLocked(target, admin, userId); 12700 mOwners.transferDeviceOwnership(target); 12701 Slog.i(LOG_TAG, "Device owner set: " + target + " on user " + userId); 12702 mOwners.writeDeviceOwner(); 12703 mDeviceAdminServiceController.startServiceForOwner( 12704 target.getPackageName(), userId, "transfer-device-owner"); 12705 } 12706 12707 private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) { 12708 Bundle extras = new Bundle(); 12709 if (bundle != null) { 12710 extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle); 12711 } 12712 return extras; 12713 } 12714 12715 @Override 12716 public void setStartUserSessionMessage( 12717 ComponentName admin, CharSequence startUserSessionMessage) { 12718 if (!mHasFeature) { 12719 return; 12720 } 12721 Preconditions.checkNotNull(admin); 12722 12723 final String startUserSessionMessageString = 12724 startUserSessionMessage != null ? startUserSessionMessage.toString() : null; 12725 12726 synchronized (this) { 12727 final ActiveAdmin deviceOwner = 12728 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12729 12730 if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) { 12731 return; 12732 } 12733 deviceOwner.startUserSessionMessage = startUserSessionMessageString; 12734 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 12735 } 12736 12737 mInjector.getActivityManagerInternal() 12738 .setSwitchingFromSystemUserMessage(startUserSessionMessageString); 12739 } 12740 12741 @Override 12742 public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) { 12743 if (!mHasFeature) { 12744 return; 12745 } 12746 Preconditions.checkNotNull(admin); 12747 12748 final String endUserSessionMessageString = 12749 endUserSessionMessage != null ? endUserSessionMessage.toString() : null; 12750 12751 synchronized (this) { 12752 final ActiveAdmin deviceOwner = 12753 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12754 12755 if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) { 12756 return; 12757 } 12758 deviceOwner.endUserSessionMessage = endUserSessionMessageString; 12759 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 12760 } 12761 12762 mInjector.getActivityManagerInternal() 12763 .setSwitchingToSystemUserMessage(endUserSessionMessageString); 12764 } 12765 12766 @Override 12767 public String getStartUserSessionMessage(ComponentName admin) { 12768 if (!mHasFeature) { 12769 return null; 12770 } 12771 Preconditions.checkNotNull(admin); 12772 12773 synchronized (this) { 12774 final ActiveAdmin deviceOwner = 12775 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12776 return deviceOwner.startUserSessionMessage; 12777 } 12778 } 12779 12780 @Override 12781 public String getEndUserSessionMessage(ComponentName admin) { 12782 if (!mHasFeature) { 12783 return null; 12784 } 12785 Preconditions.checkNotNull(admin); 12786 12787 synchronized (this) { 12788 final ActiveAdmin deviceOwner = 12789 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12790 return deviceOwner.endUserSessionMessage; 12791 } 12792 } 12793 12794 private void deleteTransferOwnershipMetadataFileLocked() { 12795 mTransferOwnershipMetadataManager.deleteMetadataFile(); 12796 } 12797 12798 @Override 12799 @Nullable 12800 public PersistableBundle getTransferOwnershipBundle() { 12801 synchronized (this) { 12802 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12803 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12804 final File bundleFile = new File( 12805 mInjector.environmentGetUserSystemDirectory(callingUserId), 12806 TRANSFER_OWNERSHIP_PARAMETERS_XML); 12807 if (!bundleFile.exists()) { 12808 return null; 12809 } 12810 try (FileInputStream stream = new FileInputStream(bundleFile)) { 12811 XmlPullParser parser = Xml.newPullParser(); 12812 parser.setInput(stream, null); 12813 parser.next(); 12814 return PersistableBundle.restoreFromXml(parser); 12815 } catch (IOException | XmlPullParserException | IllegalArgumentException e) { 12816 Slog.e(LOG_TAG, "Caught exception while trying to load the " 12817 + "owner transfer parameters from file " + bundleFile, e); 12818 return null; 12819 } 12820 } 12821 } 12822 12823 @Override 12824 public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) { 12825 if (!mHasFeature) { 12826 return -1; 12827 } 12828 Preconditions.checkNotNull(who, "ComponentName is null in addOverrideApn"); 12829 Preconditions.checkNotNull(apnSetting, "ApnSetting is null in addOverrideApn"); 12830 synchronized (this) { 12831 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12832 } 12833 12834 int operatedId = -1; 12835 Uri resultUri; 12836 final long id = mInjector.binderClearCallingIdentity(); 12837 try { 12838 resultUri = mContext.getContentResolver().insert(DPC_URI, apnSetting.toContentValues()); 12839 } finally { 12840 mInjector.binderRestoreCallingIdentity(id); 12841 } 12842 if (resultUri != null) { 12843 try { 12844 operatedId = Integer.parseInt(resultUri.getLastPathSegment()); 12845 } catch (NumberFormatException e) { 12846 Slog.e(LOG_TAG, "Failed to parse inserted override APN id.", e); 12847 } 12848 } 12849 12850 return operatedId; 12851 } 12852 12853 @Override 12854 public boolean updateOverrideApn(@NonNull ComponentName who, int apnId, 12855 @NonNull ApnSetting apnSetting) { 12856 if (!mHasFeature) { 12857 return false; 12858 } 12859 Preconditions.checkNotNull(who, "ComponentName is null in updateOverrideApn"); 12860 Preconditions.checkNotNull(apnSetting, "ApnSetting is null in updateOverrideApn"); 12861 synchronized (this) { 12862 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12863 } 12864 12865 if (apnId < 0) { 12866 return false; 12867 } 12868 final long id = mInjector.binderClearCallingIdentity(); 12869 try { 12870 return mContext.getContentResolver().update( 12871 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), 12872 apnSetting.toContentValues(), null, null) > 0; 12873 } finally { 12874 mInjector.binderRestoreCallingIdentity(id); 12875 } 12876 } 12877 12878 @Override 12879 public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) { 12880 if (!mHasFeature) { 12881 return false; 12882 } 12883 Preconditions.checkNotNull(who, "ComponentName is null in removeOverrideApn"); 12884 synchronized (this) { 12885 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12886 } 12887 12888 return removeOverrideApnUnchecked(apnId); 12889 } 12890 12891 private boolean removeOverrideApnUnchecked(int apnId) { 12892 if(apnId < 0) { 12893 return false; 12894 } 12895 int numDeleted = 0; 12896 final long id = mInjector.binderClearCallingIdentity(); 12897 try { 12898 numDeleted = mContext.getContentResolver().delete( 12899 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null); 12900 } finally { 12901 mInjector.binderRestoreCallingIdentity(id); 12902 } 12903 return numDeleted > 0; 12904 } 12905 12906 @Override 12907 public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) { 12908 if (!mHasFeature) { 12909 return Collections.emptyList(); 12910 } 12911 Preconditions.checkNotNull(who, "ComponentName is null in getOverrideApns"); 12912 synchronized (this) { 12913 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12914 } 12915 12916 return getOverrideApnsUnchecked(); 12917 } 12918 12919 private List<ApnSetting> getOverrideApnsUnchecked() { 12920 final Cursor cursor; 12921 final long id = mInjector.binderClearCallingIdentity(); 12922 try { 12923 cursor = mContext.getContentResolver().query(DPC_URI, null, null, null, null); 12924 } finally { 12925 mInjector.binderRestoreCallingIdentity(id); 12926 } 12927 12928 if (cursor == null) { 12929 return Collections.emptyList(); 12930 } 12931 try { 12932 List<ApnSetting> apnList = new ArrayList<ApnSetting>(); 12933 cursor.moveToPosition(-1); 12934 while (cursor.moveToNext()) { 12935 ApnSetting apn = ApnSetting.makeApnSetting(cursor); 12936 apnList.add(apn); 12937 } 12938 return apnList; 12939 } finally { 12940 cursor.close(); 12941 } 12942 } 12943 12944 @Override 12945 public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) { 12946 if (!mHasFeature) { 12947 return; 12948 } 12949 Preconditions.checkNotNull(who, "ComponentName is null in setOverrideApnEnabled"); 12950 synchronized (this) { 12951 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12952 } 12953 12954 setOverrideApnsEnabledUnchecked(enabled); 12955 } 12956 12957 private void setOverrideApnsEnabledUnchecked(boolean enabled) { 12958 ContentValues value = new ContentValues(); 12959 value.put(ENFORCE_KEY, enabled); 12960 final long id = mInjector.binderClearCallingIdentity(); 12961 try { 12962 mContext.getContentResolver().update( 12963 ENFORCE_MANAGED_URI, value, null, null); 12964 } finally { 12965 mInjector.binderRestoreCallingIdentity(id); 12966 } 12967 } 12968 12969 @Override 12970 public boolean isOverrideApnEnabled(@NonNull ComponentName who) { 12971 if (!mHasFeature) { 12972 return false; 12973 } 12974 Preconditions.checkNotNull(who, "ComponentName is null in isOverrideApnEnabled"); 12975 synchronized (this) { 12976 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12977 } 12978 12979 Cursor enforceCursor; 12980 final long id = mInjector.binderClearCallingIdentity(); 12981 try { 12982 enforceCursor = mContext.getContentResolver().query( 12983 ENFORCE_MANAGED_URI, null, null, null, null); 12984 } finally { 12985 mInjector.binderRestoreCallingIdentity(id); 12986 } 12987 12988 if (enforceCursor == null) { 12989 return false; 12990 } 12991 try { 12992 if (enforceCursor.moveToFirst()) { 12993 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1; 12994 } 12995 } catch (IllegalArgumentException e) { 12996 Slog.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain " 12997 + "correct info.", e); 12998 } finally { 12999 enforceCursor.close(); 13000 } 13001 return false; 13002 } 13003 13004 @VisibleForTesting 13005 void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) { 13006 final File parametersFile = new File( 13007 mInjector.environmentGetUserSystemDirectory(userId), 13008 TRANSFER_OWNERSHIP_PARAMETERS_XML); 13009 final AtomicFile atomicFile = new AtomicFile(parametersFile); 13010 FileOutputStream stream = null; 13011 try { 13012 stream = atomicFile.startWrite(); 13013 final XmlSerializer serializer = new FastXmlSerializer(); 13014 serializer.setOutput(stream, StandardCharsets.UTF_8.name()); 13015 serializer.startDocument(null, true); 13016 serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 13017 bundle.saveToXml(serializer); 13018 serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 13019 serializer.endDocument(); 13020 atomicFile.finishWrite(stream); 13021 } catch (IOException | XmlPullParserException e) { 13022 Slog.e(LOG_TAG, "Caught exception while trying to save the " 13023 + "owner transfer parameters to file " + parametersFile, e); 13024 parametersFile.delete(); 13025 atomicFile.failWrite(stream); 13026 } 13027 } 13028 13029 void deleteTransferOwnershipBundleLocked(int userId) { 13030 final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId), 13031 TRANSFER_OWNERSHIP_PARAMETERS_XML); 13032 parametersFile.delete(); 13033 } 13034 13035 private void maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent, 13036 PasswordMetrics metrics) { 13037 if (SecurityLog.isLoggingEnabled()) { 13038 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 13039 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(), 13040 userId, affectedUserId, metrics.length, metrics.quality, metrics.letters, 13041 metrics.nonLetter, metrics.numeric, metrics.upperCase, metrics.lowerCase, 13042 metrics.symbols); 13043 } 13044 } 13045} 13046