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