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