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