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