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