DevicePolicyManagerService.java revision 25102ef75e01e3cb691aacf1c5f5d953e835cfa1
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 enforceUserUnlocked(userHandle, parent); 4081 4082 synchronized (this) { 4083 // This API can only be called by an active device admin, 4084 // so try to retrieve it to check that the caller is one. 4085 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4086 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4087 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent); 4088 } 4089 } 4090 4091 @Override 4092 public boolean isProfileActivePasswordSufficientForParent(int userHandle) { 4093 if (!mHasFeature) { 4094 return true; 4095 } 4096 enforceFullCrossUsersPermission(userHandle); 4097 enforceManagedProfile(userHandle, "call APIs refering to the parent profile"); 4098 4099 synchronized (this) { 4100 final int targetUser = getProfileParentId(userHandle); 4101 enforceUserUnlocked(targetUser, false); 4102 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false)); 4103 return isActivePasswordSufficientForUserLocked(policy, targetUser, false); 4104 } 4105 } 4106 4107 private boolean isActivePasswordSufficientForUserLocked( 4108 DevicePolicyData policy, int userHandle, boolean parent) { 4109 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent); 4110 if (requiredPasswordQuality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 4111 // A special case is when there is no required password quality, then we just return 4112 // true since any password would be sufficient. This is for the scenario when a work 4113 // profile is first created so there is no information about the current password but 4114 // it should be considered sufficient as there is no password requirement either. 4115 // This is useful since it short-circuits the password checkpoint for FDE device below. 4116 return true; 4117 } 4118 4119 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() 4120 && !policy.mPasswordStateHasBeenSetSinceBoot) { 4121 // Before user enters their password for the first time after a reboot, return the 4122 // value of this flag, which tells us whether the password was valid the last time 4123 // settings were saved. If DPC changes password requirements on boot so that the 4124 // current password no longer meets the requirements, this value will be stale until 4125 // the next time the password is entered. 4126 return policy.mPasswordValidAtLastCheckpoint; 4127 } 4128 4129 if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) { 4130 return false; 4131 } 4132 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC 4133 && policy.mActivePasswordMetrics.length < getPasswordMinimumLength( 4134 null, userHandle, parent)) { 4135 return false; 4136 } 4137 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4138 return true; 4139 } 4140 return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase( 4141 null, userHandle, parent) 4142 && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase( 4143 null, userHandle, parent) 4144 && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters( 4145 null, userHandle, parent) 4146 && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric( 4147 null, userHandle, parent) 4148 && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols( 4149 null, userHandle, parent) 4150 && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter( 4151 null, userHandle, parent); 4152 } 4153 4154 @Override 4155 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) { 4156 enforceFullCrossUsersPermission(userHandle); 4157 synchronized (this) { 4158 if (!isCallerWithSystemUid()) { 4159 // This API can only be called by an active device admin, 4160 // so try to retrieve it to check that the caller is one. 4161 getActiveAdminForCallerLocked( 4162 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4163 } 4164 4165 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4166 4167 return policy.mFailedPasswordAttempts; 4168 } 4169 } 4170 4171 @Override 4172 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) { 4173 if (!mHasFeature) { 4174 return; 4175 } 4176 Preconditions.checkNotNull(who, "ComponentName is null"); 4177 synchronized (this) { 4178 // This API can only be called by an active device admin, 4179 // so try to retrieve it to check that the caller is one. 4180 getActiveAdminForCallerLocked( 4181 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent); 4182 ActiveAdmin ap = getActiveAdminForCallerLocked( 4183 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4184 if (ap.maximumFailedPasswordsForWipe != num) { 4185 ap.maximumFailedPasswordsForWipe = num; 4186 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 4187 } 4188 } 4189 } 4190 4191 @Override 4192 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) { 4193 if (!mHasFeature) { 4194 return 0; 4195 } 4196 enforceFullCrossUsersPermission(userHandle); 4197 synchronized (this) { 4198 ActiveAdmin admin = (who != null) 4199 ? getActiveAdminUncheckedLocked(who, userHandle, parent) 4200 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent); 4201 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 4202 } 4203 } 4204 4205 @Override 4206 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) { 4207 if (!mHasFeature) { 4208 return UserHandle.USER_NULL; 4209 } 4210 enforceFullCrossUsersPermission(userHandle); 4211 synchronized (this) { 4212 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked( 4213 userHandle, parent); 4214 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL; 4215 } 4216 } 4217 4218 /** 4219 * Returns the admin with the strictest policy on maximum failed passwords for: 4220 * <ul> 4221 * <li>this user if it has a separate profile challenge, or 4222 * <li>this user and all profiles that don't have their own challenge otherwise. 4223 * </ul> 4224 * <p>If the policy for the primary and any other profile are equal, it returns the admin for 4225 * the primary profile. 4226 * Returns {@code null} if no participating admin has that policy set. 4227 */ 4228 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked( 4229 int userHandle, boolean parent) { 4230 int count = 0; 4231 ActiveAdmin strictestAdmin = null; 4232 4233 // Return the strictest policy across all participating admins. 4234 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4235 final int N = admins.size(); 4236 for (int i = 0; i < N; i++) { 4237 ActiveAdmin admin = admins.get(i); 4238 if (admin.maximumFailedPasswordsForWipe == 4239 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 4240 continue; // No max number of failed passwords policy set for this profile. 4241 } 4242 4243 // We always favor the primary profile if several profiles have the same value set. 4244 int userId = admin.getUserHandle().getIdentifier(); 4245 if (count == 0 || 4246 count > admin.maximumFailedPasswordsForWipe || 4247 (count == admin.maximumFailedPasswordsForWipe && 4248 getUserInfo(userId).isPrimary())) { 4249 count = admin.maximumFailedPasswordsForWipe; 4250 strictestAdmin = admin; 4251 } 4252 } 4253 return strictestAdmin; 4254 } 4255 4256 private UserInfo getUserInfo(@UserIdInt int userId) { 4257 final long token = mInjector.binderClearCallingIdentity(); 4258 try { 4259 return mUserManager.getUserInfo(userId); 4260 } finally { 4261 mInjector.binderRestoreCallingIdentity(token); 4262 } 4263 } 4264 4265 @Override 4266 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException { 4267 final int callingUid = mInjector.binderGetCallingUid(); 4268 final int userHandle = mInjector.userHandleGetCallingUserId(); 4269 4270 String password = passwordOrNull != null ? passwordOrNull : ""; 4271 4272 // Password resetting to empty/null is not allowed for managed profiles. 4273 if (TextUtils.isEmpty(password)) { 4274 enforceNotManagedProfile(userHandle, "clear the active password"); 4275 } 4276 4277 synchronized (this) { 4278 // If caller has PO (or DO) it can change the password, so see if that's the case first. 4279 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked( 4280 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid); 4281 final boolean preN; 4282 if (admin != null) { 4283 final int targetSdk = getTargetSdk(admin.info.getPackageName(), userHandle); 4284 if (targetSdk >= Build.VERSION_CODES.O) { 4285 throw new SecurityException("resetPassword() is deprecated for DPC targeting O" 4286 + " or later"); 4287 } 4288 preN = targetSdk <= android.os.Build.VERSION_CODES.M; 4289 } else { 4290 // Otherwise, make sure the caller has any active admin with the right policy. 4291 admin = getActiveAdminForCallerLocked(null, 4292 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD); 4293 preN = getTargetSdk(admin.info.getPackageName(), 4294 userHandle) <= android.os.Build.VERSION_CODES.M; 4295 4296 // As of N, password resetting to empty/null is not allowed anymore. 4297 // TODO Should we allow DO/PO to set an empty password? 4298 if (TextUtils.isEmpty(password)) { 4299 if (!preN) { 4300 throw new SecurityException("Cannot call with null password"); 4301 } else { 4302 Slog.e(LOG_TAG, "Cannot call with null password"); 4303 return false; 4304 } 4305 } 4306 // As of N, password cannot be changed by the admin if it is already set. 4307 if (isLockScreenSecureUnchecked(userHandle)) { 4308 if (!preN) { 4309 throw new SecurityException("Admin cannot change current password"); 4310 } else { 4311 Slog.e(LOG_TAG, "Admin cannot change current password"); 4312 return false; 4313 } 4314 } 4315 } 4316 // Do not allow to reset password when current user has a managed profile 4317 if (!isManagedProfile(userHandle)) { 4318 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4319 if (userInfo.isManagedProfile()) { 4320 if (!preN) { 4321 throw new IllegalStateException( 4322 "Cannot reset password on user has managed profile"); 4323 } else { 4324 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile"); 4325 return false; 4326 } 4327 } 4328 } 4329 } 4330 // Do not allow to reset password when user is locked 4331 if (!mUserManager.isUserUnlocked(userHandle)) { 4332 if (!preN) { 4333 throw new IllegalStateException("Cannot reset password when user is locked"); 4334 } else { 4335 Slog.e(LOG_TAG, "Cannot reset password when user is locked"); 4336 return false; 4337 } 4338 } 4339 } 4340 4341 return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle); 4342 } 4343 4344 private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token, 4345 int flags, int callingUid, int userHandle) { 4346 int quality; 4347 synchronized (this) { 4348 quality = getPasswordQuality(null, userHandle, /* parent */ false); 4349 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) { 4350 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 4351 } 4352 final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password); 4353 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 4354 final int realQuality = metrics.quality; 4355 if (realQuality < quality 4356 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4357 Slog.w(LOG_TAG, "resetPassword: password quality 0x" 4358 + Integer.toHexString(realQuality) 4359 + " does not meet required quality 0x" 4360 + Integer.toHexString(quality)); 4361 return false; 4362 } 4363 quality = Math.max(realQuality, quality); 4364 } 4365 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false); 4366 if (password.length() < length) { 4367 Slog.w(LOG_TAG, "resetPassword: password length " + password.length() 4368 + " does not meet required length " + length); 4369 return false; 4370 } 4371 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4372 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false); 4373 if(metrics.letters < neededLetters) { 4374 Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters 4375 + " does not meet required number of letters " + neededLetters); 4376 return false; 4377 } 4378 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false); 4379 if (metrics.numeric < neededNumeric) { 4380 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric 4381 + " does not meet required number of numerical digits " 4382 + neededNumeric); 4383 return false; 4384 } 4385 int neededLowerCase = getPasswordMinimumLowerCase( 4386 null, userHandle, /* parent */ false); 4387 if (metrics.lowerCase < neededLowerCase) { 4388 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " 4389 + metrics.lowerCase 4390 + " does not meet required number of lowercase letters " 4391 + neededLowerCase); 4392 return false; 4393 } 4394 int neededUpperCase = getPasswordMinimumUpperCase( 4395 null, userHandle, /* parent */ false); 4396 if (metrics.upperCase < neededUpperCase) { 4397 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " 4398 + metrics.upperCase 4399 + " does not meet required number of uppercase letters " 4400 + neededUpperCase); 4401 return false; 4402 } 4403 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false); 4404 if (metrics.symbols < neededSymbols) { 4405 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols 4406 + " does not meet required number of special symbols " + neededSymbols); 4407 return false; 4408 } 4409 int neededNonLetter = getPasswordMinimumNonLetter( 4410 null, userHandle, /* parent */ false); 4411 if (metrics.nonLetter < neededNonLetter) { 4412 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " 4413 + metrics.nonLetter 4414 + " does not meet required number of non-letter characters " 4415 + neededNonLetter); 4416 return false; 4417 } 4418 } 4419 } 4420 4421 DevicePolicyData policy = getUserData(userHandle); 4422 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 4423 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 4424 return false; 4425 } 4426 4427 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid); 4428 boolean doNotAskCredentialsOnBoot = 4429 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 4430 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 4431 setDoNotAskCredentialsOnBoot(); 4432 } 4433 4434 // Don't do this with the lock held, because it is going to call 4435 // back in to the service. 4436 final long ident = mInjector.binderClearCallingIdentity(); 4437 final boolean result; 4438 try { 4439 if (token == null) { 4440 if (!TextUtils.isEmpty(password)) { 4441 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle); 4442 } else { 4443 mLockPatternUtils.clearLock(null, userHandle); 4444 } 4445 result = true; 4446 } else { 4447 result = mLockPatternUtils.setLockCredentialWithToken(password, 4448 TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE 4449 : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 4450 quality, tokenHandle, token, userHandle); 4451 } 4452 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 4453 if (requireEntry) { 4454 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, 4455 UserHandle.USER_ALL); 4456 } 4457 synchronized (this) { 4458 int newOwner = requireEntry ? callingUid : -1; 4459 if (policy.mPasswordOwner != newOwner) { 4460 policy.mPasswordOwner = newOwner; 4461 saveSettingsLocked(userHandle); 4462 } 4463 } 4464 } finally { 4465 mInjector.binderRestoreCallingIdentity(ident); 4466 } 4467 return result; 4468 } 4469 4470 private boolean isLockScreenSecureUnchecked(int userId) { 4471 long ident = mInjector.binderClearCallingIdentity(); 4472 try { 4473 return mLockPatternUtils.isSecure(userId); 4474 } finally { 4475 mInjector.binderRestoreCallingIdentity(ident); 4476 } 4477 } 4478 4479 private void setDoNotAskCredentialsOnBoot() { 4480 synchronized (this) { 4481 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4482 if (!policyData.doNotAskCredentialsOnBoot) { 4483 policyData.doNotAskCredentialsOnBoot = true; 4484 saveSettingsLocked(UserHandle.USER_SYSTEM); 4485 } 4486 } 4487 } 4488 4489 @Override 4490 public boolean getDoNotAskCredentialsOnBoot() { 4491 mContext.enforceCallingOrSelfPermission( 4492 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null); 4493 synchronized (this) { 4494 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4495 return policyData.doNotAskCredentialsOnBoot; 4496 } 4497 } 4498 4499 @Override 4500 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) { 4501 if (!mHasFeature) { 4502 return; 4503 } 4504 Preconditions.checkNotNull(who, "ComponentName is null"); 4505 final int userHandle = mInjector.userHandleGetCallingUserId(); 4506 synchronized (this) { 4507 ActiveAdmin ap = getActiveAdminForCallerLocked( 4508 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 4509 if (ap.maximumTimeToUnlock != timeMs) { 4510 ap.maximumTimeToUnlock = timeMs; 4511 saveSettingsLocked(userHandle); 4512 updateMaximumTimeToLockLocked(userHandle); 4513 } 4514 } 4515 } 4516 4517 void updateMaximumTimeToLockLocked(int userHandle) { 4518 // Calculate the min timeout for all profiles - including the ones with a separate 4519 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that 4520 // challenge only and keep the screen on. However there is no easy way of doing that at the 4521 // moment so we set the screen off timeout regardless of whether it affects the parent user 4522 // or the profile challenge only. 4523 long timeMs = Long.MAX_VALUE; 4524 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle); 4525 for (int profileId : profileIds) { 4526 DevicePolicyData policy = getUserDataUnchecked(profileId); 4527 final int N = policy.mAdminList.size(); 4528 for (int i = 0; i < N; i++) { 4529 ActiveAdmin admin = policy.mAdminList.get(i); 4530 if (admin.maximumTimeToUnlock > 0 4531 && timeMs > admin.maximumTimeToUnlock) { 4532 timeMs = admin.maximumTimeToUnlock; 4533 } 4534 // If userInfo.id is a managed profile, we also need to look at 4535 // the policies set on the parent. 4536 if (admin.hasParentActiveAdmin()) { 4537 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin(); 4538 if (parentAdmin.maximumTimeToUnlock > 0 4539 && timeMs > parentAdmin.maximumTimeToUnlock) { 4540 timeMs = parentAdmin.maximumTimeToUnlock; 4541 } 4542 } 4543 } 4544 } 4545 4546 // We only store the last maximum time to lock on the parent profile. So if calling from a 4547 // managed profile, retrieve the policy for the parent. 4548 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle)); 4549 if (policy.mLastMaximumTimeToLock == timeMs) { 4550 return; 4551 } 4552 policy.mLastMaximumTimeToLock = timeMs; 4553 4554 final long ident = mInjector.binderClearCallingIdentity(); 4555 try { 4556 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) { 4557 // Make sure KEEP_SCREEN_ON is disabled, since that 4558 // would allow bypassing of the maximum time to lock. 4559 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 4560 } 4561 4562 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 4563 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE)); 4564 } finally { 4565 mInjector.binderRestoreCallingIdentity(ident); 4566 } 4567 } 4568 4569 @Override 4570 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) { 4571 if (!mHasFeature) { 4572 return 0; 4573 } 4574 enforceFullCrossUsersPermission(userHandle); 4575 synchronized (this) { 4576 if (who != null) { 4577 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4578 return admin != null ? admin.maximumTimeToUnlock : 0; 4579 } 4580 // Return the strictest policy across all participating admins. 4581 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4582 userHandle, parent); 4583 return getMaximumTimeToLockPolicyFromAdmins(admins); 4584 } 4585 } 4586 4587 @Override 4588 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) { 4589 if (!mHasFeature) { 4590 return 0; 4591 } 4592 enforceFullCrossUsersPermission(userHandle); 4593 synchronized (this) { 4594 // All admins for this user. 4595 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>(); 4596 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4597 DevicePolicyData policy = getUserData(userInfo.id); 4598 admins.addAll(policy.mAdminList); 4599 // If it is a managed profile, it may have parent active admins 4600 if (userInfo.isManagedProfile()) { 4601 for (ActiveAdmin admin : policy.mAdminList) { 4602 if (admin.hasParentActiveAdmin()) { 4603 admins.add(admin.getParentActiveAdmin()); 4604 } 4605 } 4606 } 4607 } 4608 return getMaximumTimeToLockPolicyFromAdmins(admins); 4609 } 4610 } 4611 4612 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) { 4613 long time = 0; 4614 final int N = admins.size(); 4615 for (int i = 0; i < N; i++) { 4616 ActiveAdmin admin = admins.get(i); 4617 if (time == 0) { 4618 time = admin.maximumTimeToUnlock; 4619 } else if (admin.maximumTimeToUnlock != 0 4620 && time > admin.maximumTimeToUnlock) { 4621 time = admin.maximumTimeToUnlock; 4622 } 4623 } 4624 return time; 4625 } 4626 4627 @Override 4628 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, 4629 boolean parent) { 4630 if (!mHasFeature) { 4631 return; 4632 } 4633 Preconditions.checkNotNull(who, "ComponentName is null"); 4634 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number."); 4635 // timeoutMs with value 0 means that the admin doesn't participate 4636 // timeoutMs is clamped to the interval in case the internal constants change in the future 4637 final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs(); 4638 if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) { 4639 timeoutMs = minimumStrongAuthTimeout; 4640 } 4641 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 4642 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4643 } 4644 4645 final int userHandle = mInjector.userHandleGetCallingUserId(); 4646 synchronized (this) { 4647 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 4648 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent); 4649 if (ap.strongAuthUnlockTimeout != timeoutMs) { 4650 ap.strongAuthUnlockTimeout = timeoutMs; 4651 saveSettingsLocked(userHandle); 4652 } 4653 } 4654 } 4655 4656 /** 4657 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all 4658 * admins if who is null. 4659 * Returns 0 if not configured for the provided admin. 4660 */ 4661 @Override 4662 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) { 4663 if (!mHasFeature) { 4664 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4665 } 4666 enforceFullCrossUsersPermission(userId); 4667 synchronized (this) { 4668 if (who != null) { 4669 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent); 4670 return admin != null ? admin.strongAuthUnlockTimeout : 0; 4671 } 4672 4673 // Return the strictest policy across all participating admins. 4674 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent); 4675 4676 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4677 for (int i = 0; i < admins.size(); i++) { 4678 final long timeout = admins.get(i).strongAuthUnlockTimeout; 4679 if (timeout != 0) { // take only participating admins into account 4680 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout); 4681 } 4682 } 4683 return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs()); 4684 } 4685 } 4686 4687 private long getMinimumStrongAuthTimeoutMs() { 4688 if (!mInjector.isBuildDebuggable()) { 4689 return MINIMUM_STRONG_AUTH_TIMEOUT_MS; 4690 } 4691 // ideally the property was named persist.sys.min_strong_auth_timeout, but system property 4692 // name cannot be longer than 31 characters 4693 return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo", 4694 MINIMUM_STRONG_AUTH_TIMEOUT_MS), 4695 MINIMUM_STRONG_AUTH_TIMEOUT_MS); 4696 } 4697 4698 @Override 4699 public void lockNow(int flags, boolean parent) { 4700 if (!mHasFeature) { 4701 return; 4702 } 4703 4704 final int callingUserId = mInjector.userHandleGetCallingUserId(); 4705 synchronized (this) { 4706 // This API can only be called by an active device admin, 4707 // so try to retrieve it to check that the caller is one. 4708 final ActiveAdmin admin = getActiveAdminForCallerLocked( 4709 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 4710 4711 final long ident = mInjector.binderClearCallingIdentity(); 4712 try { 4713 // Evict key 4714 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) { 4715 enforceManagedProfile( 4716 callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 4717 if (!isProfileOwner(admin.info.getComponent(), callingUserId)) { 4718 throw new SecurityException("Only profile owner admins can set " 4719 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 4720 } 4721 if (parent) { 4722 throw new IllegalArgumentException( 4723 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent"); 4724 } 4725 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 4726 throw new UnsupportedOperationException( 4727 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices"); 4728 } 4729 mUserManager.evictCredentialEncryptionKey(callingUserId); 4730 } 4731 4732 // Lock all users unless this is a managed profile with a separate challenge 4733 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId) 4734 ? UserHandle.USER_ALL : callingUserId); 4735 mLockPatternUtils.requireStrongAuth( 4736 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock); 4737 4738 // Require authentication for the device or profile 4739 if (userToLock == UserHandle.USER_ALL) { 4740 // Power off the display 4741 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(), 4742 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 4743 mInjector.getIWindowManager().lockNow(null); 4744 } else { 4745 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true); 4746 } 4747 } catch (RemoteException e) { 4748 } finally { 4749 mInjector.binderRestoreCallingIdentity(ident); 4750 } 4751 } 4752 } 4753 4754 @Override 4755 public void enforceCanManageCaCerts(ComponentName who, String callerPackage) { 4756 if (who == null) { 4757 if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) { 4758 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 4759 } 4760 } else { 4761 enforceProfileOrDeviceOwner(who); 4762 } 4763 } 4764 4765 private void enforceProfileOrDeviceOwner(ComponentName who) { 4766 synchronized (this) { 4767 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4768 } 4769 } 4770 4771 @Override 4772 public boolean approveCaCert(String alias, int userId, boolean approval) { 4773 enforceManageUsers(); 4774 synchronized (this) { 4775 Set<String> certs = getUserData(userId).mAcceptedCaCertificates; 4776 boolean changed = (approval ? certs.add(alias) : certs.remove(alias)); 4777 if (!changed) { 4778 return false; 4779 } 4780 saveSettingsLocked(userId); 4781 } 4782 mCertificateMonitor.onCertificateApprovalsChanged(userId); 4783 return true; 4784 } 4785 4786 @Override 4787 public boolean isCaCertApproved(String alias, int userId) { 4788 enforceManageUsers(); 4789 synchronized (this) { 4790 return getUserData(userId).mAcceptedCaCertificates.contains(alias); 4791 } 4792 } 4793 4794 private void removeCaApprovalsIfNeeded(int userId) { 4795 for (UserInfo userInfo : mUserManager.getProfiles(userId)) { 4796 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id); 4797 if (userInfo.isManagedProfile()){ 4798 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id)); 4799 } 4800 if (!isSecure) { 4801 synchronized (this) { 4802 getUserData(userInfo.id).mAcceptedCaCertificates.clear(); 4803 saveSettingsLocked(userInfo.id); 4804 } 4805 mCertificateMonitor.onCertificateApprovalsChanged(userId); 4806 } 4807 } 4808 } 4809 4810 @Override 4811 public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) 4812 throws RemoteException { 4813 if (!mHasFeature) { 4814 return false; 4815 } 4816 enforceCanManageCaCerts(admin, callerPackage); 4817 4818 final String alias; 4819 4820 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 4821 final long id = mInjector.binderClearCallingIdentity(); 4822 try { 4823 alias = mCertificateMonitor.installCaCert(userHandle, certBuffer); 4824 if (alias == null) { 4825 Log.w(LOG_TAG, "Problem installing cert"); 4826 return false; 4827 } 4828 } finally { 4829 mInjector.binderRestoreCallingIdentity(id); 4830 } 4831 4832 synchronized (this) { 4833 getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias); 4834 saveSettingsLocked(userHandle.getIdentifier()); 4835 } 4836 return true; 4837 } 4838 4839 @Override 4840 public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) { 4841 if (!mHasFeature) { 4842 return; 4843 } 4844 enforceCanManageCaCerts(admin, callerPackage); 4845 4846 final int userId = mInjector.userHandleGetCallingUserId(); 4847 final long id = mInjector.binderClearCallingIdentity(); 4848 try { 4849 mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases); 4850 } finally { 4851 mInjector.binderRestoreCallingIdentity(id); 4852 } 4853 4854 synchronized (this) { 4855 if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) { 4856 saveSettingsLocked(userId); 4857 } 4858 } 4859 } 4860 4861 @Override 4862 public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey, 4863 byte[] cert, byte[] chain, String alias, boolean requestAccess) { 4864 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 4865 DELEGATION_CERT_INSTALL); 4866 4867 4868 final int callingUid = mInjector.binderGetCallingUid(); 4869 final long id = mInjector.binderClearCallingIdentity(); 4870 try { 4871 final KeyChainConnection keyChainConnection = 4872 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid)); 4873 try { 4874 IKeyChainService keyChain = keyChainConnection.getService(); 4875 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) { 4876 return false; 4877 } 4878 if (requestAccess) { 4879 keyChain.setGrant(callingUid, alias, true); 4880 } 4881 return true; 4882 } catch (RemoteException e) { 4883 Log.e(LOG_TAG, "Installing certificate", e); 4884 } finally { 4885 keyChainConnection.close(); 4886 } 4887 } catch (InterruptedException e) { 4888 Log.w(LOG_TAG, "Interrupted while installing certificate", e); 4889 Thread.currentThread().interrupt(); 4890 } finally { 4891 mInjector.binderRestoreCallingIdentity(id); 4892 } 4893 return false; 4894 } 4895 4896 @Override 4897 public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) { 4898 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 4899 DELEGATION_CERT_INSTALL); 4900 4901 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 4902 final long id = Binder.clearCallingIdentity(); 4903 try { 4904 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 4905 try { 4906 IKeyChainService keyChain = keyChainConnection.getService(); 4907 return keyChain.removeKeyPair(alias); 4908 } catch (RemoteException e) { 4909 Log.e(LOG_TAG, "Removing keypair", e); 4910 } finally { 4911 keyChainConnection.close(); 4912 } 4913 } catch (InterruptedException e) { 4914 Log.w(LOG_TAG, "Interrupted while removing keypair", e); 4915 Thread.currentThread().interrupt(); 4916 } finally { 4917 Binder.restoreCallingIdentity(id); 4918 } 4919 return false; 4920 } 4921 4922 @Override 4923 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, 4924 final IBinder response) { 4925 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers. 4926 if (!isCallerWithSystemUid()) { 4927 return; 4928 } 4929 4930 final UserHandle caller = mInjector.binderGetCallingUserHandle(); 4931 // If there is a profile owner, redirect to that; otherwise query the device owner. 4932 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier()); 4933 if (aliasChooser == null && caller.isSystem()) { 4934 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 4935 if (deviceOwnerAdmin != null) { 4936 aliasChooser = deviceOwnerAdmin.info.getComponent(); 4937 } 4938 } 4939 if (aliasChooser == null) { 4940 sendPrivateKeyAliasResponse(null, response); 4941 return; 4942 } 4943 4944 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 4945 intent.setComponent(aliasChooser); 4946 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 4947 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri); 4948 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 4949 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 4950 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 4951 4952 final long id = mInjector.binderClearCallingIdentity(); 4953 try { 4954 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() { 4955 @Override 4956 public void onReceive(Context context, Intent intent) { 4957 final String chosenAlias = getResultData(); 4958 sendPrivateKeyAliasResponse(chosenAlias, response); 4959 } 4960 }, null, Activity.RESULT_OK, null, null); 4961 } finally { 4962 mInjector.binderRestoreCallingIdentity(id); 4963 } 4964 } 4965 4966 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 4967 final IKeyChainAliasCallback keyChainAliasResponse = 4968 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 4969 // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback 4970 // is oneway, which means it won't block if the recipient lives in another process. 4971 try { 4972 keyChainAliasResponse.alias(alias); 4973 } catch (Exception e) { 4974 // Caller could throw RuntimeException or RemoteException back across processes. Catch 4975 // everything just to be sure. 4976 Log.e(LOG_TAG, "error while responding to callback", e); 4977 } 4978 } 4979 4980 /** 4981 * Determine whether DPMS should check if a delegate package is already installed before 4982 * granting it new delegations via {@link #setDelegatedScopes}. 4983 */ 4984 private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, 4985 int targetSdk, List<String> scopes) { 4986 // 1) Never skip is installed check from N. 4987 if (targetSdk >= Build.VERSION_CODES.N) { 4988 return true; 4989 } 4990 // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given. 4991 if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) { 4992 return false; 4993 } 4994 // 3) Skip if all previously granted scopes are being cleared. 4995 if (scopes.isEmpty()) { 4996 return false; 4997 } 4998 // Otherwise it should check that delegatePackage is installed. 4999 return true; 5000 } 5001 5002 /** 5003 * Set the scopes of a device owner or profile owner delegate. 5004 * 5005 * @param who the device owner or profile owner. 5006 * @param delegatePackage the name of the delegate package. 5007 * @param scopes the list of delegation scopes to be given to the delegate package. 5008 */ 5009 @Override 5010 public void setDelegatedScopes(ComponentName who, String delegatePackage, 5011 List<String> scopes) throws SecurityException { 5012 Preconditions.checkNotNull(who, "ComponentName is null"); 5013 Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty"); 5014 Preconditions.checkCollectionElementsNotNull(scopes, "Scopes"); 5015 // Remove possible duplicates. 5016 scopes = new ArrayList(new ArraySet(scopes)); 5017 // Ensure given scopes are valid. 5018 if (scopes.retainAll(Arrays.asList(DELEGATIONS))) { 5019 throw new IllegalArgumentException("Unexpected delegation scopes"); 5020 } 5021 5022 // Retrieve the user ID of the calling process. 5023 final int userId = mInjector.userHandleGetCallingUserId(); 5024 synchronized (this) { 5025 // Ensure calling process is device/profile owner. 5026 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5027 // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N). 5028 if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage, 5029 getTargetSdk(who.getPackageName(), userId), scopes)) { 5030 // Throw when the delegate package is not installed. 5031 if (!isPackageInstalledForUser(delegatePackage, userId)) { 5032 throw new IllegalArgumentException("Package " + delegatePackage 5033 + " is not installed on the current user"); 5034 } 5035 } 5036 5037 // Set the new delegate in user policies. 5038 final DevicePolicyData policy = getUserData(userId); 5039 if (!scopes.isEmpty()) { 5040 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes)); 5041 } else { 5042 // Remove any delegation info if the given scopes list is empty. 5043 policy.mDelegationMap.remove(delegatePackage); 5044 } 5045 5046 // Notify delegate package of updates. 5047 final Intent intent = new Intent( 5048 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED); 5049 // Only call receivers registered with Context#registerReceiver (don’t wake delegate). 5050 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 5051 // Limit components this intent resolves to to the delegate package. 5052 intent.setPackage(delegatePackage); 5053 // Include the list of delegated scopes as an extra. 5054 intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, 5055 (ArrayList<String>) scopes); 5056 // Send the broadcast. 5057 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 5058 5059 // Persist updates. 5060 saveSettingsLocked(userId); 5061 } 5062 } 5063 5064 /** 5065 * Get the delegation scopes given to a delegate package by a device owner or profile owner. 5066 * 5067 * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by 5068 * passing in {@code null} as the {@code who} parameter and its own name as the 5069 * {@code delegatepackage}. 5070 * 5071 * @param who the device owner or profile owner, or {@code null} if the caller is 5072 * {@code delegatePackage}. 5073 * @param delegatePackage the name of the delegate package whose scopes are to be retrieved. 5074 * @return a list of the delegation scopes currently given to {@code delegatePackage}. 5075 */ 5076 @Override 5077 @NonNull 5078 public List<String> getDelegatedScopes(ComponentName who, 5079 String delegatePackage) throws SecurityException { 5080 Preconditions.checkNotNull(delegatePackage, "Delegate package is null"); 5081 5082 // Retrieve the user ID of the calling process. 5083 final int callingUid = mInjector.binderGetCallingUid(); 5084 final int userId = UserHandle.getUserId(callingUid); 5085 synchronized (this) { 5086 // Ensure calling process is device/profile owner. 5087 if (who != null) { 5088 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5089 // Or ensure calling process is delegatePackage itself. 5090 } else { 5091 int uid = 0; 5092 try { 5093 uid = mInjector.getPackageManager() 5094 .getPackageUidAsUser(delegatePackage, userId); 5095 } catch(NameNotFoundException e) { 5096 } 5097 if (uid != callingUid) { 5098 throw new SecurityException("Caller with uid " + callingUid + " is not " 5099 + delegatePackage); 5100 } 5101 } 5102 final DevicePolicyData policy = getUserData(userId); 5103 // Retrieve the scopes assigned to delegatePackage, or null if no scope was given. 5104 final List<String> scopes = policy.mDelegationMap.get(delegatePackage); 5105 return scopes == null ? Collections.EMPTY_LIST : scopes; 5106 } 5107 } 5108 5109 /** 5110 * Get a list of packages that were given a specific delegation scopes by a device owner or 5111 * profile owner. 5112 * 5113 * @param who the device owner or profile owner. 5114 * @param scope the scope whose delegates are to be retrieved. 5115 * @return a list of the delegate packages currently given the {@code scope} delegation. 5116 */ 5117 @NonNull 5118 public List<String> getDelegatePackages(ComponentName who, String scope) 5119 throws SecurityException { 5120 Preconditions.checkNotNull(who, "ComponentName is null"); 5121 Preconditions.checkNotNull(scope, "Scope is null"); 5122 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 5123 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 5124 } 5125 5126 // Retrieve the user ID of the calling process. 5127 final int userId = mInjector.userHandleGetCallingUserId(); 5128 synchronized (this) { 5129 // Ensure calling process is device/profile owner. 5130 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5131 final DevicePolicyData policy = getUserData(userId); 5132 5133 // Create a list to hold the resulting delegate packages. 5134 final List<String> delegatePackagesWithScope = new ArrayList<>(); 5135 // Add all delegations containing scope to the result list. 5136 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 5137 if (policy.mDelegationMap.valueAt(i).contains(scope)) { 5138 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i)); 5139 } 5140 } 5141 return delegatePackagesWithScope; 5142 } 5143 } 5144 5145 /** 5146 * Check whether a caller application has been delegated a given scope via 5147 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 5148 * device owner. 5149 * <p> 5150 * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and 5151 * then comparing the calling UID with the UID of {@code callerPackage} as reported by 5152 * {@link PackageManager#getPackageUidAsUser}. 5153 * 5154 * @param callerPackage the name of the package that is trying to invoke a function in the DPMS. 5155 * @param scope the delegation scope to be checked. 5156 * @return {@code true} if the calling process is a delegate of {@code scope}. 5157 */ 5158 private boolean isCallerDelegate(String callerPackage, String scope) { 5159 Preconditions.checkNotNull(callerPackage, "callerPackage is null"); 5160 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 5161 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 5162 } 5163 5164 // Retrieve the UID and user ID of the calling process. 5165 final int callingUid = mInjector.binderGetCallingUid(); 5166 final int userId = UserHandle.getUserId(callingUid); 5167 synchronized (this) { 5168 // Retrieve user policy data. 5169 final DevicePolicyData policy = getUserData(userId); 5170 // Retrieve the list of delegation scopes granted to callerPackage. 5171 final List<String> scopes = policy.mDelegationMap.get(callerPackage); 5172 // Check callingUid only if callerPackage has the required scope delegation. 5173 if (scopes != null && scopes.contains(scope)) { 5174 try { 5175 // Retrieve the expected UID for callerPackage. 5176 final int uid = mInjector.getPackageManager() 5177 .getPackageUidAsUser(callerPackage, userId); 5178 // Return true if the caller is actually callerPackage. 5179 return uid == callingUid; 5180 } catch (NameNotFoundException e) { 5181 // Ignore. 5182 } 5183 } 5184 return false; 5185 } 5186 } 5187 5188 /** 5189 * Throw a security exception if a ComponentName is given and it is not a device/profile owner 5190 * or if the calling process is not a delegate of the given scope. 5191 * 5192 * @param who the device owner of profile owner, or null if {@code callerPackage} is a 5193 * {@code scope} delegate. 5194 * @param callerPackage the name of the calling package. Required if {@code who} is 5195 * {@code null}. 5196 * @param reqPolicy the policy used in the API whose access permission is being checked. 5197 * @param scope the delegation scope corresponding to the API being checked. 5198 * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy}; 5199 * or when {@code who} is {@code null} and {@code callerPackage} is not a delegate 5200 * of {@code scope}. 5201 */ 5202 private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, 5203 String scope) { 5204 // If a ComponentName is given ensure it is a device or profile owner according to policy. 5205 if (who != null) { 5206 synchronized (this) { 5207 getActiveAdminForCallerLocked(who, reqPolicy); 5208 } 5209 // If no ComponentName is given ensure calling process has scope delegation. 5210 } else if (!isCallerDelegate(callerPackage, scope)) { 5211 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() 5212 + " is not a delegate of scope " + scope + "."); 5213 } 5214 } 5215 5216 /** 5217 * Helper function to preserve delegation behavior pre-O when using the deprecated functions 5218 * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}. 5219 */ 5220 private void setDelegatedScopePreO(ComponentName who, 5221 String delegatePackage, String scope) { 5222 Preconditions.checkNotNull(who, "ComponentName is null"); 5223 5224 final int userId = mInjector.userHandleGetCallingUserId(); 5225 synchronized(this) { 5226 // Ensure calling process is device/profile owner. 5227 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5228 final DevicePolicyData policy = getUserData(userId); 5229 5230 if (delegatePackage != null) { 5231 // Set package as a delegate for scope if it is not already one. 5232 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 5233 if (scopes == null) { 5234 scopes = new ArrayList<>(); 5235 } 5236 if (!scopes.contains(scope)) { 5237 scopes.add(scope); 5238 setDelegatedScopes(who, delegatePackage, scopes); 5239 } 5240 } 5241 5242 // Clear any existing scope delegates. 5243 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 5244 final String currentPackage = policy.mDelegationMap.keyAt(i); 5245 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 5246 5247 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) { 5248 final List<String> newScopes = new ArrayList(currentScopes); 5249 newScopes.remove(scope); 5250 setDelegatedScopes(who, currentPackage, newScopes); 5251 } 5252 } 5253 } 5254 } 5255 5256 @Override 5257 public void setCertInstallerPackage(ComponentName who, String installerPackage) 5258 throws SecurityException { 5259 setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL); 5260 } 5261 5262 @Override 5263 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 5264 final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL); 5265 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 5266 } 5267 5268 /** 5269 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is 5270 * not installed and therefore not available. 5271 * 5272 * @throws SecurityException if the caller is not a profile or device owner. 5273 * @throws UnsupportedOperationException if the package does not support being set as always-on. 5274 */ 5275 @Override 5276 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown) 5277 throws SecurityException { 5278 enforceProfileOrDeviceOwner(admin); 5279 5280 final int userId = mInjector.userHandleGetCallingUserId(); 5281 final long token = mInjector.binderClearCallingIdentity(); 5282 try { 5283 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) { 5284 return false; 5285 } 5286 ConnectivityManager connectivityManager = (ConnectivityManager) 5287 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5288 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) { 5289 throw new UnsupportedOperationException(); 5290 } 5291 } finally { 5292 mInjector.binderRestoreCallingIdentity(token); 5293 } 5294 return true; 5295 } 5296 5297 @Override 5298 public String getAlwaysOnVpnPackage(ComponentName admin) 5299 throws SecurityException { 5300 enforceProfileOrDeviceOwner(admin); 5301 5302 final int userId = mInjector.userHandleGetCallingUserId(); 5303 final long token = mInjector.binderClearCallingIdentity(); 5304 try{ 5305 ConnectivityManager connectivityManager = (ConnectivityManager) 5306 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5307 return connectivityManager.getAlwaysOnVpnPackageForUser(userId); 5308 } finally { 5309 mInjector.binderRestoreCallingIdentity(token); 5310 } 5311 } 5312 5313 private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) { 5314 wtfIfInLock(); 5315 5316 if (wipeExtRequested) { 5317 StorageManager sm = (StorageManager) mContext.getSystemService( 5318 Context.STORAGE_SERVICE); 5319 sm.wipeAdoptableDisks(); 5320 } 5321 try { 5322 mInjector.recoverySystemRebootWipeUserData( 5323 /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc); 5324 } catch (IOException | SecurityException e) { 5325 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 5326 } 5327 } 5328 5329 private void forceWipeUser(int userId) { 5330 try { 5331 IActivityManager am = mInjector.getIActivityManager(); 5332 if (am.getCurrentUser().id == userId) { 5333 am.switchUser(UserHandle.USER_SYSTEM); 5334 } 5335 5336 boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId); 5337 if (!userRemoved) { 5338 Slog.w(LOG_TAG, "Couldn't remove user " + userId); 5339 } else if (isManagedProfile(userId)) { 5340 sendWipeProfileNotification(); 5341 } 5342 } catch (RemoteException re) { 5343 // Shouldn't happen 5344 } 5345 } 5346 5347 @Override 5348 public void wipeData(int flags) { 5349 if (!mHasFeature) { 5350 return; 5351 } 5352 enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId()); 5353 5354 final ActiveAdmin admin; 5355 synchronized (this) { 5356 admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA); 5357 } 5358 String reason = "DevicePolicyManager.wipeData() from " 5359 + admin.info.getComponent().flattenToShortString(); 5360 wipeDataNoLock( 5361 admin.info.getComponent(), flags, reason, admin.getUserHandle().getIdentifier()); 5362 } 5363 5364 private void wipeDataNoLock(ComponentName admin, int flags, String reason, int userId) { 5365 wtfIfInLock(); 5366 5367 long ident = mInjector.binderClearCallingIdentity(); 5368 try { 5369 // First check whether the admin is allowed to wipe the device/user/profile. 5370 final String restriction; 5371 if (userId == UserHandle.USER_SYSTEM) { 5372 restriction = UserManager.DISALLOW_FACTORY_RESET; 5373 } else if (isManagedProfile(userId)) { 5374 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 5375 } else { 5376 restriction = UserManager.DISALLOW_REMOVE_USER; 5377 } 5378 if (isAdminAffectedByRestriction(admin, restriction, userId)) { 5379 throw new SecurityException("Cannot wipe data. " + restriction 5380 + " restriction is set for user " + userId); 5381 } 5382 5383 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 5384 if (!isDeviceOwner(admin, userId)) { 5385 throw new SecurityException( 5386 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA"); 5387 } 5388 PersistentDataBlockManager manager = (PersistentDataBlockManager) 5389 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 5390 if (manager != null) { 5391 manager.wipe(); 5392 } 5393 } 5394 5395 // TODO If split user is enabled and the device owner is set in the primary user 5396 // (rather than system), we should probably trigger factory reset. Current code just 5397 // removes that user (but still clears FRP...) 5398 if (userId == UserHandle.USER_SYSTEM) { 5399 forceWipeDeviceNoLock(/*wipeExtRequested=*/ (flags & WIPE_EXTERNAL_STORAGE) != 0, 5400 reason, /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0); 5401 } else { 5402 forceWipeUser(userId); 5403 } 5404 } finally { 5405 mInjector.binderRestoreCallingIdentity(ident); 5406 } 5407 } 5408 5409 private void sendWipeProfileNotification() { 5410 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe); 5411 Notification notification = 5412 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 5413 .setSmallIcon(android.R.drawable.stat_sys_warning) 5414 .setContentTitle(mContext.getString(R.string.work_profile_deleted)) 5415 .setContentText(contentText) 5416 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 5417 .setStyle(new Notification.BigTextStyle().bigText(contentText)) 5418 .build(); 5419 mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification); 5420 } 5421 5422 private void clearWipeProfileNotification() { 5423 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED); 5424 } 5425 5426 @Override 5427 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 5428 if (!mHasFeature) { 5429 return; 5430 } 5431 enforceFullCrossUsersPermission(userHandle); 5432 mContext.enforceCallingOrSelfPermission( 5433 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5434 5435 synchronized (this) { 5436 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 5437 if (admin == null) { 5438 result.sendResult(null); 5439 return; 5440 } 5441 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 5442 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 5443 intent.setComponent(admin.info.getComponent()); 5444 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 5445 null, new BroadcastReceiver() { 5446 @Override 5447 public void onReceive(Context context, Intent intent) { 5448 result.sendResult(getResultExtras(false)); 5449 } 5450 }, null, Activity.RESULT_OK, null, null); 5451 } 5452 } 5453 5454 /** 5455 * Notify DPMS regarding the metric of the current password. This happens when the user changes 5456 * the password, but also when the user just unlocks the keyguard. In comparison, 5457 * reportPasswordChanged() is only called when the user changes the password. 5458 */ 5459 @Override 5460 public void setActivePasswordState(PasswordMetrics metrics, int userHandle) { 5461 if (!mHasFeature) { 5462 return; 5463 } 5464 enforceFullCrossUsersPermission(userHandle); 5465 mContext.enforceCallingOrSelfPermission( 5466 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5467 5468 // If the managed profile doesn't have a separate password, set the metrics to default 5469 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 5470 metrics = new PasswordMetrics(); 5471 } 5472 5473 validateQualityConstant(metrics.quality); 5474 DevicePolicyData policy = getUserData(userHandle); 5475 synchronized (this) { 5476 policy.mActivePasswordMetrics = metrics; 5477 policy.mPasswordStateHasBeenSetSinceBoot = true; 5478 } 5479 } 5480 5481 @Override 5482 public void reportPasswordChanged(@UserIdInt int userId) { 5483 if (!mHasFeature) { 5484 return; 5485 } 5486 enforceFullCrossUsersPermission(userId); 5487 5488 // Managed Profile password can only be changed when it has a separate challenge. 5489 if (!isSeparateProfileChallengeEnabled(userId)) { 5490 enforceNotManagedProfile(userId, "set the active password"); 5491 } 5492 5493 mContext.enforceCallingOrSelfPermission( 5494 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5495 5496 DevicePolicyData policy = getUserData(userId); 5497 5498 long ident = mInjector.binderClearCallingIdentity(); 5499 try { 5500 synchronized (this) { 5501 policy.mFailedPasswordAttempts = 0; 5502 updatePasswordValidityCheckpointLocked(userId); 5503 saveSettingsLocked(userId); 5504 updatePasswordExpirationsLocked(userId); 5505 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 5506 5507 // Send a broadcast to each profile using this password as its primary unlock. 5508 sendAdminCommandForLockscreenPoliciesLocked( 5509 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 5510 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 5511 } 5512 removeCaApprovalsIfNeeded(userId); 5513 } finally { 5514 mInjector.binderRestoreCallingIdentity(ident); 5515 } 5516 } 5517 5518 /** 5519 * Called any time the device password is updated. Resets all password expiration clocks. 5520 */ 5521 private void updatePasswordExpirationsLocked(int userHandle) { 5522 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>(); 5523 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5524 userHandle, /* parent */ false); 5525 final int N = admins.size(); 5526 for (int i = 0; i < N; i++) { 5527 ActiveAdmin admin = admins.get(i); 5528 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 5529 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 5530 long timeout = admin.passwordExpirationTimeout; 5531 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 5532 admin.passwordExpirationDate = expiration; 5533 } 5534 } 5535 for (int affectedUserId : affectedUserIds) { 5536 saveSettingsLocked(affectedUserId); 5537 } 5538 } 5539 5540 @Override 5541 public void reportFailedPasswordAttempt(int userHandle) { 5542 enforceFullCrossUsersPermission(userHandle); 5543 if (!isSeparateProfileChallengeEnabled(userHandle)) { 5544 enforceNotManagedProfile(userHandle, 5545 "report failed password attempt if separate profile challenge is not in place"); 5546 } 5547 mContext.enforceCallingOrSelfPermission( 5548 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5549 5550 boolean wipeData = false; 5551 ActiveAdmin strictestAdmin = null; 5552 final long ident = mInjector.binderClearCallingIdentity(); 5553 try { 5554 synchronized (this) { 5555 DevicePolicyData policy = getUserData(userHandle); 5556 policy.mFailedPasswordAttempts++; 5557 saveSettingsLocked(userHandle); 5558 if (mHasFeature) { 5559 strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 5560 userHandle, /* parent */ false); 5561 int max = strictestAdmin != null 5562 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 5563 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 5564 wipeData = true; 5565 } 5566 5567 sendAdminCommandForLockscreenPoliciesLocked( 5568 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 5569 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 5570 } 5571 } 5572 } finally { 5573 mInjector.binderRestoreCallingIdentity(ident); 5574 } 5575 5576 if (wipeData && strictestAdmin != null) { 5577 final int userId = strictestAdmin.getUserHandle().getIdentifier(); 5578 Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: " 5579 + strictestAdmin.info.getComponent().flattenToShortString() 5580 + ". Calling wipeData for user " + userId); 5581 5582 // Attempt to wipe the device/user/profile associated with the admin, as if the 5583 // admin had called wipeData(). That way we can check whether the admin is actually 5584 // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the 5585 // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be 5586 // able to do so). 5587 // IMPORTANT: Call without holding the lock to prevent deadlock. 5588 try { 5589 wipeDataNoLock(strictestAdmin.info.getComponent(), 5590 /*flags=*/ 0, 5591 /*reason=*/ "reportFailedPasswordAttempt()", 5592 userId); 5593 } catch (SecurityException e) { 5594 Slog.w(LOG_TAG, "Failed to wipe user " + userId 5595 + " after max failed password attempts reached.", e); 5596 } 5597 } 5598 5599 if (mInjector.securityLogIsLoggingEnabled()) { 5600 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 5601 /*method strength*/ 1); 5602 } 5603 } 5604 5605 @Override 5606 public void reportSuccessfulPasswordAttempt(int userHandle) { 5607 enforceFullCrossUsersPermission(userHandle); 5608 mContext.enforceCallingOrSelfPermission( 5609 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5610 5611 synchronized (this) { 5612 DevicePolicyData policy = getUserData(userHandle); 5613 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 5614 long ident = mInjector.binderClearCallingIdentity(); 5615 try { 5616 policy.mFailedPasswordAttempts = 0; 5617 policy.mPasswordOwner = -1; 5618 saveSettingsLocked(userHandle); 5619 if (mHasFeature) { 5620 sendAdminCommandForLockscreenPoliciesLocked( 5621 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 5622 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 5623 } 5624 } finally { 5625 mInjector.binderRestoreCallingIdentity(ident); 5626 } 5627 } 5628 } 5629 5630 if (mInjector.securityLogIsLoggingEnabled()) { 5631 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 5632 /*method strength*/ 1); 5633 } 5634 } 5635 5636 @Override 5637 public void reportFailedFingerprintAttempt(int userHandle) { 5638 enforceFullCrossUsersPermission(userHandle); 5639 mContext.enforceCallingOrSelfPermission( 5640 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5641 if (mInjector.securityLogIsLoggingEnabled()) { 5642 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 5643 /*method strength*/ 0); 5644 } 5645 } 5646 5647 @Override 5648 public void reportSuccessfulFingerprintAttempt(int userHandle) { 5649 enforceFullCrossUsersPermission(userHandle); 5650 mContext.enforceCallingOrSelfPermission( 5651 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5652 if (mInjector.securityLogIsLoggingEnabled()) { 5653 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 5654 /*method strength*/ 0); 5655 } 5656 } 5657 5658 @Override 5659 public void reportKeyguardDismissed(int userHandle) { 5660 enforceFullCrossUsersPermission(userHandle); 5661 mContext.enforceCallingOrSelfPermission( 5662 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5663 5664 if (mInjector.securityLogIsLoggingEnabled()) { 5665 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 5666 } 5667 } 5668 5669 @Override 5670 public void reportKeyguardSecured(int userHandle) { 5671 enforceFullCrossUsersPermission(userHandle); 5672 mContext.enforceCallingOrSelfPermission( 5673 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5674 5675 if (mInjector.securityLogIsLoggingEnabled()) { 5676 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 5677 } 5678 } 5679 5680 @Override 5681 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 5682 String exclusionList) { 5683 if (!mHasFeature) { 5684 return null; 5685 } 5686 synchronized(this) { 5687 Preconditions.checkNotNull(who, "ComponentName is null"); 5688 5689 // Only check if system user has set global proxy. We don't allow other users to set it. 5690 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5691 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5692 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 5693 5694 // Scan through active admins and find if anyone has already 5695 // set the global proxy. 5696 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 5697 for (ComponentName component : compSet) { 5698 ActiveAdmin ap = policy.mAdminMap.get(component); 5699 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 5700 // Another admin already sets the global proxy 5701 // Return it to the caller. 5702 return component; 5703 } 5704 } 5705 5706 // If the user is not system, don't set the global proxy. Fail silently. 5707 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 5708 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 5709 + UserHandle.getCallingUserId() + " is not permitted."); 5710 return null; 5711 } 5712 if (proxySpec == null) { 5713 admin.specifiesGlobalProxy = false; 5714 admin.globalProxySpec = null; 5715 admin.globalProxyExclusionList = null; 5716 } else { 5717 5718 admin.specifiesGlobalProxy = true; 5719 admin.globalProxySpec = proxySpec; 5720 admin.globalProxyExclusionList = exclusionList; 5721 } 5722 5723 // Reset the global proxy accordingly 5724 // Do this using system permissions, as apps cannot write to secure settings 5725 long origId = mInjector.binderClearCallingIdentity(); 5726 try { 5727 resetGlobalProxyLocked(policy); 5728 } finally { 5729 mInjector.binderRestoreCallingIdentity(origId); 5730 } 5731 return null; 5732 } 5733 } 5734 5735 @Override 5736 public ComponentName getGlobalProxyAdmin(int userHandle) { 5737 if (!mHasFeature) { 5738 return null; 5739 } 5740 enforceFullCrossUsersPermission(userHandle); 5741 synchronized(this) { 5742 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5743 // Scan through active admins and find if anyone has already 5744 // set the global proxy. 5745 final int N = policy.mAdminList.size(); 5746 for (int i = 0; i < N; i++) { 5747 ActiveAdmin ap = policy.mAdminList.get(i); 5748 if (ap.specifiesGlobalProxy) { 5749 // Device admin sets the global proxy 5750 // Return it to the caller. 5751 return ap.info.getComponent(); 5752 } 5753 } 5754 } 5755 // No device admin sets the global proxy. 5756 return null; 5757 } 5758 5759 @Override 5760 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 5761 synchronized (this) { 5762 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5763 } 5764 long token = mInjector.binderClearCallingIdentity(); 5765 try { 5766 ConnectivityManager connectivityManager = (ConnectivityManager) 5767 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5768 connectivityManager.setGlobalProxy(proxyInfo); 5769 } finally { 5770 mInjector.binderRestoreCallingIdentity(token); 5771 } 5772 } 5773 5774 private void resetGlobalProxyLocked(DevicePolicyData policy) { 5775 final int N = policy.mAdminList.size(); 5776 for (int i = 0; i < N; i++) { 5777 ActiveAdmin ap = policy.mAdminList.get(i); 5778 if (ap.specifiesGlobalProxy) { 5779 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 5780 return; 5781 } 5782 } 5783 // No device admins defining global proxies - reset global proxy settings to none 5784 saveGlobalProxyLocked(null, null); 5785 } 5786 5787 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 5788 if (exclusionList == null) { 5789 exclusionList = ""; 5790 } 5791 if (proxySpec == null) { 5792 proxySpec = ""; 5793 } 5794 // Remove white spaces 5795 proxySpec = proxySpec.trim(); 5796 String data[] = proxySpec.split(":"); 5797 int proxyPort = 8080; 5798 if (data.length > 1) { 5799 try { 5800 proxyPort = Integer.parseInt(data[1]); 5801 } catch (NumberFormatException e) {} 5802 } 5803 exclusionList = exclusionList.trim(); 5804 5805 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 5806 if (!proxyProperties.isValid()) { 5807 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 5808 return; 5809 } 5810 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 5811 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 5812 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 5813 exclusionList); 5814 } 5815 5816 /** 5817 * Set the storage encryption request for a single admin. Returns the new total request 5818 * status (for all admins). 5819 */ 5820 @Override 5821 public int setStorageEncryption(ComponentName who, boolean encrypt) { 5822 if (!mHasFeature) { 5823 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5824 } 5825 Preconditions.checkNotNull(who, "ComponentName is null"); 5826 final int userHandle = UserHandle.getCallingUserId(); 5827 synchronized (this) { 5828 // Check for permissions 5829 // Only system user can set storage encryption 5830 if (userHandle != UserHandle.USER_SYSTEM) { 5831 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User " 5832 + UserHandle.getCallingUserId() + " is not permitted."); 5833 return 0; 5834 } 5835 5836 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5837 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 5838 5839 // Quick exit: If the filesystem does not support encryption, we can exit early. 5840 if (!isEncryptionSupported()) { 5841 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5842 } 5843 5844 // (1) Record the value for the admin so it's sticky 5845 if (ap.encryptionRequested != encrypt) { 5846 ap.encryptionRequested = encrypt; 5847 saveSettingsLocked(userHandle); 5848 } 5849 5850 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5851 // (2) Compute "max" for all admins 5852 boolean newRequested = false; 5853 final int N = policy.mAdminList.size(); 5854 for (int i = 0; i < N; i++) { 5855 newRequested |= policy.mAdminList.get(i).encryptionRequested; 5856 } 5857 5858 // Notify OS of new request 5859 setEncryptionRequested(newRequested); 5860 5861 // Return the new global request status 5862 return newRequested 5863 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 5864 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 5865 } 5866 } 5867 5868 /** 5869 * Get the current storage encryption request status for a given admin, or aggregate of all 5870 * active admins. 5871 */ 5872 @Override 5873 public boolean getStorageEncryption(ComponentName who, int userHandle) { 5874 if (!mHasFeature) { 5875 return false; 5876 } 5877 enforceFullCrossUsersPermission(userHandle); 5878 synchronized (this) { 5879 // Check for permissions if a particular caller is specified 5880 if (who != null) { 5881 // When checking for a single caller, status is based on caller's request 5882 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 5883 return ap != null ? ap.encryptionRequested : false; 5884 } 5885 5886 // If no particular caller is specified, return the aggregate set of requests. 5887 // This is short circuited by returning true on the first hit. 5888 DevicePolicyData policy = getUserData(userHandle); 5889 final int N = policy.mAdminList.size(); 5890 for (int i = 0; i < N; i++) { 5891 if (policy.mAdminList.get(i).encryptionRequested) { 5892 return true; 5893 } 5894 } 5895 return false; 5896 } 5897 } 5898 5899 /** 5900 * Get the current encryption status of the device. 5901 */ 5902 @Override 5903 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 5904 if (!mHasFeature) { 5905 // Ok to return current status. 5906 } 5907 enforceFullCrossUsersPermission(userHandle); 5908 5909 // It's not critical here, but let's make sure the package name is correct, in case 5910 // we start using it for different purposes. 5911 ensureCallerPackage(callerPackage); 5912 5913 final ApplicationInfo ai; 5914 try { 5915 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 5916 } catch (RemoteException e) { 5917 throw new SecurityException(e); 5918 } 5919 5920 boolean legacyApp = false; 5921 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 5922 legacyApp = true; 5923 } 5924 5925 final int rawStatus = getEncryptionStatus(); 5926 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 5927 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 5928 } 5929 return rawStatus; 5930 } 5931 5932 /** 5933 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 5934 */ 5935 private boolean isEncryptionSupported() { 5936 // Note, this can be implemented as 5937 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5938 // But is provided as a separate internal method if there's a faster way to do a 5939 // simple check for supported-or-not. 5940 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5941 } 5942 5943 /** 5944 * Hook to low-levels: Reporting the current status of encryption. 5945 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 5946 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 5947 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 5948 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or 5949 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 5950 */ 5951 private int getEncryptionStatus() { 5952 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5953 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 5954 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) { 5955 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 5956 } else if (mInjector.storageManagerIsEncrypted()) { 5957 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 5958 } else if (mInjector.storageManagerIsEncryptable()) { 5959 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 5960 } else { 5961 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5962 } 5963 } 5964 5965 /** 5966 * Hook to low-levels: If needed, record the new admin setting for encryption. 5967 */ 5968 private void setEncryptionRequested(boolean encrypt) { 5969 } 5970 5971 /** 5972 * Set whether the screen capture is disabled for the user managed by the specified admin. 5973 */ 5974 @Override 5975 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) { 5976 if (!mHasFeature) { 5977 return; 5978 } 5979 Preconditions.checkNotNull(who, "ComponentName is null"); 5980 final int userHandle = UserHandle.getCallingUserId(); 5981 synchronized (this) { 5982 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5983 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5984 if (ap.disableScreenCapture != disabled) { 5985 ap.disableScreenCapture = disabled; 5986 saveSettingsLocked(userHandle); 5987 updateScreenCaptureDisabledInWindowManager(userHandle, disabled); 5988 } 5989 } 5990 } 5991 5992 /** 5993 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 5994 * active admin (if given admin is null). 5995 */ 5996 @Override 5997 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) { 5998 if (!mHasFeature) { 5999 return false; 6000 } 6001 synchronized (this) { 6002 if (who != null) { 6003 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 6004 return (admin != null) ? admin.disableScreenCapture : false; 6005 } 6006 6007 DevicePolicyData policy = getUserData(userHandle); 6008 final int N = policy.mAdminList.size(); 6009 for (int i = 0; i < N; i++) { 6010 ActiveAdmin admin = policy.mAdminList.get(i); 6011 if (admin.disableScreenCapture) { 6012 return true; 6013 } 6014 } 6015 return false; 6016 } 6017 } 6018 6019 private void updateScreenCaptureDisabledInWindowManager(final int userHandle, 6020 final boolean disabled) { 6021 mHandler.post(new Runnable() { 6022 @Override 6023 public void run() { 6024 try { 6025 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled); 6026 } catch (RemoteException e) { 6027 Log.w(LOG_TAG, "Unable to notify WindowManager.", e); 6028 } 6029 } 6030 }); 6031 } 6032 6033 /** 6034 * Set whether auto time is required by the specified admin (must be device or profile owner). 6035 */ 6036 @Override 6037 public void setAutoTimeRequired(ComponentName who, boolean required) { 6038 if (!mHasFeature) { 6039 return; 6040 } 6041 Preconditions.checkNotNull(who, "ComponentName is null"); 6042 final int userHandle = UserHandle.getCallingUserId(); 6043 synchronized (this) { 6044 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6045 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6046 if (admin.requireAutoTime != required) { 6047 admin.requireAutoTime = required; 6048 saveSettingsLocked(userHandle); 6049 } 6050 } 6051 6052 // Turn AUTO_TIME on in settings if it is required 6053 if (required) { 6054 long ident = mInjector.binderClearCallingIdentity(); 6055 try { 6056 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */); 6057 } finally { 6058 mInjector.binderRestoreCallingIdentity(ident); 6059 } 6060 } 6061 } 6062 6063 /** 6064 * Returns whether or not auto time is required by the device owner or any profile owner. 6065 */ 6066 @Override 6067 public boolean getAutoTimeRequired() { 6068 if (!mHasFeature) { 6069 return false; 6070 } 6071 synchronized (this) { 6072 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6073 if (deviceOwner != null && deviceOwner.requireAutoTime) { 6074 // If the device owner enforces auto time, we don't need to check the PO's 6075 return true; 6076 } 6077 6078 // Now check to see if any profile owner on any user enforces auto time 6079 for (Integer userId : mOwners.getProfileOwnerKeys()) { 6080 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 6081 if (profileOwner != null && profileOwner.requireAutoTime) { 6082 return true; 6083 } 6084 } 6085 6086 return false; 6087 } 6088 } 6089 6090 @Override 6091 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 6092 if (!mHasFeature) { 6093 return; 6094 } 6095 Preconditions.checkNotNull(who, "ComponentName is null"); 6096 // Allow setting this policy to true only if there is a split system user. 6097 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) { 6098 throw new UnsupportedOperationException( 6099 "Cannot force ephemeral users on systems without split system user."); 6100 } 6101 boolean removeAllUsers = false; 6102 synchronized (this) { 6103 final ActiveAdmin deviceOwner = 6104 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6105 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) { 6106 deviceOwner.forceEphemeralUsers = forceEphemeralUsers; 6107 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 6108 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers); 6109 removeAllUsers = forceEphemeralUsers; 6110 } 6111 } 6112 if (removeAllUsers) { 6113 long identitity = mInjector.binderClearCallingIdentity(); 6114 try { 6115 mUserManagerInternal.removeAllUsers(); 6116 } finally { 6117 mInjector.binderRestoreCallingIdentity(identitity); 6118 } 6119 } 6120 } 6121 6122 @Override 6123 public boolean getForceEphemeralUsers(ComponentName who) { 6124 if (!mHasFeature) { 6125 return false; 6126 } 6127 Preconditions.checkNotNull(who, "ComponentName is null"); 6128 synchronized (this) { 6129 final ActiveAdmin deviceOwner = 6130 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6131 return deviceOwner.forceEphemeralUsers; 6132 } 6133 } 6134 6135 private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException { 6136 synchronized (this) { 6137 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6138 if (!areAllUsersAffiliatedWithDeviceLocked()) { 6139 throw new SecurityException("Not all users are affiliated."); 6140 } 6141 } 6142 } 6143 6144 @Override 6145 public boolean requestBugreport(ComponentName who) { 6146 if (!mHasFeature) { 6147 return false; 6148 } 6149 Preconditions.checkNotNull(who, "ComponentName is null"); 6150 6151 // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport 6152 // which could still contain data related to that user. Should we disallow that, e.g. until 6153 // next boot? Might not be needed given that this still requires user consent. 6154 ensureDeviceOwnerAndAllUsersAffiliated(who); 6155 6156 if (mRemoteBugreportServiceIsActive.get() 6157 || (getDeviceOwnerRemoteBugreportUri() != null)) { 6158 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running."); 6159 return false; 6160 } 6161 6162 final long currentTime = System.currentTimeMillis(); 6163 synchronized (this) { 6164 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 6165 if (currentTime > policyData.mLastBugReportRequestTime) { 6166 policyData.mLastBugReportRequestTime = currentTime; 6167 saveSettingsLocked(UserHandle.USER_SYSTEM); 6168 } 6169 } 6170 6171 final long callingIdentity = mInjector.binderClearCallingIdentity(); 6172 try { 6173 mInjector.getIActivityManager().requestBugReport( 6174 ActivityManager.BUGREPORT_OPTION_REMOTE); 6175 6176 mRemoteBugreportServiceIsActive.set(true); 6177 mRemoteBugreportSharingAccepted.set(false); 6178 registerRemoteBugreportReceivers(); 6179 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, 6180 RemoteBugreportUtils.NOTIFICATION_ID, 6181 RemoteBugreportUtils.buildNotification(mContext, 6182 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL); 6183 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable, 6184 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS); 6185 return true; 6186 } catch (RemoteException re) { 6187 // should never happen 6188 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re); 6189 return false; 6190 } finally { 6191 mInjector.binderRestoreCallingIdentity(callingIdentity); 6192 } 6193 } 6194 6195 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) { 6196 Intent intent = new Intent(action); 6197 intent.setComponent(mOwners.getDeviceOwnerComponent()); 6198 if (extras != null) { 6199 intent.putExtras(extras); 6200 } 6201 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 6202 } 6203 6204 private synchronized String getDeviceOwnerRemoteBugreportUri() { 6205 return mOwners.getDeviceOwnerRemoteBugreportUri(); 6206 } 6207 6208 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, 6209 String bugreportHash) { 6210 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 6211 } 6212 6213 private void registerRemoteBugreportReceivers() { 6214 try { 6215 IntentFilter filterFinished = new IntentFilter( 6216 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH, 6217 RemoteBugreportUtils.BUGREPORT_MIMETYPE); 6218 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished); 6219 } catch (IntentFilter.MalformedMimeTypeException e) { 6220 // should never happen, as setting a constant 6221 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e); 6222 } 6223 IntentFilter filterConsent = new IntentFilter(); 6224 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 6225 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 6226 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 6227 } 6228 6229 private void onBugreportFinished(Intent intent) { 6230 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 6231 mRemoteBugreportServiceIsActive.set(false); 6232 Uri bugreportUri = intent.getData(); 6233 String bugreportUriString = null; 6234 if (bugreportUri != null) { 6235 bugreportUriString = bugreportUri.toString(); 6236 } 6237 String bugreportHash = intent.getStringExtra( 6238 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH); 6239 if (mRemoteBugreportSharingAccepted.get()) { 6240 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 6241 mInjector.getNotificationManager().cancel(LOG_TAG, 6242 RemoteBugreportUtils.NOTIFICATION_ID); 6243 } else { 6244 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash); 6245 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 6246 RemoteBugreportUtils.buildNotification(mContext, 6247 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 6248 UserHandle.ALL); 6249 } 6250 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6251 } 6252 6253 private void onBugreportFailed() { 6254 mRemoteBugreportServiceIsActive.set(false); 6255 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 6256 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 6257 mRemoteBugreportSharingAccepted.set(false); 6258 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6259 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID); 6260 Bundle extras = new Bundle(); 6261 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 6262 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING); 6263 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 6264 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 6265 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6266 } 6267 6268 private void onBugreportSharingAccepted() { 6269 mRemoteBugreportSharingAccepted.set(true); 6270 String bugreportUriString = null; 6271 String bugreportHash = null; 6272 synchronized (this) { 6273 bugreportUriString = getDeviceOwnerRemoteBugreportUri(); 6274 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash(); 6275 } 6276 if (bugreportUriString != null) { 6277 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 6278 } else if (mRemoteBugreportServiceIsActive.get()) { 6279 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 6280 RemoteBugreportUtils.buildNotification(mContext, 6281 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED), 6282 UserHandle.ALL); 6283 } 6284 } 6285 6286 private void onBugreportSharingDeclined() { 6287 if (mRemoteBugreportServiceIsActive.get()) { 6288 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 6289 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 6290 mRemoteBugreportServiceIsActive.set(false); 6291 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 6292 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6293 } 6294 mRemoteBugreportSharingAccepted.set(false); 6295 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6296 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null); 6297 } 6298 6299 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, 6300 String bugreportHash) { 6301 ParcelFileDescriptor pfd = null; 6302 try { 6303 if (bugreportUriString == null) { 6304 throw new FileNotFoundException(); 6305 } 6306 Uri bugreportUri = Uri.parse(bugreportUriString); 6307 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r"); 6308 6309 synchronized (this) { 6310 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 6311 intent.setComponent(mOwners.getDeviceOwnerComponent()); 6312 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE); 6313 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 6314 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6315 6316 LocalServices.getService(ActivityManagerInternal.class) 6317 .grantUriPermissionFromIntent(Process.SHELL_UID, 6318 mOwners.getDeviceOwnerComponent().getPackageName(), 6319 intent, mOwners.getDeviceOwnerUserId()); 6320 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 6321 } 6322 } catch (FileNotFoundException e) { 6323 Bundle extras = new Bundle(); 6324 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 6325 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE); 6326 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 6327 } finally { 6328 try { 6329 if (pfd != null) { 6330 pfd.close(); 6331 } 6332 } catch (IOException ex) { 6333 // Ignore 6334 } 6335 mRemoteBugreportSharingAccepted.set(false); 6336 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6337 } 6338 } 6339 6340 /** 6341 * Disables all device cameras according to the specified admin. 6342 */ 6343 @Override 6344 public void setCameraDisabled(ComponentName who, boolean disabled) { 6345 if (!mHasFeature) { 6346 return; 6347 } 6348 Preconditions.checkNotNull(who, "ComponentName is null"); 6349 final int userHandle = mInjector.userHandleGetCallingUserId(); 6350 synchronized (this) { 6351 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 6352 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 6353 if (ap.disableCamera != disabled) { 6354 ap.disableCamera = disabled; 6355 saveSettingsLocked(userHandle); 6356 } 6357 } 6358 // Tell the user manager that the restrictions have changed. 6359 pushUserRestrictions(userHandle); 6360 } 6361 6362 /** 6363 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 6364 * active admins. 6365 */ 6366 @Override 6367 public boolean getCameraDisabled(ComponentName who, int userHandle) { 6368 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true); 6369 } 6370 6371 private boolean getCameraDisabled(ComponentName who, int userHandle, 6372 boolean mergeDeviceOwnerRestriction) { 6373 if (!mHasFeature) { 6374 return false; 6375 } 6376 synchronized (this) { 6377 if (who != null) { 6378 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 6379 return (admin != null) ? admin.disableCamera : false; 6380 } 6381 // First, see if DO has set it. If so, it's device-wide. 6382 if (mergeDeviceOwnerRestriction) { 6383 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6384 if (deviceOwner != null && deviceOwner.disableCamera) { 6385 return true; 6386 } 6387 } 6388 6389 // Then check each device admin on the user. 6390 DevicePolicyData policy = getUserData(userHandle); 6391 // Determine whether or not the device camera is disabled for any active admins. 6392 final int N = policy.mAdminList.size(); 6393 for (int i = 0; i < N; i++) { 6394 ActiveAdmin admin = policy.mAdminList.get(i); 6395 if (admin.disableCamera) { 6396 return true; 6397 } 6398 } 6399 return false; 6400 } 6401 } 6402 6403 @Override 6404 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 6405 if (!mHasFeature) { 6406 return; 6407 } 6408 Preconditions.checkNotNull(who, "ComponentName is null"); 6409 final int userHandle = mInjector.userHandleGetCallingUserId(); 6410 if (isManagedProfile(userHandle)) { 6411 if (parent) { 6412 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 6413 } else { 6414 which = which & PROFILE_KEYGUARD_FEATURES; 6415 } 6416 } 6417 synchronized (this) { 6418 ActiveAdmin ap = getActiveAdminForCallerLocked( 6419 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 6420 if (ap.disabledKeyguardFeatures != which) { 6421 ap.disabledKeyguardFeatures = which; 6422 saveSettingsLocked(userHandle); 6423 } 6424 } 6425 } 6426 6427 /** 6428 * Gets the disabled state for features in keyguard for the given admin, 6429 * or the aggregate of all active admins if who is null. 6430 */ 6431 @Override 6432 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 6433 if (!mHasFeature) { 6434 return 0; 6435 } 6436 enforceFullCrossUsersPermission(userHandle); 6437 final long ident = mInjector.binderClearCallingIdentity(); 6438 try { 6439 synchronized (this) { 6440 if (who != null) { 6441 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 6442 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 6443 } 6444 6445 final List<ActiveAdmin> admins; 6446 if (!parent && isManagedProfile(userHandle)) { 6447 // If we are being asked about a managed profile, just return keyguard features 6448 // disabled by admins in the profile. 6449 admins = getUserDataUnchecked(userHandle).mAdminList; 6450 } else { 6451 // Otherwise return those set by admins in the user and its profiles. 6452 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 6453 } 6454 6455 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 6456 final int N = admins.size(); 6457 for (int i = 0; i < N; i++) { 6458 ActiveAdmin admin = admins.get(i); 6459 int userId = admin.getUserHandle().getIdentifier(); 6460 boolean isRequestedUser = !parent && (userId == userHandle); 6461 if (isRequestedUser || !isManagedProfile(userId)) { 6462 // If we are being asked explicitly about this user 6463 // return all disabled features even if its a managed profile. 6464 which |= admin.disabledKeyguardFeatures; 6465 } else { 6466 // Otherwise a managed profile is only allowed to disable 6467 // some features on the parent user. 6468 which |= (admin.disabledKeyguardFeatures 6469 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 6470 } 6471 } 6472 return which; 6473 } 6474 } finally { 6475 mInjector.binderRestoreCallingIdentity(ident); 6476 } 6477 } 6478 6479 @Override 6480 public void setKeepUninstalledPackages(ComponentName who, String callerPackage, 6481 List<String> packageList) { 6482 if (!mHasFeature) { 6483 return; 6484 } 6485 Preconditions.checkNotNull(packageList, "packageList is null"); 6486 final int userHandle = UserHandle.getCallingUserId(); 6487 synchronized (this) { 6488 // Ensure the caller is a DO or a keep uninstalled packages delegate. 6489 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 6490 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 6491 // Get the device owner 6492 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6493 // Set list of packages to be kept even if uninstalled. 6494 deviceOwner.keepUninstalledPackages = packageList; 6495 // Save settings. 6496 saveSettingsLocked(userHandle); 6497 // Notify package manager. 6498 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 6499 } 6500 } 6501 6502 @Override 6503 public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) { 6504 if (!mHasFeature) { 6505 return null; 6506 } 6507 // TODO In split system user mode, allow apps on user 0 to query the list 6508 synchronized (this) { 6509 // Ensure the caller is a DO or a keep uninstalled packages delegate. 6510 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 6511 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 6512 return getKeepUninstalledPackagesLocked(); 6513 } 6514 } 6515 6516 private List<String> getKeepUninstalledPackagesLocked() { 6517 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6518 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 6519 } 6520 6521 @Override 6522 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) { 6523 if (!mHasFeature) { 6524 return false; 6525 } 6526 if (admin == null 6527 || !isPackageInstalledForUser(admin.getPackageName(), userId)) { 6528 throw new IllegalArgumentException("Invalid component " + admin 6529 + " for device owner"); 6530 } 6531 final boolean hasIncompatibleAccountsOrNonAdb = 6532 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin); 6533 synchronized (this) { 6534 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb); 6535 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 6536 if (activeAdmin == null 6537 || getUserData(userId).mRemovingAdmins.contains(admin)) { 6538 throw new IllegalArgumentException("Not active admin: " + admin); 6539 } 6540 6541 // Shutting down backup manager service permanently. 6542 long ident = mInjector.binderClearCallingIdentity(); 6543 try { 6544 if (mInjector.getIBackupManager() != null) { 6545 mInjector.getIBackupManager() 6546 .setBackupServiceActive(UserHandle.USER_SYSTEM, false); 6547 } 6548 } catch (RemoteException e) { 6549 throw new IllegalStateException("Failed deactivating backup service.", e); 6550 } finally { 6551 mInjector.binderRestoreCallingIdentity(ident); 6552 } 6553 6554 if (isAdb()) { 6555 // Log device owner provisioning was started using adb. 6556 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 6557 } 6558 6559 mOwners.setDeviceOwner(admin, ownerName, userId); 6560 mOwners.writeDeviceOwner(); 6561 updateDeviceOwnerLocked(); 6562 setDeviceOwnerSystemPropertyLocked(); 6563 6564 final Set<String> restrictions = 6565 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner(); 6566 if (!restrictions.isEmpty()) { 6567 for (String restriction : restrictions) { 6568 activeAdmin.ensureUserRestrictions().putBoolean(restriction, true); 6569 } 6570 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions); 6571 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions); 6572 6573 saveUserRestrictionsLocked(userId); 6574 } 6575 6576 ident = mInjector.binderClearCallingIdentity(); 6577 try { 6578 // TODO Send to system too? 6579 mContext.sendBroadcastAsUser( 6580 new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED) 6581 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND), 6582 UserHandle.of(userId)); 6583 } finally { 6584 mInjector.binderRestoreCallingIdentity(ident); 6585 } 6586 mDeviceAdminServiceController.startServiceForOwner( 6587 admin.getPackageName(), userId, "set-device-owner"); 6588 6589 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 6590 return true; 6591 } 6592 } 6593 6594 @Override 6595 public boolean hasDeviceOwner() { 6596 enforceDeviceOwnerOrManageUsers(); 6597 return mOwners.hasDeviceOwner(); 6598 } 6599 6600 boolean isDeviceOwner(ActiveAdmin admin) { 6601 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 6602 } 6603 6604 public boolean isDeviceOwner(ComponentName who, int userId) { 6605 synchronized (this) { 6606 return mOwners.hasDeviceOwner() 6607 && mOwners.getDeviceOwnerUserId() == userId 6608 && mOwners.getDeviceOwnerComponent().equals(who); 6609 } 6610 } 6611 6612 private boolean isDeviceOwnerPackage(String packageName, int userId) { 6613 synchronized (this) { 6614 return mOwners.hasDeviceOwner() 6615 && mOwners.getDeviceOwnerUserId() == userId 6616 && mOwners.getDeviceOwnerPackageName().equals(packageName); 6617 } 6618 } 6619 6620 private boolean isProfileOwnerPackage(String packageName, int userId) { 6621 synchronized (this) { 6622 return mOwners.hasProfileOwner(userId) 6623 && mOwners.getProfileOwnerPackage(userId).equals(packageName); 6624 } 6625 } 6626 6627 public boolean isProfileOwner(ComponentName who, int userId) { 6628 final ComponentName profileOwner = getProfileOwner(userId); 6629 return who != null && who.equals(profileOwner); 6630 } 6631 6632 @Override 6633 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 6634 if (!mHasFeature) { 6635 return null; 6636 } 6637 if (!callingUserOnly) { 6638 enforceManageUsers(); 6639 } 6640 synchronized (this) { 6641 if (!mOwners.hasDeviceOwner()) { 6642 return null; 6643 } 6644 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 6645 mOwners.getDeviceOwnerUserId()) { 6646 return null; 6647 } 6648 return mOwners.getDeviceOwnerComponent(); 6649 } 6650 } 6651 6652 @Override 6653 public int getDeviceOwnerUserId() { 6654 if (!mHasFeature) { 6655 return UserHandle.USER_NULL; 6656 } 6657 enforceManageUsers(); 6658 synchronized (this) { 6659 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 6660 } 6661 } 6662 6663 /** 6664 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 6665 * MANAGE_USERS. 6666 */ 6667 @Override 6668 public String getDeviceOwnerName() { 6669 if (!mHasFeature) { 6670 return null; 6671 } 6672 enforceManageUsers(); 6673 synchronized (this) { 6674 if (!mOwners.hasDeviceOwner()) { 6675 return null; 6676 } 6677 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 6678 // Should setDeviceOwner/ProfileOwner still take a name? 6679 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 6680 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 6681 } 6682 } 6683 6684 /** Returns the active device owner or {@code null} if there is no device owner. */ 6685 @VisibleForTesting 6686 ActiveAdmin getDeviceOwnerAdminLocked() { 6687 ComponentName component = mOwners.getDeviceOwnerComponent(); 6688 if (component == null) { 6689 return null; 6690 } 6691 6692 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 6693 final int n = policy.mAdminList.size(); 6694 for (int i = 0; i < n; i++) { 6695 ActiveAdmin admin = policy.mAdminList.get(i); 6696 if (component.equals(admin.info.getComponent())) { 6697 return admin; 6698 } 6699 } 6700 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 6701 return null; 6702 } 6703 6704 @Override 6705 public void clearDeviceOwner(String packageName) { 6706 Preconditions.checkNotNull(packageName, "packageName is null"); 6707 final int callingUid = mInjector.binderGetCallingUid(); 6708 try { 6709 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 6710 UserHandle.getUserId(callingUid)); 6711 if (uid != callingUid) { 6712 throw new SecurityException("Invalid packageName"); 6713 } 6714 } catch (NameNotFoundException e) { 6715 throw new SecurityException(e); 6716 } 6717 synchronized (this) { 6718 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 6719 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 6720 if (!mOwners.hasDeviceOwner() 6721 || !deviceOwnerComponent.getPackageName().equals(packageName) 6722 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) { 6723 throw new SecurityException( 6724 "clearDeviceOwner can only be called by the device owner"); 6725 } 6726 enforceUserUnlocked(deviceOwnerUserId); 6727 6728 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 6729 long ident = mInjector.binderClearCallingIdentity(); 6730 try { 6731 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 6732 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 6733 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED); 6734 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 6735 mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId)); 6736 } finally { 6737 mInjector.binderRestoreCallingIdentity(ident); 6738 } 6739 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 6740 } 6741 } 6742 6743 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 6744 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner"); 6745 6746 if (admin != null) { 6747 admin.disableCamera = false; 6748 admin.userRestrictions = null; 6749 admin.defaultEnabledRestrictionsAlreadySet.clear(); 6750 admin.forceEphemeralUsers = false; 6751 admin.isNetworkLoggingEnabled = false; 6752 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 6753 } 6754 final DevicePolicyData policyData = getUserData(userId); 6755 policyData.mCurrentInputMethodSet = false; 6756 saveSettingsLocked(userId); 6757 final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM); 6758 systemPolicyData.mLastSecurityLogRetrievalTime = -1; 6759 systemPolicyData.mLastBugReportRequestTime = -1; 6760 systemPolicyData.mLastNetworkLogsRetrievalTime = -1; 6761 saveSettingsLocked(UserHandle.USER_SYSTEM); 6762 clearUserPoliciesLocked(userId); 6763 6764 mOwners.clearDeviceOwner(); 6765 mOwners.writeDeviceOwner(); 6766 updateDeviceOwnerLocked(); 6767 6768 clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId)); 6769 mInjector.securityLogSetLoggingEnabledProperty(false); 6770 mSecurityLogMonitor.stop(); 6771 setNetworkLoggingActiveInternal(false); 6772 6773 try { 6774 if (mInjector.getIBackupManager() != null) { 6775 // Reactivate backup service. 6776 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true); 6777 } 6778 } catch (RemoteException e) { 6779 throw new IllegalStateException("Failed reactivating backup service.", e); 6780 } 6781 } 6782 6783 @Override 6784 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 6785 if (!mHasFeature) { 6786 return false; 6787 } 6788 if (who == null 6789 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) { 6790 throw new IllegalArgumentException("Component " + who 6791 + " not installed for userId:" + userHandle); 6792 } 6793 final boolean hasIncompatibleAccountsOrNonAdb = 6794 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who); 6795 synchronized (this) { 6796 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb); 6797 6798 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 6799 if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) { 6800 throw new IllegalArgumentException("Not active admin: " + who); 6801 } 6802 6803 if (isAdb()) { 6804 // Log profile owner provisioning was started using adb. 6805 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 6806 } 6807 6808 mOwners.setProfileOwner(who, ownerName, userHandle); 6809 mOwners.writeProfileOwner(userHandle); 6810 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 6811 6812 final long id = mInjector.binderClearCallingIdentity(); 6813 try { 6814 if (mUserManager.isManagedProfile(userHandle)) { 6815 maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin, 6816 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 6817 ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin, 6818 true /* newOwner */); 6819 } 6820 } finally { 6821 mInjector.binderRestoreCallingIdentity(id); 6822 } 6823 mDeviceAdminServiceController.startServiceForOwner( 6824 who.getPackageName(), userHandle, "set-profile-owner"); 6825 return true; 6826 } 6827 } 6828 6829 @Override 6830 public void clearProfileOwner(ComponentName who) { 6831 if (!mHasFeature) { 6832 return; 6833 } 6834 Preconditions.checkNotNull(who, "ComponentName is null"); 6835 6836 final int userId = mInjector.userHandleGetCallingUserId(); 6837 enforceNotManagedProfile(userId, "clear profile owner"); 6838 enforceUserUnlocked(userId); 6839 synchronized (this) { 6840 // Check if this is the profile owner who is calling 6841 final ActiveAdmin admin = 6842 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6843 6844 final long ident = mInjector.binderClearCallingIdentity(); 6845 try { 6846 clearProfileOwnerLocked(admin, userId); 6847 removeActiveAdminLocked(who, userId); 6848 } finally { 6849 mInjector.binderRestoreCallingIdentity(ident); 6850 } 6851 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 6852 } 6853 } 6854 6855 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 6856 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner"); 6857 6858 if (admin != null) { 6859 admin.disableCamera = false; 6860 admin.userRestrictions = null; 6861 admin.defaultEnabledRestrictionsAlreadySet.clear(); 6862 } 6863 final DevicePolicyData policyData = getUserData(userId); 6864 policyData.mCurrentInputMethodSet = false; 6865 policyData.mOwnerInstalledCaCerts.clear(); 6866 saveSettingsLocked(userId); 6867 clearUserPoliciesLocked(userId); 6868 mOwners.removeProfileOwner(userId); 6869 mOwners.writeProfileOwner(userId); 6870 } 6871 6872 @Override 6873 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 6874 Preconditions.checkNotNull(who, "ComponentName is null"); 6875 if (!mHasFeature) { 6876 return; 6877 } 6878 6879 synchronized (this) { 6880 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6881 long token = mInjector.binderClearCallingIdentity(); 6882 try { 6883 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null); 6884 } finally { 6885 mInjector.binderRestoreCallingIdentity(token); 6886 } 6887 } 6888 } 6889 6890 @Override 6891 public CharSequence getDeviceOwnerLockScreenInfo() { 6892 return mLockPatternUtils.getDeviceOwnerInfo(); 6893 } 6894 6895 private void clearUserPoliciesLocked(int userId) { 6896 // Reset some of the user-specific policies. 6897 final DevicePolicyData policy = getUserData(userId); 6898 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 6899 // Clear delegations. 6900 policy.mDelegationMap.clear(); 6901 policy.mStatusBarDisabled = false; 6902 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 6903 policy.mAffiliationIds.clear(); 6904 policy.mLockTaskPackages.clear(); 6905 saveSettingsLocked(userId); 6906 6907 try { 6908 mIPackageManager.updatePermissionFlagsForAllApps( 6909 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 6910 0 /* flagValues */, userId); 6911 pushUserRestrictions(userId); 6912 } catch (RemoteException re) { 6913 // Shouldn't happen. 6914 } 6915 } 6916 6917 @Override 6918 public boolean hasUserSetupCompleted() { 6919 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 6920 } 6921 6922 // This checks only if the Setup Wizard has run. Since Wear devices pair before 6923 // completing Setup Wizard, and pairing involves transferring user data, calling 6924 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). 6925 private boolean hasUserSetupCompleted(int userHandle) { 6926 if (!mHasFeature) { 6927 return true; 6928 } 6929 return getUserData(userHandle).mUserSetupComplete; 6930 } 6931 6932 private boolean hasPaired(int userHandle) { 6933 if (!mHasFeature) { 6934 return true; 6935 } 6936 return getUserData(userHandle).mPaired; 6937 } 6938 6939 @Override 6940 public int getUserProvisioningState() { 6941 if (!mHasFeature) { 6942 return DevicePolicyManager.STATE_USER_UNMANAGED; 6943 } 6944 int userHandle = mInjector.userHandleGetCallingUserId(); 6945 return getUserProvisioningState(userHandle); 6946 } 6947 6948 private int getUserProvisioningState(int userHandle) { 6949 return getUserData(userHandle).mUserProvisioningState; 6950 } 6951 6952 @Override 6953 public void setUserProvisioningState(int newState, int userHandle) { 6954 if (!mHasFeature) { 6955 return; 6956 } 6957 6958 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle) 6959 && getManagedUserId(userHandle) == -1) { 6960 // No managed device, user or profile, so setting provisioning state makes no sense. 6961 throw new IllegalStateException("Not allowed to change provisioning state unless a " 6962 + "device or profile owner is set."); 6963 } 6964 6965 synchronized (this) { 6966 boolean transitionCheckNeeded = true; 6967 6968 // Calling identity/permission checks. 6969 if (isAdb()) { 6970 // ADB shell can only move directly from un-managed to finalized as part of directly 6971 // setting profile-owner or device-owner. 6972 if (getUserProvisioningState(userHandle) != 6973 DevicePolicyManager.STATE_USER_UNMANAGED 6974 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 6975 throw new IllegalStateException("Not allowed to change provisioning state " 6976 + "unless current provisioning state is unmanaged, and new state is " 6977 + "finalized."); 6978 } 6979 transitionCheckNeeded = false; 6980 } else { 6981 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS. 6982 enforceCanManageProfileAndDeviceOwners(); 6983 } 6984 6985 final DevicePolicyData policyData = getUserData(userHandle); 6986 if (transitionCheckNeeded) { 6987 // Optional state transition check for non-ADB case. 6988 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState); 6989 } 6990 policyData.mUserProvisioningState = newState; 6991 saveSettingsLocked(userHandle); 6992 } 6993 } 6994 6995 private void checkUserProvisioningStateTransition(int currentState, int newState) { 6996 // Valid transitions for normal use-cases. 6997 switch (currentState) { 6998 case DevicePolicyManager.STATE_USER_UNMANAGED: 6999 // Can move to any state from unmanaged (except itself as an edge case).. 7000 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 7001 return; 7002 } 7003 break; 7004 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 7005 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 7006 // Can only move to finalized from these states. 7007 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 7008 return; 7009 } 7010 break; 7011 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 7012 // Current user has a managed-profile, but current user is not managed, so 7013 // rather than moving to finalized state, go back to unmanaged once 7014 // profile provisioning is complete. 7015 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 7016 return; 7017 } 7018 break; 7019 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED: 7020 // Cannot transition out of finalized. 7021 break; 7022 } 7023 7024 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 7025 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 7026 + "from state [" + currentState + "]"); 7027 } 7028 7029 @Override 7030 public void setProfileEnabled(ComponentName who) { 7031 if (!mHasFeature) { 7032 return; 7033 } 7034 Preconditions.checkNotNull(who, "ComponentName is null"); 7035 synchronized (this) { 7036 // Check if this is the profile owner who is calling 7037 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7038 final int userId = UserHandle.getCallingUserId(); 7039 enforceManagedProfile(userId, "enable the profile"); 7040 // Check if the profile is already enabled. 7041 UserInfo managedProfile = getUserInfo(userId); 7042 if (managedProfile.isEnabled()) { 7043 Slog.e(LOG_TAG, 7044 "setProfileEnabled is called when the profile is already enabled"); 7045 return; 7046 } 7047 long id = mInjector.binderClearCallingIdentity(); 7048 try { 7049 mUserManager.setUserEnabled(userId); 7050 UserInfo parent = mUserManager.getProfileParent(userId); 7051 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 7052 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 7053 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 7054 Intent.FLAG_RECEIVER_FOREGROUND); 7055 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id)); 7056 } finally { 7057 mInjector.binderRestoreCallingIdentity(id); 7058 } 7059 } 7060 } 7061 7062 @Override 7063 public void setProfileName(ComponentName who, String profileName) { 7064 Preconditions.checkNotNull(who, "ComponentName is null"); 7065 int userId = UserHandle.getCallingUserId(); 7066 // Check if this is the profile owner (includes device owner). 7067 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7068 7069 long id = mInjector.binderClearCallingIdentity(); 7070 try { 7071 mUserManager.setUserName(userId, profileName); 7072 } finally { 7073 mInjector.binderRestoreCallingIdentity(id); 7074 } 7075 } 7076 7077 @Override 7078 public ComponentName getProfileOwner(int userHandle) { 7079 if (!mHasFeature) { 7080 return null; 7081 } 7082 7083 synchronized (this) { 7084 return mOwners.getProfileOwnerComponent(userHandle); 7085 } 7086 } 7087 7088 // Returns the active profile owner for this user or null if the current user has no 7089 // profile owner. 7090 @VisibleForTesting 7091 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 7092 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 7093 if (profileOwner == null) { 7094 return null; 7095 } 7096 DevicePolicyData policy = getUserData(userHandle); 7097 final int n = policy.mAdminList.size(); 7098 for (int i = 0; i < n; i++) { 7099 ActiveAdmin admin = policy.mAdminList.get(i); 7100 if (profileOwner.equals(admin.info.getComponent())) { 7101 return admin; 7102 } 7103 } 7104 return null; 7105 } 7106 7107 @Override 7108 public String getProfileOwnerName(int userHandle) { 7109 if (!mHasFeature) { 7110 return null; 7111 } 7112 enforceManageUsers(); 7113 ComponentName profileOwner = getProfileOwner(userHandle); 7114 if (profileOwner == null) { 7115 return null; 7116 } 7117 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 7118 } 7119 7120 /** 7121 * Canonical name for a given package. 7122 */ 7123 private String getApplicationLabel(String packageName, int userHandle) { 7124 long token = mInjector.binderClearCallingIdentity(); 7125 try { 7126 final Context userContext; 7127 try { 7128 UserHandle handle = new UserHandle(userHandle); 7129 userContext = mContext.createPackageContextAsUser(packageName, 0, handle); 7130 } catch (PackageManager.NameNotFoundException nnfe) { 7131 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe); 7132 return null; 7133 } 7134 ApplicationInfo appInfo = userContext.getApplicationInfo(); 7135 CharSequence result = null; 7136 if (appInfo != null) { 7137 PackageManager pm = userContext.getPackageManager(); 7138 result = pm.getApplicationLabel(appInfo); 7139 } 7140 return result != null ? result.toString() : null; 7141 } finally { 7142 mInjector.binderRestoreCallingIdentity(token); 7143 } 7144 } 7145 7146 /** 7147 * Calls wtfStack() if called with the DPMS lock held. 7148 */ 7149 private void wtfIfInLock() { 7150 if (Thread.holdsLock(this)) { 7151 Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held"); 7152 } 7153 } 7154 7155 /** 7156 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 7157 * permission. 7158 * The profile owner can only be set before the user setup phase has completed, 7159 * except for: 7160 * - SYSTEM_UID 7161 * - adb unless hasIncompatibleAccountsOrNonAdb is true. 7162 */ 7163 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle, 7164 boolean hasIncompatibleAccountsOrNonAdb) { 7165 UserInfo info = getUserInfo(userHandle); 7166 if (info == null) { 7167 // User doesn't exist. 7168 throw new IllegalArgumentException( 7169 "Attempted to set profile owner for invalid userId: " + userHandle); 7170 } 7171 if (info.isGuest()) { 7172 throw new IllegalStateException("Cannot set a profile owner on a guest"); 7173 } 7174 if (mOwners.hasProfileOwner(userHandle)) { 7175 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 7176 + "is already set."); 7177 } 7178 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 7179 throw new IllegalStateException("Trying to set the profile owner, but the user " 7180 + "already has a device owner."); 7181 } 7182 if (isAdb()) { 7183 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 7184 && hasIncompatibleAccountsOrNonAdb) { 7185 throw new IllegalStateException("Not allowed to set the profile owner because " 7186 + "there are already some accounts on the profile"); 7187 } 7188 return; 7189 } 7190 enforceCanManageProfileAndDeviceOwners(); 7191 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) { 7192 throw new IllegalStateException("Cannot set the profile owner on a user which is " 7193 + "already set-up"); 7194 } 7195 } 7196 7197 /** 7198 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 7199 * permission. 7200 */ 7201 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId, 7202 boolean hasIncompatibleAccountsOrNonAdb) { 7203 if (!isAdb()) { 7204 enforceCanManageProfileAndDeviceOwners(); 7205 } 7206 7207 final int code = checkDeviceOwnerProvisioningPreConditionLocked( 7208 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb); 7209 switch (code) { 7210 case CODE_OK: 7211 return; 7212 case CODE_HAS_DEVICE_OWNER: 7213 throw new IllegalStateException( 7214 "Trying to set the device owner, but device owner is already set."); 7215 case CODE_USER_HAS_PROFILE_OWNER: 7216 throw new IllegalStateException("Trying to set the device owner, but the user " 7217 + "already has a profile owner."); 7218 case CODE_USER_NOT_RUNNING: 7219 throw new IllegalStateException("User not running: " + userId); 7220 case CODE_NOT_SYSTEM_USER: 7221 throw new IllegalStateException("User is not system user"); 7222 case CODE_USER_SETUP_COMPLETED: 7223 throw new IllegalStateException( 7224 "Cannot set the device owner if the device is already set-up"); 7225 case CODE_NONSYSTEM_USER_EXISTS: 7226 throw new IllegalStateException("Not allowed to set the device owner because there " 7227 + "are already several users on the device"); 7228 case CODE_ACCOUNTS_NOT_EMPTY: 7229 throw new IllegalStateException("Not allowed to set the device owner because there " 7230 + "are already some accounts on the device"); 7231 case CODE_HAS_PAIRED: 7232 throw new IllegalStateException("Not allowed to set the device owner because this " 7233 + "device has already paired"); 7234 default: 7235 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code); 7236 } 7237 } 7238 7239 private void enforceUserUnlocked(int userId) { 7240 // Since we're doing this operation on behalf of an app, we only 7241 // want to use the actual "unlocked" state. 7242 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 7243 "User must be running and unlocked"); 7244 } 7245 7246 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 7247 if (parent) { 7248 enforceUserUnlocked(getProfileParentId(userId)); 7249 } else { 7250 enforceUserUnlocked(userId); 7251 } 7252 } 7253 7254 private void enforceManageUsers() { 7255 final int callingUid = mInjector.binderGetCallingUid(); 7256 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 7257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7258 } 7259 } 7260 7261 private void enforceFullCrossUsersPermission(int userHandle) { 7262 enforceSystemUserOrPermissionIfCrossUser(userHandle, 7263 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 7264 } 7265 7266 private void enforceCrossUsersPermission(int userHandle) { 7267 enforceSystemUserOrPermissionIfCrossUser(userHandle, 7268 android.Manifest.permission.INTERACT_ACROSS_USERS); 7269 } 7270 7271 private void enforceSystemUserOrPermission(String permission) { 7272 if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) { 7273 mContext.enforceCallingOrSelfPermission(permission, 7274 "Must be system or have " + permission + " permission"); 7275 } 7276 } 7277 7278 private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) { 7279 if (userHandle < 0) { 7280 throw new IllegalArgumentException("Invalid userId " + userHandle); 7281 } 7282 if (userHandle == mInjector.userHandleGetCallingUserId()) { 7283 return; 7284 } 7285 enforceSystemUserOrPermission(permission); 7286 } 7287 7288 private void enforceManagedProfile(int userHandle, String message) { 7289 if(!isManagedProfile(userHandle)) { 7290 throw new SecurityException("You can not " + message + " outside a managed profile."); 7291 } 7292 } 7293 7294 private void enforceNotManagedProfile(int userHandle, String message) { 7295 if(isManagedProfile(userHandle)) { 7296 throw new SecurityException("You can not " + message + " for a managed profile."); 7297 } 7298 } 7299 7300 private void enforceDeviceOwnerOrManageUsers() { 7301 synchronized (this) { 7302 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7303 mInjector.binderGetCallingUid()) != null) { 7304 return; 7305 } 7306 } 7307 enforceManageUsers(); 7308 } 7309 7310 private void enforceProfileOwnerOrSystemUser() { 7311 synchronized (this) { 7312 if (getActiveAdminWithPolicyForUidLocked(null, 7313 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 7314 != null) { 7315 return; 7316 } 7317 } 7318 Preconditions.checkState(isCallerWithSystemUid(), 7319 "Only profile owner, device owner and system may call this method."); 7320 } 7321 7322 private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) { 7323 if (userId == mInjector.userHandleGetCallingUserId()) { 7324 synchronized (this) { 7325 if (getActiveAdminWithPolicyForUidLocked(null, 7326 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 7327 != null) { 7328 // Device Owner/Profile Owner may access the user it runs on. 7329 return; 7330 } 7331 } 7332 } 7333 // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required. 7334 enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 7335 } 7336 7337 private void ensureCallerPackage(@Nullable String packageName) { 7338 if (packageName == null) { 7339 Preconditions.checkState(isCallerWithSystemUid(), 7340 "Only caller can omit package name"); 7341 } else { 7342 final int callingUid = mInjector.binderGetCallingUid(); 7343 final int userId = mInjector.userHandleGetCallingUserId(); 7344 try { 7345 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 7346 packageName, 0, userId); 7347 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name"); 7348 } catch (RemoteException e) { 7349 // Shouldn't happen 7350 } 7351 } 7352 } 7353 7354 private boolean isCallerWithSystemUid() { 7355 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID); 7356 } 7357 7358 protected int getProfileParentId(int userHandle) { 7359 final long ident = mInjector.binderClearCallingIdentity(); 7360 try { 7361 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 7362 return parentUser != null ? parentUser.id : userHandle; 7363 } finally { 7364 mInjector.binderRestoreCallingIdentity(ident); 7365 } 7366 } 7367 7368 private int getCredentialOwner(int userHandle, boolean parent) { 7369 final long ident = mInjector.binderClearCallingIdentity(); 7370 try { 7371 if (parent) { 7372 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 7373 if (parentProfile != null) { 7374 userHandle = parentProfile.id; 7375 } 7376 } 7377 return mUserManager.getCredentialOwnerProfile(userHandle); 7378 } finally { 7379 mInjector.binderRestoreCallingIdentity(ident); 7380 } 7381 } 7382 7383 private boolean isManagedProfile(int userHandle) { 7384 final UserInfo user = getUserInfo(userHandle); 7385 return user != null && user.isManagedProfile(); 7386 } 7387 7388 private void enableIfNecessary(String packageName, int userId) { 7389 try { 7390 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 7391 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId); 7392 if (ai.enabledSetting 7393 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 7394 mIPackageManager.setApplicationEnabledSetting(packageName, 7395 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 7396 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 7397 } 7398 } catch (RemoteException e) { 7399 } 7400 } 7401 7402 @Override 7403 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 7404 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return; 7405 7406 synchronized (this) { 7407 pw.println("Current Device Policy Manager state:"); 7408 7409 mOwners.dump(" ", pw); 7410 mDeviceAdminServiceController.dump(" ", pw); 7411 int userCount = mUserData.size(); 7412 for (int u = 0; u < userCount; u++) { 7413 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 7414 pw.println(); 7415 pw.println(" Enabled Device Admins (User " + policy.mUserHandle 7416 + ", provisioningState: " + policy.mUserProvisioningState + "):"); 7417 final int N = policy.mAdminList.size(); 7418 for (int i=0; i<N; i++) { 7419 ActiveAdmin ap = policy.mAdminList.get(i); 7420 if (ap != null) { 7421 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 7422 pw.println(":"); 7423 ap.dump(" ", pw); 7424 } 7425 } 7426 if (!policy.mRemovingAdmins.isEmpty()) { 7427 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 7428 + policy.mRemovingAdmins); 7429 } 7430 7431 pw.println(" "); 7432 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 7433 } 7434 pw.println(); 7435 mConstants.dump(" ", pw); 7436 pw.println(); 7437 pw.println(" Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 7438 } 7439 } 7440 7441 private String getEncryptionStatusName(int encryptionStatus) { 7442 switch (encryptionStatus) { 7443 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 7444 return "inactive"; 7445 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 7446 return "block default key"; 7447 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 7448 return "block"; 7449 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 7450 return "per-user"; 7451 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 7452 return "unsupported"; 7453 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 7454 return "activating"; 7455 default: 7456 return "unknown"; 7457 } 7458 } 7459 7460 @Override 7461 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 7462 ComponentName activity) { 7463 Preconditions.checkNotNull(who, "ComponentName is null"); 7464 final int userHandle = UserHandle.getCallingUserId(); 7465 synchronized (this) { 7466 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7467 7468 long id = mInjector.binderClearCallingIdentity(); 7469 try { 7470 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 7471 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 7472 } catch (RemoteException re) { 7473 // Shouldn't happen 7474 } finally { 7475 mInjector.binderRestoreCallingIdentity(id); 7476 } 7477 } 7478 } 7479 7480 @Override 7481 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 7482 Preconditions.checkNotNull(who, "ComponentName is null"); 7483 final int userHandle = UserHandle.getCallingUserId(); 7484 synchronized (this) { 7485 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7486 7487 long id = mInjector.binderClearCallingIdentity(); 7488 try { 7489 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 7490 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 7491 } catch (RemoteException re) { 7492 // Shouldn't happen 7493 } finally { 7494 mInjector.binderRestoreCallingIdentity(id); 7495 } 7496 } 7497 } 7498 7499 @Override 7500 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 7501 String packageName) { 7502 try { 7503 setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS); 7504 } catch (IllegalArgumentException e) { 7505 return false; 7506 } 7507 return true; 7508 } 7509 7510 @Override 7511 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 7512 final List<String> delegatePackages = getDelegatePackages(admin, 7513 DELEGATION_APP_RESTRICTIONS); 7514 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 7515 } 7516 7517 @Override 7518 public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) { 7519 return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS); 7520 } 7521 7522 @Override 7523 public void setApplicationRestrictions(ComponentName who, String callerPackage, 7524 String packageName, Bundle settings) { 7525 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 7526 DELEGATION_APP_RESTRICTIONS); 7527 7528 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 7529 final long id = mInjector.binderClearCallingIdentity(); 7530 try { 7531 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 7532 } finally { 7533 mInjector.binderRestoreCallingIdentity(id); 7534 } 7535 } 7536 7537 @Override 7538 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 7539 PersistableBundle args, boolean parent) { 7540 if (!mHasFeature) { 7541 return; 7542 } 7543 Preconditions.checkNotNull(admin, "admin is null"); 7544 Preconditions.checkNotNull(agent, "agent is null"); 7545 final int userHandle = UserHandle.getCallingUserId(); 7546 synchronized (this) { 7547 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 7548 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 7549 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 7550 saveSettingsLocked(userHandle); 7551 } 7552 } 7553 7554 @Override 7555 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 7556 ComponentName agent, int userHandle, boolean parent) { 7557 if (!mHasFeature) { 7558 return null; 7559 } 7560 Preconditions.checkNotNull(agent, "agent null"); 7561 enforceFullCrossUsersPermission(userHandle); 7562 7563 synchronized (this) { 7564 final String componentName = agent.flattenToString(); 7565 if (admin != null) { 7566 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 7567 if (ap == null) return null; 7568 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 7569 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 7570 List<PersistableBundle> result = new ArrayList<>(); 7571 result.add(trustAgentInfo.options); 7572 return result; 7573 } 7574 7575 // Return strictest policy for this user and profiles that are visible from this user. 7576 List<PersistableBundle> result = null; 7577 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 7578 // of the options. If any admin doesn't have options, discard options for the rest 7579 // and return null. 7580 List<ActiveAdmin> admins = 7581 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 7582 boolean allAdminsHaveOptions = true; 7583 final int N = admins.size(); 7584 for (int i = 0; i < N; i++) { 7585 final ActiveAdmin active = admins.get(i); 7586 7587 final boolean disablesTrust = (active.disabledKeyguardFeatures 7588 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 7589 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 7590 if (info != null && info.options != null && !info.options.isEmpty()) { 7591 if (disablesTrust) { 7592 if (result == null) { 7593 result = new ArrayList<>(); 7594 } 7595 result.add(info.options); 7596 } else { 7597 Log.w(LOG_TAG, "Ignoring admin " + active.info 7598 + " because it has trust options but doesn't declare " 7599 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 7600 } 7601 } else if (disablesTrust) { 7602 allAdminsHaveOptions = false; 7603 break; 7604 } 7605 } 7606 return allAdminsHaveOptions ? result : null; 7607 } 7608 } 7609 7610 @Override 7611 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 7612 Preconditions.checkNotNull(who, "ComponentName is null"); 7613 synchronized (this) { 7614 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7615 7616 int userHandle = UserHandle.getCallingUserId(); 7617 DevicePolicyData userData = getUserData(userHandle); 7618 userData.mRestrictionsProvider = permissionProvider; 7619 saveSettingsLocked(userHandle); 7620 } 7621 } 7622 7623 @Override 7624 public ComponentName getRestrictionsProvider(int userHandle) { 7625 synchronized (this) { 7626 if (!isCallerWithSystemUid()) { 7627 throw new SecurityException("Only the system can query the permission provider"); 7628 } 7629 DevicePolicyData userData = getUserData(userHandle); 7630 return userData != null ? userData.mRestrictionsProvider : null; 7631 } 7632 } 7633 7634 @Override 7635 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 7636 Preconditions.checkNotNull(who, "ComponentName is null"); 7637 int callingUserId = UserHandle.getCallingUserId(); 7638 synchronized (this) { 7639 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7640 7641 long id = mInjector.binderClearCallingIdentity(); 7642 try { 7643 UserInfo parent = mUserManager.getProfileParent(callingUserId); 7644 if (parent == null) { 7645 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 7646 + "parent"); 7647 return; 7648 } 7649 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 7650 mIPackageManager.addCrossProfileIntentFilter( 7651 filter, who.getPackageName(), callingUserId, parent.id, 0); 7652 } 7653 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 7654 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 7655 parent.id, callingUserId, 0); 7656 } 7657 } catch (RemoteException re) { 7658 // Shouldn't happen 7659 } finally { 7660 mInjector.binderRestoreCallingIdentity(id); 7661 } 7662 } 7663 } 7664 7665 @Override 7666 public void clearCrossProfileIntentFilters(ComponentName who) { 7667 Preconditions.checkNotNull(who, "ComponentName is null"); 7668 int callingUserId = UserHandle.getCallingUserId(); 7669 synchronized (this) { 7670 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7671 long id = mInjector.binderClearCallingIdentity(); 7672 try { 7673 UserInfo parent = mUserManager.getProfileParent(callingUserId); 7674 if (parent == null) { 7675 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 7676 + "parent"); 7677 return; 7678 } 7679 // Removing those that go from the managed profile to the parent. 7680 mIPackageManager.clearCrossProfileIntentFilters( 7681 callingUserId, who.getPackageName()); 7682 // And those that go from the parent to the managed profile. 7683 // If we want to support multiple managed profiles, we will have to only remove 7684 // those that have callingUserId as their target. 7685 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 7686 } catch (RemoteException re) { 7687 // Shouldn't happen 7688 } finally { 7689 mInjector.binderRestoreCallingIdentity(id); 7690 } 7691 } 7692 } 7693 7694 /** 7695 * @return true if all packages in enabledPackages are either in the list 7696 * permittedList or are a system app. 7697 */ 7698 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 7699 List<String> permittedList, int userIdToCheck) { 7700 long id = mInjector.binderClearCallingIdentity(); 7701 try { 7702 // If we have an enabled packages list for a managed profile the packages 7703 // we should check are installed for the parent user. 7704 UserInfo user = getUserInfo(userIdToCheck); 7705 if (user.isManagedProfile()) { 7706 userIdToCheck = user.profileGroupId; 7707 } 7708 7709 for (String enabledPackage : enabledPackages) { 7710 boolean systemService = false; 7711 try { 7712 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 7713 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 7714 userIdToCheck); 7715 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7716 } catch (RemoteException e) { 7717 Log.i(LOG_TAG, "Can't talk to package managed", e); 7718 } 7719 if (!systemService && !permittedList.contains(enabledPackage)) { 7720 return false; 7721 } 7722 } 7723 } finally { 7724 mInjector.binderRestoreCallingIdentity(id); 7725 } 7726 return true; 7727 } 7728 7729 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 7730 // Not using AccessibilityManager.getInstance because that guesses 7731 // at the user you require based on callingUid and caches for a given 7732 // process. 7733 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 7734 IAccessibilityManager service = iBinder == null 7735 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 7736 return new AccessibilityManager(mContext, service, userId); 7737 } 7738 7739 @Override 7740 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 7741 if (!mHasFeature) { 7742 return false; 7743 } 7744 Preconditions.checkNotNull(who, "ComponentName is null"); 7745 7746 if (packageList != null) { 7747 int userId = UserHandle.getCallingUserId(); 7748 List<AccessibilityServiceInfo> enabledServices = null; 7749 long id = mInjector.binderClearCallingIdentity(); 7750 try { 7751 UserInfo user = getUserInfo(userId); 7752 if (user.isManagedProfile()) { 7753 userId = user.profileGroupId; 7754 } 7755 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 7756 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 7757 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 7758 } finally { 7759 mInjector.binderRestoreCallingIdentity(id); 7760 } 7761 7762 if (enabledServices != null) { 7763 List<String> enabledPackages = new ArrayList<String>(); 7764 for (AccessibilityServiceInfo service : enabledServices) { 7765 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 7766 } 7767 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 7768 userId)) { 7769 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 7770 + "because it contains already enabled accesibility services."); 7771 return false; 7772 } 7773 } 7774 } 7775 7776 synchronized (this) { 7777 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7778 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7779 admin.permittedAccessiblityServices = packageList; 7780 saveSettingsLocked(UserHandle.getCallingUserId()); 7781 } 7782 return true; 7783 } 7784 7785 @Override 7786 public List getPermittedAccessibilityServices(ComponentName who) { 7787 if (!mHasFeature) { 7788 return null; 7789 } 7790 Preconditions.checkNotNull(who, "ComponentName is null"); 7791 7792 synchronized (this) { 7793 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7794 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7795 return admin.permittedAccessiblityServices; 7796 } 7797 } 7798 7799 @Override 7800 public List getPermittedAccessibilityServicesForUser(int userId) { 7801 if (!mHasFeature) { 7802 return null; 7803 } 7804 synchronized (this) { 7805 List<String> result = null; 7806 // If we have multiple profiles we return the intersection of the 7807 // permitted lists. This can happen in cases where we have a device 7808 // and profile owner. 7809 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 7810 for (int profileId : profileIds) { 7811 // Just loop though all admins, only device or profiles 7812 // owners can have permitted lists set. 7813 DevicePolicyData policy = getUserDataUnchecked(profileId); 7814 final int N = policy.mAdminList.size(); 7815 for (int j = 0; j < N; j++) { 7816 ActiveAdmin admin = policy.mAdminList.get(j); 7817 List<String> fromAdmin = admin.permittedAccessiblityServices; 7818 if (fromAdmin != null) { 7819 if (result == null) { 7820 result = new ArrayList<>(fromAdmin); 7821 } else { 7822 result.retainAll(fromAdmin); 7823 } 7824 } 7825 } 7826 } 7827 7828 // If we have a permitted list add all system accessibility services. 7829 if (result != null) { 7830 long id = mInjector.binderClearCallingIdentity(); 7831 try { 7832 UserInfo user = getUserInfo(userId); 7833 if (user.isManagedProfile()) { 7834 userId = user.profileGroupId; 7835 } 7836 AccessibilityManager accessibilityManager = 7837 getAccessibilityManagerForUser(userId); 7838 List<AccessibilityServiceInfo> installedServices = 7839 accessibilityManager.getInstalledAccessibilityServiceList(); 7840 7841 if (installedServices != null) { 7842 for (AccessibilityServiceInfo service : installedServices) { 7843 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 7844 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 7845 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7846 result.add(serviceInfo.packageName); 7847 } 7848 } 7849 } 7850 } finally { 7851 mInjector.binderRestoreCallingIdentity(id); 7852 } 7853 } 7854 7855 return result; 7856 } 7857 } 7858 7859 @Override 7860 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 7861 int userHandle) { 7862 if (!mHasFeature) { 7863 return true; 7864 } 7865 Preconditions.checkNotNull(who, "ComponentName is null"); 7866 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 7867 if (!isCallerWithSystemUid()){ 7868 throw new SecurityException( 7869 "Only the system can query if an accessibility service is disabled by admin"); 7870 } 7871 synchronized (this) { 7872 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7873 if (admin == null) { 7874 return false; 7875 } 7876 if (admin.permittedAccessiblityServices == null) { 7877 return true; 7878 } 7879 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 7880 admin.permittedAccessiblityServices, userHandle); 7881 } 7882 } 7883 7884 private boolean checkCallerIsCurrentUserOrProfile() { 7885 final int callingUserId = UserHandle.getCallingUserId(); 7886 final long token = mInjector.binderClearCallingIdentity(); 7887 try { 7888 UserInfo currentUser; 7889 UserInfo callingUser = getUserInfo(callingUserId); 7890 try { 7891 currentUser = mInjector.getIActivityManager().getCurrentUser(); 7892 } catch (RemoteException e) { 7893 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 7894 return false; 7895 } 7896 7897 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 7898 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 7899 + "of a user that isn't the foreground user."); 7900 return false; 7901 } 7902 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 7903 Slog.e(LOG_TAG, "Cannot set permitted input methods " 7904 + "of a user that isn't the foreground user."); 7905 return false; 7906 } 7907 } finally { 7908 mInjector.binderRestoreCallingIdentity(token); 7909 } 7910 return true; 7911 } 7912 7913 @Override 7914 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 7915 if (!mHasFeature) { 7916 return false; 7917 } 7918 Preconditions.checkNotNull(who, "ComponentName is null"); 7919 7920 // TODO When InputMethodManager supports per user calls remove 7921 // this restriction. 7922 if (!checkCallerIsCurrentUserOrProfile()) { 7923 return false; 7924 } 7925 7926 final int callingUserId = mInjector.userHandleGetCallingUserId(); 7927 if (packageList != null) { 7928 // InputMethodManager fetches input methods for current user. 7929 // So this can only be set when calling user is the current user 7930 // or parent is current user in case of managed profiles. 7931 InputMethodManager inputMethodManager = 7932 mContext.getSystemService(InputMethodManager.class); 7933 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList(); 7934 7935 if (enabledImes != null) { 7936 List<String> enabledPackages = new ArrayList<String>(); 7937 for (InputMethodInfo ime : enabledImes) { 7938 enabledPackages.add(ime.getPackageName()); 7939 } 7940 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 7941 callingUserId)) { 7942 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 7943 + "because it contains already enabled input method."); 7944 return false; 7945 } 7946 } 7947 } 7948 7949 synchronized (this) { 7950 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7951 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7952 admin.permittedInputMethods = packageList; 7953 saveSettingsLocked(callingUserId); 7954 } 7955 return true; 7956 } 7957 7958 @Override 7959 public List getPermittedInputMethods(ComponentName who) { 7960 if (!mHasFeature) { 7961 return null; 7962 } 7963 Preconditions.checkNotNull(who, "ComponentName is null"); 7964 7965 synchronized (this) { 7966 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7967 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7968 return admin.permittedInputMethods; 7969 } 7970 } 7971 7972 @Override 7973 public List getPermittedInputMethodsForCurrentUser() { 7974 UserInfo currentUser; 7975 try { 7976 currentUser = mInjector.getIActivityManager().getCurrentUser(); 7977 } catch (RemoteException e) { 7978 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e); 7979 // Activity managed is dead, just allow all IMEs 7980 return null; 7981 } 7982 7983 int userId = currentUser.id; 7984 synchronized (this) { 7985 List<String> result = null; 7986 // If we have multiple profiles we return the intersection of the 7987 // permitted lists. This can happen in cases where we have a device 7988 // and profile owner. 7989 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 7990 for (int profileId : profileIds) { 7991 // Just loop though all admins, only device or profiles 7992 // owners can have permitted lists set. 7993 DevicePolicyData policy = getUserDataUnchecked(profileId); 7994 final int N = policy.mAdminList.size(); 7995 for (int j = 0; j < N; j++) { 7996 ActiveAdmin admin = policy.mAdminList.get(j); 7997 List<String> fromAdmin = admin.permittedInputMethods; 7998 if (fromAdmin != null) { 7999 if (result == null) { 8000 result = new ArrayList<String>(fromAdmin); 8001 } else { 8002 result.retainAll(fromAdmin); 8003 } 8004 } 8005 } 8006 } 8007 8008 // If we have a permitted list add all system input methods. 8009 if (result != null) { 8010 InputMethodManager inputMethodManager = 8011 mContext.getSystemService(InputMethodManager.class); 8012 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList(); 8013 long id = mInjector.binderClearCallingIdentity(); 8014 try { 8015 if (imes != null) { 8016 for (InputMethodInfo ime : imes) { 8017 ServiceInfo serviceInfo = ime.getServiceInfo(); 8018 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 8019 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8020 result.add(serviceInfo.packageName); 8021 } 8022 } 8023 } 8024 } finally { 8025 mInjector.binderRestoreCallingIdentity(id); 8026 } 8027 } 8028 return result; 8029 } 8030 } 8031 8032 @Override 8033 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 8034 int userHandle) { 8035 if (!mHasFeature) { 8036 return true; 8037 } 8038 Preconditions.checkNotNull(who, "ComponentName is null"); 8039 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 8040 if (!isCallerWithSystemUid()) { 8041 throw new SecurityException( 8042 "Only the system can query if an input method is disabled by admin"); 8043 } 8044 synchronized (this) { 8045 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 8046 if (admin == null) { 8047 return false; 8048 } 8049 if (admin.permittedInputMethods == null) { 8050 return true; 8051 } 8052 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 8053 admin.permittedInputMethods, userHandle); 8054 } 8055 } 8056 8057 @Override 8058 public boolean setPermittedCrossProfileNotificationListeners( 8059 ComponentName who, List<String> packageList) { 8060 if (!mHasFeature) { 8061 return false; 8062 } 8063 Preconditions.checkNotNull(who, "ComponentName is null"); 8064 8065 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8066 if (!isManagedProfile(callingUserId)) { 8067 return false; 8068 } 8069 8070 synchronized (this) { 8071 ActiveAdmin admin = getActiveAdminForCallerLocked( 8072 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8073 admin.permittedNotificationListeners = packageList; 8074 saveSettingsLocked(callingUserId); 8075 } 8076 return true; 8077 } 8078 8079 @Override 8080 public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) { 8081 if (!mHasFeature) { 8082 return null; 8083 } 8084 Preconditions.checkNotNull(who, "ComponentName is null"); 8085 8086 synchronized (this) { 8087 ActiveAdmin admin = getActiveAdminForCallerLocked( 8088 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8089 return admin.permittedNotificationListeners; 8090 } 8091 } 8092 8093 @Override 8094 public boolean isNotificationListenerServicePermitted(String packageName, int userId) { 8095 if (!mHasFeature) { 8096 return true; 8097 } 8098 8099 Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty"); 8100 if (!isCallerWithSystemUid()) { 8101 throw new SecurityException( 8102 "Only the system can query if a notification listener service is permitted"); 8103 } 8104 synchronized (this) { 8105 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 8106 if (profileOwner == null || profileOwner.permittedNotificationListeners == null) { 8107 return true; 8108 } 8109 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 8110 profileOwner.permittedNotificationListeners, userId); 8111 8112 } 8113 } 8114 8115 8116 private void sendAdminEnabledBroadcastLocked(int userHandle) { 8117 DevicePolicyData policyData = getUserData(userHandle); 8118 if (policyData.mAdminBroadcastPending) { 8119 // Send the initialization data to profile owner and delete the data 8120 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 8121 if (admin != null) { 8122 PersistableBundle initBundle = policyData.mInitBundle; 8123 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 8124 initBundle == null ? null : new Bundle(initBundle), null); 8125 } 8126 policyData.mInitBundle = null; 8127 policyData.mAdminBroadcastPending = false; 8128 saveSettingsLocked(userHandle); 8129 } 8130 } 8131 8132 @Override 8133 public UserHandle createAndManageUser(ComponentName admin, String name, 8134 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 8135 Preconditions.checkNotNull(admin, "admin is null"); 8136 Preconditions.checkNotNull(profileOwner, "profileOwner is null"); 8137 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 8138 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 8139 + admin + " are not in the same package"); 8140 } 8141 // Only allow the system user to use this method 8142 if (!mInjector.binderGetCallingUserHandle().isSystem()) { 8143 throw new SecurityException("createAndManageUser was called from non-system user"); 8144 } 8145 final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0; 8146 final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0 8147 && UserManager.isDeviceInDemoMode(mContext); 8148 if (ephemeral && !mInjector.userManagerIsSplitSystemUser() && !demo) { 8149 throw new IllegalArgumentException( 8150 "Ephemeral users are only supported on systems with a split system user."); 8151 } 8152 // Create user. 8153 UserHandle user = null; 8154 synchronized (this) { 8155 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8156 8157 final long id = mInjector.binderClearCallingIdentity(); 8158 try { 8159 int userInfoFlags = 0; 8160 if (ephemeral) { 8161 userInfoFlags |= UserInfo.FLAG_EPHEMERAL; 8162 } 8163 if (demo) { 8164 userInfoFlags |= UserInfo.FLAG_DEMO; 8165 } 8166 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 8167 userInfoFlags); 8168 if (userInfo != null) { 8169 user = userInfo.getUserHandle(); 8170 } 8171 } finally { 8172 mInjector.binderRestoreCallingIdentity(id); 8173 } 8174 } 8175 if (user == null) { 8176 return null; 8177 } 8178 // Set admin. 8179 final long id = mInjector.binderClearCallingIdentity(); 8180 try { 8181 final String adminPkg = admin.getPackageName(); 8182 8183 final int userHandle = user.getIdentifier(); 8184 try { 8185 // Install the profile owner if not present. 8186 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) { 8187 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle, 8188 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 8189 } 8190 } catch (RemoteException e) { 8191 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, " 8192 + "removing created user", e); 8193 mUserManager.removeUser(user.getIdentifier()); 8194 return null; 8195 } 8196 8197 setActiveAdmin(profileOwner, true, userHandle); 8198 // User is not started yet, the broadcast by setActiveAdmin will not be received. 8199 // So we store adminExtras for broadcasting when the user starts for first time. 8200 synchronized(this) { 8201 DevicePolicyData policyData = getUserData(userHandle); 8202 policyData.mInitBundle = adminExtras; 8203 policyData.mAdminBroadcastPending = true; 8204 saveSettingsLocked(userHandle); 8205 } 8206 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier()); 8207 setProfileOwner(profileOwner, ownerName, userHandle); 8208 8209 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 8210 Settings.Secure.putIntForUser(mContext.getContentResolver(), 8211 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 8212 } 8213 8214 return user; 8215 } finally { 8216 mInjector.binderRestoreCallingIdentity(id); 8217 } 8218 } 8219 8220 @Override 8221 public boolean removeUser(ComponentName who, UserHandle userHandle) { 8222 Preconditions.checkNotNull(who, "ComponentName is null"); 8223 synchronized (this) { 8224 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8225 } 8226 8227 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8228 final long id = mInjector.binderClearCallingIdentity(); 8229 try { 8230 String restriction = isManagedProfile(userHandle.getIdentifier()) 8231 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 8232 : UserManager.DISALLOW_REMOVE_USER; 8233 if (isAdminAffectedByRestriction(who, restriction, callingUserId)) { 8234 Log.w(LOG_TAG, "The device owner cannot remove a user because " 8235 + restriction + " is enabled, and was not set by the device owner"); 8236 return false; 8237 } 8238 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 8239 } finally { 8240 mInjector.binderRestoreCallingIdentity(id); 8241 } 8242 } 8243 8244 private boolean isAdminAffectedByRestriction( 8245 ComponentName admin, String userRestriction, int userId) { 8246 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 8247 case UserManager.RESTRICTION_NOT_SET: 8248 return false; 8249 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 8250 return !isDeviceOwner(admin, userId); 8251 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 8252 return !isProfileOwner(admin, userId); 8253 default: 8254 return true; 8255 } 8256 } 8257 8258 @Override 8259 public boolean switchUser(ComponentName who, UserHandle userHandle) { 8260 Preconditions.checkNotNull(who, "ComponentName is null"); 8261 synchronized (this) { 8262 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8263 8264 long id = mInjector.binderClearCallingIdentity(); 8265 try { 8266 int userId = UserHandle.USER_SYSTEM; 8267 if (userHandle != null) { 8268 userId = userHandle.getIdentifier(); 8269 } 8270 return mInjector.getIActivityManager().switchUser(userId); 8271 } catch (RemoteException e) { 8272 Log.e(LOG_TAG, "Couldn't switch user", e); 8273 return false; 8274 } finally { 8275 mInjector.binderRestoreCallingIdentity(id); 8276 } 8277 } 8278 } 8279 8280 @Override 8281 public Bundle getApplicationRestrictions(ComponentName who, String callerPackage, 8282 String packageName) { 8283 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8284 DELEGATION_APP_RESTRICTIONS); 8285 8286 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 8287 final long id = mInjector.binderClearCallingIdentity(); 8288 try { 8289 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 8290 // if no restrictions were saved, mUserManager.getApplicationRestrictions 8291 // returns null, but DPM method should return an empty Bundle as per JavaDoc 8292 return bundle != null ? bundle : Bundle.EMPTY; 8293 } finally { 8294 mInjector.binderRestoreCallingIdentity(id); 8295 } 8296 } 8297 8298 @Override 8299 public String[] setPackagesSuspended(ComponentName who, String callerPackage, 8300 String[] packageNames, boolean suspended) { 8301 int callingUserId = UserHandle.getCallingUserId(); 8302 synchronized (this) { 8303 // Ensure the caller is a DO/PO or a package access delegate. 8304 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8305 DELEGATION_PACKAGE_ACCESS); 8306 8307 long id = mInjector.binderClearCallingIdentity(); 8308 try { 8309 return mIPackageManager.setPackagesSuspendedAsUser( 8310 packageNames, suspended, callingUserId); 8311 } catch (RemoteException re) { 8312 // Shouldn't happen. 8313 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 8314 } finally { 8315 mInjector.binderRestoreCallingIdentity(id); 8316 } 8317 return packageNames; 8318 } 8319 } 8320 8321 @Override 8322 public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) { 8323 int callingUserId = UserHandle.getCallingUserId(); 8324 synchronized (this) { 8325 // Ensure the caller is a DO/PO or a package access delegate. 8326 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8327 DELEGATION_PACKAGE_ACCESS); 8328 8329 long id = mInjector.binderClearCallingIdentity(); 8330 try { 8331 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId); 8332 } catch (RemoteException re) { 8333 // Shouldn't happen. 8334 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 8335 } finally { 8336 mInjector.binderRestoreCallingIdentity(id); 8337 } 8338 return false; 8339 } 8340 } 8341 8342 @Override 8343 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) { 8344 Preconditions.checkNotNull(who, "ComponentName is null"); 8345 if (!UserRestrictionsUtils.isValidRestriction(key)) { 8346 return; 8347 } 8348 8349 final int userHandle = mInjector.userHandleGetCallingUserId(); 8350 synchronized (this) { 8351 final ActiveAdmin activeAdmin = 8352 getActiveAdminForCallerLocked(who, 8353 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8354 final boolean isDeviceOwner = isDeviceOwner(who, userHandle); 8355 if (isDeviceOwner) { 8356 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 8357 throw new SecurityException("Device owner cannot set user restriction " + key); 8358 } 8359 } else { // profile owner 8360 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) { 8361 throw new SecurityException("Profile owner cannot set user restriction " + key); 8362 } 8363 } 8364 8365 // Save the restriction to ActiveAdmin. 8366 final Bundle restrictions = activeAdmin.ensureUserRestrictions(); 8367 if (enabledFromThisOwner) { 8368 restrictions.putBoolean(key, true); 8369 } else { 8370 restrictions.remove(key); 8371 } 8372 saveUserRestrictionsLocked(userHandle); 8373 } 8374 } 8375 8376 private void saveUserRestrictionsLocked(int userId) { 8377 saveSettingsLocked(userId); 8378 pushUserRestrictions(userId); 8379 sendChangedNotification(userId); 8380 } 8381 8382 private void pushUserRestrictions(int userId) { 8383 synchronized (this) { 8384 final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId); 8385 final Bundle userRestrictions; 8386 // Whether device owner enforces camera restriction. 8387 boolean disallowCameraGlobally = false; 8388 8389 if (isDeviceOwner) { 8390 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 8391 if (deviceOwner == null) { 8392 return; // Shouldn't happen. 8393 } 8394 userRestrictions = deviceOwner.userRestrictions; 8395 // DO can disable camera globally. 8396 disallowCameraGlobally = deviceOwner.disableCamera; 8397 } else { 8398 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 8399 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null; 8400 } 8401 8402 // Whether any admin enforces camera restriction. 8403 final int cameraRestrictionScope = 8404 getCameraRestrictionScopeLocked(userId, disallowCameraGlobally); 8405 8406 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions, 8407 isDeviceOwner, cameraRestrictionScope); 8408 } 8409 } 8410 8411 /** 8412 * Get the scope of camera restriction for a given user if any. 8413 */ 8414 private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) { 8415 if (disallowCameraGlobally) { 8416 return UserManagerInternal.CAMERA_DISABLED_GLOBALLY; 8417 } else if (getCameraDisabled( 8418 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) { 8419 return UserManagerInternal.CAMERA_DISABLED_LOCALLY; 8420 } 8421 return UserManagerInternal.CAMERA_NOT_DISABLED; 8422 } 8423 8424 @Override 8425 public Bundle getUserRestrictions(ComponentName who) { 8426 if (!mHasFeature) { 8427 return null; 8428 } 8429 Preconditions.checkNotNull(who, "ComponentName is null"); 8430 synchronized (this) { 8431 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who, 8432 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8433 return activeAdmin.userRestrictions; 8434 } 8435 } 8436 8437 @Override 8438 public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName, 8439 boolean hidden) { 8440 int callingUserId = UserHandle.getCallingUserId(); 8441 synchronized (this) { 8442 // Ensure the caller is a DO/PO or a package access delegate. 8443 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8444 DELEGATION_PACKAGE_ACCESS); 8445 8446 long id = mInjector.binderClearCallingIdentity(); 8447 try { 8448 return mIPackageManager.setApplicationHiddenSettingAsUser( 8449 packageName, hidden, callingUserId); 8450 } catch (RemoteException re) { 8451 // shouldn't happen 8452 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 8453 } finally { 8454 mInjector.binderRestoreCallingIdentity(id); 8455 } 8456 return false; 8457 } 8458 } 8459 8460 @Override 8461 public boolean isApplicationHidden(ComponentName who, String callerPackage, 8462 String packageName) { 8463 int callingUserId = UserHandle.getCallingUserId(); 8464 synchronized (this) { 8465 // Ensure the caller is a DO/PO or a package access delegate. 8466 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8467 DELEGATION_PACKAGE_ACCESS); 8468 8469 long id = mInjector.binderClearCallingIdentity(); 8470 try { 8471 return mIPackageManager.getApplicationHiddenSettingAsUser( 8472 packageName, callingUserId); 8473 } catch (RemoteException re) { 8474 // shouldn't happen 8475 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 8476 } finally { 8477 mInjector.binderRestoreCallingIdentity(id); 8478 } 8479 return false; 8480 } 8481 } 8482 8483 @Override 8484 public void enableSystemApp(ComponentName who, String callerPackage, String packageName) { 8485 synchronized (this) { 8486 // Ensure the caller is a DO/PO or an enable system app delegate. 8487 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8488 DELEGATION_ENABLE_SYSTEM_APP); 8489 8490 final boolean isDemo = isCurrentUserDemo(); 8491 8492 int userId = UserHandle.getCallingUserId(); 8493 long id = mInjector.binderClearCallingIdentity(); 8494 8495 try { 8496 if (VERBOSE_LOG) { 8497 Slog.v(LOG_TAG, "installing " + packageName + " for " 8498 + userId); 8499 } 8500 8501 int parentUserId = getProfileParentId(userId); 8502 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) { 8503 throw new IllegalArgumentException("Only system apps can be enabled this way."); 8504 } 8505 8506 // Install the app. 8507 mIPackageManager.installExistingPackageAsUser(packageName, userId, 8508 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 8509 if (isDemo) { 8510 // Ensure the app is also ENABLED for demo users. 8511 mIPackageManager.setApplicationEnabledSetting(packageName, 8512 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 8513 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 8514 } 8515 } catch (RemoteException re) { 8516 // shouldn't happen 8517 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 8518 } finally { 8519 mInjector.binderRestoreCallingIdentity(id); 8520 } 8521 } 8522 } 8523 8524 @Override 8525 public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) { 8526 synchronized (this) { 8527 // Ensure the caller is a DO/PO or an enable system app delegate. 8528 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8529 DELEGATION_ENABLE_SYSTEM_APP); 8530 8531 int userId = UserHandle.getCallingUserId(); 8532 long id = mInjector.binderClearCallingIdentity(); 8533 8534 try { 8535 int parentUserId = getProfileParentId(userId); 8536 List<ResolveInfo> activitiesToEnable = mIPackageManager 8537 .queryIntentActivities(intent, 8538 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 8539 PackageManager.MATCH_DIRECT_BOOT_AWARE 8540 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 8541 parentUserId) 8542 .getList(); 8543 8544 if (VERBOSE_LOG) { 8545 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 8546 } 8547 int numberOfAppsInstalled = 0; 8548 if (activitiesToEnable != null) { 8549 for (ResolveInfo info : activitiesToEnable) { 8550 if (info.activityInfo != null) { 8551 String packageName = info.activityInfo.packageName; 8552 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 8553 numberOfAppsInstalled++; 8554 mIPackageManager.installExistingPackageAsUser(packageName, userId, 8555 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 8556 } else { 8557 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 8558 + " system app"); 8559 } 8560 } 8561 } 8562 } 8563 return numberOfAppsInstalled; 8564 } catch (RemoteException e) { 8565 // shouldn't happen 8566 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 8567 return 0; 8568 } finally { 8569 mInjector.binderRestoreCallingIdentity(id); 8570 } 8571 } 8572 } 8573 8574 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 8575 throws RemoteException { 8576 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 8577 userId); 8578 if (appInfo == null) { 8579 throw new IllegalArgumentException("The application " + packageName + 8580 " is not present on this device"); 8581 } 8582 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 8583 } 8584 8585 @Override 8586 public void setAccountManagementDisabled(ComponentName who, String accountType, 8587 boolean disabled) { 8588 if (!mHasFeature) { 8589 return; 8590 } 8591 Preconditions.checkNotNull(who, "ComponentName is null"); 8592 synchronized (this) { 8593 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 8594 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8595 if (disabled) { 8596 ap.accountTypesWithManagementDisabled.add(accountType); 8597 } else { 8598 ap.accountTypesWithManagementDisabled.remove(accountType); 8599 } 8600 saveSettingsLocked(UserHandle.getCallingUserId()); 8601 } 8602 } 8603 8604 @Override 8605 public String[] getAccountTypesWithManagementDisabled() { 8606 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 8607 } 8608 8609 @Override 8610 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 8611 enforceFullCrossUsersPermission(userId); 8612 if (!mHasFeature) { 8613 return null; 8614 } 8615 synchronized (this) { 8616 DevicePolicyData policy = getUserData(userId); 8617 final int N = policy.mAdminList.size(); 8618 ArraySet<String> resultSet = new ArraySet<>(); 8619 for (int i = 0; i < N; i++) { 8620 ActiveAdmin admin = policy.mAdminList.get(i); 8621 resultSet.addAll(admin.accountTypesWithManagementDisabled); 8622 } 8623 return resultSet.toArray(new String[resultSet.size()]); 8624 } 8625 } 8626 8627 @Override 8628 public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName, 8629 boolean uninstallBlocked) { 8630 final int userId = UserHandle.getCallingUserId(); 8631 synchronized (this) { 8632 // Ensure the caller is a DO/PO or a block uninstall delegate 8633 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8634 DELEGATION_BLOCK_UNINSTALL); 8635 8636 long id = mInjector.binderClearCallingIdentity(); 8637 try { 8638 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 8639 } catch (RemoteException re) { 8640 // Shouldn't happen. 8641 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 8642 } finally { 8643 mInjector.binderRestoreCallingIdentity(id); 8644 } 8645 } 8646 } 8647 8648 @Override 8649 public boolean isUninstallBlocked(ComponentName who, String packageName) { 8650 // This function should return true if and only if the package is blocked by 8651 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 8652 // when the package is a system app, or when it is an active device admin. 8653 final int userId = UserHandle.getCallingUserId(); 8654 8655 synchronized (this) { 8656 if (who != null) { 8657 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8658 } 8659 8660 long id = mInjector.binderClearCallingIdentity(); 8661 try { 8662 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 8663 } catch (RemoteException re) { 8664 // Shouldn't happen. 8665 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 8666 } finally { 8667 mInjector.binderRestoreCallingIdentity(id); 8668 } 8669 } 8670 return false; 8671 } 8672 8673 @Override 8674 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 8675 if (!mHasFeature) { 8676 return; 8677 } 8678 Preconditions.checkNotNull(who, "ComponentName is null"); 8679 synchronized (this) { 8680 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8681 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8682 if (admin.disableCallerId != disabled) { 8683 admin.disableCallerId = disabled; 8684 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 8685 } 8686 } 8687 } 8688 8689 @Override 8690 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 8691 if (!mHasFeature) { 8692 return false; 8693 } 8694 Preconditions.checkNotNull(who, "ComponentName is null"); 8695 synchronized (this) { 8696 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8697 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8698 return admin.disableCallerId; 8699 } 8700 } 8701 8702 @Override 8703 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 8704 enforceCrossUsersPermission(userId); 8705 synchronized (this) { 8706 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8707 return (admin != null) ? admin.disableCallerId : false; 8708 } 8709 } 8710 8711 @Override 8712 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 8713 if (!mHasFeature) { 8714 return; 8715 } 8716 Preconditions.checkNotNull(who, "ComponentName is null"); 8717 synchronized (this) { 8718 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8719 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8720 if (admin.disableContactsSearch != disabled) { 8721 admin.disableContactsSearch = disabled; 8722 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 8723 } 8724 } 8725 } 8726 8727 @Override 8728 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 8729 if (!mHasFeature) { 8730 return false; 8731 } 8732 Preconditions.checkNotNull(who, "ComponentName is null"); 8733 synchronized (this) { 8734 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8735 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8736 return admin.disableContactsSearch; 8737 } 8738 } 8739 8740 @Override 8741 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 8742 enforceCrossUsersPermission(userId); 8743 synchronized (this) { 8744 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8745 return (admin != null) ? admin.disableContactsSearch : false; 8746 } 8747 } 8748 8749 @Override 8750 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 8751 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 8752 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 8753 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 8754 final int callingUserId = UserHandle.getCallingUserId(); 8755 8756 final long ident = mInjector.binderClearCallingIdentity(); 8757 try { 8758 synchronized (this) { 8759 final int managedUserId = getManagedUserId(callingUserId); 8760 if (managedUserId < 0) { 8761 return; 8762 } 8763 if (isCrossProfileQuickContactDisabled(managedUserId)) { 8764 if (VERBOSE_LOG) { 8765 Log.v(LOG_TAG, 8766 "Cross-profile contacts access disabled for user " + managedUserId); 8767 } 8768 return; 8769 } 8770 ContactsInternal.startQuickContactWithErrorToastForUser( 8771 mContext, intent, new UserHandle(managedUserId)); 8772 } 8773 } finally { 8774 mInjector.binderRestoreCallingIdentity(ident); 8775 } 8776 } 8777 8778 /** 8779 * @return true if cross-profile QuickContact is disabled 8780 */ 8781 private boolean isCrossProfileQuickContactDisabled(int userId) { 8782 return getCrossProfileCallerIdDisabledForUser(userId) 8783 && getCrossProfileContactsSearchDisabledForUser(userId); 8784 } 8785 8786 /** 8787 * @return the user ID of the managed user that is linked to the current user, if any. 8788 * Otherwise -1. 8789 */ 8790 public int getManagedUserId(int callingUserId) { 8791 if (VERBOSE_LOG) { 8792 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 8793 } 8794 8795 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 8796 if (ui.id == callingUserId || !ui.isManagedProfile()) { 8797 continue; // Caller user self, or not a managed profile. Skip. 8798 } 8799 if (VERBOSE_LOG) { 8800 Log.v(LOG_TAG, "Managed user=" + ui.id); 8801 } 8802 return ui.id; 8803 } 8804 if (VERBOSE_LOG) { 8805 Log.v(LOG_TAG, "Managed user not found."); 8806 } 8807 return -1; 8808 } 8809 8810 @Override 8811 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 8812 if (!mHasFeature) { 8813 return; 8814 } 8815 Preconditions.checkNotNull(who, "ComponentName is null"); 8816 synchronized (this) { 8817 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8818 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8819 if (admin.disableBluetoothContactSharing != disabled) { 8820 admin.disableBluetoothContactSharing = disabled; 8821 saveSettingsLocked(UserHandle.getCallingUserId()); 8822 } 8823 } 8824 } 8825 8826 @Override 8827 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 8828 if (!mHasFeature) { 8829 return false; 8830 } 8831 Preconditions.checkNotNull(who, "ComponentName is null"); 8832 synchronized (this) { 8833 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8834 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8835 return admin.disableBluetoothContactSharing; 8836 } 8837 } 8838 8839 @Override 8840 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 8841 // TODO: Should there be a check to make sure this relationship is 8842 // within a profile group? 8843 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 8844 synchronized (this) { 8845 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8846 return (admin != null) ? admin.disableBluetoothContactSharing : false; 8847 } 8848 } 8849 8850 @Override 8851 public void setLockTaskPackages(ComponentName who, String[] packages) 8852 throws SecurityException { 8853 Preconditions.checkNotNull(who, "ComponentName is null"); 8854 Preconditions.checkNotNull(packages, "packages is null"); 8855 8856 synchronized (this) { 8857 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8858 final int userHandle = mInjector.userHandleGetCallingUserId(); 8859 if (isUserAffiliatedWithDeviceLocked(userHandle)) { 8860 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 8861 } else { 8862 throw new SecurityException("Admin " + who + 8863 " is neither the device owner or affiliated user's profile owner."); 8864 } 8865 } 8866 } 8867 8868 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 8869 DevicePolicyData policy = getUserData(userHandle); 8870 policy.mLockTaskPackages = packages; 8871 8872 // Store the settings persistently. 8873 saveSettingsLocked(userHandle); 8874 updateLockTaskPackagesLocked(packages, userHandle); 8875 } 8876 8877 private void maybeClearLockTaskPackagesLocked() { 8878 final long ident = mInjector.binderClearCallingIdentity(); 8879 try { 8880 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 8881 for (int i = 0; i < userInfos.size(); i++) { 8882 int userId = userInfos.get(i).id; 8883 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages; 8884 if (!lockTaskPackages.isEmpty() && 8885 !isUserAffiliatedWithDeviceLocked(userId)) { 8886 Slog.d(LOG_TAG, 8887 "User id " + userId + " not affiliated. Clearing lock task packages"); 8888 setLockTaskPackagesLocked(userId, Collections.<String>emptyList()); 8889 } 8890 } 8891 } finally { 8892 mInjector.binderRestoreCallingIdentity(ident); 8893 } 8894 } 8895 8896 @Override 8897 public String[] getLockTaskPackages(ComponentName who) { 8898 Preconditions.checkNotNull(who, "ComponentName is null"); 8899 8900 final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 8901 synchronized (this) { 8902 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8903 if (!isUserAffiliatedWithDeviceLocked(userHandle)) { 8904 throw new SecurityException("Admin " + who + 8905 " is neither the device owner or affiliated user's profile owner."); 8906 } 8907 8908 final List<String> packages = getUserData(userHandle).mLockTaskPackages; 8909 return packages.toArray(new String[packages.size()]); 8910 } 8911 } 8912 8913 @Override 8914 public boolean isLockTaskPermitted(String pkg) { 8915 final int userHandle = mInjector.userHandleGetCallingUserId(); 8916 synchronized (this) { 8917 return getUserData(userHandle).mLockTaskPackages.contains(pkg); 8918 } 8919 } 8920 8921 @Override 8922 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 8923 if (!isCallerWithSystemUid()) { 8924 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 8925 } 8926 synchronized (this) { 8927 final DevicePolicyData policy = getUserData(userHandle); 8928 Bundle adminExtras = new Bundle(); 8929 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 8930 for (ActiveAdmin admin : policy.mAdminList) { 8931 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 8932 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 8933 if (ownsDevice || ownsProfile) { 8934 if (isEnabled) { 8935 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 8936 adminExtras, null); 8937 } else { 8938 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 8939 } 8940 } 8941 } 8942 } 8943 } 8944 8945 @Override 8946 public void setGlobalSetting(ComponentName who, String setting, String value) { 8947 Preconditions.checkNotNull(who, "ComponentName is null"); 8948 8949 synchronized (this) { 8950 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8951 8952 // Some settings are no supported any more. However we do not want to throw a 8953 // SecurityException to avoid breaking apps. 8954 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 8955 Log.i(LOG_TAG, "Global setting no longer supported: " + setting); 8956 return; 8957 } 8958 8959 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting) 8960 && !UserManager.isDeviceInDemoMode(mContext)) { 8961 throw new SecurityException(String.format( 8962 "Permission denial: device owners cannot update %1$s", setting)); 8963 } 8964 8965 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 8966 // ignore if it contradicts an existing policy 8967 long timeMs = getMaximumTimeToLock( 8968 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 8969 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) { 8970 return; 8971 } 8972 } 8973 8974 long id = mInjector.binderClearCallingIdentity(); 8975 try { 8976 mInjector.settingsGlobalPutString(setting, value); 8977 } finally { 8978 mInjector.binderRestoreCallingIdentity(id); 8979 } 8980 } 8981 } 8982 8983 @Override 8984 public void setSecureSetting(ComponentName who, String setting, String value) { 8985 Preconditions.checkNotNull(who, "ComponentName is null"); 8986 int callingUserId = mInjector.userHandleGetCallingUserId(); 8987 8988 synchronized (this) { 8989 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8990 8991 if (isDeviceOwner(who, callingUserId)) { 8992 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting) 8993 && !isCurrentUserDemo()) { 8994 throw new SecurityException(String.format( 8995 "Permission denial: Device owners cannot update %1$s", setting)); 8996 } 8997 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) { 8998 throw new SecurityException(String.format( 8999 "Permission denial: Profile owners cannot update %1$s", setting)); 9000 } 9001 if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) { 9002 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) { 9003 throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS 9004 + " is deprecated. Please use the user restriction " 9005 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead."); 9006 } 9007 if (!mUserManager.isManagedProfile(callingUserId)) { 9008 Slog.e(LOG_TAG, "Ignoring setSecureSetting request for " 9009 + setting + ". User restriction " 9010 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES 9011 + " should be used instead."); 9012 } else { 9013 try { 9014 setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 9015 (Integer.parseInt(value) == 0) ? true : false); 9016 } catch (NumberFormatException exc) { 9017 Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting); 9018 } 9019 } 9020 return; 9021 } 9022 long id = mInjector.binderClearCallingIdentity(); 9023 try { 9024 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) { 9025 final String currentValue = mInjector.settingsSecureGetStringForUser( 9026 Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId); 9027 if (!TextUtils.equals(currentValue, value)) { 9028 // Tell the content observer that the next change will be due to the owner 9029 // changing the value. There is a small race condition here that we cannot 9030 // avoid: Change notifications are sent asynchronously, so it is possible 9031 // that there are prior notifications queued up before the one we are about 9032 // to trigger. This is a corner case that will have no impact in practice. 9033 mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId); 9034 } 9035 getUserData(callingUserId).mCurrentInputMethodSet = true; 9036 saveSettingsLocked(callingUserId); 9037 } 9038 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 9039 } finally { 9040 mInjector.binderRestoreCallingIdentity(id); 9041 } 9042 } 9043 } 9044 9045 @Override 9046 public void setMasterVolumeMuted(ComponentName who, boolean on) { 9047 Preconditions.checkNotNull(who, "ComponentName is null"); 9048 synchronized (this) { 9049 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9050 setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on); 9051 } 9052 } 9053 9054 @Override 9055 public boolean isMasterVolumeMuted(ComponentName who) { 9056 Preconditions.checkNotNull(who, "ComponentName is null"); 9057 synchronized (this) { 9058 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9059 9060 AudioManager audioManager = 9061 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 9062 return audioManager.isMasterMute(); 9063 } 9064 } 9065 9066 @Override 9067 public void setUserIcon(ComponentName who, Bitmap icon) { 9068 synchronized (this) { 9069 Preconditions.checkNotNull(who, "ComponentName is null"); 9070 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9071 9072 int userId = UserHandle.getCallingUserId(); 9073 long id = mInjector.binderClearCallingIdentity(); 9074 try { 9075 mUserManagerInternal.setUserIcon(userId, icon); 9076 } finally { 9077 mInjector.binderRestoreCallingIdentity(id); 9078 } 9079 } 9080 } 9081 9082 @Override 9083 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 9084 Preconditions.checkNotNull(who, "ComponentName is null"); 9085 synchronized (this) { 9086 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9087 } 9088 final int userId = UserHandle.getCallingUserId(); 9089 9090 long ident = mInjector.binderClearCallingIdentity(); 9091 try { 9092 // disallow disabling the keyguard if a password is currently set 9093 if (disabled && mLockPatternUtils.isSecure(userId)) { 9094 return false; 9095 } 9096 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 9097 } finally { 9098 mInjector.binderRestoreCallingIdentity(ident); 9099 } 9100 return true; 9101 } 9102 9103 @Override 9104 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 9105 int userId = UserHandle.getCallingUserId(); 9106 synchronized (this) { 9107 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9108 DevicePolicyData policy = getUserData(userId); 9109 if (policy.mStatusBarDisabled != disabled) { 9110 if (!setStatusBarDisabledInternal(disabled, userId)) { 9111 return false; 9112 } 9113 policy.mStatusBarDisabled = disabled; 9114 saveSettingsLocked(userId); 9115 } 9116 } 9117 return true; 9118 } 9119 9120 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 9121 long ident = mInjector.binderClearCallingIdentity(); 9122 try { 9123 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 9124 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 9125 if (statusBarService != null) { 9126 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 9127 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 9128 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 9129 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 9130 return true; 9131 } 9132 } catch (RemoteException e) { 9133 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 9134 } finally { 9135 mInjector.binderRestoreCallingIdentity(ident); 9136 } 9137 return false; 9138 } 9139 9140 /** 9141 * We need to update the internal state of whether a user has completed setup or a 9142 * device has paired once. After that, we ignore any changes that reset the 9143 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 9144 * as we don't trust any apps that might try to reset them. 9145 * <p> 9146 * Unfortunately, we don't know which user's setup state was changed, so we write all of 9147 * them. 9148 */ 9149 void updateUserSetupCompleteAndPaired() { 9150 List<UserInfo> users = mUserManager.getUsers(true); 9151 final int N = users.size(); 9152 for (int i = 0; i < N; i++) { 9153 int userHandle = users.get(i).id; 9154 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 9155 userHandle) != 0) { 9156 DevicePolicyData policy = getUserData(userHandle); 9157 if (!policy.mUserSetupComplete) { 9158 policy.mUserSetupComplete = true; 9159 synchronized (this) { 9160 saveSettingsLocked(userHandle); 9161 } 9162 } 9163 } 9164 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 9165 userHandle) != 0) { 9166 DevicePolicyData policy = getUserData(userHandle); 9167 if (!policy.mPaired) { 9168 policy.mPaired = true; 9169 synchronized (this) { 9170 saveSettingsLocked(userHandle); 9171 } 9172 } 9173 } 9174 } 9175 } 9176 9177 private class SetupContentObserver extends ContentObserver { 9178 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 9179 Settings.Secure.USER_SETUP_COMPLETE); 9180 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 9181 Settings.Global.DEVICE_PROVISIONED); 9182 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 9183 private final Uri mDefaultImeChanged = Settings.Secure.getUriFor( 9184 Settings.Secure.DEFAULT_INPUT_METHOD); 9185 9186 @GuardedBy("DevicePolicyManagerService.this") 9187 private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>(); 9188 9189 public SetupContentObserver(Handler handler) { 9190 super(handler); 9191 } 9192 9193 void register() { 9194 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 9195 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 9196 if (mIsWatch) { 9197 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 9198 } 9199 mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL); 9200 } 9201 9202 private void addPendingChangeByOwnerLocked(int userId) { 9203 mUserIdsWithPendingChangesByOwner.add(userId); 9204 } 9205 9206 @Override 9207 public void onChange(boolean selfChange, Uri uri, int userId) { 9208 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 9209 updateUserSetupCompleteAndPaired(); 9210 } else if (mDeviceProvisioned.equals(uri)) { 9211 synchronized (DevicePolicyManagerService.this) { 9212 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 9213 // is delayed until device is marked as provisioned. 9214 setDeviceOwnerSystemPropertyLocked(); 9215 } 9216 } else if (mDefaultImeChanged.equals(uri)) { 9217 synchronized (DevicePolicyManagerService.this) { 9218 if (mUserIdsWithPendingChangesByOwner.contains(userId)) { 9219 // This change notification was triggered by the owner changing the current 9220 // IME. Ignore it. 9221 mUserIdsWithPendingChangesByOwner.remove(userId); 9222 } else { 9223 // This change notification was triggered by the user manually changing the 9224 // current IME. 9225 getUserData(userId).mCurrentInputMethodSet = false; 9226 saveSettingsLocked(userId); 9227 } 9228 } 9229 } 9230 } 9231 } 9232 9233 @VisibleForTesting 9234 final class LocalService extends DevicePolicyManagerInternal { 9235 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 9236 9237 @Override 9238 public List<String> getCrossProfileWidgetProviders(int profileId) { 9239 synchronized (DevicePolicyManagerService.this) { 9240 if (mOwners == null) { 9241 return Collections.emptyList(); 9242 } 9243 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 9244 if (ownerComponent == null) { 9245 return Collections.emptyList(); 9246 } 9247 9248 DevicePolicyData policy = getUserDataUnchecked(profileId); 9249 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 9250 9251 if (admin == null || admin.crossProfileWidgetProviders == null 9252 || admin.crossProfileWidgetProviders.isEmpty()) { 9253 return Collections.emptyList(); 9254 } 9255 9256 return admin.crossProfileWidgetProviders; 9257 } 9258 } 9259 9260 @Override 9261 public void addOnCrossProfileWidgetProvidersChangeListener( 9262 OnCrossProfileWidgetProvidersChangeListener listener) { 9263 synchronized (DevicePolicyManagerService.this) { 9264 if (mWidgetProviderListeners == null) { 9265 mWidgetProviderListeners = new ArrayList<>(); 9266 } 9267 if (!mWidgetProviderListeners.contains(listener)) { 9268 mWidgetProviderListeners.add(listener); 9269 } 9270 } 9271 } 9272 9273 @Override 9274 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 9275 synchronized(DevicePolicyManagerService.this) { 9276 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 9277 } 9278 } 9279 9280 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 9281 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 9282 synchronized (DevicePolicyManagerService.this) { 9283 listeners = new ArrayList<>(mWidgetProviderListeners); 9284 } 9285 final int listenerCount = listeners.size(); 9286 for (int i = 0; i < listenerCount; i++) { 9287 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 9288 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 9289 } 9290 } 9291 9292 @Override 9293 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 9294 // This method is called from AM with its lock held, so don't take the DPMS lock. 9295 // b/29242568 9296 9297 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 9298 if (profileOwner != null) { 9299 return DevicePolicyManagerService.this 9300 .createShowAdminSupportIntent(profileOwner, userId); 9301 } 9302 9303 final Pair<Integer, ComponentName> deviceOwner = 9304 mOwners.getDeviceOwnerUserIdAndComponent(); 9305 if (deviceOwner != null && deviceOwner.first == userId) { 9306 return DevicePolicyManagerService.this 9307 .createShowAdminSupportIntent(deviceOwner.second, userId); 9308 } 9309 9310 // We're not specifying the device admin because there isn't one. 9311 if (useDefaultIfNoAdmin) { 9312 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 9313 } 9314 return null; 9315 } 9316 9317 @Override 9318 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 9319 int source; 9320 long ident = mInjector.binderClearCallingIdentity(); 9321 try { 9322 source = mUserManager.getUserRestrictionSource(userRestriction, 9323 UserHandle.of(userId)); 9324 } finally { 9325 mInjector.binderRestoreCallingIdentity(ident); 9326 } 9327 if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) { 9328 /* 9329 * In this case, the user restriction is enforced by the system. 9330 * So we won't show an admin support intent, even if it is also 9331 * enforced by a profile/device owner. 9332 */ 9333 return null; 9334 } 9335 boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0; 9336 boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0; 9337 if (enforcedByDo && enforcedByPo) { 9338 // In this case, we'll show an admin support dialog that does not 9339 // specify the admin. 9340 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 9341 } else if (enforcedByPo) { 9342 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 9343 if (profileOwner != null) { 9344 return DevicePolicyManagerService.this 9345 .createShowAdminSupportIntent(profileOwner, userId); 9346 } 9347 // This could happen if another thread has changed the profile owner since we called 9348 // getUserRestrictionSource 9349 return null; 9350 } else if (enforcedByDo) { 9351 final Pair<Integer, ComponentName> deviceOwner 9352 = mOwners.getDeviceOwnerUserIdAndComponent(); 9353 if (deviceOwner != null) { 9354 return DevicePolicyManagerService.this 9355 .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first); 9356 } 9357 // This could happen if another thread has changed the device owner since we called 9358 // getUserRestrictionSource 9359 return null; 9360 } 9361 return null; 9362 } 9363 } 9364 9365 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) { 9366 // This method is called with AMS lock held, so don't take DPMS lock 9367 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 9368 intent.putExtra(Intent.EXTRA_USER_ID, userId); 9369 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin); 9370 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 9371 return intent; 9372 } 9373 9374 @Override 9375 public Intent createAdminSupportIntent(String restriction) { 9376 Preconditions.checkNotNull(restriction); 9377 final int uid = mInjector.binderGetCallingUid(); 9378 final int userId = UserHandle.getUserId(uid); 9379 Intent intent = null; 9380 if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) || 9381 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) { 9382 synchronized(this) { 9383 final DevicePolicyData policy = getUserData(userId); 9384 final int N = policy.mAdminList.size(); 9385 for (int i = 0; i < N; i++) { 9386 final ActiveAdmin admin = policy.mAdminList.get(i); 9387 if ((admin.disableCamera && 9388 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) || 9389 (admin.disableScreenCapture && DevicePolicyManager 9390 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) { 9391 intent = createShowAdminSupportIntent(admin.info.getComponent(), userId); 9392 break; 9393 } 9394 } 9395 // For the camera, a device owner on a different user can disable it globally, 9396 // so we need an additional check. 9397 if (intent == null 9398 && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) { 9399 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 9400 if (admin != null && admin.disableCamera) { 9401 intent = createShowAdminSupportIntent(admin.info.getComponent(), 9402 mOwners.getDeviceOwnerUserId()); 9403 } 9404 } 9405 } 9406 } else { 9407 // if valid, |restriction| can only be a user restriction 9408 intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction); 9409 } 9410 if (intent != null) { 9411 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction); 9412 } 9413 return intent; 9414 } 9415 9416 /** 9417 * Returns true if specified admin is allowed to limit passwords and has a 9418 * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality} 9419 */ 9420 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 9421 if (admin.minimumPasswordMetrics.quality < minPasswordQuality) { 9422 return false; 9423 } 9424 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 9425 } 9426 9427 @Override 9428 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 9429 if (policy != null && !policy.isValid()) { 9430 throw new IllegalArgumentException("Invalid system update policy."); 9431 } 9432 synchronized (this) { 9433 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9434 if (policy == null) { 9435 mOwners.clearSystemUpdatePolicy(); 9436 } else { 9437 mOwners.setSystemUpdatePolicy(policy); 9438 } 9439 mOwners.writeDeviceOwner(); 9440 } 9441 mContext.sendBroadcastAsUser( 9442 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 9443 UserHandle.SYSTEM); 9444 } 9445 9446 @Override 9447 public SystemUpdatePolicy getSystemUpdatePolicy() { 9448 synchronized (this) { 9449 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 9450 if (policy != null && !policy.isValid()) { 9451 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 9452 return null; 9453 } 9454 return policy; 9455 } 9456 } 9457 9458 /** 9459 * Checks if the caller of the method is the device owner app. 9460 * 9461 * @param callerUid UID of the caller. 9462 * @return true if the caller is the device owner app 9463 */ 9464 @VisibleForTesting 9465 boolean isCallerDeviceOwner(int callerUid) { 9466 synchronized (this) { 9467 if (!mOwners.hasDeviceOwner()) { 9468 return false; 9469 } 9470 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 9471 return false; 9472 } 9473 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 9474 .getPackageName(); 9475 try { 9476 String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid); 9477 for (String pkg : pkgs) { 9478 if (deviceOwnerPackageName.equals(pkg)) { 9479 return true; 9480 } 9481 } 9482 } catch (RemoteException e) { 9483 return false; 9484 } 9485 } 9486 9487 return false; 9488 } 9489 9490 @Override 9491 public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) { 9492 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 9493 "Only the system update service can broadcast update information"); 9494 9495 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 9496 Slog.w(LOG_TAG, "Only the system update service in the system user " + 9497 "can broadcast update information."); 9498 return; 9499 } 9500 9501 if (!mOwners.saveSystemUpdateInfo(info)) { 9502 // Pending system update hasn't changed, don't send duplicate notification. 9503 return; 9504 } 9505 9506 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE) 9507 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 9508 info == null ? -1 : info.getReceivedTime()); 9509 9510 final long ident = mInjector.binderClearCallingIdentity(); 9511 try { 9512 synchronized (this) { 9513 // Broadcast to device owner first if there is one. 9514 if (mOwners.hasDeviceOwner()) { 9515 final UserHandle deviceOwnerUser = 9516 UserHandle.of(mOwners.getDeviceOwnerUserId()); 9517 intent.setComponent(mOwners.getDeviceOwnerComponent()); 9518 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 9519 } 9520 } 9521 // Get running users. 9522 final int runningUserIds[]; 9523 try { 9524 runningUserIds = mInjector.getIActivityManager().getRunningUserIds(); 9525 } catch (RemoteException e) { 9526 // Shouldn't happen. 9527 Log.e(LOG_TAG, "Could not retrieve the list of running users", e); 9528 return; 9529 } 9530 // Send broadcasts to corresponding profile owners if any. 9531 for (final int userId : runningUserIds) { 9532 synchronized (this) { 9533 final ComponentName profileOwnerPackage = 9534 mOwners.getProfileOwnerComponent(userId); 9535 if (profileOwnerPackage != null) { 9536 intent.setComponent(profileOwnerPackage); 9537 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 9538 } 9539 } 9540 } 9541 } finally { 9542 mInjector.binderRestoreCallingIdentity(ident); 9543 } 9544 } 9545 9546 @Override 9547 public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) { 9548 Preconditions.checkNotNull(admin, "ComponentName is null"); 9549 enforceProfileOrDeviceOwner(admin); 9550 9551 return mOwners.getSystemUpdateInfo(); 9552 } 9553 9554 @Override 9555 public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) 9556 throws RemoteException { 9557 int userId = UserHandle.getCallingUserId(); 9558 synchronized (this) { 9559 // Ensure the caller is a DO/PO or a permission grant state delegate. 9560 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9561 DELEGATION_PERMISSION_GRANT); 9562 DevicePolicyData userPolicy = getUserData(userId); 9563 if (userPolicy.mPermissionPolicy != policy) { 9564 userPolicy.mPermissionPolicy = policy; 9565 saveSettingsLocked(userId); 9566 } 9567 } 9568 } 9569 9570 @Override 9571 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 9572 int userId = UserHandle.getCallingUserId(); 9573 synchronized (this) { 9574 DevicePolicyData userPolicy = getUserData(userId); 9575 return userPolicy.mPermissionPolicy; 9576 } 9577 } 9578 9579 @Override 9580 public boolean setPermissionGrantState(ComponentName admin, String callerPackage, 9581 String packageName, String permission, int grantState) throws RemoteException { 9582 UserHandle user = mInjector.binderGetCallingUserHandle(); 9583 synchronized (this) { 9584 // Ensure the caller is a DO/PO or a permission grant state delegate. 9585 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9586 DELEGATION_PERMISSION_GRANT); 9587 long ident = mInjector.binderClearCallingIdentity(); 9588 try { 9589 if (getTargetSdk(packageName, user.getIdentifier()) 9590 < android.os.Build.VERSION_CODES.M) { 9591 return false; 9592 } 9593 final PackageManager packageManager = mInjector.getPackageManager(); 9594 switch (grantState) { 9595 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: { 9596 mInjector.getPackageManagerInternal().grantRuntimePermission(packageName, 9597 permission, user.getIdentifier(), true /* override policy */); 9598 packageManager.updatePermissionFlags(permission, packageName, 9599 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 9600 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 9601 } break; 9602 9603 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: { 9604 mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName, 9605 permission, user.getIdentifier(), true /* override policy */); 9606 packageManager.updatePermissionFlags(permission, packageName, 9607 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 9608 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 9609 } break; 9610 9611 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: { 9612 packageManager.updatePermissionFlags(permission, packageName, 9613 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user); 9614 } break; 9615 } 9616 return true; 9617 } catch (SecurityException se) { 9618 return false; 9619 } finally { 9620 mInjector.binderRestoreCallingIdentity(ident); 9621 } 9622 } 9623 } 9624 9625 @Override 9626 public int getPermissionGrantState(ComponentName admin, String callerPackage, 9627 String packageName, String permission) throws RemoteException { 9628 PackageManager packageManager = mInjector.getPackageManager(); 9629 9630 UserHandle user = mInjector.binderGetCallingUserHandle(); 9631 if (!isCallerWithSystemUid()) { 9632 // Ensure the caller is a DO/PO or a permission grant state delegate. 9633 enforceCanManageScope(admin, callerPackage, 9634 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT); 9635 } 9636 synchronized (this) { 9637 long ident = mInjector.binderClearCallingIdentity(); 9638 try { 9639 int granted = mIPackageManager.checkPermission(permission, 9640 packageName, user.getIdentifier()); 9641 int permFlags = packageManager.getPermissionFlags(permission, packageName, user); 9642 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 9643 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 9644 // Not controlled by policy 9645 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 9646 } else { 9647 // Policy controlled so return result based on permission grant state 9648 return granted == PackageManager.PERMISSION_GRANTED 9649 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 9650 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 9651 } 9652 } finally { 9653 mInjector.binderRestoreCallingIdentity(ident); 9654 } 9655 } 9656 } 9657 9658 boolean isPackageInstalledForUser(String packageName, int userHandle) { 9659 try { 9660 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 9661 userHandle); 9662 return (pi != null) && (pi.applicationInfo.flags != 0); 9663 } catch (RemoteException re) { 9664 throw new RuntimeException("Package manager has died", re); 9665 } 9666 } 9667 9668 @Override 9669 public boolean isProvisioningAllowed(String action, String packageName) { 9670 Preconditions.checkNotNull(packageName); 9671 9672 final int callingUid = mInjector.binderGetCallingUid(); 9673 final long ident = mInjector.binderClearCallingIdentity(); 9674 try { 9675 final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser( 9676 packageName, UserHandle.getUserId(callingUid)); 9677 Preconditions.checkArgument(callingUid == uidForPackage, 9678 "Caller uid doesn't match the one for the provided package."); 9679 } catch (NameNotFoundException e) { 9680 throw new IllegalArgumentException("Invalid package provided " + packageName, e); 9681 } finally { 9682 mInjector.binderRestoreCallingIdentity(ident); 9683 } 9684 9685 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK; 9686 } 9687 9688 @Override 9689 public int checkProvisioningPreCondition(String action, String packageName) { 9690 Preconditions.checkNotNull(packageName); 9691 enforceCanManageProfileAndDeviceOwners(); 9692 return checkProvisioningPreConditionSkipPermission(action, packageName); 9693 } 9694 9695 private int checkProvisioningPreConditionSkipPermission(String action, String packageName) { 9696 if (!mHasFeature) { 9697 return CODE_DEVICE_ADMIN_NOT_SUPPORTED; 9698 } 9699 9700 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9701 if (action != null) { 9702 switch (action) { 9703 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 9704 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 9705 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 9706 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 9707 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER: 9708 return checkManagedUserProvisioningPreCondition(callingUserId); 9709 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE: 9710 return checkManagedShareableDeviceProvisioningPreCondition(callingUserId); 9711 } 9712 } 9713 throw new IllegalArgumentException("Unknown provisioning action " + action); 9714 } 9715 9716 /** 9717 * The device owner can only be set before the setup phase of the primary user has completed, 9718 * except for adb command if no accounts or additional users are present on the device. 9719 */ 9720 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 9721 int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) { 9722 if (mOwners.hasDeviceOwner()) { 9723 return CODE_HAS_DEVICE_OWNER; 9724 } 9725 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 9726 return CODE_USER_HAS_PROFILE_OWNER; 9727 } 9728 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 9729 return CODE_USER_NOT_RUNNING; 9730 } 9731 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 9732 return CODE_HAS_PAIRED; 9733 } 9734 if (isAdb) { 9735 // if shell command runs after user setup completed check device status. Otherwise, OK. 9736 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 9737 if (!mInjector.userManagerIsSplitSystemUser()) { 9738 if (mUserManager.getUserCount() > 1) { 9739 return CODE_NONSYSTEM_USER_EXISTS; 9740 } 9741 if (hasIncompatibleAccountsOrNonAdb) { 9742 return CODE_ACCOUNTS_NOT_EMPTY; 9743 } 9744 } else { 9745 // STOPSHIP Do proper check in split user mode 9746 } 9747 } 9748 return CODE_OK; 9749 } else { 9750 if (!mInjector.userManagerIsSplitSystemUser()) { 9751 // In non-split user mode, DO has to be user 0 9752 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 9753 return CODE_NOT_SYSTEM_USER; 9754 } 9755 // In non-split user mode, only provision DO before setup wizard completes 9756 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 9757 return CODE_USER_SETUP_COMPLETED; 9758 } 9759 } else { 9760 // STOPSHIP Do proper check in split user mode 9761 } 9762 return CODE_OK; 9763 } 9764 } 9765 9766 private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) { 9767 synchronized (this) { 9768 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb. 9769 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 9770 deviceOwnerUserId, /* isAdb= */ false, 9771 /* hasIncompatibleAccountsOrNonAdb=*/ true); 9772 } 9773 } 9774 9775 private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) { 9776 if (!hasFeatureManagedUsers()) { 9777 return CODE_MANAGED_USERS_NOT_SUPPORTED; 9778 } 9779 if (callingUserId == UserHandle.USER_SYSTEM 9780 && mInjector.userManagerIsSplitSystemUser()) { 9781 // Managed-profiles cannot be setup on the system user. 9782 return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 9783 } 9784 if (getProfileOwner(callingUserId) != null) { 9785 // Managed user cannot have a managed profile. 9786 return CODE_USER_HAS_PROFILE_OWNER; 9787 } 9788 9789 final long ident = mInjector.binderClearCallingIdentity(); 9790 try { 9791 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 9792 final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId); 9793 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, 9794 callingUserHandle)) { 9795 // An admin can initiate provisioning if it has set the restriction. 9796 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 9797 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) { 9798 return CODE_ADD_MANAGED_PROFILE_DISALLOWED; 9799 } 9800 } 9801 boolean canRemoveProfile = true; 9802 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 9803 callingUserHandle)) { 9804 // We can remove a profile if the admin itself has set the restriction. 9805 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 9806 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 9807 callingUserId)) { 9808 canRemoveProfile = false; 9809 } 9810 } 9811 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) { 9812 return CODE_CANNOT_ADD_MANAGED_PROFILE; 9813 } 9814 } finally { 9815 mInjector.binderRestoreCallingIdentity(ident); 9816 } 9817 return CODE_OK; 9818 } 9819 9820 private ComponentName getOwnerComponent(String packageName, int userId) { 9821 if (isDeviceOwnerPackage(packageName, userId)) { 9822 return mOwners.getDeviceOwnerComponent(); 9823 } 9824 if (isProfileOwnerPackage(packageName, userId)) { 9825 return mOwners.getProfileOwnerComponent(userId); 9826 } 9827 return null; 9828 } 9829 9830 /** 9831 * Return device owner or profile owner set on a given user. 9832 */ 9833 private @Nullable ComponentName getOwnerComponent(int userId) { 9834 synchronized (this) { 9835 if (mOwners.getDeviceOwnerUserId() == userId) { 9836 return mOwners.getDeviceOwnerComponent(); 9837 } 9838 if (mOwners.hasProfileOwner(userId)) { 9839 return mOwners.getProfileOwnerComponent(userId); 9840 } 9841 } 9842 return null; 9843 } 9844 9845 private int checkManagedUserProvisioningPreCondition(int callingUserId) { 9846 if (!hasFeatureManagedUsers()) { 9847 return CODE_MANAGED_USERS_NOT_SUPPORTED; 9848 } 9849 if (!mInjector.userManagerIsSplitSystemUser()) { 9850 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems. 9851 return CODE_NOT_SYSTEM_USER_SPLIT; 9852 } 9853 if (callingUserId == UserHandle.USER_SYSTEM) { 9854 // System user cannot be a managed user. 9855 return CODE_SYSTEM_USER; 9856 } 9857 if (hasUserSetupCompleted(callingUserId)) { 9858 return CODE_USER_SETUP_COMPLETED; 9859 } 9860 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 9861 return CODE_HAS_PAIRED; 9862 } 9863 return CODE_OK; 9864 } 9865 9866 private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) { 9867 if (!mInjector.userManagerIsSplitSystemUser()) { 9868 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems. 9869 return CODE_NOT_SYSTEM_USER_SPLIT; 9870 } 9871 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 9872 } 9873 9874 private boolean hasFeatureManagedUsers() { 9875 try { 9876 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 9877 } catch (RemoteException e) { 9878 return false; 9879 } 9880 } 9881 9882 @Override 9883 public String getWifiMacAddress(ComponentName admin) { 9884 // Make sure caller has DO. 9885 synchronized (this) { 9886 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9887 } 9888 9889 final long ident = mInjector.binderClearCallingIdentity(); 9890 try { 9891 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo(); 9892 if (wifiInfo == null) { 9893 return null; 9894 } 9895 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null; 9896 } finally { 9897 mInjector.binderRestoreCallingIdentity(ident); 9898 } 9899 } 9900 9901 /** 9902 * Returns the target sdk version number that the given packageName was built for 9903 * in the given user. 9904 */ 9905 private int getTargetSdk(String packageName, int userId) { 9906 final ApplicationInfo ai; 9907 try { 9908 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 9909 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion; 9910 return targetSdkVersion; 9911 } catch (RemoteException e) { 9912 // Shouldn't happen 9913 return 0; 9914 } 9915 } 9916 9917 @Override 9918 public boolean isManagedProfile(ComponentName admin) { 9919 enforceProfileOrDeviceOwner(admin); 9920 return isManagedProfile(mInjector.userHandleGetCallingUserId()); 9921 } 9922 9923 @Override 9924 public boolean isSystemOnlyUser(ComponentName admin) { 9925 synchronized (this) { 9926 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9927 } 9928 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9929 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM; 9930 } 9931 9932 @Override 9933 public void reboot(ComponentName admin) { 9934 Preconditions.checkNotNull(admin); 9935 // Make sure caller has DO. 9936 synchronized (this) { 9937 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9938 } 9939 long ident = mInjector.binderClearCallingIdentity(); 9940 try { 9941 // Make sure there are no ongoing calls on the device. 9942 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 9943 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 9944 } 9945 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 9946 } finally { 9947 mInjector.binderRestoreCallingIdentity(ident); 9948 } 9949 } 9950 9951 @Override 9952 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 9953 if (!mHasFeature) { 9954 return; 9955 } 9956 Preconditions.checkNotNull(who, "ComponentName is null"); 9957 final int userHandle = mInjector.userHandleGetCallingUserId(); 9958 synchronized (this) { 9959 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9960 mInjector.binderGetCallingUid()); 9961 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 9962 admin.shortSupportMessage = message; 9963 saveSettingsLocked(userHandle); 9964 } 9965 } 9966 } 9967 9968 @Override 9969 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 9970 if (!mHasFeature) { 9971 return null; 9972 } 9973 Preconditions.checkNotNull(who, "ComponentName is null"); 9974 synchronized (this) { 9975 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9976 mInjector.binderGetCallingUid()); 9977 return admin.shortSupportMessage; 9978 } 9979 } 9980 9981 @Override 9982 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 9983 if (!mHasFeature) { 9984 return; 9985 } 9986 Preconditions.checkNotNull(who, "ComponentName is null"); 9987 final int userHandle = mInjector.userHandleGetCallingUserId(); 9988 synchronized (this) { 9989 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9990 mInjector.binderGetCallingUid()); 9991 if (!TextUtils.equals(admin.longSupportMessage, message)) { 9992 admin.longSupportMessage = message; 9993 saveSettingsLocked(userHandle); 9994 } 9995 } 9996 } 9997 9998 @Override 9999 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 10000 if (!mHasFeature) { 10001 return null; 10002 } 10003 Preconditions.checkNotNull(who, "ComponentName is null"); 10004 synchronized (this) { 10005 ActiveAdmin admin = getActiveAdminForUidLocked(who, 10006 mInjector.binderGetCallingUid()); 10007 return admin.longSupportMessage; 10008 } 10009 } 10010 10011 @Override 10012 public CharSequence getShortSupportMessageForUser(@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.shortSupportMessage; 10024 } 10025 } 10026 return null; 10027 } 10028 10029 @Override 10030 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 10031 if (!mHasFeature) { 10032 return null; 10033 } 10034 Preconditions.checkNotNull(who, "ComponentName is null"); 10035 if (!isCallerWithSystemUid()) { 10036 throw new SecurityException("Only the system can query support message for user"); 10037 } 10038 synchronized (this) { 10039 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 10040 if (admin != null) { 10041 return admin.longSupportMessage; 10042 } 10043 } 10044 return null; 10045 } 10046 10047 @Override 10048 public void setOrganizationColor(@NonNull ComponentName who, int color) { 10049 if (!mHasFeature) { 10050 return; 10051 } 10052 Preconditions.checkNotNull(who, "ComponentName is null"); 10053 final int userHandle = mInjector.userHandleGetCallingUserId(); 10054 enforceManagedProfile(userHandle, "set organization color"); 10055 synchronized (this) { 10056 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10057 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10058 admin.organizationColor = color; 10059 saveSettingsLocked(userHandle); 10060 } 10061 } 10062 10063 @Override 10064 public void setOrganizationColorForUser(int color, int userId) { 10065 if (!mHasFeature) { 10066 return; 10067 } 10068 enforceFullCrossUsersPermission(userId); 10069 enforceManageUsers(); 10070 enforceManagedProfile(userId, "set organization color"); 10071 synchronized (this) { 10072 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 10073 admin.organizationColor = color; 10074 saveSettingsLocked(userId); 10075 } 10076 } 10077 10078 @Override 10079 public int getOrganizationColor(@NonNull ComponentName who) { 10080 if (!mHasFeature) { 10081 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 10082 } 10083 Preconditions.checkNotNull(who, "ComponentName is null"); 10084 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color"); 10085 synchronized (this) { 10086 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10087 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10088 return admin.organizationColor; 10089 } 10090 } 10091 10092 @Override 10093 public int getOrganizationColorForUser(int userHandle) { 10094 if (!mHasFeature) { 10095 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 10096 } 10097 enforceFullCrossUsersPermission(userHandle); 10098 enforceManagedProfile(userHandle, "get organization color"); 10099 synchronized (this) { 10100 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 10101 return (profileOwner != null) 10102 ? profileOwner.organizationColor 10103 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 10104 } 10105 } 10106 10107 @Override 10108 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 10109 if (!mHasFeature) { 10110 return; 10111 } 10112 Preconditions.checkNotNull(who, "ComponentName is null"); 10113 final int userHandle = mInjector.userHandleGetCallingUserId(); 10114 10115 synchronized (this) { 10116 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10117 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10118 if (!TextUtils.equals(admin.organizationName, text)) { 10119 admin.organizationName = (text == null || text.length() == 0) 10120 ? null : text.toString(); 10121 saveSettingsLocked(userHandle); 10122 } 10123 } 10124 } 10125 10126 @Override 10127 public CharSequence getOrganizationName(@NonNull ComponentName who) { 10128 if (!mHasFeature) { 10129 return null; 10130 } 10131 Preconditions.checkNotNull(who, "ComponentName is null"); 10132 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name"); 10133 synchronized(this) { 10134 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10135 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10136 return admin.organizationName; 10137 } 10138 } 10139 10140 @Override 10141 public CharSequence getDeviceOwnerOrganizationName() { 10142 if (!mHasFeature) { 10143 return null; 10144 } 10145 enforceDeviceOwnerOrManageUsers(); 10146 synchronized(this) { 10147 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 10148 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 10149 } 10150 } 10151 10152 @Override 10153 public CharSequence getOrganizationNameForUser(int userHandle) { 10154 if (!mHasFeature) { 10155 return null; 10156 } 10157 enforceFullCrossUsersPermission(userHandle); 10158 enforceManagedProfile(userHandle, "get organization name"); 10159 synchronized (this) { 10160 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 10161 return (profileOwner != null) 10162 ? profileOwner.organizationName 10163 : null; 10164 } 10165 } 10166 10167 @Override 10168 public void setAffiliationIds(ComponentName admin, List<String> ids) { 10169 if (!mHasFeature) { 10170 return; 10171 } 10172 if (ids == null) { 10173 throw new IllegalArgumentException("ids must not be null"); 10174 } 10175 for (String id : ids) { 10176 if (TextUtils.isEmpty(id)) { 10177 throw new IllegalArgumentException("ids must not contain empty string"); 10178 } 10179 } 10180 10181 final Set<String> affiliationIds = new ArraySet<>(ids); 10182 final int callingUserId = mInjector.userHandleGetCallingUserId(); 10183 synchronized (this) { 10184 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10185 getUserData(callingUserId).mAffiliationIds = affiliationIds; 10186 saveSettingsLocked(callingUserId); 10187 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 10188 // Affiliation ids specified by the device owner are additionally stored in 10189 // UserHandle.USER_SYSTEM's DevicePolicyData. 10190 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 10191 saveSettingsLocked(UserHandle.USER_SYSTEM); 10192 } 10193 10194 // Affiliation status for any user, not just the calling user, might have changed. 10195 // The device owner user will still be affiliated after changing its affiliation ids, 10196 // but as a result of that other users might become affiliated or un-affiliated. 10197 maybePauseDeviceWideLoggingLocked(); 10198 maybeResumeDeviceWideLoggingLocked(); 10199 maybeClearLockTaskPackagesLocked(); 10200 } 10201 } 10202 10203 @Override 10204 public List<String> getAffiliationIds(ComponentName admin) { 10205 if (!mHasFeature) { 10206 return Collections.emptyList(); 10207 } 10208 10209 Preconditions.checkNotNull(admin); 10210 synchronized (this) { 10211 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10212 return new ArrayList<String>( 10213 getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds); 10214 } 10215 } 10216 10217 @Override 10218 public boolean isAffiliatedUser() { 10219 if (!mHasFeature) { 10220 return false; 10221 } 10222 10223 synchronized (this) { 10224 return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId()); 10225 } 10226 } 10227 10228 private boolean isUserAffiliatedWithDeviceLocked(int userId) { 10229 if (!mOwners.hasDeviceOwner()) { 10230 return false; 10231 } 10232 if (userId == mOwners.getDeviceOwnerUserId()) { 10233 // The user that the DO is installed on is always affiliated with the device. 10234 return true; 10235 } 10236 if (userId == UserHandle.USER_SYSTEM) { 10237 // The system user is always affiliated in a DO device, even if the DO is set on a 10238 // different user. This could be the case if the DO is set in the primary user 10239 // of a split user device. 10240 return true; 10241 } 10242 final ComponentName profileOwner = getProfileOwner(userId); 10243 if (profileOwner == null) { 10244 return false; 10245 } 10246 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 10247 final Set<String> deviceAffiliationIds = 10248 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 10249 for (String id : userAffiliationIds) { 10250 if (deviceAffiliationIds.contains(id)) { 10251 return true; 10252 } 10253 } 10254 return false; 10255 } 10256 10257 private boolean areAllUsersAffiliatedWithDeviceLocked() { 10258 final long ident = mInjector.binderClearCallingIdentity(); 10259 try { 10260 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 10261 for (int i = 0; i < userInfos.size(); i++) { 10262 int userId = userInfos.get(i).id; 10263 if (!isUserAffiliatedWithDeviceLocked(userId)) { 10264 Slog.d(LOG_TAG, "User id " + userId + " not affiliated."); 10265 return false; 10266 } 10267 } 10268 } finally { 10269 mInjector.binderRestoreCallingIdentity(ident); 10270 } 10271 10272 return true; 10273 } 10274 10275 @Override 10276 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) { 10277 if (!mHasFeature) { 10278 return; 10279 } 10280 Preconditions.checkNotNull(admin); 10281 10282 synchronized (this) { 10283 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10284 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 10285 return; 10286 } 10287 mInjector.securityLogSetLoggingEnabledProperty(enabled); 10288 if (enabled) { 10289 mSecurityLogMonitor.start(); 10290 maybePauseDeviceWideLoggingLocked(); 10291 } else { 10292 mSecurityLogMonitor.stop(); 10293 } 10294 } 10295 } 10296 10297 @Override 10298 public boolean isSecurityLoggingEnabled(ComponentName admin) { 10299 if (!mHasFeature) { 10300 return false; 10301 } 10302 10303 synchronized (this) { 10304 if (!isCallerWithSystemUid()) { 10305 Preconditions.checkNotNull(admin); 10306 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10307 } 10308 return mInjector.securityLogGetLoggingEnabledProperty(); 10309 } 10310 } 10311 10312 private synchronized void recordSecurityLogRetrievalTime() { 10313 final long currentTime = System.currentTimeMillis(); 10314 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 10315 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 10316 policyData.mLastSecurityLogRetrievalTime = currentTime; 10317 saveSettingsLocked(UserHandle.USER_SYSTEM); 10318 } 10319 } 10320 10321 @Override 10322 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) { 10323 if (!mHasFeature) { 10324 return null; 10325 } 10326 10327 Preconditions.checkNotNull(admin); 10328 ensureDeviceOwnerAndAllUsersAffiliated(admin); 10329 10330 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs) 10331 || !mInjector.securityLogGetLoggingEnabledProperty()) { 10332 return null; 10333 } 10334 10335 recordSecurityLogRetrievalTime(); 10336 10337 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 10338 try { 10339 SecurityLog.readPreviousEvents(output); 10340 return new ParceledListSlice<SecurityEvent>(output); 10341 } catch (IOException e) { 10342 Slog.w(LOG_TAG, "Fail to read previous events" , e); 10343 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 10344 } 10345 } 10346 10347 @Override 10348 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) { 10349 if (!mHasFeature) { 10350 return null; 10351 } 10352 10353 Preconditions.checkNotNull(admin); 10354 ensureDeviceOwnerAndAllUsersAffiliated(admin); 10355 10356 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 10357 return null; 10358 } 10359 10360 recordSecurityLogRetrievalTime(); 10361 10362 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 10363 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 10364 } 10365 10366 private void enforceCanManageDeviceAdmin() { 10367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS, 10368 null); 10369 } 10370 10371 private void enforceCanManageProfileAndDeviceOwners() { 10372 mContext.enforceCallingOrSelfPermission( 10373 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 10374 } 10375 10376 private void enforceCallerSystemUserHandle() { 10377 final int callingUid = mInjector.binderGetCallingUid(); 10378 final int userId = UserHandle.getUserId(callingUid); 10379 if (userId != UserHandle.USER_SYSTEM) { 10380 throw new SecurityException("Caller has to be in user 0"); 10381 } 10382 } 10383 10384 @Override 10385 public boolean isUninstallInQueue(final String packageName) { 10386 enforceCanManageDeviceAdmin(); 10387 final int userId = mInjector.userHandleGetCallingUserId(); 10388 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 10389 synchronized (this) { 10390 return mPackagesToRemove.contains(packageUserPair); 10391 } 10392 } 10393 10394 @Override 10395 public void uninstallPackageWithActiveAdmins(final String packageName) { 10396 enforceCanManageDeviceAdmin(); 10397 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 10398 10399 final int userId = mInjector.userHandleGetCallingUserId(); 10400 10401 enforceUserUnlocked(userId); 10402 10403 final ComponentName profileOwner = getProfileOwner(userId); 10404 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 10405 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 10406 } 10407 10408 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 10409 if (getDeviceOwnerUserId() == userId && deviceOwner != null 10410 && packageName.equals(deviceOwner.getPackageName())) { 10411 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 10412 } 10413 10414 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 10415 synchronized (this) { 10416 mPackagesToRemove.add(packageUserPair); 10417 } 10418 10419 // All active admins on the user. 10420 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 10421 10422 // Active admins in the target package. 10423 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 10424 if (allActiveAdmins != null) { 10425 for (ComponentName activeAdmin : allActiveAdmins) { 10426 if (packageName.equals(activeAdmin.getPackageName())) { 10427 packageActiveAdmins.add(activeAdmin); 10428 removeActiveAdmin(activeAdmin, userId); 10429 } 10430 } 10431 } 10432 if (packageActiveAdmins.size() == 0) { 10433 startUninstallIntent(packageName, userId); 10434 } else { 10435 mHandler.postDelayed(new Runnable() { 10436 @Override 10437 public void run() { 10438 for (ComponentName activeAdmin : packageActiveAdmins) { 10439 removeAdminArtifacts(activeAdmin, userId); 10440 } 10441 startUninstallIntent(packageName, userId); 10442 } 10443 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 10444 } 10445 } 10446 10447 @Override 10448 public boolean isDeviceProvisioned() { 10449 synchronized (this) { 10450 return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete; 10451 } 10452 } 10453 10454 private boolean isCurrentUserDemo() { 10455 if (UserManager.isDeviceInDemoMode(mContext)) { 10456 final int userId = mInjector.userHandleGetCallingUserId(); 10457 final long callingIdentity = mInjector.binderClearCallingIdentity(); 10458 try { 10459 return mUserManager.getUserInfo(userId).isDemo(); 10460 } finally { 10461 mInjector.binderRestoreCallingIdentity(callingIdentity); 10462 } 10463 } 10464 return false; 10465 } 10466 10467 private void removePackageIfRequired(final String packageName, final int userId) { 10468 if (!packageHasActiveAdmins(packageName, userId)) { 10469 // Will not do anything if uninstall was not requested or was already started. 10470 startUninstallIntent(packageName, userId); 10471 } 10472 } 10473 10474 private void startUninstallIntent(final String packageName, final int userId) { 10475 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 10476 synchronized (this) { 10477 if (!mPackagesToRemove.contains(packageUserPair)) { 10478 // Do nothing if uninstall was not requested or was already started. 10479 return; 10480 } 10481 mPackagesToRemove.remove(packageUserPair); 10482 } 10483 try { 10484 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) { 10485 // Package does not exist. Nothing to do. 10486 return; 10487 } 10488 } catch (RemoteException re) { 10489 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info"); 10490 } 10491 10492 try { // force stop the package before uninstalling 10493 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 10494 } catch (RemoteException re) { 10495 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 10496 } 10497 final Uri packageURI = Uri.parse("package:" + packageName); 10498 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 10499 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 10500 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 10501 } 10502 10503 /** 10504 * Removes the admin from the policy. Ideally called after the admin's 10505 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 10506 * 10507 * @param adminReceiver The admin to remove 10508 * @param userHandle The user for which this admin has to be removed. 10509 */ 10510 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 10511 synchronized (this) { 10512 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 10513 if (admin == null) { 10514 return; 10515 } 10516 final DevicePolicyData policy = getUserData(userHandle); 10517 final boolean doProxyCleanup = admin.info.usesPolicy( 10518 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 10519 policy.mAdminList.remove(admin); 10520 policy.mAdminMap.remove(adminReceiver); 10521 validatePasswordOwnerLocked(policy); 10522 if (doProxyCleanup) { 10523 resetGlobalProxyLocked(policy); 10524 } 10525 saveSettingsLocked(userHandle); 10526 updateMaximumTimeToLockLocked(userHandle); 10527 policy.mRemovingAdmins.remove(adminReceiver); 10528 10529 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 10530 } 10531 // The removed admin might have disabled camera, so update user 10532 // restrictions. 10533 pushUserRestrictions(userHandle); 10534 } 10535 10536 @Override 10537 public void setDeviceProvisioningConfigApplied() { 10538 enforceManageUsers(); 10539 synchronized (this) { 10540 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 10541 policy.mDeviceProvisioningConfigApplied = true; 10542 saveSettingsLocked(UserHandle.USER_SYSTEM); 10543 } 10544 } 10545 10546 @Override 10547 public boolean isDeviceProvisioningConfigApplied() { 10548 enforceManageUsers(); 10549 synchronized (this) { 10550 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 10551 return policy.mDeviceProvisioningConfigApplied; 10552 } 10553 } 10554 10555 /** 10556 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 10557 * 10558 * It's added for testing only. Please use this API carefully if it's used by other system app 10559 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 10560 * apps. 10561 */ 10562 @Override 10563 public void forceUpdateUserSetupComplete() { 10564 enforceCanManageProfileAndDeviceOwners(); 10565 enforceCallerSystemUserHandle(); 10566 // no effect if it's called from user build 10567 if (!mInjector.isBuildDebuggable()) { 10568 return; 10569 } 10570 final int userId = UserHandle.USER_SYSTEM; 10571 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 10572 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 10573 DevicePolicyData policy = getUserData(userId); 10574 policy.mUserSetupComplete = isUserCompleted; 10575 synchronized (this) { 10576 saveSettingsLocked(userId); 10577 } 10578 } 10579 10580 // TODO(b/22388012): When backup is available for secondary users and profiles, consider 10581 // whether there are any privacy/security implications of enabling the backup service here 10582 // if there are other users or profiles unmanaged or managed by a different entity (i.e. not 10583 // affiliated). 10584 @Override 10585 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 10586 if (!mHasFeature) { 10587 return; 10588 } 10589 Preconditions.checkNotNull(admin); 10590 synchronized (this) { 10591 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10592 } 10593 10594 final long ident = mInjector.binderClearCallingIdentity(); 10595 try { 10596 IBackupManager ibm = mInjector.getIBackupManager(); 10597 if (ibm != null) { 10598 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled); 10599 } 10600 } catch (RemoteException e) { 10601 throw new IllegalStateException( 10602 "Failed " + (enabled ? "" : "de") + "activating backup service.", e); 10603 } finally { 10604 mInjector.binderRestoreCallingIdentity(ident); 10605 } 10606 } 10607 10608 @Override 10609 public boolean isBackupServiceEnabled(ComponentName admin) { 10610 Preconditions.checkNotNull(admin); 10611 if (!mHasFeature) { 10612 return true; 10613 } 10614 synchronized (this) { 10615 try { 10616 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10617 IBackupManager ibm = mInjector.getIBackupManager(); 10618 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM); 10619 } catch (RemoteException e) { 10620 throw new IllegalStateException("Failed requesting backup service state.", e); 10621 } 10622 } 10623 } 10624 10625 @Override 10626 public boolean bindDeviceAdminServiceAsUser( 10627 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 10628 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 10629 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 10630 if (!mHasFeature) { 10631 return false; 10632 } 10633 Preconditions.checkNotNull(admin); 10634 Preconditions.checkNotNull(caller); 10635 Preconditions.checkNotNull(serviceIntent); 10636 Preconditions.checkArgument( 10637 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 10638 "Service intent must be explicit (with a package name or component): " 10639 + serviceIntent); 10640 Preconditions.checkNotNull(connection); 10641 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 10642 "target user id must be different from the calling user id"); 10643 10644 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 10645 throw new SecurityException("Not allowed to bind to target user id"); 10646 } 10647 10648 final String targetPackage; 10649 synchronized (this) { 10650 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 10651 } 10652 10653 final long callingIdentity = mInjector.binderClearCallingIdentity(); 10654 try { 10655 // Validate and sanitize the incoming service intent. 10656 final Intent sanitizedIntent = 10657 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 10658 if (sanitizedIntent == null) { 10659 // Fail, cannot lookup the target service. 10660 return false; 10661 } 10662 // Ask ActivityManager to bind it. Notice that we are binding the service with the 10663 // caller app instead of DevicePolicyManagerService. 10664 return mInjector.getIActivityManager().bindService( 10665 caller, activtiyToken, serviceIntent, 10666 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 10667 connection, flags, mContext.getOpPackageName(), 10668 targetUserId) != 0; 10669 } catch (RemoteException ex) { 10670 // Same process, should not happen. 10671 } finally { 10672 mInjector.binderRestoreCallingIdentity(callingIdentity); 10673 } 10674 10675 // Failed to bind. 10676 return false; 10677 } 10678 10679 @Override 10680 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 10681 if (!mHasFeature) { 10682 return Collections.emptyList(); 10683 } 10684 Preconditions.checkNotNull(admin); 10685 10686 synchronized (this) { 10687 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10688 10689 final int callingUserId = mInjector.userHandleGetCallingUserId(); 10690 final long callingIdentity = mInjector.binderClearCallingIdentity(); 10691 try { 10692 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 10693 if (!isDeviceOwner(admin, callingUserId)) { 10694 // Profile owners can only bind to the device owner. 10695 if (canUserBindToDeviceOwnerLocked(callingUserId)) { 10696 targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId())); 10697 } 10698 } else { 10699 // Caller is the device owner: Look for profile owners that it can bind to. 10700 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 10701 for (int i = 0; i < userInfos.size(); i++) { 10702 final int userId = userInfos.get(i).id; 10703 if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) { 10704 targetUsers.add(UserHandle.of(userId)); 10705 } 10706 } 10707 } 10708 10709 return targetUsers; 10710 } finally { 10711 mInjector.binderRestoreCallingIdentity(callingIdentity); 10712 } 10713 } 10714 } 10715 10716 private boolean canUserBindToDeviceOwnerLocked(int userId) { 10717 // There has to be a device owner, under another user id. 10718 if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) { 10719 return false; 10720 } 10721 10722 // The user must have a profile owner that belongs to the same package as the device owner. 10723 if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals( 10724 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) { 10725 return false; 10726 } 10727 10728 // The user must be affiliated. 10729 return isUserAffiliatedWithDeviceLocked(userId); 10730 } 10731 10732 /** 10733 * Return true if a given user has any accounts that'll prevent installing a device or profile 10734 * owner {@code owner}. 10735 * - If the user has no accounts, then return false. 10736 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 10737 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 10738 * ..._DISALLOWED, return true. 10739 * - Otherwise return false. 10740 * 10741 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used 10742 * when the caller is not ADB. 10743 * 10744 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 10745 */ 10746 private boolean hasIncompatibleAccountsOrNonAdbNoLock( 10747 int userId, @Nullable ComponentName owner) { 10748 if (!isAdb()) { 10749 return true; 10750 } 10751 wtfIfInLock(); 10752 10753 final long token = mInjector.binderClearCallingIdentity(); 10754 try { 10755 final AccountManager am = AccountManager.get(mContext); 10756 final Account accounts[] = am.getAccountsAsUser(userId); 10757 if (accounts.length == 0) { 10758 return false; 10759 } 10760 synchronized (this) { 10761 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 10762 Log.w(LOG_TAG, 10763 "Non test-only owner can't be installed with existing accounts."); 10764 return true; 10765 } 10766 } 10767 10768 final String[] feature_allow = 10769 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 10770 final String[] feature_disallow = 10771 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 10772 10773 boolean compatible = true; 10774 for (Account account : accounts) { 10775 if (hasAccountFeatures(am, account, feature_disallow)) { 10776 Log.e(LOG_TAG, account + " has " + feature_disallow[0]); 10777 compatible = false; 10778 break; 10779 } 10780 if (!hasAccountFeatures(am, account, feature_allow)) { 10781 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]); 10782 compatible = false; 10783 break; 10784 } 10785 } 10786 if (compatible) { 10787 Log.w(LOG_TAG, "All accounts are compatible"); 10788 } else { 10789 Log.e(LOG_TAG, "Found incompatible accounts"); 10790 } 10791 return !compatible; 10792 } finally { 10793 mInjector.binderRestoreCallingIdentity(token); 10794 } 10795 } 10796 10797 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 10798 try { 10799 return am.hasFeatures(account, features, null, null).getResult(); 10800 } catch (Exception e) { 10801 Log.w(LOG_TAG, "Failed to get account feature", e); 10802 return false; 10803 } 10804 } 10805 10806 private boolean isAdb() { 10807 final int callingUid = mInjector.binderGetCallingUid(); 10808 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 10809 } 10810 10811 @Override 10812 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) { 10813 if (!mHasFeature) { 10814 return; 10815 } 10816 Preconditions.checkNotNull(admin); 10817 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10818 10819 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 10820 // already in the requested state 10821 return; 10822 } 10823 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10824 deviceOwner.isNetworkLoggingEnabled = enabled; 10825 if (!enabled) { 10826 deviceOwner.numNetworkLoggingNotifications = 0; 10827 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 10828 } 10829 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 10830 10831 setNetworkLoggingActiveInternal(enabled); 10832 } 10833 10834 private synchronized void setNetworkLoggingActiveInternal(boolean active) { 10835 final long callingIdentity = mInjector.binderClearCallingIdentity(); 10836 try { 10837 if (active) { 10838 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal()); 10839 if (!mNetworkLogger.startNetworkLogging()) { 10840 mNetworkLogger = null; 10841 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging" 10842 + " service not being available yet."); 10843 } 10844 maybePauseDeviceWideLoggingLocked(); 10845 sendNetworkLoggingNotificationLocked(); 10846 } else { 10847 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 10848 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 10849 + " service not being available yet."); 10850 } 10851 mNetworkLogger = null; 10852 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING); 10853 } 10854 } finally { 10855 mInjector.binderRestoreCallingIdentity(callingIdentity); 10856 } 10857 } 10858 10859 /** Pauses security and network logging if there are unaffiliated users on the device */ 10860 private void maybePauseDeviceWideLoggingLocked() { 10861 if (!areAllUsersAffiliatedWithDeviceLocked()) { 10862 Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be " 10863 + "paused if enabled."); 10864 mSecurityLogMonitor.pause(); 10865 if (mNetworkLogger != null) { 10866 mNetworkLogger.pause(); 10867 } 10868 } 10869 } 10870 10871 /** Resumes security and network logging (if they are enabled) if all users are affiliated */ 10872 private void maybeResumeDeviceWideLoggingLocked() { 10873 if (areAllUsersAffiliatedWithDeviceLocked()) { 10874 final long ident = mInjector.binderClearCallingIdentity(); 10875 try { 10876 mSecurityLogMonitor.resume(); 10877 if (mNetworkLogger != null) { 10878 mNetworkLogger.resume(); 10879 } 10880 } finally { 10881 mInjector.binderRestoreCallingIdentity(ident); 10882 } 10883 } 10884 } 10885 10886 /** Deletes any security and network logs that might have been collected so far */ 10887 private void discardDeviceWideLogsLocked() { 10888 mSecurityLogMonitor.discardLogs(); 10889 if (mNetworkLogger != null) { 10890 mNetworkLogger.discardLogs(); 10891 } 10892 // TODO: We should discard pre-boot security logs here too, as otherwise those 10893 // logs (which might contain data from the user just removed) will be 10894 // available after next boot. 10895 } 10896 10897 @Override 10898 public boolean isNetworkLoggingEnabled(ComponentName admin) { 10899 if (!mHasFeature) { 10900 return false; 10901 } 10902 synchronized (this) { 10903 enforceDeviceOwnerOrManageUsers(); 10904 return isNetworkLoggingEnabledInternalLocked(); 10905 } 10906 } 10907 10908 private boolean isNetworkLoggingEnabledInternalLocked() { 10909 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10910 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled; 10911 } 10912 10913 /* 10914 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 10915 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 10916 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 10917 * 10918 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 10919 */ 10920 @Override 10921 public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) { 10922 if (!mHasFeature) { 10923 return null; 10924 } 10925 Preconditions.checkNotNull(admin); 10926 ensureDeviceOwnerAndAllUsersAffiliated(admin); 10927 10928 synchronized (this) { 10929 if (mNetworkLogger == null 10930 || !isNetworkLoggingEnabledInternalLocked()) { 10931 return null; 10932 } 10933 10934 final long currentTime = System.currentTimeMillis(); 10935 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 10936 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 10937 policyData.mLastNetworkLogsRetrievalTime = currentTime; 10938 saveSettingsLocked(UserHandle.USER_SYSTEM); 10939 } 10940 return mNetworkLogger.retrieveLogs(batchToken); 10941 } 10942 } 10943 10944 private void sendNetworkLoggingNotificationLocked() { 10945 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10946 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 10947 return; 10948 } 10949 if (deviceOwner.numNetworkLoggingNotifications >= 10950 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 10951 return; 10952 } 10953 final long now = System.currentTimeMillis(); 10954 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 10955 return; 10956 } 10957 deviceOwner.numNetworkLoggingNotifications++; 10958 if (deviceOwner.numNetworkLoggingNotifications 10959 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 10960 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 10961 } else { 10962 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 10963 } 10964 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 10965 intent.setPackage("com.android.systemui"); 10966 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0, 10967 UserHandle.CURRENT); 10968 Notification notification = 10969 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 10970 .setSmallIcon(R.drawable.ic_info_outline) 10971 .setContentTitle(mContext.getString(R.string.network_logging_notification_title)) 10972 .setContentText(mContext.getString(R.string.network_logging_notification_text)) 10973 .setTicker(mContext.getString(R.string.network_logging_notification_title)) 10974 .setShowWhen(true) 10975 .setContentIntent(pendingIntent) 10976 .setStyle(new Notification.BigTextStyle() 10977 .bigText(mContext.getString(R.string.network_logging_notification_text))) 10978 .build(); 10979 mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification); 10980 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 10981 } 10982 10983 /** 10984 * Return the package name of owner in a given user. 10985 */ 10986 private String getOwnerPackageNameForUserLocked(int userId) { 10987 return mOwners.getDeviceOwnerUserId() == userId 10988 ? mOwners.getDeviceOwnerPackageName() 10989 : mOwners.getProfileOwnerPackage(userId); 10990 } 10991 10992 /** 10993 * @param rawIntent Original service intent specified by caller. It must be explicit. 10994 * @param expectedPackageName The expected package name of the resolved service. 10995 * @return Intent that have component explicitly set. {@code null} if no service is resolved 10996 * with the given intent. 10997 * @throws SecurityException if the intent is resolved to an invalid service. 10998 */ 10999 private Intent createCrossUserServiceIntent( 11000 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 11001 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 11002 ResolveInfo info = mIPackageManager.resolveService( 11003 rawIntent, 11004 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 11005 0, // flags 11006 targetUserId); 11007 if (info == null || info.serviceInfo == null) { 11008 Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent 11009 + " or user " + targetUserId + " is not running"); 11010 return null; 11011 } 11012 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 11013 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 11014 } 11015 // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release. 11016 if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) { 11017 throw new SecurityException( 11018 "Service must be protected by BIND_DEVICE_ADMIN permission"); 11019 } 11020 // It is the system server to bind the service, it would be extremely dangerous if it 11021 // can be exploited to bind any service. Set the component explicitly to make sure we 11022 // do not bind anything accidentally. 11023 rawIntent.setComponent(info.serviceInfo.getComponentName()); 11024 return rawIntent; 11025 } 11026 11027 @Override 11028 public long getLastSecurityLogRetrievalTime() { 11029 enforceDeviceOwnerOrManageUsers(); 11030 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 11031 } 11032 11033 @Override 11034 public long getLastBugReportRequestTime() { 11035 enforceDeviceOwnerOrManageUsers(); 11036 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 11037 } 11038 11039 @Override 11040 public long getLastNetworkLogRetrievalTime() { 11041 enforceDeviceOwnerOrManageUsers(); 11042 return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime; 11043 } 11044 11045 @Override 11046 public boolean setResetPasswordToken(ComponentName admin, byte[] token) { 11047 if (!mHasFeature) { 11048 return false; 11049 } 11050 if (token == null || token.length < 32) { 11051 throw new IllegalArgumentException("token must be at least 32-byte long"); 11052 } 11053 synchronized (this) { 11054 final int userHandle = mInjector.userHandleGetCallingUserId(); 11055 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11056 11057 DevicePolicyData policy = getUserData(userHandle); 11058 long ident = mInjector.binderClearCallingIdentity(); 11059 try { 11060 if (policy.mPasswordTokenHandle != 0) { 11061 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle); 11062 } 11063 11064 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle); 11065 saveSettingsLocked(userHandle); 11066 return policy.mPasswordTokenHandle != 0; 11067 } finally { 11068 mInjector.binderRestoreCallingIdentity(ident); 11069 } 11070 } 11071 } 11072 11073 @Override 11074 public boolean clearResetPasswordToken(ComponentName admin) { 11075 if (!mHasFeature) { 11076 return false; 11077 } 11078 synchronized (this) { 11079 final int userHandle = mInjector.userHandleGetCallingUserId(); 11080 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11081 11082 DevicePolicyData policy = getUserData(userHandle); 11083 if (policy.mPasswordTokenHandle != 0) { 11084 long ident = mInjector.binderClearCallingIdentity(); 11085 try { 11086 boolean result = mLockPatternUtils.removeEscrowToken( 11087 policy.mPasswordTokenHandle, userHandle); 11088 policy.mPasswordTokenHandle = 0; 11089 saveSettingsLocked(userHandle); 11090 return result; 11091 } finally { 11092 mInjector.binderRestoreCallingIdentity(ident); 11093 } 11094 } 11095 } 11096 return false; 11097 } 11098 11099 @Override 11100 public boolean isResetPasswordTokenActive(ComponentName admin) { 11101 synchronized (this) { 11102 final int userHandle = mInjector.userHandleGetCallingUserId(); 11103 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11104 11105 DevicePolicyData policy = getUserData(userHandle); 11106 if (policy.mPasswordTokenHandle != 0) { 11107 long ident = mInjector.binderClearCallingIdentity(); 11108 try { 11109 return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle, 11110 userHandle); 11111 } finally { 11112 mInjector.binderRestoreCallingIdentity(ident); 11113 } 11114 } 11115 } 11116 return false; 11117 } 11118 11119 @Override 11120 public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, 11121 int flags) { 11122 Preconditions.checkNotNull(token); 11123 synchronized (this) { 11124 final int userHandle = mInjector.userHandleGetCallingUserId(); 11125 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11126 11127 DevicePolicyData policy = getUserData(userHandle); 11128 if (policy.mPasswordTokenHandle != 0) { 11129 final String password = passwordOrNull != null ? passwordOrNull : ""; 11130 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token, 11131 flags, mInjector.binderGetCallingUid(), userHandle); 11132 } else { 11133 Slog.w(LOG_TAG, "No saved token handle"); 11134 } 11135 } 11136 return false; 11137 } 11138 11139 @Override 11140 public boolean isCurrentInputMethodSetByOwner() { 11141 enforceProfileOwnerOrSystemUser(); 11142 return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet; 11143 } 11144 11145 @Override 11146 public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) { 11147 final int userId = user.getIdentifier(); 11148 enforceProfileOwnerOrFullCrossUsersPermission(userId); 11149 synchronized (this) { 11150 return new StringParceledListSlice( 11151 new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts)); 11152 } 11153 } 11154} 11155