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