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