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