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