DevicePolicyManagerService.java revision 9ecde42164cf1a3d24878d52411f12fcb348092e
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 saveSettingsLocked(userId); 3948 } 3949 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 3950 } 3951 } 3952 3953 /** 3954 * Updates a flag that tells us whether the user's password currently satisfies the 3955 * requirements set by all of the user's active admins. The flag is updated both in memory 3956 * and persisted to disk by calling {@link #saveSettingsLocked}, for the value of the flag 3957 * be the correct one upon boot. 3958 * This should be called whenever the password or the admin policies have changed. 3959 */ 3960 private void updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) { 3961 final int credentialOwner = getCredentialOwner(userHandle, parent); 3962 DevicePolicyData policy = getUserData(credentialOwner); 3963 PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner); 3964 if (metrics == null) { 3965 metrics = new PasswordMetrics(); 3966 } 3967 policy.mPasswordValidAtLastCheckpoint = 3968 isPasswordSufficientForUserWithoutCheckpointLocked( 3969 metrics, userHandle, parent); 3970 3971 saveSettingsLocked(credentialOwner); 3972 } 3973 3974 @Override 3975 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) { 3976 if (!mHasFeature) { 3977 return PASSWORD_QUALITY_UNSPECIFIED; 3978 } 3979 enforceFullCrossUsersPermission(userHandle); 3980 synchronized (getLockObject()) { 3981 int mode = PASSWORD_QUALITY_UNSPECIFIED; 3982 3983 if (who != null) { 3984 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3985 return admin != null ? admin.minimumPasswordMetrics.quality : mode; 3986 } 3987 3988 // Return the strictest policy across all participating admins. 3989 List<ActiveAdmin> admins = 3990 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3991 final int N = admins.size(); 3992 for (int i = 0; i < N; i++) { 3993 ActiveAdmin admin = admins.get(i); 3994 if (mode < admin.minimumPasswordMetrics.quality) { 3995 mode = admin.minimumPasswordMetrics.quality; 3996 } 3997 } 3998 return mode; 3999 } 4000 } 4001 4002 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked( 4003 int userHandle, boolean parent) { 4004 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) { 4005 // If this user has a separate challenge, only return its restrictions. 4006 return getUserDataUnchecked(userHandle).mAdminList; 4007 } else { 4008 // Return all admins for this user and the profiles that are visible from this 4009 // user that do not use a separate work challenge. 4010 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>(); 4011 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4012 DevicePolicyData policy = getUserData(userInfo.id); 4013 if (!userInfo.isManagedProfile()) { 4014 admins.addAll(policy.mAdminList); 4015 } else { 4016 // For managed profiles, we always include the policies set on the parent 4017 // profile. Additionally, we include the ones set on the managed profile 4018 // if no separate challenge is in place. 4019 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id); 4020 final int N = policy.mAdminList.size(); 4021 for (int i = 0; i < N; i++) { 4022 ActiveAdmin admin = policy.mAdminList.get(i); 4023 if (admin.hasParentActiveAdmin()) { 4024 admins.add(admin.getParentActiveAdmin()); 4025 } 4026 if (!hasSeparateChallenge) { 4027 admins.add(admin); 4028 } 4029 } 4030 } 4031 } 4032 return admins; 4033 } 4034 } 4035 4036 private boolean isSeparateProfileChallengeEnabled(int userHandle) { 4037 long ident = mInjector.binderClearCallingIdentity(); 4038 try { 4039 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle); 4040 } finally { 4041 mInjector.binderRestoreCallingIdentity(ident); 4042 } 4043 } 4044 4045 @Override 4046 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) { 4047 if (!mHasFeature) { 4048 return; 4049 } 4050 Preconditions.checkNotNull(who, "ComponentName is null"); 4051 final int userId = mInjector.userHandleGetCallingUserId(); 4052 synchronized (getLockObject()) { 4053 ActiveAdmin ap = getActiveAdminForCallerLocked( 4054 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4055 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4056 if (metrics.length != length) { 4057 metrics.length = length; 4058 updatePasswordValidityCheckpointLocked(userId, parent); 4059 saveSettingsLocked(userId); 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 saveSettingsLocked(userId); 4085 } 4086 } 4087 if (SecurityLog.isLoggingEnabled()) { 4088 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4089 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET, 4090 who.getPackageName(), userId, affectedUserId, length); 4091 } 4092 } 4093 4094 @Override 4095 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) { 4096 return getStrictestPasswordRequirement(who, userHandle, parent, 4097 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED); 4098 } 4099 4100 @Override 4101 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) { 4102 if (!mHasFeature) { 4103 return; 4104 } 4105 Preconditions.checkNotNull(who, "ComponentName is null"); 4106 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms"); 4107 final int userHandle = mInjector.userHandleGetCallingUserId(); 4108 synchronized (getLockObject()) { 4109 ActiveAdmin ap = getActiveAdminForCallerLocked( 4110 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent); 4111 // Calling this API automatically bumps the expiration date 4112 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 4113 ap.passwordExpirationDate = expiration; 4114 ap.passwordExpirationTimeout = timeout; 4115 if (timeout > 0L) { 4116 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 4117 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 4118 .format(new Date(expiration))); 4119 } 4120 saveSettingsLocked(userHandle); 4121 4122 // in case this is the first one, set the alarm on the appropriate user. 4123 setExpirationAlarmCheckLocked(mContext, userHandle, parent); 4124 } 4125 if (SecurityLog.isLoggingEnabled()) { 4126 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 4127 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(), 4128 userHandle, affectedUserId, timeout); 4129 } 4130 } 4131 4132 /** 4133 * Return a single admin's expiration cycle time, or the min of all cycle times. 4134 * Returns 0 if not configured. 4135 */ 4136 @Override 4137 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) { 4138 if (!mHasFeature) { 4139 return 0L; 4140 } 4141 enforceFullCrossUsersPermission(userHandle); 4142 synchronized (getLockObject()) { 4143 long timeout = 0L; 4144 4145 if (who != null) { 4146 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4147 return admin != null ? admin.passwordExpirationTimeout : timeout; 4148 } 4149 4150 // Return the strictest policy across all participating admins. 4151 List<ActiveAdmin> admins = 4152 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4153 final int N = admins.size(); 4154 for (int i = 0; i < N; i++) { 4155 ActiveAdmin admin = admins.get(i); 4156 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 4157 && timeout > admin.passwordExpirationTimeout)) { 4158 timeout = admin.passwordExpirationTimeout; 4159 } 4160 } 4161 return timeout; 4162 } 4163 } 4164 4165 @Override 4166 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4167 final int userId = UserHandle.getCallingUserId(); 4168 List<String> changedProviders = null; 4169 4170 synchronized (getLockObject()) { 4171 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4172 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4173 if (activeAdmin.crossProfileWidgetProviders == null) { 4174 activeAdmin.crossProfileWidgetProviders = new ArrayList<>(); 4175 } 4176 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4177 if (!providers.contains(packageName)) { 4178 providers.add(packageName); 4179 changedProviders = new ArrayList<>(providers); 4180 saveSettingsLocked(userId); 4181 } 4182 } 4183 4184 if (changedProviders != null) { 4185 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 4186 return true; 4187 } 4188 4189 return false; 4190 } 4191 4192 @Override 4193 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4194 final int userId = UserHandle.getCallingUserId(); 4195 List<String> changedProviders = null; 4196 4197 synchronized (getLockObject()) { 4198 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4199 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4200 if (activeAdmin.crossProfileWidgetProviders == null 4201 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4202 return false; 4203 } 4204 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4205 if (providers.remove(packageName)) { 4206 changedProviders = new ArrayList<>(providers); 4207 saveSettingsLocked(userId); 4208 } 4209 } 4210 4211 if (changedProviders != null) { 4212 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 4213 return true; 4214 } 4215 4216 return false; 4217 } 4218 4219 @Override 4220 public List<String> getCrossProfileWidgetProviders(ComponentName admin) { 4221 synchronized (getLockObject()) { 4222 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4223 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4224 if (activeAdmin.crossProfileWidgetProviders == null 4225 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4226 return null; 4227 } 4228 if (mInjector.binderIsCallingUidMyUid()) { 4229 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders); 4230 } else { 4231 return activeAdmin.crossProfileWidgetProviders; 4232 } 4233 } 4234 } 4235 4236 /** 4237 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 4238 * Returns 0 if not configured. 4239 */ 4240 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) { 4241 long timeout = 0L; 4242 4243 if (who != null) { 4244 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4245 return admin != null ? admin.passwordExpirationDate : timeout; 4246 } 4247 4248 // Return the strictest policy across all participating admins. 4249 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4250 final int N = admins.size(); 4251 for (int i = 0; i < N; i++) { 4252 ActiveAdmin admin = admins.get(i); 4253 if (timeout == 0L || (admin.passwordExpirationDate != 0 4254 && timeout > admin.passwordExpirationDate)) { 4255 timeout = admin.passwordExpirationDate; 4256 } 4257 } 4258 return timeout; 4259 } 4260 4261 @Override 4262 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) { 4263 if (!mHasFeature) { 4264 return 0L; 4265 } 4266 enforceFullCrossUsersPermission(userHandle); 4267 synchronized (getLockObject()) { 4268 return getPasswordExpirationLocked(who, userHandle, parent); 4269 } 4270 } 4271 4272 @Override 4273 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) { 4274 if (!mHasFeature) { 4275 return; 4276 } 4277 Preconditions.checkNotNull(who, "ComponentName is null"); 4278 final int userId = mInjector.userHandleGetCallingUserId(); 4279 synchronized (getLockObject()) { 4280 final ActiveAdmin ap = getActiveAdminForCallerLocked( 4281 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4282 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4283 if (metrics.upperCase != length) { 4284 metrics.upperCase = length; 4285 updatePasswordValidityCheckpointLocked(userId, parent); 4286 saveSettingsLocked(userId); 4287 } 4288 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4289 } 4290 } 4291 4292 @Override 4293 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) { 4294 return getStrictestPasswordRequirement(who, userHandle, parent, 4295 admin -> admin.minimumPasswordMetrics.upperCase, PASSWORD_QUALITY_COMPLEX); 4296 } 4297 4298 @Override 4299 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) { 4300 Preconditions.checkNotNull(who, "ComponentName is null"); 4301 final int userId = mInjector.userHandleGetCallingUserId(); 4302 synchronized (getLockObject()) { 4303 ActiveAdmin ap = getActiveAdminForCallerLocked( 4304 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4305 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4306 if (metrics.lowerCase != length) { 4307 metrics.lowerCase = length; 4308 updatePasswordValidityCheckpointLocked(userId, parent); 4309 saveSettingsLocked(userId); 4310 } 4311 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4312 } 4313 } 4314 4315 @Override 4316 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) { 4317 return getStrictestPasswordRequirement(who, userHandle, parent, 4318 admin -> admin.minimumPasswordMetrics.lowerCase, PASSWORD_QUALITY_COMPLEX); 4319 } 4320 4321 @Override 4322 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) { 4323 if (!mHasFeature) { 4324 return; 4325 } 4326 Preconditions.checkNotNull(who, "ComponentName is null"); 4327 final int userId = mInjector.userHandleGetCallingUserId(); 4328 synchronized (getLockObject()) { 4329 ActiveAdmin ap = getActiveAdminForCallerLocked( 4330 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4331 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4332 if (metrics.letters != length) { 4333 metrics.letters = length; 4334 updatePasswordValidityCheckpointLocked(userId, parent); 4335 saveSettingsLocked(userId); 4336 } 4337 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4338 } 4339 } 4340 4341 @Override 4342 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) { 4343 return getStrictestPasswordRequirement(who, userHandle, parent, 4344 admin -> admin.minimumPasswordMetrics.letters, PASSWORD_QUALITY_COMPLEX); 4345 } 4346 4347 @Override 4348 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) { 4349 if (!mHasFeature) { 4350 return; 4351 } 4352 Preconditions.checkNotNull(who, "ComponentName is null"); 4353 final int userId = mInjector.userHandleGetCallingUserId(); 4354 synchronized (getLockObject()) { 4355 ActiveAdmin ap = getActiveAdminForCallerLocked( 4356 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4357 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4358 if (metrics.numeric != length) { 4359 metrics.numeric = length; 4360 updatePasswordValidityCheckpointLocked(userId, parent); 4361 saveSettingsLocked(userId); 4362 } 4363 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4364 } 4365 } 4366 4367 @Override 4368 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) { 4369 return getStrictestPasswordRequirement(who, userHandle, parent, 4370 admin -> admin.minimumPasswordMetrics.numeric, PASSWORD_QUALITY_COMPLEX); 4371 } 4372 4373 @Override 4374 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) { 4375 if (!mHasFeature) { 4376 return; 4377 } 4378 Preconditions.checkNotNull(who, "ComponentName is null"); 4379 final int userId = mInjector.userHandleGetCallingUserId(); 4380 synchronized (getLockObject()) { 4381 ActiveAdmin ap = getActiveAdminForCallerLocked( 4382 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4383 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4384 if (metrics.symbols != length) { 4385 ap.minimumPasswordMetrics.symbols = length; 4386 updatePasswordValidityCheckpointLocked(userId, parent); 4387 saveSettingsLocked(userId); 4388 } 4389 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4390 } 4391 } 4392 4393 @Override 4394 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) { 4395 return getStrictestPasswordRequirement(who, userHandle, parent, 4396 admin -> admin.minimumPasswordMetrics.symbols, PASSWORD_QUALITY_COMPLEX); 4397 } 4398 4399 @Override 4400 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) { 4401 if (!mHasFeature) { 4402 return; 4403 } 4404 Preconditions.checkNotNull(who, "ComponentName is null"); 4405 final int userId = mInjector.userHandleGetCallingUserId(); 4406 synchronized (getLockObject()) { 4407 ActiveAdmin ap = getActiveAdminForCallerLocked( 4408 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4409 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4410 if (metrics.nonLetter != length) { 4411 ap.minimumPasswordMetrics.nonLetter = length; 4412 updatePasswordValidityCheckpointLocked(userId, parent); 4413 saveSettingsLocked(userId); 4414 } 4415 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4416 } 4417 } 4418 4419 @Override 4420 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) { 4421 return getStrictestPasswordRequirement(who, userHandle, parent, 4422 admin -> admin.minimumPasswordMetrics.nonLetter, PASSWORD_QUALITY_COMPLEX); 4423 } 4424 4425 /** 4426 * Calculates strictest (maximum) value for a given password property enforced by admin[s]. 4427 */ 4428 private int getStrictestPasswordRequirement(ComponentName who, int userHandle, 4429 boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) { 4430 if (!mHasFeature) { 4431 return 0; 4432 } 4433 enforceFullCrossUsersPermission(userHandle); 4434 synchronized (getLockObject()) { 4435 if (who != null) { 4436 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4437 return admin != null ? getter.apply(admin) : 0; 4438 } 4439 4440 int maxValue = 0; 4441 final List<ActiveAdmin> admins = 4442 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4443 final int N = admins.size(); 4444 for (int i = 0; i < N; i++) { 4445 final ActiveAdmin admin = admins.get(i); 4446 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) { 4447 continue; 4448 } 4449 final Integer adminValue = getter.apply(admin); 4450 if (adminValue > maxValue) { 4451 maxValue = adminValue; 4452 } 4453 } 4454 return maxValue; 4455 } 4456 } 4457 4458 @Override 4459 public boolean isActivePasswordSufficient(int userHandle, boolean parent) { 4460 if (!mHasFeature) { 4461 return true; 4462 } 4463 enforceFullCrossUsersPermission(userHandle); 4464 enforceUserUnlocked(userHandle, parent); 4465 4466 synchronized (getLockObject()) { 4467 // This API can only be called by an active device admin, 4468 // so try to retrieve it to check that the caller is one. 4469 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4470 int credentialOwner = getCredentialOwner(userHandle, parent); 4471 DevicePolicyData policy = getUserDataUnchecked(credentialOwner); 4472 PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner); 4473 return isActivePasswordSufficientForUserLocked( 4474 policy.mPasswordValidAtLastCheckpoint, metrics, userHandle, parent); 4475 } 4476 } 4477 4478 @Override 4479 public boolean isUsingUnifiedPassword(ComponentName admin) { 4480 if (!mHasFeature) { 4481 return true; 4482 } 4483 final int userId = mInjector.userHandleGetCallingUserId(); 4484 enforceProfileOrDeviceOwner(admin); 4485 enforceManagedProfile(userId, "query unified challenge status"); 4486 return !isSeparateProfileChallengeEnabled(userId); 4487 } 4488 4489 @Override 4490 public boolean isProfileActivePasswordSufficientForParent(int userHandle) { 4491 if (!mHasFeature) { 4492 return true; 4493 } 4494 enforceFullCrossUsersPermission(userHandle); 4495 enforceManagedProfile(userHandle, "call APIs refering to the parent profile"); 4496 4497 synchronized (getLockObject()) { 4498 final int targetUser = getProfileParentId(userHandle); 4499 enforceUserUnlocked(targetUser, false); 4500 int credentialOwner = getCredentialOwner(userHandle, false); 4501 DevicePolicyData policy = getUserDataUnchecked(credentialOwner); 4502 PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner); 4503 return isActivePasswordSufficientForUserLocked( 4504 policy.mPasswordValidAtLastCheckpoint, metrics, targetUser, false); 4505 } 4506 } 4507 4508 private boolean isActivePasswordSufficientForUserLocked( 4509 boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle, 4510 boolean parent) { 4511 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) { 4512 // Before user enters their password for the first time after a reboot, return the 4513 // value of this flag, which tells us whether the password was valid the last time 4514 // settings were saved. If DPC changes password requirements on boot so that the 4515 // current password no longer meets the requirements, this value will be stale until 4516 // the next time the password is entered. 4517 return passwordValidAtLastCheckpoint; 4518 } 4519 4520 if (metrics == null) { 4521 // This could happen if the user never had a password set, for example, so 4522 // setActivePasswordState has never been called for it. 4523 metrics = new PasswordMetrics(); 4524 } 4525 return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle, parent); 4526 } 4527 4528 /** 4529 * Returns {@code true} if the password represented by the {@code passwordMetrics} argument 4530 * sufficiently fulfills the password requirements for the user corresponding to 4531 * {@code userHandle} (or its parent, if {@code parent} is set to {@code true}). 4532 */ 4533 private boolean isPasswordSufficientForUserWithoutCheckpointLocked( 4534 PasswordMetrics passwordMetrics, int userHandle, boolean parent) { 4535 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent); 4536 4537 if (passwordMetrics.quality < requiredPasswordQuality) { 4538 return false; 4539 } 4540 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC 4541 && passwordMetrics.length < getPasswordMinimumLength( 4542 null, userHandle, parent)) { 4543 return false; 4544 } 4545 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4546 return true; 4547 } 4548 return passwordMetrics.upperCase >= getPasswordMinimumUpperCase( 4549 null, userHandle, parent) 4550 && passwordMetrics.lowerCase >= getPasswordMinimumLowerCase( 4551 null, userHandle, parent) 4552 && passwordMetrics.letters >= getPasswordMinimumLetters( 4553 null, userHandle, parent) 4554 && passwordMetrics.numeric >= getPasswordMinimumNumeric( 4555 null, userHandle, parent) 4556 && passwordMetrics.symbols >= getPasswordMinimumSymbols( 4557 null, userHandle, parent) 4558 && passwordMetrics.nonLetter >= getPasswordMinimumNonLetter( 4559 null, userHandle, parent); 4560 } 4561 4562 @Override 4563 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) { 4564 enforceFullCrossUsersPermission(userHandle); 4565 synchronized (getLockObject()) { 4566 if (!isCallerWithSystemUid()) { 4567 // This API can only be called by an active device admin, 4568 // so try to retrieve it to check that the caller is one. 4569 getActiveAdminForCallerLocked( 4570 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4571 } 4572 4573 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4574 4575 return policy.mFailedPasswordAttempts; 4576 } 4577 } 4578 4579 @Override 4580 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) { 4581 if (!mHasFeature) { 4582 return; 4583 } 4584 Preconditions.checkNotNull(who, "ComponentName is null"); 4585 final int userId = mInjector.userHandleGetCallingUserId(); 4586 synchronized (getLockObject()) { 4587 // This API can only be called by an active device admin, 4588 // so try to retrieve it to check that the caller is one. 4589 getActiveAdminForCallerLocked( 4590 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent); 4591 ActiveAdmin ap = getActiveAdminForCallerLocked( 4592 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4593 if (ap.maximumFailedPasswordsForWipe != num) { 4594 ap.maximumFailedPasswordsForWipe = num; 4595 saveSettingsLocked(userId); 4596 } 4597 } 4598 if (SecurityLog.isLoggingEnabled()) { 4599 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4600 SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(), 4601 userId, affectedUserId, num); 4602 } 4603 } 4604 4605 @Override 4606 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) { 4607 if (!mHasFeature) { 4608 return 0; 4609 } 4610 enforceFullCrossUsersPermission(userHandle); 4611 synchronized (getLockObject()) { 4612 ActiveAdmin admin = (who != null) 4613 ? getActiveAdminUncheckedLocked(who, userHandle, parent) 4614 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent); 4615 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 4616 } 4617 } 4618 4619 @Override 4620 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) { 4621 if (!mHasFeature) { 4622 return UserHandle.USER_NULL; 4623 } 4624 enforceFullCrossUsersPermission(userHandle); 4625 synchronized (getLockObject()) { 4626 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked( 4627 userHandle, parent); 4628 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL; 4629 } 4630 } 4631 4632 /** 4633 * Returns the admin with the strictest policy on maximum failed passwords for: 4634 * <ul> 4635 * <li>this user if it has a separate profile challenge, or 4636 * <li>this user and all profiles that don't have their own challenge otherwise. 4637 * </ul> 4638 * <p>If the policy for the primary and any other profile are equal, it returns the admin for 4639 * the primary profile. 4640 * Returns {@code null} if no participating admin has that policy set. 4641 */ 4642 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked( 4643 int userHandle, boolean parent) { 4644 int count = 0; 4645 ActiveAdmin strictestAdmin = null; 4646 4647 // Return the strictest policy across all participating admins. 4648 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4649 final int N = admins.size(); 4650 for (int i = 0; i < N; i++) { 4651 ActiveAdmin admin = admins.get(i); 4652 if (admin.maximumFailedPasswordsForWipe == 4653 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 4654 continue; // No max number of failed passwords policy set for this profile. 4655 } 4656 4657 // We always favor the primary profile if several profiles have the same value set. 4658 int userId = admin.getUserHandle().getIdentifier(); 4659 if (count == 0 || 4660 count > admin.maximumFailedPasswordsForWipe || 4661 (count == admin.maximumFailedPasswordsForWipe && 4662 getUserInfo(userId).isPrimary())) { 4663 count = admin.maximumFailedPasswordsForWipe; 4664 strictestAdmin = admin; 4665 } 4666 } 4667 return strictestAdmin; 4668 } 4669 4670 private UserInfo getUserInfo(@UserIdInt int userId) { 4671 final long token = mInjector.binderClearCallingIdentity(); 4672 try { 4673 return mUserManager.getUserInfo(userId); 4674 } finally { 4675 mInjector.binderRestoreCallingIdentity(token); 4676 } 4677 } 4678 4679 private boolean canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId) { 4680 // Only if the admins targets a pre-O SDK 4681 return getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.O; 4682 } 4683 4684 /* PO or DO could do an untrusted reset in certain conditions. */ 4685 private boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) { 4686 synchronized (getLockObject()) { 4687 // An active DO or PO might be able to fo an untrusted credential reset 4688 for (final ActiveAdmin admin : getUserData(userId).mAdminList) { 4689 if (!isActiveAdminWithPolicyForUserLocked(admin, 4690 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, userId)) { 4691 continue; 4692 } 4693 if (canPOorDOCallResetPassword(admin, userId)) { 4694 return true; 4695 } 4696 } 4697 return false; 4698 } 4699 } 4700 @Override 4701 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException { 4702 final int callingUid = mInjector.binderGetCallingUid(); 4703 final int userHandle = mInjector.userHandleGetCallingUserId(); 4704 4705 String password = passwordOrNull != null ? passwordOrNull : ""; 4706 4707 // Password resetting to empty/null is not allowed for managed profiles. 4708 if (TextUtils.isEmpty(password)) { 4709 enforceNotManagedProfile(userHandle, "clear the active password"); 4710 } 4711 4712 synchronized (getLockObject()) { 4713 // If caller has PO (or DO) it can change the password, so see if that's the case first. 4714 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked( 4715 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid); 4716 final boolean preN; 4717 if (admin != null) { 4718 if (!canPOorDOCallResetPassword(admin, userHandle)) { 4719 throw new SecurityException("resetPassword() is deprecated for DPC targeting O" 4720 + " or later"); 4721 } 4722 preN = getTargetSdk(admin.info.getPackageName(), 4723 userHandle) <= android.os.Build.VERSION_CODES.M; 4724 } else { 4725 // Otherwise, make sure the caller has any active admin with the right policy. 4726 admin = getActiveAdminForCallerLocked(null, 4727 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD); 4728 preN = getTargetSdk(admin.info.getPackageName(), 4729 userHandle) <= android.os.Build.VERSION_CODES.M; 4730 4731 // As of N, password resetting to empty/null is not allowed anymore. 4732 // TODO Should we allow DO/PO to set an empty password? 4733 if (TextUtils.isEmpty(password)) { 4734 if (!preN) { 4735 throw new SecurityException("Cannot call with null password"); 4736 } else { 4737 Slog.e(LOG_TAG, "Cannot call with null password"); 4738 return false; 4739 } 4740 } 4741 // As of N, password cannot be changed by the admin if it is already set. 4742 if (isLockScreenSecureUnchecked(userHandle)) { 4743 if (!preN) { 4744 throw new SecurityException("Admin cannot change current password"); 4745 } else { 4746 Slog.e(LOG_TAG, "Admin cannot change current password"); 4747 return false; 4748 } 4749 } 4750 } 4751 // Do not allow to reset password when current user has a managed profile 4752 if (!isManagedProfile(userHandle)) { 4753 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4754 if (userInfo.isManagedProfile()) { 4755 if (!preN) { 4756 throw new IllegalStateException( 4757 "Cannot reset password on user has managed profile"); 4758 } else { 4759 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile"); 4760 return false; 4761 } 4762 } 4763 } 4764 } 4765 // Do not allow to reset password when user is locked 4766 if (!mUserManager.isUserUnlocked(userHandle)) { 4767 if (!preN) { 4768 throw new IllegalStateException("Cannot reset password when user is locked"); 4769 } else { 4770 Slog.e(LOG_TAG, "Cannot reset password when user is locked"); 4771 return false; 4772 } 4773 } 4774 } 4775 4776 return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle); 4777 } 4778 4779 private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token, 4780 int flags, int callingUid, int userHandle) { 4781 int quality; 4782 synchronized (getLockObject()) { 4783 quality = getPasswordQuality(null, userHandle, /* parent */ false); 4784 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) { 4785 quality = PASSWORD_QUALITY_UNSPECIFIED; 4786 } 4787 final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password); 4788 if (quality != PASSWORD_QUALITY_UNSPECIFIED) { 4789 final int realQuality = metrics.quality; 4790 if (realQuality < quality 4791 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4792 Slog.w(LOG_TAG, "resetPassword: password quality 0x" 4793 + Integer.toHexString(realQuality) 4794 + " does not meet required quality 0x" 4795 + Integer.toHexString(quality)); 4796 return false; 4797 } 4798 quality = Math.max(realQuality, quality); 4799 } 4800 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false); 4801 if (password.length() < length) { 4802 Slog.w(LOG_TAG, "resetPassword: password length " + password.length() 4803 + " does not meet required length " + length); 4804 return false; 4805 } 4806 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4807 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false); 4808 if(metrics.letters < neededLetters) { 4809 Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters 4810 + " does not meet required number of letters " + neededLetters); 4811 return false; 4812 } 4813 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false); 4814 if (metrics.numeric < neededNumeric) { 4815 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric 4816 + " does not meet required number of numerical digits " 4817 + neededNumeric); 4818 return false; 4819 } 4820 int neededLowerCase = getPasswordMinimumLowerCase( 4821 null, userHandle, /* parent */ false); 4822 if (metrics.lowerCase < neededLowerCase) { 4823 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " 4824 + metrics.lowerCase 4825 + " does not meet required number of lowercase letters " 4826 + neededLowerCase); 4827 return false; 4828 } 4829 int neededUpperCase = getPasswordMinimumUpperCase( 4830 null, userHandle, /* parent */ false); 4831 if (metrics.upperCase < neededUpperCase) { 4832 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " 4833 + metrics.upperCase 4834 + " does not meet required number of uppercase letters " 4835 + neededUpperCase); 4836 return false; 4837 } 4838 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false); 4839 if (metrics.symbols < neededSymbols) { 4840 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols 4841 + " does not meet required number of special symbols " + neededSymbols); 4842 return false; 4843 } 4844 int neededNonLetter = getPasswordMinimumNonLetter( 4845 null, userHandle, /* parent */ false); 4846 if (metrics.nonLetter < neededNonLetter) { 4847 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " 4848 + metrics.nonLetter 4849 + " does not meet required number of non-letter characters " 4850 + neededNonLetter); 4851 return false; 4852 } 4853 } 4854 } 4855 4856 DevicePolicyData policy = getUserData(userHandle); 4857 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 4858 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 4859 return false; 4860 } 4861 4862 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid); 4863 boolean doNotAskCredentialsOnBoot = 4864 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 4865 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 4866 setDoNotAskCredentialsOnBoot(); 4867 } 4868 4869 // Don't do this with the lock held, because it is going to call 4870 // back in to the service. 4871 final long ident = mInjector.binderClearCallingIdentity(); 4872 final boolean result; 4873 try { 4874 if (token == null) { 4875 if (!TextUtils.isEmpty(password)) { 4876 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle); 4877 } else { 4878 mLockPatternUtils.clearLock(null, userHandle); 4879 } 4880 result = true; 4881 } else { 4882 result = mLockPatternUtils.setLockCredentialWithToken(password, 4883 TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE 4884 : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 4885 quality, tokenHandle, token, userHandle); 4886 } 4887 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 4888 if (requireEntry) { 4889 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, 4890 UserHandle.USER_ALL); 4891 } 4892 synchronized (getLockObject()) { 4893 int newOwner = requireEntry ? callingUid : -1; 4894 if (policy.mPasswordOwner != newOwner) { 4895 policy.mPasswordOwner = newOwner; 4896 saveSettingsLocked(userHandle); 4897 } 4898 } 4899 } finally { 4900 mInjector.binderRestoreCallingIdentity(ident); 4901 } 4902 return result; 4903 } 4904 4905 private boolean isLockScreenSecureUnchecked(int userId) { 4906 long ident = mInjector.binderClearCallingIdentity(); 4907 try { 4908 return mLockPatternUtils.isSecure(userId); 4909 } finally { 4910 mInjector.binderRestoreCallingIdentity(ident); 4911 } 4912 } 4913 4914 private void setDoNotAskCredentialsOnBoot() { 4915 synchronized (getLockObject()) { 4916 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4917 if (!policyData.doNotAskCredentialsOnBoot) { 4918 policyData.doNotAskCredentialsOnBoot = true; 4919 saveSettingsLocked(UserHandle.USER_SYSTEM); 4920 } 4921 } 4922 } 4923 4924 @Override 4925 public boolean getDoNotAskCredentialsOnBoot() { 4926 mContext.enforceCallingOrSelfPermission( 4927 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null); 4928 synchronized (getLockObject()) { 4929 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4930 return policyData.doNotAskCredentialsOnBoot; 4931 } 4932 } 4933 4934 @Override 4935 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) { 4936 if (!mHasFeature) { 4937 return; 4938 } 4939 Preconditions.checkNotNull(who, "ComponentName is null"); 4940 final int userHandle = mInjector.userHandleGetCallingUserId(); 4941 synchronized (getLockObject()) { 4942 ActiveAdmin ap = getActiveAdminForCallerLocked( 4943 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 4944 if (ap.maximumTimeToUnlock != timeMs) { 4945 ap.maximumTimeToUnlock = timeMs; 4946 saveSettingsLocked(userHandle); 4947 updateMaximumTimeToLockLocked(userHandle); 4948 } 4949 } 4950 if (SecurityLog.isLoggingEnabled()) { 4951 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 4952 SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET, 4953 who.getPackageName(), userHandle, affectedUserId, timeMs); 4954 } 4955 } 4956 4957 private void updateMaximumTimeToLockLocked(@UserIdInt int userId) { 4958 // Update the profile's timeout 4959 if (isManagedProfile(userId)) { 4960 updateProfileLockTimeoutLocked(userId); 4961 } 4962 4963 final long timeMs; 4964 final long ident = mInjector.binderClearCallingIdentity(); 4965 try { 4966 // Update the device timeout 4967 final int parentId = getProfileParentId(userId); 4968 timeMs = getMaximumTimeToLockPolicyFromAdmins( 4969 getActiveAdminsForLockscreenPoliciesLocked(parentId, false)); 4970 4971 final DevicePolicyData policy = getUserDataUnchecked(parentId); 4972 if (policy.mLastMaximumTimeToLock == timeMs) { 4973 return; 4974 } 4975 policy.mLastMaximumTimeToLock = timeMs; 4976 4977 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) { 4978 // Make sure KEEP_SCREEN_ON is disabled, since that 4979 // would allow bypassing of the maximum time to lock. 4980 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 4981 } 4982 } finally { 4983 mInjector.binderRestoreCallingIdentity(ident); 4984 } 4985 4986 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 4987 UserHandle.USER_SYSTEM, timeMs); 4988 } 4989 4990 private void updateProfileLockTimeoutLocked(@UserIdInt int userId) { 4991 final long timeMs; 4992 if (isSeparateProfileChallengeEnabled(userId)) { 4993 timeMs = getMaximumTimeToLockPolicyFromAdmins( 4994 getActiveAdminsForLockscreenPoliciesLocked(userId, false /* parent */)); 4995 } else { 4996 timeMs = Long.MAX_VALUE; 4997 } 4998 4999 final DevicePolicyData policy = getUserDataUnchecked(userId); 5000 if (policy.mLastMaximumTimeToLock == timeMs) { 5001 return; 5002 } 5003 policy.mLastMaximumTimeToLock = timeMs; 5004 5005 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5006 userId, policy.mLastMaximumTimeToLock); 5007 } 5008 5009 @Override 5010 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) { 5011 if (!mHasFeature) { 5012 return 0; 5013 } 5014 enforceFullCrossUsersPermission(userHandle); 5015 synchronized (getLockObject()) { 5016 if (who != null) { 5017 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 5018 return admin != null ? admin.maximumTimeToUnlock : 0; 5019 } 5020 // Return the strictest policy across all participating admins. 5021 final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5022 userHandle, parent); 5023 final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins); 5024 return timeMs == Long.MAX_VALUE ? 0 : timeMs; 5025 } 5026 } 5027 5028 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) { 5029 long time = Long.MAX_VALUE; 5030 for (final ActiveAdmin admin : admins) { 5031 if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) { 5032 time = admin.maximumTimeToUnlock; 5033 } 5034 } 5035 return time; 5036 } 5037 5038 @Override 5039 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, 5040 boolean parent) { 5041 if (!mHasFeature) { 5042 return; 5043 } 5044 Preconditions.checkNotNull(who, "ComponentName is null"); 5045 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number."); 5046 // timeoutMs with value 0 means that the admin doesn't participate 5047 // timeoutMs is clamped to the interval in case the internal constants change in the future 5048 final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs(); 5049 if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) { 5050 timeoutMs = minimumStrongAuthTimeout; 5051 } 5052 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 5053 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5054 } 5055 5056 final int userHandle = mInjector.userHandleGetCallingUserId(); 5057 synchronized (getLockObject()) { 5058 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5059 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent); 5060 if (ap.strongAuthUnlockTimeout != timeoutMs) { 5061 ap.strongAuthUnlockTimeout = timeoutMs; 5062 saveSettingsLocked(userHandle); 5063 } 5064 } 5065 } 5066 5067 /** 5068 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all 5069 * admins if who is null. 5070 * Returns 0 if not configured for the provided admin. 5071 */ 5072 @Override 5073 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) { 5074 if (!mHasFeature) { 5075 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5076 } 5077 enforceFullCrossUsersPermission(userId); 5078 synchronized (getLockObject()) { 5079 if (who != null) { 5080 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent); 5081 return admin != null ? admin.strongAuthUnlockTimeout : 0; 5082 } 5083 5084 // Return the strictest policy across all participating admins. 5085 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent); 5086 5087 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5088 for (int i = 0; i < admins.size(); i++) { 5089 final long timeout = admins.get(i).strongAuthUnlockTimeout; 5090 if (timeout != 0) { // take only participating admins into account 5091 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout); 5092 } 5093 } 5094 return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs()); 5095 } 5096 } 5097 5098 private long getMinimumStrongAuthTimeoutMs() { 5099 if (!mInjector.isBuildDebuggable()) { 5100 return MINIMUM_STRONG_AUTH_TIMEOUT_MS; 5101 } 5102 // ideally the property was named persist.sys.min_strong_auth_timeout, but system property 5103 // name cannot be longer than 31 characters 5104 return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo", 5105 MINIMUM_STRONG_AUTH_TIMEOUT_MS), 5106 MINIMUM_STRONG_AUTH_TIMEOUT_MS); 5107 } 5108 5109 @Override 5110 public void lockNow(int flags, boolean parent) { 5111 if (!mHasFeature) { 5112 return; 5113 } 5114 5115 final int callingUserId = mInjector.userHandleGetCallingUserId(); 5116 synchronized (getLockObject()) { 5117 // This API can only be called by an active device admin, 5118 // so try to retrieve it to check that the caller is one. 5119 final ActiveAdmin admin = getActiveAdminForCallerLocked( 5120 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 5121 5122 final long ident = mInjector.binderClearCallingIdentity(); 5123 try { 5124 final ComponentName adminComponent = admin.info.getComponent(); 5125 // Evict key 5126 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) { 5127 enforceManagedProfile( 5128 callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 5129 if (!isProfileOwner(adminComponent, callingUserId)) { 5130 throw new SecurityException("Only profile owner admins can set " 5131 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 5132 } 5133 if (parent) { 5134 throw new IllegalArgumentException( 5135 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent"); 5136 } 5137 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5138 throw new UnsupportedOperationException( 5139 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices"); 5140 } 5141 mUserManager.evictCredentialEncryptionKey(callingUserId); 5142 } 5143 5144 // Lock all users unless this is a managed profile with a separate challenge 5145 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId) 5146 ? UserHandle.USER_ALL : callingUserId); 5147 mLockPatternUtils.requireStrongAuth( 5148 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock); 5149 5150 // Require authentication for the device or profile 5151 if (userToLock == UserHandle.USER_ALL) { 5152 // Power off the display 5153 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(), 5154 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 5155 mInjector.getIWindowManager().lockNow(null); 5156 } else { 5157 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true); 5158 } 5159 5160 if (SecurityLog.isLoggingEnabled()) { 5161 final int affectedUserId = 5162 parent ? getProfileParentId(callingUserId) : callingUserId; 5163 SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK, 5164 adminComponent.getPackageName(), callingUserId, affectedUserId); 5165 } 5166 } catch (RemoteException e) { 5167 } finally { 5168 mInjector.binderRestoreCallingIdentity(ident); 5169 } 5170 } 5171 } 5172 5173 @Override 5174 public void enforceCanManageCaCerts(ComponentName who, String callerPackage) { 5175 if (who == null) { 5176 if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) { 5177 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 5178 } 5179 } else { 5180 enforceProfileOrDeviceOwner(who); 5181 } 5182 } 5183 5184 private void enforceProfileOrDeviceOwner(ComponentName who) { 5185 synchronized (getLockObject()) { 5186 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5187 } 5188 } 5189 5190 @Override 5191 public boolean approveCaCert(String alias, int userId, boolean approval) { 5192 enforceManageUsers(); 5193 synchronized (getLockObject()) { 5194 Set<String> certs = getUserData(userId).mAcceptedCaCertificates; 5195 boolean changed = (approval ? certs.add(alias) : certs.remove(alias)); 5196 if (!changed) { 5197 return false; 5198 } 5199 saveSettingsLocked(userId); 5200 } 5201 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5202 return true; 5203 } 5204 5205 @Override 5206 public boolean isCaCertApproved(String alias, int userId) { 5207 enforceManageUsers(); 5208 synchronized (getLockObject()) { 5209 return getUserData(userId).mAcceptedCaCertificates.contains(alias); 5210 } 5211 } 5212 5213 private void removeCaApprovalsIfNeeded(int userId) { 5214 for (UserInfo userInfo : mUserManager.getProfiles(userId)) { 5215 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id); 5216 if (userInfo.isManagedProfile()){ 5217 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id)); 5218 } 5219 if (!isSecure) { 5220 synchronized (getLockObject()) { 5221 getUserData(userInfo.id).mAcceptedCaCertificates.clear(); 5222 saveSettingsLocked(userInfo.id); 5223 } 5224 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5225 } 5226 } 5227 } 5228 5229 @Override 5230 public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) 5231 throws RemoteException { 5232 if (!mHasFeature) { 5233 return false; 5234 } 5235 enforceCanManageCaCerts(admin, callerPackage); 5236 5237 final String alias; 5238 5239 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 5240 final long id = mInjector.binderClearCallingIdentity(); 5241 try { 5242 alias = mCertificateMonitor.installCaCert(userHandle, certBuffer); 5243 if (alias == null) { 5244 Log.w(LOG_TAG, "Problem installing cert"); 5245 return false; 5246 } 5247 } finally { 5248 mInjector.binderRestoreCallingIdentity(id); 5249 } 5250 5251 synchronized (getLockObject()) { 5252 getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias); 5253 saveSettingsLocked(userHandle.getIdentifier()); 5254 } 5255 return true; 5256 } 5257 5258 @Override 5259 public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) { 5260 if (!mHasFeature) { 5261 return; 5262 } 5263 enforceCanManageCaCerts(admin, callerPackage); 5264 5265 final int userId = mInjector.userHandleGetCallingUserId(); 5266 final long id = mInjector.binderClearCallingIdentity(); 5267 try { 5268 mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases); 5269 } finally { 5270 mInjector.binderRestoreCallingIdentity(id); 5271 } 5272 5273 synchronized (getLockObject()) { 5274 if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) { 5275 saveSettingsLocked(userId); 5276 } 5277 } 5278 } 5279 5280 @Override 5281 public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey, 5282 byte[] cert, byte[] chain, String alias, boolean requestAccess, 5283 boolean isUserSelectable) { 5284 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5285 DELEGATION_CERT_INSTALL); 5286 5287 5288 final int callingUid = mInjector.binderGetCallingUid(); 5289 final long id = mInjector.binderClearCallingIdentity(); 5290 try { 5291 final KeyChainConnection keyChainConnection = 5292 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid)); 5293 try { 5294 IKeyChainService keyChain = keyChainConnection.getService(); 5295 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) { 5296 return false; 5297 } 5298 if (requestAccess) { 5299 keyChain.setGrant(callingUid, alias, true); 5300 } 5301 keyChain.setUserSelectable(alias, isUserSelectable); 5302 return true; 5303 } catch (RemoteException e) { 5304 Log.e(LOG_TAG, "Installing certificate", e); 5305 } finally { 5306 keyChainConnection.close(); 5307 } 5308 } catch (InterruptedException e) { 5309 Log.w(LOG_TAG, "Interrupted while installing certificate", e); 5310 Thread.currentThread().interrupt(); 5311 } finally { 5312 mInjector.binderRestoreCallingIdentity(id); 5313 } 5314 return false; 5315 } 5316 5317 @Override 5318 public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) { 5319 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5320 DELEGATION_CERT_INSTALL); 5321 5322 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 5323 final long id = Binder.clearCallingIdentity(); 5324 try { 5325 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 5326 try { 5327 IKeyChainService keyChain = keyChainConnection.getService(); 5328 return keyChain.removeKeyPair(alias); 5329 } catch (RemoteException e) { 5330 Log.e(LOG_TAG, "Removing keypair", e); 5331 } finally { 5332 keyChainConnection.close(); 5333 } 5334 } catch (InterruptedException e) { 5335 Log.w(LOG_TAG, "Interrupted while removing keypair", e); 5336 Thread.currentThread().interrupt(); 5337 } finally { 5338 Binder.restoreCallingIdentity(id); 5339 } 5340 return false; 5341 } 5342 5343 private void enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner( 5344 ComponentName who, String callerPackage, int callerUid) throws SecurityException { 5345 if (who == null) { 5346 if (!mOwners.hasDeviceOwner()) { 5347 throw new SecurityException("Not in Device Owner mode."); 5348 } 5349 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 5350 throw new SecurityException("Caller not from device owner user"); 5351 } 5352 if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) { 5353 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() + 5354 "has no permission to generate keys."); 5355 } 5356 } else { 5357 // Caller provided - check it is the device owner. 5358 synchronized (getLockObject()) { 5359 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5360 } 5361 } 5362 } 5363 5364 @VisibleForTesting 5365 public static int[] translateIdAttestationFlags( 5366 int idAttestationFlags) { 5367 Map<Integer, Integer> idTypeToAttestationFlag = new HashMap(); 5368 idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL); 5369 idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI); 5370 idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID); 5371 5372 int numFlagsSet = Integer.bitCount(idAttestationFlags); 5373 // No flags are set - return null to indicate no device ID attestation information should 5374 // be included in the attestation record. 5375 if (numFlagsSet == 0) { 5376 return null; 5377 } 5378 5379 // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if 5380 // no other flag is set. That will lead to inclusion of general device make data in the 5381 // attestation record, but no specific device identifiers. 5382 if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) { 5383 numFlagsSet -= 1; 5384 idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO); 5385 } 5386 5387 int[] attestationUtilsFlags = new int[numFlagsSet]; 5388 int i = 0; 5389 for (Integer idType: idTypeToAttestationFlag.keySet()) { 5390 if ((idType & idAttestationFlags) != 0) { 5391 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType); 5392 } 5393 } 5394 5395 return attestationUtilsFlags; 5396 } 5397 5398 @Override 5399 public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm, 5400 ParcelableKeyGenParameterSpec parcelableKeySpec, 5401 int idAttestationFlags, 5402 KeymasterCertificateChain attestationChain) { 5403 // Get attestation flags, if any. 5404 final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags); 5405 final boolean deviceIdAttestationRequired = attestationUtilsFlags != null; 5406 final int callingUid = mInjector.binderGetCallingUid(); 5407 5408 if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) { 5409 enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner(who, callerPackage, callingUid); 5410 } else { 5411 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5412 DELEGATION_CERT_INSTALL); 5413 } 5414 final KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec(); 5415 final String alias = keySpec.getKeystoreAlias(); 5416 if (TextUtils.isEmpty(alias)) { 5417 throw new IllegalArgumentException("Empty alias provided."); 5418 } 5419 // As the caller will be granted access to the key, ensure no UID was specified, as 5420 // it will not have the desired effect. 5421 if (keySpec.getUid() != KeyStore.UID_SELF) { 5422 Log.e(LOG_TAG, "Only the caller can be granted access to the generated keypair."); 5423 return false; 5424 } 5425 5426 if (deviceIdAttestationRequired && (keySpec.getAttestationChallenge() == null)) { 5427 throw new IllegalArgumentException( 5428 "Requested Device ID attestation but challenge is empty."); 5429 } 5430 5431 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 5432 final long id = mInjector.binderClearCallingIdentity(); 5433 try { 5434 try (KeyChainConnection keyChainConnection = 5435 KeyChain.bindAsUser(mContext, userHandle)) { 5436 IKeyChainService keyChain = keyChainConnection.getService(); 5437 5438 // Copy the provided keySpec, excluding the attestation challenge, which will be 5439 // used later for requesting key attestation record. 5440 final KeyGenParameterSpec noAttestationSpec = 5441 new KeyGenParameterSpec.Builder(keySpec) 5442 .setAttestationChallenge(null) 5443 .build(); 5444 5445 final int generationResult = keyChain.generateKeyPair(algorithm, 5446 new ParcelableKeyGenParameterSpec(noAttestationSpec)); 5447 if (generationResult != KeyChain.KEY_GEN_SUCCESS) { 5448 Log.e(LOG_TAG, String.format( 5449 "KeyChain failed to generate a keypair, error %d.", generationResult)); 5450 return false; 5451 } 5452 5453 // Set a grant for the caller here so that when the client calls 5454 // requestPrivateKey, it will be able to get the key from Keystore. 5455 // Note the use of the calling UID, since the request for the private 5456 // key will come from the client's process, so the grant has to be for 5457 // that UID. 5458 keyChain.setGrant(callingUid, alias, true); 5459 5460 final byte[] attestationChallenge = keySpec.getAttestationChallenge(); 5461 if (attestationChallenge != null) { 5462 final int attestationResult = keyChain.attestKey( 5463 alias, attestationChallenge, attestationUtilsFlags, attestationChain); 5464 if (attestationResult != KeyChain.KEY_ATTESTATION_SUCCESS) { 5465 Log.e(LOG_TAG, String.format( 5466 "Attestation for %s failed (rc=%d), deleting key.", 5467 alias, attestationResult)); 5468 keyChain.removeKeyPair(alias); 5469 if (attestationResult == KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS) { 5470 throw new UnsupportedOperationException( 5471 "Device does not support Device ID attestation."); 5472 } 5473 return false; 5474 } 5475 } 5476 return true; 5477 } 5478 } catch (RemoteException e) { 5479 Log.e(LOG_TAG, "KeyChain error while generating a keypair", e); 5480 } catch (InterruptedException e) { 5481 Log.w(LOG_TAG, "Interrupted while generating keypair", e); 5482 Thread.currentThread().interrupt(); 5483 } finally { 5484 mInjector.binderRestoreCallingIdentity(id); 5485 } 5486 return false; 5487 } 5488 5489 @Override 5490 public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias, 5491 byte[] cert, byte[] chain, boolean isUserSelectable) { 5492 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5493 DELEGATION_CERT_INSTALL); 5494 5495 final int callingUid = mInjector.binderGetCallingUid(); 5496 final long id = mInjector.binderClearCallingIdentity(); 5497 try (final KeyChainConnection keyChainConnection = 5498 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid))) { 5499 IKeyChainService keyChain = keyChainConnection.getService(); 5500 if (!keyChain.setKeyPairCertificate(alias, cert, chain)) { 5501 return false; 5502 } 5503 keyChain.setUserSelectable(alias, isUserSelectable); 5504 return true; 5505 } catch (InterruptedException e) { 5506 Log.w(LOG_TAG, "Interrupted while setting keypair certificate", e); 5507 Thread.currentThread().interrupt(); 5508 } catch (RemoteException e) { 5509 Log.e(LOG_TAG, "Failed setting keypair certificate", e); 5510 } finally { 5511 mInjector.binderRestoreCallingIdentity(id); 5512 } 5513 return false; 5514 } 5515 5516 @Override 5517 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, 5518 final IBinder response) { 5519 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers. 5520 if (!isCallerWithSystemUid()) { 5521 return; 5522 } 5523 5524 final UserHandle caller = mInjector.binderGetCallingUserHandle(); 5525 // If there is a profile owner, redirect to that; otherwise query the device owner. 5526 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier()); 5527 if (aliasChooser == null && caller.isSystem()) { 5528 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 5529 if (deviceOwnerAdmin != null) { 5530 aliasChooser = deviceOwnerAdmin.info.getComponent(); 5531 } 5532 } 5533 if (aliasChooser == null) { 5534 sendPrivateKeyAliasResponse(null, response); 5535 return; 5536 } 5537 5538 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 5539 intent.setComponent(aliasChooser); 5540 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 5541 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri); 5542 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 5543 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 5544 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 5545 5546 final long id = mInjector.binderClearCallingIdentity(); 5547 try { 5548 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() { 5549 @Override 5550 public void onReceive(Context context, Intent intent) { 5551 final String chosenAlias = getResultData(); 5552 sendPrivateKeyAliasResponse(chosenAlias, response); 5553 } 5554 }, null, Activity.RESULT_OK, null, null); 5555 } finally { 5556 mInjector.binderRestoreCallingIdentity(id); 5557 } 5558 } 5559 5560 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 5561 final IKeyChainAliasCallback keyChainAliasResponse = 5562 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 5563 // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback 5564 // is oneway, which means it won't block if the recipient lives in another process. 5565 try { 5566 keyChainAliasResponse.alias(alias); 5567 } catch (Exception e) { 5568 // Caller could throw RuntimeException or RemoteException back across processes. Catch 5569 // everything just to be sure. 5570 Log.e(LOG_TAG, "error while responding to callback", e); 5571 } 5572 } 5573 5574 /** 5575 * Determine whether DPMS should check if a delegate package is already installed before 5576 * granting it new delegations via {@link #setDelegatedScopes}. 5577 */ 5578 private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, 5579 int targetSdk, List<String> scopes) { 5580 // 1) Never skip is installed check from N. 5581 if (targetSdk >= Build.VERSION_CODES.N) { 5582 return true; 5583 } 5584 // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given. 5585 if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) { 5586 return false; 5587 } 5588 // 3) Skip if all previously granted scopes are being cleared. 5589 if (scopes.isEmpty()) { 5590 return false; 5591 } 5592 // Otherwise it should check that delegatePackage is installed. 5593 return true; 5594 } 5595 5596 /** 5597 * Set the scopes of a device owner or profile owner delegate. 5598 * 5599 * @param who the device owner or profile owner. 5600 * @param delegatePackage the name of the delegate package. 5601 * @param scopes the list of delegation scopes to be given to the delegate package. 5602 */ 5603 @Override 5604 public void setDelegatedScopes(ComponentName who, String delegatePackage, 5605 List<String> scopes) throws SecurityException { 5606 Preconditions.checkNotNull(who, "ComponentName is null"); 5607 Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty"); 5608 Preconditions.checkCollectionElementsNotNull(scopes, "Scopes"); 5609 // Remove possible duplicates. 5610 scopes = new ArrayList(new ArraySet(scopes)); 5611 // Ensure given scopes are valid. 5612 if (scopes.retainAll(Arrays.asList(DELEGATIONS))) { 5613 throw new IllegalArgumentException("Unexpected delegation scopes"); 5614 } 5615 5616 // Retrieve the user ID of the calling process. 5617 final int userId = mInjector.userHandleGetCallingUserId(); 5618 synchronized (getLockObject()) { 5619 // Ensure calling process is device/profile owner. 5620 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5621 // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N). 5622 if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage, 5623 getTargetSdk(who.getPackageName(), userId), scopes)) { 5624 // Throw when the delegate package is not installed. 5625 if (!isPackageInstalledForUser(delegatePackage, userId)) { 5626 throw new IllegalArgumentException("Package " + delegatePackage 5627 + " is not installed on the current user"); 5628 } 5629 } 5630 5631 // Set the new delegate in user policies. 5632 final DevicePolicyData policy = getUserData(userId); 5633 if (!scopes.isEmpty()) { 5634 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes)); 5635 } else { 5636 // Remove any delegation info if the given scopes list is empty. 5637 policy.mDelegationMap.remove(delegatePackage); 5638 } 5639 5640 // Notify delegate package of updates. 5641 final Intent intent = new Intent( 5642 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED); 5643 // Only call receivers registered with Context#registerReceiver (don’t wake delegate). 5644 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 5645 // Limit components this intent resolves to to the delegate package. 5646 intent.setPackage(delegatePackage); 5647 // Include the list of delegated scopes as an extra. 5648 intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, 5649 (ArrayList<String>) scopes); 5650 // Send the broadcast. 5651 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 5652 5653 // Persist updates. 5654 saveSettingsLocked(userId); 5655 } 5656 } 5657 5658 /** 5659 * Get the delegation scopes given to a delegate package by a device owner or profile owner. 5660 * 5661 * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by 5662 * passing in {@code null} as the {@code who} parameter and its own name as the 5663 * {@code delegatepackage}. 5664 * 5665 * @param who the device owner or profile owner, or {@code null} if the caller is 5666 * {@code delegatePackage}. 5667 * @param delegatePackage the name of the delegate package whose scopes are to be retrieved. 5668 * @return a list of the delegation scopes currently given to {@code delegatePackage}. 5669 */ 5670 @Override 5671 @NonNull 5672 public List<String> getDelegatedScopes(ComponentName who, 5673 String delegatePackage) throws SecurityException { 5674 Preconditions.checkNotNull(delegatePackage, "Delegate package is null"); 5675 5676 // Retrieve the user ID of the calling process. 5677 final int callingUid = mInjector.binderGetCallingUid(); 5678 final int userId = UserHandle.getUserId(callingUid); 5679 synchronized (getLockObject()) { 5680 // Ensure calling process is device/profile owner. 5681 if (who != null) { 5682 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5683 // Or ensure calling process is delegatePackage itself. 5684 } else { 5685 int uid = 0; 5686 try { 5687 uid = mInjector.getPackageManager() 5688 .getPackageUidAsUser(delegatePackage, userId); 5689 } catch(NameNotFoundException e) { 5690 } 5691 if (uid != callingUid) { 5692 throw new SecurityException("Caller with uid " + callingUid + " is not " 5693 + delegatePackage); 5694 } 5695 } 5696 final DevicePolicyData policy = getUserData(userId); 5697 // Retrieve the scopes assigned to delegatePackage, or null if no scope was given. 5698 final List<String> scopes = policy.mDelegationMap.get(delegatePackage); 5699 return scopes == null ? Collections.EMPTY_LIST : scopes; 5700 } 5701 } 5702 5703 /** 5704 * Get a list of packages that were given a specific delegation scopes by a device owner or 5705 * profile owner. 5706 * 5707 * @param who the device owner or profile owner. 5708 * @param scope the scope whose delegates are to be retrieved. 5709 * @return a list of the delegate packages currently given the {@code scope} delegation. 5710 */ 5711 @NonNull 5712 public List<String> getDelegatePackages(ComponentName who, String scope) 5713 throws SecurityException { 5714 Preconditions.checkNotNull(who, "ComponentName is null"); 5715 Preconditions.checkNotNull(scope, "Scope is null"); 5716 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 5717 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 5718 } 5719 5720 // Retrieve the user ID of the calling process. 5721 final int userId = mInjector.userHandleGetCallingUserId(); 5722 synchronized (getLockObject()) { 5723 // Ensure calling process is device/profile owner. 5724 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5725 final DevicePolicyData policy = getUserData(userId); 5726 5727 // Create a list to hold the resulting delegate packages. 5728 final List<String> delegatePackagesWithScope = new ArrayList<>(); 5729 // Add all delegations containing scope to the result list. 5730 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 5731 if (policy.mDelegationMap.valueAt(i).contains(scope)) { 5732 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i)); 5733 } 5734 } 5735 return delegatePackagesWithScope; 5736 } 5737 } 5738 5739 /** 5740 * Check whether a caller application has been delegated a given scope via 5741 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 5742 * device owner. 5743 * <p> 5744 * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and 5745 * then comparing the calling UID with the UID of {@code callerPackage} as reported by 5746 * {@link PackageManager#getPackageUidAsUser}. 5747 * 5748 * @param callerPackage the name of the package that is trying to invoke a function in the DPMS. 5749 * @param scope the delegation scope to be checked. 5750 * @return {@code true} if the calling process is a delegate of {@code scope}. 5751 */ 5752 private boolean isCallerDelegate(String callerPackage, String scope) { 5753 Preconditions.checkNotNull(callerPackage, "callerPackage is null"); 5754 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 5755 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 5756 } 5757 5758 // Retrieve the UID and user ID of the calling process. 5759 final int callingUid = mInjector.binderGetCallingUid(); 5760 final int userId = UserHandle.getUserId(callingUid); 5761 synchronized (getLockObject()) { 5762 // Retrieve user policy data. 5763 final DevicePolicyData policy = getUserData(userId); 5764 // Retrieve the list of delegation scopes granted to callerPackage. 5765 final List<String> scopes = policy.mDelegationMap.get(callerPackage); 5766 // Check callingUid only if callerPackage has the required scope delegation. 5767 if (scopes != null && scopes.contains(scope)) { 5768 try { 5769 // Retrieve the expected UID for callerPackage. 5770 final int uid = mInjector.getPackageManager() 5771 .getPackageUidAsUser(callerPackage, userId); 5772 // Return true if the caller is actually callerPackage. 5773 return uid == callingUid; 5774 } catch (NameNotFoundException e) { 5775 // Ignore. 5776 } 5777 } 5778 return false; 5779 } 5780 } 5781 5782 /** 5783 * Throw a security exception if a ComponentName is given and it is not a device/profile owner 5784 * or if the calling process is not a delegate of the given scope. 5785 * 5786 * @param who the device owner of profile owner, or null if {@code callerPackage} is a 5787 * {@code scope} delegate. 5788 * @param callerPackage the name of the calling package. Required if {@code who} is 5789 * {@code null}. 5790 * @param reqPolicy the policy used in the API whose access permission is being checked. 5791 * @param scope the delegation scope corresponding to the API being checked. 5792 * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy}; 5793 * or when {@code who} is {@code null} and {@code callerPackage} is not a delegate 5794 * of {@code scope}. 5795 */ 5796 private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, 5797 String scope) { 5798 // If a ComponentName is given ensure it is a device or profile owner according to policy. 5799 if (who != null) { 5800 synchronized (getLockObject()) { 5801 getActiveAdminForCallerLocked(who, reqPolicy); 5802 } 5803 // If no ComponentName is given ensure calling process has scope delegation. 5804 } else if (!isCallerDelegate(callerPackage, scope)) { 5805 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() 5806 + " is not a delegate of scope " + scope + "."); 5807 } 5808 } 5809 5810 /** 5811 * Helper function to preserve delegation behavior pre-O when using the deprecated functions 5812 * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}. 5813 */ 5814 private void setDelegatedScopePreO(ComponentName who, 5815 String delegatePackage, String scope) { 5816 Preconditions.checkNotNull(who, "ComponentName is null"); 5817 5818 final int userId = mInjector.userHandleGetCallingUserId(); 5819 synchronized (getLockObject()) { 5820 // Ensure calling process is device/profile owner. 5821 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5822 final DevicePolicyData policy = getUserData(userId); 5823 5824 if (delegatePackage != null) { 5825 // Set package as a delegate for scope if it is not already one. 5826 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 5827 if (scopes == null) { 5828 scopes = new ArrayList<>(); 5829 } 5830 if (!scopes.contains(scope)) { 5831 scopes.add(scope); 5832 setDelegatedScopes(who, delegatePackage, scopes); 5833 } 5834 } 5835 5836 // Clear any existing scope delegates. 5837 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 5838 final String currentPackage = policy.mDelegationMap.keyAt(i); 5839 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 5840 5841 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) { 5842 final List<String> newScopes = new ArrayList(currentScopes); 5843 newScopes.remove(scope); 5844 setDelegatedScopes(who, currentPackage, newScopes); 5845 } 5846 } 5847 } 5848 } 5849 5850 @Override 5851 public void setCertInstallerPackage(ComponentName who, String installerPackage) 5852 throws SecurityException { 5853 setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL); 5854 } 5855 5856 @Override 5857 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 5858 final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL); 5859 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 5860 } 5861 5862 /** 5863 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is 5864 * not installed and therefore not available. 5865 * 5866 * @throws SecurityException if the caller is not a profile or device owner. 5867 * @throws UnsupportedOperationException if the package does not support being set as always-on. 5868 */ 5869 @Override 5870 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown) 5871 throws SecurityException { 5872 enforceProfileOrDeviceOwner(admin); 5873 5874 final int userId = mInjector.userHandleGetCallingUserId(); 5875 final long token = mInjector.binderClearCallingIdentity(); 5876 try { 5877 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) { 5878 return false; 5879 } 5880 ConnectivityManager connectivityManager = (ConnectivityManager) 5881 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5882 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) { 5883 throw new UnsupportedOperationException(); 5884 } 5885 } finally { 5886 mInjector.binderRestoreCallingIdentity(token); 5887 } 5888 return true; 5889 } 5890 5891 @Override 5892 public String getAlwaysOnVpnPackage(ComponentName admin) 5893 throws SecurityException { 5894 enforceProfileOrDeviceOwner(admin); 5895 5896 final int userId = mInjector.userHandleGetCallingUserId(); 5897 final long token = mInjector.binderClearCallingIdentity(); 5898 try{ 5899 ConnectivityManager connectivityManager = (ConnectivityManager) 5900 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5901 return connectivityManager.getAlwaysOnVpnPackageForUser(userId); 5902 } finally { 5903 mInjector.binderRestoreCallingIdentity(token); 5904 } 5905 } 5906 5907 private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) { 5908 wtfIfInLock(); 5909 5910 if (wipeExtRequested) { 5911 StorageManager sm = (StorageManager) mContext.getSystemService( 5912 Context.STORAGE_SERVICE); 5913 sm.wipeAdoptableDisks(); 5914 } 5915 try { 5916 mInjector.recoverySystemRebootWipeUserData( 5917 /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc); 5918 } catch (IOException | SecurityException e) { 5919 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 5920 } 5921 } 5922 5923 private void forceWipeUser(int userId, String wipeReasonForUser) { 5924 try { 5925 IActivityManager am = mInjector.getIActivityManager(); 5926 if (am.getCurrentUser().id == userId) { 5927 am.switchUser(UserHandle.USER_SYSTEM); 5928 } 5929 5930 boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId); 5931 if (!userRemoved) { 5932 Slog.w(LOG_TAG, "Couldn't remove user " + userId); 5933 } else if (isManagedProfile(userId)) { 5934 sendWipeProfileNotification(wipeReasonForUser); 5935 } 5936 } catch (RemoteException re) { 5937 // Shouldn't happen 5938 } 5939 } 5940 5941 @Override 5942 public void wipeDataWithReason(int flags, String wipeReasonForUser) { 5943 if (!mHasFeature) { 5944 return; 5945 } 5946 Preconditions.checkStringNotEmpty(wipeReasonForUser, "wipeReasonForUser is null or empty"); 5947 enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId()); 5948 5949 final ActiveAdmin admin; 5950 synchronized (getLockObject()) { 5951 admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA); 5952 } 5953 String internalReason = "DevicePolicyManager.wipeDataWithReason() from " 5954 + admin.info.getComponent().flattenToShortString(); 5955 wipeDataNoLock( 5956 admin.info.getComponent(), flags, internalReason, wipeReasonForUser, 5957 admin.getUserHandle().getIdentifier()); 5958 } 5959 5960 private void wipeDataNoLock(ComponentName admin, int flags, String internalReason, 5961 String wipeReasonForUser, int userId) { 5962 wtfIfInLock(); 5963 5964 long ident = mInjector.binderClearCallingIdentity(); 5965 try { 5966 // First check whether the admin is allowed to wipe the device/user/profile. 5967 final String restriction; 5968 if (userId == UserHandle.USER_SYSTEM) { 5969 restriction = UserManager.DISALLOW_FACTORY_RESET; 5970 } else if (isManagedProfile(userId)) { 5971 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 5972 } else { 5973 restriction = UserManager.DISALLOW_REMOVE_USER; 5974 } 5975 if (isAdminAffectedByRestriction(admin, restriction, userId)) { 5976 throw new SecurityException("Cannot wipe data. " + restriction 5977 + " restriction is set for user " + userId); 5978 } 5979 5980 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 5981 if (!isDeviceOwner(admin, userId)) { 5982 throw new SecurityException( 5983 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA"); 5984 } 5985 PersistentDataBlockManager manager = (PersistentDataBlockManager) 5986 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 5987 if (manager != null) { 5988 manager.wipe(); 5989 } 5990 } 5991 5992 // TODO If split user is enabled and the device owner is set in the primary user 5993 // (rather than system), we should probably trigger factory reset. Current code just 5994 // removes that user (but still clears FRP...) 5995 if (userId == UserHandle.USER_SYSTEM) { 5996 forceWipeDeviceNoLock(/*wipeExtRequested=*/ ( 5997 flags & WIPE_EXTERNAL_STORAGE) != 0, 5998 internalReason, 5999 /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0); 6000 } else { 6001 forceWipeUser(userId, wipeReasonForUser); 6002 } 6003 } finally { 6004 mInjector.binderRestoreCallingIdentity(ident); 6005 } 6006 } 6007 6008 private void sendWipeProfileNotification(String wipeReasonForUser) { 6009 Notification notification = 6010 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 6011 .setSmallIcon(android.R.drawable.stat_sys_warning) 6012 .setContentTitle(mContext.getString(R.string.work_profile_deleted)) 6013 .setContentText(wipeReasonForUser) 6014 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 6015 .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser)) 6016 .build(); 6017 mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification); 6018 } 6019 6020 private void clearWipeProfileNotification() { 6021 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED); 6022 } 6023 6024 @Override 6025 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 6026 if (!mHasFeature) { 6027 return; 6028 } 6029 enforceFullCrossUsersPermission(userHandle); 6030 mContext.enforceCallingOrSelfPermission( 6031 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6032 6033 synchronized (getLockObject()) { 6034 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 6035 if (admin == null) { 6036 result.sendResult(null); 6037 return; 6038 } 6039 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 6040 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 6041 intent.setComponent(admin.info.getComponent()); 6042 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 6043 null, new BroadcastReceiver() { 6044 @Override 6045 public void onReceive(Context context, Intent intent) { 6046 result.sendResult(getResultExtras(false)); 6047 } 6048 }, null, Activity.RESULT_OK, null, null); 6049 } 6050 } 6051 6052 /** 6053 * Notify DPMS regarding the metric of the current password. This happens when the user changes 6054 * the password, but also when the user just unlocks the keyguard. In comparison, 6055 * reportPasswordChanged() is only called when the user changes the password. 6056 */ 6057 @Override 6058 public void setActivePasswordState(PasswordMetrics metrics, int userHandle) { 6059 if (!mHasFeature) { 6060 return; 6061 } 6062 enforceFullCrossUsersPermission(userHandle); 6063 mContext.enforceCallingOrSelfPermission( 6064 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6065 6066 // If the managed profile doesn't have a separate password, set the metrics to default 6067 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 6068 metrics = new PasswordMetrics(); 6069 } 6070 6071 validateQualityConstant(metrics.quality); 6072 synchronized (getLockObject()) { 6073 mUserPasswordMetrics.put(userHandle, metrics); 6074 } 6075 } 6076 6077 @Override 6078 public void reportPasswordChanged(@UserIdInt int userId) { 6079 if (!mHasFeature) { 6080 return; 6081 } 6082 enforceFullCrossUsersPermission(userId); 6083 6084 // Managed Profile password can only be changed when it has a separate challenge. 6085 if (!isSeparateProfileChallengeEnabled(userId)) { 6086 enforceNotManagedProfile(userId, "set the active password"); 6087 } 6088 6089 mContext.enforceCallingOrSelfPermission( 6090 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6091 6092 DevicePolicyData policy = getUserData(userId); 6093 6094 long ident = mInjector.binderClearCallingIdentity(); 6095 try { 6096 synchronized (getLockObject()) { 6097 policy.mFailedPasswordAttempts = 0; 6098 updatePasswordValidityCheckpointLocked(userId, /* parent */ false); 6099 saveSettingsLocked(userId); 6100 updatePasswordExpirationsLocked(userId); 6101 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 6102 6103 // Send a broadcast to each profile using this password as its primary unlock. 6104 sendAdminCommandForLockscreenPoliciesLocked( 6105 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 6106 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 6107 } 6108 removeCaApprovalsIfNeeded(userId); 6109 } finally { 6110 mInjector.binderRestoreCallingIdentity(ident); 6111 } 6112 } 6113 6114 /** 6115 * Called any time the device password is updated. Resets all password expiration clocks. 6116 */ 6117 private void updatePasswordExpirationsLocked(int userHandle) { 6118 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>(); 6119 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 6120 userHandle, /* parent */ false); 6121 final int N = admins.size(); 6122 for (int i = 0; i < N; i++) { 6123 ActiveAdmin admin = admins.get(i); 6124 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 6125 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 6126 long timeout = admin.passwordExpirationTimeout; 6127 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 6128 admin.passwordExpirationDate = expiration; 6129 } 6130 } 6131 for (int affectedUserId : affectedUserIds) { 6132 saveSettingsLocked(affectedUserId); 6133 } 6134 } 6135 6136 @Override 6137 public void reportFailedPasswordAttempt(int userHandle) { 6138 enforceFullCrossUsersPermission(userHandle); 6139 if (!isSeparateProfileChallengeEnabled(userHandle)) { 6140 enforceNotManagedProfile(userHandle, 6141 "report failed password attempt if separate profile challenge is not in place"); 6142 } 6143 mContext.enforceCallingOrSelfPermission( 6144 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6145 6146 boolean wipeData = false; 6147 ActiveAdmin strictestAdmin = null; 6148 final long ident = mInjector.binderClearCallingIdentity(); 6149 try { 6150 synchronized (getLockObject()) { 6151 DevicePolicyData policy = getUserData(userHandle); 6152 policy.mFailedPasswordAttempts++; 6153 saveSettingsLocked(userHandle); 6154 if (mHasFeature) { 6155 strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 6156 userHandle, /* parent */ false); 6157 int max = strictestAdmin != null 6158 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 6159 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 6160 wipeData = true; 6161 } 6162 6163 sendAdminCommandForLockscreenPoliciesLocked( 6164 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 6165 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 6166 } 6167 } 6168 } finally { 6169 mInjector.binderRestoreCallingIdentity(ident); 6170 } 6171 6172 if (wipeData && strictestAdmin != null) { 6173 final int userId = strictestAdmin.getUserHandle().getIdentifier(); 6174 Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: " 6175 + strictestAdmin.info.getComponent().flattenToShortString() 6176 + ". Calling wipeData for user " + userId); 6177 6178 // Attempt to wipe the device/user/profile associated with the admin, as if the 6179 // admin had called wipeData(). That way we can check whether the admin is actually 6180 // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the 6181 // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be 6182 // able to do so). 6183 // IMPORTANT: Call without holding the lock to prevent deadlock. 6184 try { 6185 String wipeReasonForUser = mContext.getString( 6186 R.string.work_profile_deleted_reason_maximum_password_failure); 6187 wipeDataNoLock(strictestAdmin.info.getComponent(), 6188 /*flags=*/ 0, 6189 /*reason=*/ "reportFailedPasswordAttempt()", 6190 wipeReasonForUser, 6191 userId); 6192 } catch (SecurityException e) { 6193 Slog.w(LOG_TAG, "Failed to wipe user " + userId 6194 + " after max failed password attempts reached.", e); 6195 } 6196 } 6197 6198 if (mInjector.securityLogIsLoggingEnabled()) { 6199 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, 6200 /*result*/ 0, /*method strength*/ 1); 6201 } 6202 } 6203 6204 @Override 6205 public void reportSuccessfulPasswordAttempt(int userHandle) { 6206 enforceFullCrossUsersPermission(userHandle); 6207 mContext.enforceCallingOrSelfPermission( 6208 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6209 6210 synchronized (getLockObject()) { 6211 DevicePolicyData policy = getUserData(userHandle); 6212 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 6213 long ident = mInjector.binderClearCallingIdentity(); 6214 try { 6215 policy.mFailedPasswordAttempts = 0; 6216 policy.mPasswordOwner = -1; 6217 saveSettingsLocked(userHandle); 6218 if (mHasFeature) { 6219 sendAdminCommandForLockscreenPoliciesLocked( 6220 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 6221 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 6222 } 6223 } finally { 6224 mInjector.binderRestoreCallingIdentity(ident); 6225 } 6226 } 6227 } 6228 6229 if (mInjector.securityLogIsLoggingEnabled()) { 6230 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 6231 /*method strength*/ 1); 6232 } 6233 } 6234 6235 @Override 6236 public void reportFailedFingerprintAttempt(int userHandle) { 6237 enforceFullCrossUsersPermission(userHandle); 6238 mContext.enforceCallingOrSelfPermission( 6239 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6240 if (mInjector.securityLogIsLoggingEnabled()) { 6241 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 6242 /*method strength*/ 0); 6243 } 6244 } 6245 6246 @Override 6247 public void reportSuccessfulFingerprintAttempt(int userHandle) { 6248 enforceFullCrossUsersPermission(userHandle); 6249 mContext.enforceCallingOrSelfPermission( 6250 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6251 if (mInjector.securityLogIsLoggingEnabled()) { 6252 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 6253 /*method strength*/ 0); 6254 } 6255 } 6256 6257 @Override 6258 public void reportKeyguardDismissed(int userHandle) { 6259 enforceFullCrossUsersPermission(userHandle); 6260 mContext.enforceCallingOrSelfPermission( 6261 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6262 6263 if (mInjector.securityLogIsLoggingEnabled()) { 6264 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 6265 } 6266 } 6267 6268 @Override 6269 public void reportKeyguardSecured(int userHandle) { 6270 enforceFullCrossUsersPermission(userHandle); 6271 mContext.enforceCallingOrSelfPermission( 6272 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6273 6274 if (mInjector.securityLogIsLoggingEnabled()) { 6275 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 6276 } 6277 } 6278 6279 @Override 6280 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 6281 String exclusionList) { 6282 if (!mHasFeature) { 6283 return null; 6284 } 6285 synchronized (getLockObject()) { 6286 Preconditions.checkNotNull(who, "ComponentName is null"); 6287 6288 // Only check if system user has set global proxy. We don't allow other users to set it. 6289 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6290 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6291 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 6292 6293 // Scan through active admins and find if anyone has already 6294 // set the global proxy. 6295 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 6296 for (ComponentName component : compSet) { 6297 ActiveAdmin ap = policy.mAdminMap.get(component); 6298 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 6299 // Another admin already sets the global proxy 6300 // Return it to the caller. 6301 return component; 6302 } 6303 } 6304 6305 // If the user is not system, don't set the global proxy. Fail silently. 6306 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 6307 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 6308 + UserHandle.getCallingUserId() + " is not permitted."); 6309 return null; 6310 } 6311 if (proxySpec == null) { 6312 admin.specifiesGlobalProxy = false; 6313 admin.globalProxySpec = null; 6314 admin.globalProxyExclusionList = null; 6315 } else { 6316 6317 admin.specifiesGlobalProxy = true; 6318 admin.globalProxySpec = proxySpec; 6319 admin.globalProxyExclusionList = exclusionList; 6320 } 6321 6322 // Reset the global proxy accordingly 6323 // Do this using system permissions, as apps cannot write to secure settings 6324 long origId = mInjector.binderClearCallingIdentity(); 6325 try { 6326 resetGlobalProxyLocked(policy); 6327 } finally { 6328 mInjector.binderRestoreCallingIdentity(origId); 6329 } 6330 return null; 6331 } 6332 } 6333 6334 @Override 6335 public ComponentName getGlobalProxyAdmin(int userHandle) { 6336 if (!mHasFeature) { 6337 return null; 6338 } 6339 enforceFullCrossUsersPermission(userHandle); 6340 synchronized (getLockObject()) { 6341 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6342 // Scan through active admins and find if anyone has already 6343 // set the global proxy. 6344 final int N = policy.mAdminList.size(); 6345 for (int i = 0; i < N; i++) { 6346 ActiveAdmin ap = policy.mAdminList.get(i); 6347 if (ap.specifiesGlobalProxy) { 6348 // Device admin sets the global proxy 6349 // Return it to the caller. 6350 return ap.info.getComponent(); 6351 } 6352 } 6353 } 6354 // No device admin sets the global proxy. 6355 return null; 6356 } 6357 6358 @Override 6359 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 6360 synchronized (getLockObject()) { 6361 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6362 } 6363 long token = mInjector.binderClearCallingIdentity(); 6364 try { 6365 ConnectivityManager connectivityManager = (ConnectivityManager) 6366 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 6367 connectivityManager.setGlobalProxy(proxyInfo); 6368 } finally { 6369 mInjector.binderRestoreCallingIdentity(token); 6370 } 6371 } 6372 6373 private void resetGlobalProxyLocked(DevicePolicyData policy) { 6374 final int N = policy.mAdminList.size(); 6375 for (int i = 0; i < N; i++) { 6376 ActiveAdmin ap = policy.mAdminList.get(i); 6377 if (ap.specifiesGlobalProxy) { 6378 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 6379 return; 6380 } 6381 } 6382 // No device admins defining global proxies - reset global proxy settings to none 6383 saveGlobalProxyLocked(null, null); 6384 } 6385 6386 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 6387 if (exclusionList == null) { 6388 exclusionList = ""; 6389 } 6390 if (proxySpec == null) { 6391 proxySpec = ""; 6392 } 6393 // Remove white spaces 6394 proxySpec = proxySpec.trim(); 6395 String data[] = proxySpec.split(":"); 6396 int proxyPort = 8080; 6397 if (data.length > 1) { 6398 try { 6399 proxyPort = Integer.parseInt(data[1]); 6400 } catch (NumberFormatException e) {} 6401 } 6402 exclusionList = exclusionList.trim(); 6403 6404 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 6405 if (!proxyProperties.isValid()) { 6406 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 6407 return; 6408 } 6409 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 6410 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 6411 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 6412 exclusionList); 6413 } 6414 6415 /** 6416 * Called by an application that is administering the device to request that the storage system 6417 * be encrypted. Does nothing if the caller is on a secondary user or a managed profile. 6418 * 6419 * @return the new total request status (for all admins), or {@link 6420 * DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user 6421 */ 6422 @Override 6423 public int setStorageEncryption(ComponentName who, boolean encrypt) { 6424 if (!mHasFeature) { 6425 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6426 } 6427 Preconditions.checkNotNull(who, "ComponentName is null"); 6428 final int userHandle = UserHandle.getCallingUserId(); 6429 synchronized (getLockObject()) { 6430 // Check for permissions 6431 // Only system user can set storage encryption 6432 if (userHandle != UserHandle.USER_SYSTEM) { 6433 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User " 6434 + UserHandle.getCallingUserId() + " is not permitted."); 6435 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6436 } 6437 6438 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 6439 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 6440 6441 // Quick exit: If the filesystem does not support encryption, we can exit early. 6442 if (!isEncryptionSupported()) { 6443 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6444 } 6445 6446 // (1) Record the value for the admin so it's sticky 6447 if (ap.encryptionRequested != encrypt) { 6448 ap.encryptionRequested = encrypt; 6449 saveSettingsLocked(userHandle); 6450 } 6451 6452 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6453 // (2) Compute "max" for all admins 6454 boolean newRequested = false; 6455 final int N = policy.mAdminList.size(); 6456 for (int i = 0; i < N; i++) { 6457 newRequested |= policy.mAdminList.get(i).encryptionRequested; 6458 } 6459 6460 // Notify OS of new request 6461 setEncryptionRequested(newRequested); 6462 6463 // Return the new global request status 6464 return newRequested 6465 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 6466 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 6467 } 6468 } 6469 6470 /** 6471 * Get the current storage encryption request status for a given admin, or aggregate of all 6472 * active admins. 6473 */ 6474 @Override 6475 public boolean getStorageEncryption(ComponentName who, int userHandle) { 6476 if (!mHasFeature) { 6477 return false; 6478 } 6479 enforceFullCrossUsersPermission(userHandle); 6480 synchronized (getLockObject()) { 6481 // Check for permissions if a particular caller is specified 6482 if (who != null) { 6483 // When checking for a single caller, status is based on caller's request 6484 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 6485 return ap != null ? ap.encryptionRequested : false; 6486 } 6487 6488 // If no particular caller is specified, return the aggregate set of requests. 6489 // This is short circuited by returning true on the first hit. 6490 DevicePolicyData policy = getUserData(userHandle); 6491 final int N = policy.mAdminList.size(); 6492 for (int i = 0; i < N; i++) { 6493 if (policy.mAdminList.get(i).encryptionRequested) { 6494 return true; 6495 } 6496 } 6497 return false; 6498 } 6499 } 6500 6501 /** 6502 * Get the current encryption status of the device. 6503 */ 6504 @Override 6505 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 6506 if (!mHasFeature) { 6507 // Ok to return current status. 6508 } 6509 enforceFullCrossUsersPermission(userHandle); 6510 6511 // It's not critical here, but let's make sure the package name is correct, in case 6512 // we start using it for different purposes. 6513 ensureCallerPackage(callerPackage); 6514 6515 final ApplicationInfo ai; 6516 try { 6517 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 6518 } catch (RemoteException e) { 6519 throw new SecurityException(e); 6520 } 6521 6522 boolean legacyApp = false; 6523 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 6524 legacyApp = true; 6525 } 6526 6527 final int rawStatus = getEncryptionStatus(); 6528 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 6529 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 6530 } 6531 return rawStatus; 6532 } 6533 6534 /** 6535 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 6536 */ 6537 private boolean isEncryptionSupported() { 6538 // Note, this can be implemented as 6539 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6540 // But is provided as a separate internal method if there's a faster way to do a 6541 // simple check for supported-or-not. 6542 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6543 } 6544 6545 /** 6546 * Hook to low-levels: Reporting the current status of encryption. 6547 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 6548 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 6549 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 6550 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or 6551 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 6552 */ 6553 private int getEncryptionStatus() { 6554 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 6555 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 6556 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) { 6557 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 6558 } else if (mInjector.storageManagerIsEncrypted()) { 6559 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 6560 } else if (mInjector.storageManagerIsEncryptable()) { 6561 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 6562 } else { 6563 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 6564 } 6565 } 6566 6567 /** 6568 * Hook to low-levels: If needed, record the new admin setting for encryption. 6569 */ 6570 private void setEncryptionRequested(boolean encrypt) { 6571 } 6572 6573 /** 6574 * Set whether the screen capture is disabled for the user managed by the specified admin. 6575 */ 6576 @Override 6577 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) { 6578 if (!mHasFeature) { 6579 return; 6580 } 6581 Preconditions.checkNotNull(who, "ComponentName is null"); 6582 final int userHandle = UserHandle.getCallingUserId(); 6583 synchronized (getLockObject()) { 6584 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 6585 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6586 if (ap.disableScreenCapture != disabled) { 6587 ap.disableScreenCapture = disabled; 6588 saveSettingsLocked(userHandle); 6589 updateScreenCaptureDisabled(userHandle, disabled); 6590 } 6591 } 6592 } 6593 6594 /** 6595 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 6596 * active admin (if given admin is null). 6597 */ 6598 @Override 6599 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) { 6600 if (!mHasFeature) { 6601 return false; 6602 } 6603 synchronized (getLockObject()) { 6604 if (who != null) { 6605 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 6606 return (admin != null) ? admin.disableScreenCapture : false; 6607 } 6608 6609 DevicePolicyData policy = getUserData(userHandle); 6610 final int N = policy.mAdminList.size(); 6611 for (int i = 0; i < N; i++) { 6612 ActiveAdmin admin = policy.mAdminList.get(i); 6613 if (admin.disableScreenCapture) { 6614 return true; 6615 } 6616 } 6617 return false; 6618 } 6619 } 6620 6621 private void updateScreenCaptureDisabled(int userHandle, boolean disabled) { 6622 mPolicyCache.setScreenCaptureDisabled(userHandle, disabled); 6623 mHandler.post(new Runnable() { 6624 @Override 6625 public void run() { 6626 try { 6627 mInjector.getIWindowManager().refreshScreenCaptureDisabled(userHandle); 6628 } catch (RemoteException e) { 6629 Log.w(LOG_TAG, "Unable to notify WindowManager.", e); 6630 } 6631 } 6632 }); 6633 } 6634 6635 /** 6636 * Set whether auto time is required by the specified admin (must be device or profile owner). 6637 */ 6638 @Override 6639 public void setAutoTimeRequired(ComponentName who, boolean required) { 6640 if (!mHasFeature) { 6641 return; 6642 } 6643 Preconditions.checkNotNull(who, "ComponentName is null"); 6644 final int userHandle = UserHandle.getCallingUserId(); 6645 synchronized (getLockObject()) { 6646 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6647 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6648 if (admin.requireAutoTime != required) { 6649 admin.requireAutoTime = required; 6650 saveSettingsLocked(userHandle); 6651 } 6652 } 6653 6654 // Turn AUTO_TIME on in settings if it is required 6655 if (required) { 6656 long ident = mInjector.binderClearCallingIdentity(); 6657 try { 6658 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */); 6659 } finally { 6660 mInjector.binderRestoreCallingIdentity(ident); 6661 } 6662 } 6663 } 6664 6665 /** 6666 * Returns whether or not auto time is required by the device owner or any profile owner. 6667 */ 6668 @Override 6669 public boolean getAutoTimeRequired() { 6670 if (!mHasFeature) { 6671 return false; 6672 } 6673 synchronized (getLockObject()) { 6674 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6675 if (deviceOwner != null && deviceOwner.requireAutoTime) { 6676 // If the device owner enforces auto time, we don't need to check the PO's 6677 return true; 6678 } 6679 6680 // Now check to see if any profile owner on any user enforces auto time 6681 for (Integer userId : mOwners.getProfileOwnerKeys()) { 6682 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 6683 if (profileOwner != null && profileOwner.requireAutoTime) { 6684 return true; 6685 } 6686 } 6687 6688 return false; 6689 } 6690 } 6691 6692 @Override 6693 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 6694 if (!mHasFeature) { 6695 return; 6696 } 6697 Preconditions.checkNotNull(who, "ComponentName is null"); 6698 // Allow setting this policy to true only if there is a split system user. 6699 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) { 6700 throw new UnsupportedOperationException( 6701 "Cannot force ephemeral users on systems without split system user."); 6702 } 6703 boolean removeAllUsers = false; 6704 synchronized (getLockObject()) { 6705 final ActiveAdmin deviceOwner = 6706 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6707 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) { 6708 deviceOwner.forceEphemeralUsers = forceEphemeralUsers; 6709 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 6710 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers); 6711 removeAllUsers = forceEphemeralUsers; 6712 } 6713 } 6714 if (removeAllUsers) { 6715 long identitity = mInjector.binderClearCallingIdentity(); 6716 try { 6717 mUserManagerInternal.removeAllUsers(); 6718 } finally { 6719 mInjector.binderRestoreCallingIdentity(identitity); 6720 } 6721 } 6722 } 6723 6724 @Override 6725 public boolean getForceEphemeralUsers(ComponentName who) { 6726 if (!mHasFeature) { 6727 return false; 6728 } 6729 Preconditions.checkNotNull(who, "ComponentName is null"); 6730 synchronized (getLockObject()) { 6731 final ActiveAdmin deviceOwner = 6732 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6733 return deviceOwner.forceEphemeralUsers; 6734 } 6735 } 6736 6737 private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException { 6738 synchronized (getLockObject()) { 6739 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6740 if (!areAllUsersAffiliatedWithDeviceLocked()) { 6741 throw new SecurityException("Not all users are affiliated."); 6742 } 6743 } 6744 } 6745 6746 @Override 6747 public boolean requestBugreport(ComponentName who) { 6748 if (!mHasFeature) { 6749 return false; 6750 } 6751 Preconditions.checkNotNull(who, "ComponentName is null"); 6752 6753 // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport 6754 // which could still contain data related to that user. Should we disallow that, e.g. until 6755 // next boot? Might not be needed given that this still requires user consent. 6756 ensureDeviceOwnerAndAllUsersAffiliated(who); 6757 6758 if (mRemoteBugreportServiceIsActive.get() 6759 || (getDeviceOwnerRemoteBugreportUri() != null)) { 6760 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running."); 6761 return false; 6762 } 6763 6764 final long currentTime = System.currentTimeMillis(); 6765 synchronized (getLockObject()) { 6766 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 6767 if (currentTime > policyData.mLastBugReportRequestTime) { 6768 policyData.mLastBugReportRequestTime = currentTime; 6769 saveSettingsLocked(UserHandle.USER_SYSTEM); 6770 } 6771 } 6772 6773 final long callingIdentity = mInjector.binderClearCallingIdentity(); 6774 try { 6775 mInjector.getIActivityManager().requestBugReport( 6776 ActivityManager.BUGREPORT_OPTION_REMOTE); 6777 6778 mRemoteBugreportServiceIsActive.set(true); 6779 mRemoteBugreportSharingAccepted.set(false); 6780 registerRemoteBugreportReceivers(); 6781 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, 6782 RemoteBugreportUtils.NOTIFICATION_ID, 6783 RemoteBugreportUtils.buildNotification(mContext, 6784 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL); 6785 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable, 6786 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS); 6787 return true; 6788 } catch (RemoteException re) { 6789 // should never happen 6790 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re); 6791 return false; 6792 } finally { 6793 mInjector.binderRestoreCallingIdentity(callingIdentity); 6794 } 6795 } 6796 6797 void sendDeviceOwnerCommand(String action, Bundle extras) { 6798 int deviceOwnerUserId; 6799 ComponentName deviceOwnerComponent; 6800 synchronized (getLockObject()) { 6801 deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 6802 deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 6803 } 6804 sendActiveAdminCommand(action, extras, deviceOwnerUserId, 6805 deviceOwnerComponent); 6806 } 6807 6808 private void sendProfileOwnerCommand(String action, Bundle extras, int userHandle) { 6809 sendActiveAdminCommand(action, extras, userHandle, 6810 mOwners.getProfileOwnerComponent(userHandle)); 6811 } 6812 6813 private void sendActiveAdminCommand(String action, Bundle extras, 6814 int userHandle, ComponentName receiverComponent) { 6815 final Intent intent = new Intent(action); 6816 intent.setComponent(receiverComponent); 6817 if (extras != null) { 6818 intent.putExtras(extras); 6819 } 6820 mContext.sendBroadcastAsUser(intent, UserHandle.of(userHandle)); 6821 } 6822 6823 private void sendOwnerChangedBroadcast(String broadcast, int userId) { 6824 final Intent intent = new Intent(broadcast) 6825 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 6826 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 6827 } 6828 6829 private String getDeviceOwnerRemoteBugreportUri() { 6830 synchronized (getLockObject()) { 6831 return mOwners.getDeviceOwnerRemoteBugreportUri(); 6832 } 6833 } 6834 6835 private void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, 6836 String bugreportHash) { 6837 synchronized (getLockObject()) { 6838 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 6839 } 6840 } 6841 6842 private void registerRemoteBugreportReceivers() { 6843 try { 6844 IntentFilter filterFinished = new IntentFilter( 6845 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH, 6846 RemoteBugreportUtils.BUGREPORT_MIMETYPE); 6847 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished); 6848 } catch (IntentFilter.MalformedMimeTypeException e) { 6849 // should never happen, as setting a constant 6850 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e); 6851 } 6852 IntentFilter filterConsent = new IntentFilter(); 6853 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 6854 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 6855 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 6856 } 6857 6858 private void onBugreportFinished(Intent intent) { 6859 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 6860 mRemoteBugreportServiceIsActive.set(false); 6861 Uri bugreportUri = intent.getData(); 6862 String bugreportUriString = null; 6863 if (bugreportUri != null) { 6864 bugreportUriString = bugreportUri.toString(); 6865 } 6866 String bugreportHash = intent.getStringExtra( 6867 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH); 6868 if (mRemoteBugreportSharingAccepted.get()) { 6869 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 6870 mInjector.getNotificationManager().cancel(LOG_TAG, 6871 RemoteBugreportUtils.NOTIFICATION_ID); 6872 } else { 6873 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash); 6874 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 6875 RemoteBugreportUtils.buildNotification(mContext, 6876 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 6877 UserHandle.ALL); 6878 } 6879 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6880 } 6881 6882 private void onBugreportFailed() { 6883 mRemoteBugreportServiceIsActive.set(false); 6884 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 6885 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 6886 mRemoteBugreportSharingAccepted.set(false); 6887 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6888 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID); 6889 Bundle extras = new Bundle(); 6890 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 6891 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING); 6892 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 6893 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 6894 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6895 } 6896 6897 private void onBugreportSharingAccepted() { 6898 mRemoteBugreportSharingAccepted.set(true); 6899 String bugreportUriString = null; 6900 String bugreportHash = null; 6901 synchronized (getLockObject()) { 6902 bugreportUriString = getDeviceOwnerRemoteBugreportUri(); 6903 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash(); 6904 } 6905 if (bugreportUriString != null) { 6906 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 6907 } else if (mRemoteBugreportServiceIsActive.get()) { 6908 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 6909 RemoteBugreportUtils.buildNotification(mContext, 6910 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED), 6911 UserHandle.ALL); 6912 } 6913 } 6914 6915 private void onBugreportSharingDeclined() { 6916 if (mRemoteBugreportServiceIsActive.get()) { 6917 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 6918 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 6919 mRemoteBugreportServiceIsActive.set(false); 6920 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 6921 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6922 } 6923 mRemoteBugreportSharingAccepted.set(false); 6924 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6925 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null); 6926 } 6927 6928 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, 6929 String bugreportHash) { 6930 ParcelFileDescriptor pfd = null; 6931 try { 6932 if (bugreportUriString == null) { 6933 throw new FileNotFoundException(); 6934 } 6935 Uri bugreportUri = Uri.parse(bugreportUriString); 6936 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r"); 6937 6938 synchronized (getLockObject()) { 6939 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 6940 intent.setComponent(mOwners.getDeviceOwnerComponent()); 6941 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE); 6942 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 6943 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6944 6945 LocalServices.getService(ActivityManagerInternal.class) 6946 .grantUriPermissionFromIntent(Process.SHELL_UID, 6947 mOwners.getDeviceOwnerComponent().getPackageName(), 6948 intent, mOwners.getDeviceOwnerUserId()); 6949 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 6950 } 6951 } catch (FileNotFoundException e) { 6952 Bundle extras = new Bundle(); 6953 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 6954 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE); 6955 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 6956 } finally { 6957 try { 6958 if (pfd != null) { 6959 pfd.close(); 6960 } 6961 } catch (IOException ex) { 6962 // Ignore 6963 } 6964 mRemoteBugreportSharingAccepted.set(false); 6965 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6966 } 6967 } 6968 6969 /** 6970 * Disables all device cameras according to the specified admin. 6971 */ 6972 @Override 6973 public void setCameraDisabled(ComponentName who, boolean disabled) { 6974 if (!mHasFeature) { 6975 return; 6976 } 6977 Preconditions.checkNotNull(who, "ComponentName is null"); 6978 final int userHandle = mInjector.userHandleGetCallingUserId(); 6979 synchronized (getLockObject()) { 6980 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 6981 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 6982 if (ap.disableCamera != disabled) { 6983 ap.disableCamera = disabled; 6984 saveSettingsLocked(userHandle); 6985 } 6986 } 6987 // Tell the user manager that the restrictions have changed. 6988 pushUserRestrictions(userHandle); 6989 } 6990 6991 /** 6992 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 6993 * active admins. 6994 */ 6995 @Override 6996 public boolean getCameraDisabled(ComponentName who, int userHandle) { 6997 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true); 6998 } 6999 7000 private boolean getCameraDisabled(ComponentName who, int userHandle, 7001 boolean mergeDeviceOwnerRestriction) { 7002 if (!mHasFeature) { 7003 return false; 7004 } 7005 synchronized (getLockObject()) { 7006 if (who != null) { 7007 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7008 return (admin != null) ? admin.disableCamera : false; 7009 } 7010 // First, see if DO has set it. If so, it's device-wide. 7011 if (mergeDeviceOwnerRestriction) { 7012 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7013 if (deviceOwner != null && deviceOwner.disableCamera) { 7014 return true; 7015 } 7016 } 7017 7018 // Then check each device admin on the user. 7019 DevicePolicyData policy = getUserData(userHandle); 7020 // Determine whether or not the device camera is disabled for any active admins. 7021 final int N = policy.mAdminList.size(); 7022 for (int i = 0; i < N; i++) { 7023 ActiveAdmin admin = policy.mAdminList.get(i); 7024 if (admin.disableCamera) { 7025 return true; 7026 } 7027 } 7028 return false; 7029 } 7030 } 7031 7032 @Override 7033 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 7034 if (!mHasFeature) { 7035 return; 7036 } 7037 Preconditions.checkNotNull(who, "ComponentName is null"); 7038 final int userHandle = mInjector.userHandleGetCallingUserId(); 7039 if (isManagedProfile(userHandle)) { 7040 if (parent) { 7041 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 7042 } else { 7043 which = which & PROFILE_KEYGUARD_FEATURES; 7044 } 7045 } 7046 synchronized (getLockObject()) { 7047 ActiveAdmin ap = getActiveAdminForCallerLocked( 7048 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 7049 if (ap.disabledKeyguardFeatures != which) { 7050 ap.disabledKeyguardFeatures = which; 7051 saveSettingsLocked(userHandle); 7052 } 7053 } 7054 if (SecurityLog.isLoggingEnabled()) { 7055 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 7056 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET, 7057 who.getPackageName(), userHandle, affectedUserId, which); 7058 } 7059 } 7060 7061 /** 7062 * Gets the disabled state for features in keyguard for the given admin, 7063 * or the aggregate of all active admins if who is null. 7064 */ 7065 @Override 7066 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 7067 if (!mHasFeature) { 7068 return 0; 7069 } 7070 enforceFullCrossUsersPermission(userHandle); 7071 final long ident = mInjector.binderClearCallingIdentity(); 7072 try { 7073 synchronized (getLockObject()) { 7074 if (who != null) { 7075 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 7076 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 7077 } 7078 7079 final List<ActiveAdmin> admins; 7080 if (!parent && isManagedProfile(userHandle)) { 7081 // If we are being asked about a managed profile, just return keyguard features 7082 // disabled by admins in the profile. 7083 admins = getUserDataUnchecked(userHandle).mAdminList; 7084 } else { 7085 // Otherwise return those set by admins in the user and its profiles. 7086 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 7087 } 7088 7089 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 7090 final int N = admins.size(); 7091 for (int i = 0; i < N; i++) { 7092 ActiveAdmin admin = admins.get(i); 7093 int userId = admin.getUserHandle().getIdentifier(); 7094 boolean isRequestedUser = !parent && (userId == userHandle); 7095 if (isRequestedUser || !isManagedProfile(userId)) { 7096 // If we are being asked explicitly about this user 7097 // return all disabled features even if its a managed profile. 7098 which |= admin.disabledKeyguardFeatures; 7099 } else { 7100 // Otherwise a managed profile is only allowed to disable 7101 // some features on the parent user. 7102 which |= (admin.disabledKeyguardFeatures 7103 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 7104 } 7105 } 7106 return which; 7107 } 7108 } finally { 7109 mInjector.binderRestoreCallingIdentity(ident); 7110 } 7111 } 7112 7113 @Override 7114 public void setKeepUninstalledPackages(ComponentName who, String callerPackage, 7115 List<String> packageList) { 7116 if (!mHasFeature) { 7117 return; 7118 } 7119 Preconditions.checkNotNull(packageList, "packageList is null"); 7120 final int userHandle = UserHandle.getCallingUserId(); 7121 synchronized (getLockObject()) { 7122 // Ensure the caller is a DO or a keep uninstalled packages delegate. 7123 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7124 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 7125 // Get the device owner 7126 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7127 // Set list of packages to be kept even if uninstalled. 7128 deviceOwner.keepUninstalledPackages = packageList; 7129 // Save settings. 7130 saveSettingsLocked(userHandle); 7131 // Notify package manager. 7132 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 7133 } 7134 } 7135 7136 @Override 7137 public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) { 7138 if (!mHasFeature) { 7139 return null; 7140 } 7141 // TODO In split system user mode, allow apps on user 0 to query the list 7142 synchronized (getLockObject()) { 7143 // Ensure the caller is a DO or a keep uninstalled packages delegate. 7144 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7145 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 7146 return getKeepUninstalledPackagesLocked(); 7147 } 7148 } 7149 7150 private List<String> getKeepUninstalledPackagesLocked() { 7151 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7152 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 7153 } 7154 7155 @Override 7156 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) { 7157 if (!mHasFeature) { 7158 return false; 7159 } 7160 if (admin == null 7161 || !isPackageInstalledForUser(admin.getPackageName(), userId)) { 7162 throw new IllegalArgumentException("Invalid component " + admin 7163 + " for device owner"); 7164 } 7165 final boolean hasIncompatibleAccountsOrNonAdb = 7166 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin); 7167 synchronized (getLockObject()) { 7168 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb); 7169 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 7170 if (activeAdmin == null 7171 || getUserData(userId).mRemovingAdmins.contains(admin)) { 7172 throw new IllegalArgumentException("Not active admin: " + admin); 7173 } 7174 7175 // Shutting down backup manager service permanently. 7176 long ident = mInjector.binderClearCallingIdentity(); 7177 try { 7178 if (mInjector.getIBackupManager() != null) { 7179 mInjector.getIBackupManager() 7180 .setBackupServiceActive(UserHandle.USER_SYSTEM, false); 7181 } 7182 } catch (RemoteException e) { 7183 throw new IllegalStateException("Failed deactivating backup service.", e); 7184 } finally { 7185 mInjector.binderRestoreCallingIdentity(ident); 7186 } 7187 7188 if (isAdb()) { 7189 // Log device owner provisioning was started using adb. 7190 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 7191 } 7192 7193 mOwners.setDeviceOwner(admin, ownerName, userId); 7194 mOwners.writeDeviceOwner(); 7195 updateDeviceOwnerLocked(); 7196 setDeviceOwnerSystemPropertyLocked(); 7197 7198 final Set<String> restrictions = 7199 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner(); 7200 if (!restrictions.isEmpty()) { 7201 for (String restriction : restrictions) { 7202 activeAdmin.ensureUserRestrictions().putBoolean(restriction, true); 7203 } 7204 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions); 7205 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions); 7206 7207 saveUserRestrictionsLocked(userId); 7208 } 7209 7210 ident = mInjector.binderClearCallingIdentity(); 7211 try { 7212 // TODO Send to system too? 7213 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId); 7214 } finally { 7215 mInjector.binderRestoreCallingIdentity(ident); 7216 } 7217 mDeviceAdminServiceController.startServiceForOwner( 7218 admin.getPackageName(), userId, "set-device-owner"); 7219 7220 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 7221 return true; 7222 } 7223 } 7224 7225 @Override 7226 public boolean hasDeviceOwner() { 7227 enforceDeviceOwnerOrManageUsers(); 7228 return mOwners.hasDeviceOwner(); 7229 } 7230 7231 boolean isDeviceOwner(ActiveAdmin admin) { 7232 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 7233 } 7234 7235 public boolean isDeviceOwner(ComponentName who, int userId) { 7236 synchronized (getLockObject()) { 7237 return mOwners.hasDeviceOwner() 7238 && mOwners.getDeviceOwnerUserId() == userId 7239 && mOwners.getDeviceOwnerComponent().equals(who); 7240 } 7241 } 7242 7243 private boolean isDeviceOwnerPackage(String packageName, int userId) { 7244 synchronized (getLockObject()) { 7245 return mOwners.hasDeviceOwner() 7246 && mOwners.getDeviceOwnerUserId() == userId 7247 && mOwners.getDeviceOwnerPackageName().equals(packageName); 7248 } 7249 } 7250 7251 private boolean isProfileOwnerPackage(String packageName, int userId) { 7252 synchronized (getLockObject()) { 7253 return mOwners.hasProfileOwner(userId) 7254 && mOwners.getProfileOwnerPackage(userId).equals(packageName); 7255 } 7256 } 7257 7258 public boolean isProfileOwner(ComponentName who, int userId) { 7259 final ComponentName profileOwner = getProfileOwner(userId); 7260 return who != null && who.equals(profileOwner); 7261 } 7262 7263 @Override 7264 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 7265 if (!mHasFeature) { 7266 return null; 7267 } 7268 if (!callingUserOnly) { 7269 enforceManageUsers(); 7270 } 7271 synchronized (getLockObject()) { 7272 if (!mOwners.hasDeviceOwner()) { 7273 return null; 7274 } 7275 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 7276 mOwners.getDeviceOwnerUserId()) { 7277 return null; 7278 } 7279 return mOwners.getDeviceOwnerComponent(); 7280 } 7281 } 7282 7283 @Override 7284 public int getDeviceOwnerUserId() { 7285 if (!mHasFeature) { 7286 return UserHandle.USER_NULL; 7287 } 7288 enforceManageUsers(); 7289 synchronized (getLockObject()) { 7290 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 7291 } 7292 } 7293 7294 /** 7295 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 7296 * MANAGE_USERS. 7297 */ 7298 @Override 7299 public String getDeviceOwnerName() { 7300 if (!mHasFeature) { 7301 return null; 7302 } 7303 enforceManageUsers(); 7304 synchronized (getLockObject()) { 7305 if (!mOwners.hasDeviceOwner()) { 7306 return null; 7307 } 7308 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 7309 // Should setDeviceOwner/ProfileOwner still take a name? 7310 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 7311 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 7312 } 7313 } 7314 7315 /** Returns the active device owner or {@code null} if there is no device owner. */ 7316 @VisibleForTesting 7317 ActiveAdmin getDeviceOwnerAdminLocked() { 7318 ensureLocked(); 7319 ComponentName component = mOwners.getDeviceOwnerComponent(); 7320 if (component == null) { 7321 return null; 7322 } 7323 7324 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 7325 final int n = policy.mAdminList.size(); 7326 for (int i = 0; i < n; i++) { 7327 ActiveAdmin admin = policy.mAdminList.get(i); 7328 if (component.equals(admin.info.getComponent())) { 7329 return admin; 7330 } 7331 } 7332 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 7333 return null; 7334 } 7335 7336 @Override 7337 public void clearDeviceOwner(String packageName) { 7338 Preconditions.checkNotNull(packageName, "packageName is null"); 7339 final int callingUid = mInjector.binderGetCallingUid(); 7340 try { 7341 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 7342 UserHandle.getUserId(callingUid)); 7343 if (uid != callingUid) { 7344 throw new SecurityException("Invalid packageName"); 7345 } 7346 } catch (NameNotFoundException e) { 7347 throw new SecurityException(e); 7348 } 7349 synchronized (getLockObject()) { 7350 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 7351 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 7352 if (!mOwners.hasDeviceOwner() 7353 || !deviceOwnerComponent.getPackageName().equals(packageName) 7354 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) { 7355 throw new SecurityException( 7356 "clearDeviceOwner can only be called by the device owner"); 7357 } 7358 enforceUserUnlocked(deviceOwnerUserId); 7359 7360 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 7361 long ident = mInjector.binderClearCallingIdentity(); 7362 try { 7363 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 7364 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 7365 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, 7366 deviceOwnerUserId); 7367 } finally { 7368 mInjector.binderRestoreCallingIdentity(ident); 7369 } 7370 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 7371 } 7372 } 7373 7374 private void clearOverrideApnUnchecked() { 7375 // Disable Override APNs and remove them from database. 7376 setOverrideApnsEnabledUnchecked(false); 7377 final List<ApnSetting> apns = getOverrideApnsUnchecked(); 7378 for (int i = 0; i < apns.size(); i ++) { 7379 removeOverrideApnUnchecked(apns.get(i).getId()); 7380 } 7381 } 7382 7383 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 7384 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner"); 7385 7386 if (admin != null) { 7387 admin.disableCamera = false; 7388 admin.userRestrictions = null; 7389 admin.defaultEnabledRestrictionsAlreadySet.clear(); 7390 admin.forceEphemeralUsers = false; 7391 admin.isNetworkLoggingEnabled = false; 7392 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 7393 } 7394 final DevicePolicyData policyData = getUserData(userId); 7395 policyData.mCurrentInputMethodSet = false; 7396 saveSettingsLocked(userId); 7397 final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM); 7398 systemPolicyData.mLastSecurityLogRetrievalTime = -1; 7399 systemPolicyData.mLastBugReportRequestTime = -1; 7400 systemPolicyData.mLastNetworkLogsRetrievalTime = -1; 7401 saveSettingsLocked(UserHandle.USER_SYSTEM); 7402 clearUserPoliciesLocked(userId); 7403 clearOverrideApnUnchecked(); 7404 7405 mOwners.clearDeviceOwner(); 7406 mOwners.writeDeviceOwner(); 7407 updateDeviceOwnerLocked(); 7408 7409 clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId)); 7410 mInjector.securityLogSetLoggingEnabledProperty(false); 7411 mSecurityLogMonitor.stop(); 7412 setNetworkLoggingActiveInternal(false); 7413 deleteTransferOwnershipBundleLocked(userId); 7414 7415 try { 7416 if (mInjector.getIBackupManager() != null) { 7417 // Reactivate backup service. 7418 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true); 7419 } 7420 } catch (RemoteException e) { 7421 throw new IllegalStateException("Failed reactivating backup service.", e); 7422 } 7423 } 7424 7425 @Override 7426 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 7427 if (!mHasFeature) { 7428 return false; 7429 } 7430 if (who == null 7431 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) { 7432 throw new IllegalArgumentException("Component " + who 7433 + " not installed for userId:" + userHandle); 7434 } 7435 final boolean hasIncompatibleAccountsOrNonAdb = 7436 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who); 7437 synchronized (getLockObject()) { 7438 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb); 7439 7440 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7441 if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) { 7442 throw new IllegalArgumentException("Not active admin: " + who); 7443 } 7444 7445 if (isAdb()) { 7446 // Log profile owner provisioning was started using adb. 7447 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 7448 } 7449 7450 mOwners.setProfileOwner(who, ownerName, userHandle); 7451 mOwners.writeProfileOwner(userHandle); 7452 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 7453 7454 final long id = mInjector.binderClearCallingIdentity(); 7455 try { 7456 if (mUserManager.isManagedProfile(userHandle)) { 7457 maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin, 7458 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 7459 ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin, 7460 true /* newOwner */); 7461 } 7462 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 7463 userHandle); 7464 } finally { 7465 mInjector.binderRestoreCallingIdentity(id); 7466 } 7467 mDeviceAdminServiceController.startServiceForOwner( 7468 who.getPackageName(), userHandle, "set-profile-owner"); 7469 return true; 7470 } 7471 } 7472 7473 @Override 7474 public void clearProfileOwner(ComponentName who) { 7475 if (!mHasFeature) { 7476 return; 7477 } 7478 Preconditions.checkNotNull(who, "ComponentName is null"); 7479 7480 final int userId = mInjector.userHandleGetCallingUserId(); 7481 enforceNotManagedProfile(userId, "clear profile owner"); 7482 enforceUserUnlocked(userId); 7483 synchronized (getLockObject()) { 7484 // Check if this is the profile owner who is calling 7485 final ActiveAdmin admin = 7486 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7487 7488 final long ident = mInjector.binderClearCallingIdentity(); 7489 try { 7490 clearProfileOwnerLocked(admin, userId); 7491 removeActiveAdminLocked(who, userId); 7492 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 7493 userId); 7494 } finally { 7495 mInjector.binderRestoreCallingIdentity(ident); 7496 } 7497 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 7498 } 7499 } 7500 7501 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 7502 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner"); 7503 7504 if (admin != null) { 7505 admin.disableCamera = false; 7506 admin.userRestrictions = null; 7507 admin.defaultEnabledRestrictionsAlreadySet.clear(); 7508 } 7509 final DevicePolicyData policyData = getUserData(userId); 7510 policyData.mCurrentInputMethodSet = false; 7511 policyData.mOwnerInstalledCaCerts.clear(); 7512 saveSettingsLocked(userId); 7513 clearUserPoliciesLocked(userId); 7514 mOwners.removeProfileOwner(userId); 7515 mOwners.writeProfileOwner(userId); 7516 deleteTransferOwnershipBundleLocked(userId); 7517 } 7518 7519 @Override 7520 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 7521 Preconditions.checkNotNull(who, "ComponentName is null"); 7522 if (!mHasFeature) { 7523 return; 7524 } 7525 7526 synchronized (getLockObject()) { 7527 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7528 long token = mInjector.binderClearCallingIdentity(); 7529 try { 7530 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null); 7531 } finally { 7532 mInjector.binderRestoreCallingIdentity(token); 7533 } 7534 } 7535 } 7536 7537 @Override 7538 public CharSequence getDeviceOwnerLockScreenInfo() { 7539 return mLockPatternUtils.getDeviceOwnerInfo(); 7540 } 7541 7542 private void clearUserPoliciesLocked(int userId) { 7543 // Reset some of the user-specific policies. 7544 final DevicePolicyData policy = getUserData(userId); 7545 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 7546 // Clear delegations. 7547 policy.mDelegationMap.clear(); 7548 policy.mStatusBarDisabled = false; 7549 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 7550 policy.mAffiliationIds.clear(); 7551 policy.mLockTaskPackages.clear(); 7552 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId); 7553 policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE; 7554 saveSettingsLocked(userId); 7555 7556 try { 7557 mIPackageManager.updatePermissionFlagsForAllApps( 7558 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 7559 0 /* flagValues */, userId); 7560 pushUserRestrictions(userId); 7561 } catch (RemoteException re) { 7562 // Shouldn't happen. 7563 } 7564 } 7565 7566 @Override 7567 public boolean hasUserSetupCompleted() { 7568 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 7569 } 7570 7571 // This checks only if the Setup Wizard has run. Since Wear devices pair before 7572 // completing Setup Wizard, and pairing involves transferring user data, calling 7573 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). 7574 private boolean hasUserSetupCompleted(int userHandle) { 7575 if (!mHasFeature) { 7576 return true; 7577 } 7578 return getUserData(userHandle).mUserSetupComplete; 7579 } 7580 7581 private boolean hasPaired(int userHandle) { 7582 if (!mHasFeature) { 7583 return true; 7584 } 7585 return getUserData(userHandle).mPaired; 7586 } 7587 7588 @Override 7589 public int getUserProvisioningState() { 7590 if (!mHasFeature) { 7591 return DevicePolicyManager.STATE_USER_UNMANAGED; 7592 } 7593 enforceManageUsers(); 7594 int userHandle = mInjector.userHandleGetCallingUserId(); 7595 return getUserProvisioningState(userHandle); 7596 } 7597 7598 private int getUserProvisioningState(int userHandle) { 7599 return getUserData(userHandle).mUserProvisioningState; 7600 } 7601 7602 @Override 7603 public void setUserProvisioningState(int newState, int userHandle) { 7604 if (!mHasFeature) { 7605 return; 7606 } 7607 7608 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle) 7609 && getManagedUserId(userHandle) == -1) { 7610 // No managed device, user or profile, so setting provisioning state makes no sense. 7611 throw new IllegalStateException("Not allowed to change provisioning state unless a " 7612 + "device or profile owner is set."); 7613 } 7614 7615 synchronized (getLockObject()) { 7616 boolean transitionCheckNeeded = true; 7617 7618 // Calling identity/permission checks. 7619 if (isAdb()) { 7620 // ADB shell can only move directly from un-managed to finalized as part of directly 7621 // setting profile-owner or device-owner. 7622 if (getUserProvisioningState(userHandle) != 7623 DevicePolicyManager.STATE_USER_UNMANAGED 7624 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 7625 throw new IllegalStateException("Not allowed to change provisioning state " 7626 + "unless current provisioning state is unmanaged, and new state is " 7627 + "finalized."); 7628 } 7629 transitionCheckNeeded = false; 7630 } else { 7631 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS. 7632 enforceCanManageProfileAndDeviceOwners(); 7633 } 7634 7635 final DevicePolicyData policyData = getUserData(userHandle); 7636 if (transitionCheckNeeded) { 7637 // Optional state transition check for non-ADB case. 7638 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState); 7639 } 7640 policyData.mUserProvisioningState = newState; 7641 saveSettingsLocked(userHandle); 7642 } 7643 } 7644 7645 private void checkUserProvisioningStateTransition(int currentState, int newState) { 7646 // Valid transitions for normal use-cases. 7647 switch (currentState) { 7648 case DevicePolicyManager.STATE_USER_UNMANAGED: 7649 // Can move to any state from unmanaged (except itself as an edge case).. 7650 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 7651 return; 7652 } 7653 break; 7654 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 7655 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 7656 // Can only move to finalized from these states. 7657 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 7658 return; 7659 } 7660 break; 7661 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 7662 // Current user has a managed-profile, but current user is not managed, so 7663 // rather than moving to finalized state, go back to unmanaged once 7664 // profile provisioning is complete. 7665 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 7666 return; 7667 } 7668 break; 7669 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED: 7670 // Cannot transition out of finalized. 7671 break; 7672 } 7673 7674 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 7675 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 7676 + "from state [" + currentState + "]"); 7677 } 7678 7679 @Override 7680 public void setProfileEnabled(ComponentName who) { 7681 if (!mHasFeature) { 7682 return; 7683 } 7684 Preconditions.checkNotNull(who, "ComponentName is null"); 7685 synchronized (getLockObject()) { 7686 // Check if this is the profile owner who is calling 7687 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7688 final int userId = UserHandle.getCallingUserId(); 7689 enforceManagedProfile(userId, "enable the profile"); 7690 // Check if the profile is already enabled. 7691 UserInfo managedProfile = getUserInfo(userId); 7692 if (managedProfile.isEnabled()) { 7693 Slog.e(LOG_TAG, 7694 "setProfileEnabled is called when the profile is already enabled"); 7695 return; 7696 } 7697 long id = mInjector.binderClearCallingIdentity(); 7698 try { 7699 mUserManager.setUserEnabled(userId); 7700 UserInfo parent = mUserManager.getProfileParent(userId); 7701 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 7702 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 7703 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 7704 Intent.FLAG_RECEIVER_FOREGROUND); 7705 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id)); 7706 } finally { 7707 mInjector.binderRestoreCallingIdentity(id); 7708 } 7709 } 7710 } 7711 7712 @Override 7713 public void setProfileName(ComponentName who, String profileName) { 7714 Preconditions.checkNotNull(who, "ComponentName is null"); 7715 int userId = UserHandle.getCallingUserId(); 7716 // Check if this is the profile owner (includes device owner). 7717 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7718 7719 long id = mInjector.binderClearCallingIdentity(); 7720 try { 7721 mUserManager.setUserName(userId, profileName); 7722 } finally { 7723 mInjector.binderRestoreCallingIdentity(id); 7724 } 7725 } 7726 7727 @Override 7728 public ComponentName getProfileOwner(int userHandle) { 7729 if (!mHasFeature) { 7730 return null; 7731 } 7732 7733 synchronized (getLockObject()) { 7734 return mOwners.getProfileOwnerComponent(userHandle); 7735 } 7736 } 7737 7738 // Returns the active profile owner for this user or null if the current user has no 7739 // profile owner. 7740 @VisibleForTesting 7741 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 7742 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 7743 if (profileOwner == null) { 7744 return null; 7745 } 7746 DevicePolicyData policy = getUserData(userHandle); 7747 final int n = policy.mAdminList.size(); 7748 for (int i = 0; i < n; i++) { 7749 ActiveAdmin admin = policy.mAdminList.get(i); 7750 if (profileOwner.equals(admin.info.getComponent())) { 7751 return admin; 7752 } 7753 } 7754 return null; 7755 } 7756 7757 @Override 7758 public String getProfileOwnerName(int userHandle) { 7759 if (!mHasFeature) { 7760 return null; 7761 } 7762 enforceManageUsers(); 7763 ComponentName profileOwner = getProfileOwner(userHandle); 7764 if (profileOwner == null) { 7765 return null; 7766 } 7767 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 7768 } 7769 7770 /** 7771 * Canonical name for a given package. 7772 */ 7773 private String getApplicationLabel(String packageName, int userHandle) { 7774 long token = mInjector.binderClearCallingIdentity(); 7775 try { 7776 final Context userContext; 7777 try { 7778 UserHandle handle = new UserHandle(userHandle); 7779 userContext = mContext.createPackageContextAsUser(packageName, 0, handle); 7780 } catch (PackageManager.NameNotFoundException nnfe) { 7781 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe); 7782 return null; 7783 } 7784 ApplicationInfo appInfo = userContext.getApplicationInfo(); 7785 CharSequence result = null; 7786 if (appInfo != null) { 7787 result = appInfo.loadUnsafeLabel(userContext.getPackageManager()); 7788 } 7789 return result != null ? result.toString() : null; 7790 } finally { 7791 mInjector.binderRestoreCallingIdentity(token); 7792 } 7793 } 7794 7795 /** 7796 * Calls wtfStack() if called with the DPMS lock held. 7797 */ 7798 private void wtfIfInLock() { 7799 if (Thread.holdsLock(this)) { 7800 Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held"); 7801 } 7802 } 7803 7804 /** 7805 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 7806 * permission. 7807 * The profile owner can only be set before the user setup phase has completed, 7808 * except for: 7809 * - SYSTEM_UID 7810 * - adb unless hasIncompatibleAccountsOrNonAdb is true. 7811 */ 7812 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle, 7813 boolean hasIncompatibleAccountsOrNonAdb) { 7814 UserInfo info = getUserInfo(userHandle); 7815 if (info == null) { 7816 // User doesn't exist. 7817 throw new IllegalArgumentException( 7818 "Attempted to set profile owner for invalid userId: " + userHandle); 7819 } 7820 if (info.isGuest()) { 7821 throw new IllegalStateException("Cannot set a profile owner on a guest"); 7822 } 7823 if (mOwners.hasProfileOwner(userHandle)) { 7824 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 7825 + "is already set."); 7826 } 7827 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 7828 throw new IllegalStateException("Trying to set the profile owner, but the user " 7829 + "already has a device owner."); 7830 } 7831 if (isAdb()) { 7832 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 7833 && hasIncompatibleAccountsOrNonAdb) { 7834 throw new IllegalStateException("Not allowed to set the profile owner because " 7835 + "there are already some accounts on the profile"); 7836 } 7837 return; 7838 } 7839 enforceCanManageProfileAndDeviceOwners(); 7840 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) { 7841 throw new IllegalStateException("Cannot set the profile owner on a user which is " 7842 + "already set-up"); 7843 } 7844 } 7845 7846 /** 7847 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 7848 * permission. 7849 */ 7850 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId, 7851 boolean hasIncompatibleAccountsOrNonAdb) { 7852 if (!isAdb()) { 7853 enforceCanManageProfileAndDeviceOwners(); 7854 } 7855 7856 final int code = checkDeviceOwnerProvisioningPreConditionLocked( 7857 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb); 7858 switch (code) { 7859 case CODE_OK: 7860 return; 7861 case CODE_HAS_DEVICE_OWNER: 7862 throw new IllegalStateException( 7863 "Trying to set the device owner, but device owner is already set."); 7864 case CODE_USER_HAS_PROFILE_OWNER: 7865 throw new IllegalStateException("Trying to set the device owner, but the user " 7866 + "already has a profile owner."); 7867 case CODE_USER_NOT_RUNNING: 7868 throw new IllegalStateException("User not running: " + userId); 7869 case CODE_NOT_SYSTEM_USER: 7870 throw new IllegalStateException("User is not system user"); 7871 case CODE_USER_SETUP_COMPLETED: 7872 throw new IllegalStateException( 7873 "Cannot set the device owner if the device is already set-up"); 7874 case CODE_NONSYSTEM_USER_EXISTS: 7875 throw new IllegalStateException("Not allowed to set the device owner because there " 7876 + "are already several users on the device"); 7877 case CODE_ACCOUNTS_NOT_EMPTY: 7878 throw new IllegalStateException("Not allowed to set the device owner because there " 7879 + "are already some accounts on the device"); 7880 case CODE_HAS_PAIRED: 7881 throw new IllegalStateException("Not allowed to set the device owner because this " 7882 + "device has already paired"); 7883 default: 7884 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code); 7885 } 7886 } 7887 7888 private void enforceUserUnlocked(int userId) { 7889 // Since we're doing this operation on behalf of an app, we only 7890 // want to use the actual "unlocked" state. 7891 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 7892 "User must be running and unlocked"); 7893 } 7894 7895 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 7896 if (parent) { 7897 enforceUserUnlocked(getProfileParentId(userId)); 7898 } else { 7899 enforceUserUnlocked(userId); 7900 } 7901 } 7902 7903 private void enforceManageUsers() { 7904 final int callingUid = mInjector.binderGetCallingUid(); 7905 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 7906 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7907 } 7908 } 7909 7910 private void enforceFullCrossUsersPermission(int userHandle) { 7911 enforceSystemUserOrPermissionIfCrossUser(userHandle, 7912 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 7913 } 7914 7915 private void enforceCrossUsersPermission(int userHandle) { 7916 enforceSystemUserOrPermissionIfCrossUser(userHandle, 7917 android.Manifest.permission.INTERACT_ACROSS_USERS); 7918 } 7919 7920 private void enforceSystemUserOrPermission(String permission) { 7921 if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) { 7922 mContext.enforceCallingOrSelfPermission(permission, 7923 "Must be system or have " + permission + " permission"); 7924 } 7925 } 7926 7927 private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) { 7928 if (userHandle < 0) { 7929 throw new IllegalArgumentException("Invalid userId " + userHandle); 7930 } 7931 if (userHandle == mInjector.userHandleGetCallingUserId()) { 7932 return; 7933 } 7934 enforceSystemUserOrPermission(permission); 7935 } 7936 7937 private void enforceManagedProfile(int userHandle, String message) { 7938 if(!isManagedProfile(userHandle)) { 7939 throw new SecurityException("You can not " + message + " outside a managed profile."); 7940 } 7941 } 7942 7943 private void enforceNotManagedProfile(int userHandle, String message) { 7944 if(isManagedProfile(userHandle)) { 7945 throw new SecurityException("You can not " + message + " for a managed profile."); 7946 } 7947 } 7948 7949 private void enforceDeviceOwnerOrManageUsers() { 7950 synchronized (getLockObject()) { 7951 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7952 mInjector.binderGetCallingUid()) != null) { 7953 return; 7954 } 7955 } 7956 enforceManageUsers(); 7957 } 7958 7959 private void enforceProfileOwnerOrSystemUser() { 7960 synchronized (getLockObject()) { 7961 if (getActiveAdminWithPolicyForUidLocked(null, 7962 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 7963 != null) { 7964 return; 7965 } 7966 } 7967 Preconditions.checkState(isCallerWithSystemUid(), 7968 "Only profile owner, device owner and system may call this method."); 7969 } 7970 7971 private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) { 7972 if (userId == mInjector.userHandleGetCallingUserId()) { 7973 synchronized (getLockObject()) { 7974 if (getActiveAdminWithPolicyForUidLocked(null, 7975 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 7976 != null) { 7977 // Device Owner/Profile Owner may access the user it runs on. 7978 return; 7979 } 7980 } 7981 } 7982 // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required. 7983 enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 7984 } 7985 7986 private boolean canUserUseLockTaskLocked(int userId) { 7987 if (isUserAffiliatedWithDeviceLocked(userId)) { 7988 return true; 7989 } 7990 7991 // Unaffiliated profile owners are not allowed to use lock when there is a device owner. 7992 if (mOwners.hasDeviceOwner()) { 7993 return false; 7994 } 7995 7996 final ComponentName profileOwner = getProfileOwner(userId); 7997 if (profileOwner == null) { 7998 return false; 7999 } 8000 8001 // Managed profiles are not allowed to use lock task 8002 if (isManagedProfile(userId)) { 8003 return false; 8004 } 8005 8006 return true; 8007 } 8008 8009 private void enforceCanCallLockTaskLocked(ComponentName who) { 8010 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8011 final int userId = mInjector.userHandleGetCallingUserId(); 8012 if (!canUserUseLockTaskLocked(userId)) { 8013 throw new SecurityException("User " + userId + " is not allowed to use lock task"); 8014 } 8015 } 8016 8017 private void ensureCallerPackage(@Nullable String packageName) { 8018 if (packageName == null) { 8019 Preconditions.checkState(isCallerWithSystemUid(), 8020 "Only caller can omit package name"); 8021 } else { 8022 final int callingUid = mInjector.binderGetCallingUid(); 8023 final int userId = mInjector.userHandleGetCallingUserId(); 8024 try { 8025 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 8026 packageName, 0, userId); 8027 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name"); 8028 } catch (RemoteException e) { 8029 // Shouldn't happen 8030 } 8031 } 8032 } 8033 8034 private boolean isCallerWithSystemUid() { 8035 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID); 8036 } 8037 8038 protected int getProfileParentId(int userHandle) { 8039 final long ident = mInjector.binderClearCallingIdentity(); 8040 try { 8041 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 8042 return parentUser != null ? parentUser.id : userHandle; 8043 } finally { 8044 mInjector.binderRestoreCallingIdentity(ident); 8045 } 8046 } 8047 8048 private int getCredentialOwner(int userHandle, boolean parent) { 8049 final long ident = mInjector.binderClearCallingIdentity(); 8050 try { 8051 if (parent) { 8052 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 8053 if (parentProfile != null) { 8054 userHandle = parentProfile.id; 8055 } 8056 } 8057 return mUserManager.getCredentialOwnerProfile(userHandle); 8058 } finally { 8059 mInjector.binderRestoreCallingIdentity(ident); 8060 } 8061 } 8062 8063 private boolean isManagedProfile(int userHandle) { 8064 final UserInfo user = getUserInfo(userHandle); 8065 return user != null && user.isManagedProfile(); 8066 } 8067 8068 private void enableIfNecessary(String packageName, int userId) { 8069 try { 8070 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 8071 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId); 8072 if (ai.enabledSetting 8073 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 8074 mIPackageManager.setApplicationEnabledSetting(packageName, 8075 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 8076 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 8077 } 8078 } catch (RemoteException e) { 8079 } 8080 } 8081 8082 @Override 8083 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 8084 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return; 8085 8086 synchronized (getLockObject()) { 8087 pw.println("Current Device Policy Manager state:"); 8088 8089 mOwners.dump(" ", pw); 8090 mDeviceAdminServiceController.dump(" ", pw); 8091 int userCount = mUserData.size(); 8092 for (int u = 0; u < userCount; u++) { 8093 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 8094 pw.println(); 8095 pw.println(" Enabled Device Admins (User " + policy.mUserHandle 8096 + ", provisioningState: " + policy.mUserProvisioningState + "):"); 8097 final int N = policy.mAdminList.size(); 8098 for (int i=0; i<N; i++) { 8099 ActiveAdmin ap = policy.mAdminList.get(i); 8100 if (ap != null) { 8101 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 8102 pw.println(":"); 8103 ap.dump(" ", pw); 8104 } 8105 } 8106 if (!policy.mRemovingAdmins.isEmpty()) { 8107 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 8108 + policy.mRemovingAdmins); 8109 } 8110 8111 pw.println(" "); 8112 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 8113 } 8114 pw.println(); 8115 mConstants.dump(" ", pw); 8116 pw.println(); 8117 mStatLogger.dump(pw, " "); 8118 pw.println(); 8119 pw.println(" Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 8120 } 8121 } 8122 8123 private String getEncryptionStatusName(int encryptionStatus) { 8124 switch (encryptionStatus) { 8125 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 8126 return "inactive"; 8127 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 8128 return "block default key"; 8129 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 8130 return "block"; 8131 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 8132 return "per-user"; 8133 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 8134 return "unsupported"; 8135 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 8136 return "activating"; 8137 default: 8138 return "unknown"; 8139 } 8140 } 8141 8142 @Override 8143 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 8144 ComponentName activity) { 8145 Preconditions.checkNotNull(who, "ComponentName is null"); 8146 final int userHandle = UserHandle.getCallingUserId(); 8147 synchronized (getLockObject()) { 8148 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8149 8150 long id = mInjector.binderClearCallingIdentity(); 8151 try { 8152 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 8153 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 8154 } catch (RemoteException re) { 8155 // Shouldn't happen 8156 } finally { 8157 mInjector.binderRestoreCallingIdentity(id); 8158 } 8159 } 8160 } 8161 8162 @Override 8163 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 8164 Preconditions.checkNotNull(who, "ComponentName is null"); 8165 final int userHandle = UserHandle.getCallingUserId(); 8166 synchronized (getLockObject()) { 8167 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8168 8169 long id = mInjector.binderClearCallingIdentity(); 8170 try { 8171 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 8172 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 8173 } catch (RemoteException re) { 8174 // Shouldn't happen 8175 } finally { 8176 mInjector.binderRestoreCallingIdentity(id); 8177 } 8178 } 8179 } 8180 8181 @Override 8182 public void setDefaultSmsApplication(ComponentName admin, String packageName) { 8183 Preconditions.checkNotNull(admin, "ComponentName is null"); 8184 synchronized (getLockObject()) { 8185 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8186 } 8187 mInjector.binderWithCleanCallingIdentity(() -> 8188 SmsApplication.setDefaultApplication(packageName, mContext)); 8189 } 8190 8191 @Override 8192 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 8193 String packageName) { 8194 try { 8195 setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS); 8196 } catch (IllegalArgumentException e) { 8197 return false; 8198 } 8199 return true; 8200 } 8201 8202 @Override 8203 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 8204 final List<String> delegatePackages = getDelegatePackages(admin, 8205 DELEGATION_APP_RESTRICTIONS); 8206 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 8207 } 8208 8209 @Override 8210 public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) { 8211 return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS); 8212 } 8213 8214 @Override 8215 public void setApplicationRestrictions(ComponentName who, String callerPackage, 8216 String packageName, Bundle settings) { 8217 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8218 DELEGATION_APP_RESTRICTIONS); 8219 8220 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 8221 final long id = mInjector.binderClearCallingIdentity(); 8222 try { 8223 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 8224 } finally { 8225 mInjector.binderRestoreCallingIdentity(id); 8226 } 8227 } 8228 8229 @Override 8230 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 8231 PersistableBundle args, boolean parent) { 8232 if (!mHasFeature) { 8233 return; 8234 } 8235 Preconditions.checkNotNull(admin, "admin is null"); 8236 Preconditions.checkNotNull(agent, "agent is null"); 8237 final int userHandle = UserHandle.getCallingUserId(); 8238 synchronized (getLockObject()) { 8239 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 8240 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 8241 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 8242 saveSettingsLocked(userHandle); 8243 } 8244 } 8245 8246 @Override 8247 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 8248 ComponentName agent, int userHandle, boolean parent) { 8249 if (!mHasFeature) { 8250 return null; 8251 } 8252 Preconditions.checkNotNull(agent, "agent null"); 8253 enforceFullCrossUsersPermission(userHandle); 8254 8255 synchronized (getLockObject()) { 8256 final String componentName = agent.flattenToString(); 8257 if (admin != null) { 8258 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 8259 if (ap == null) return null; 8260 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 8261 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 8262 List<PersistableBundle> result = new ArrayList<>(); 8263 result.add(trustAgentInfo.options); 8264 return result; 8265 } 8266 8267 // Return strictest policy for this user and profiles that are visible from this user. 8268 List<PersistableBundle> result = null; 8269 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 8270 // of the options. If any admin doesn't have options, discard options for the rest 8271 // and return null. 8272 List<ActiveAdmin> admins = 8273 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 8274 boolean allAdminsHaveOptions = true; 8275 final int N = admins.size(); 8276 for (int i = 0; i < N; i++) { 8277 final ActiveAdmin active = admins.get(i); 8278 8279 final boolean disablesTrust = (active.disabledKeyguardFeatures 8280 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 8281 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 8282 if (info != null && info.options != null && !info.options.isEmpty()) { 8283 if (disablesTrust) { 8284 if (result == null) { 8285 result = new ArrayList<>(); 8286 } 8287 result.add(info.options); 8288 } else { 8289 Log.w(LOG_TAG, "Ignoring admin " + active.info 8290 + " because it has trust options but doesn't declare " 8291 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 8292 } 8293 } else if (disablesTrust) { 8294 allAdminsHaveOptions = false; 8295 break; 8296 } 8297 } 8298 return allAdminsHaveOptions ? result : null; 8299 } 8300 } 8301 8302 @Override 8303 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 8304 Preconditions.checkNotNull(who, "ComponentName is null"); 8305 synchronized (getLockObject()) { 8306 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8307 8308 int userHandle = UserHandle.getCallingUserId(); 8309 DevicePolicyData userData = getUserData(userHandle); 8310 userData.mRestrictionsProvider = permissionProvider; 8311 saveSettingsLocked(userHandle); 8312 } 8313 } 8314 8315 @Override 8316 public ComponentName getRestrictionsProvider(int userHandle) { 8317 synchronized (getLockObject()) { 8318 if (!isCallerWithSystemUid()) { 8319 throw new SecurityException("Only the system can query the permission provider"); 8320 } 8321 DevicePolicyData userData = getUserData(userHandle); 8322 return userData != null ? userData.mRestrictionsProvider : null; 8323 } 8324 } 8325 8326 @Override 8327 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 8328 Preconditions.checkNotNull(who, "ComponentName is null"); 8329 int callingUserId = UserHandle.getCallingUserId(); 8330 synchronized (getLockObject()) { 8331 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8332 8333 long id = mInjector.binderClearCallingIdentity(); 8334 try { 8335 UserInfo parent = mUserManager.getProfileParent(callingUserId); 8336 if (parent == null) { 8337 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 8338 + "parent"); 8339 return; 8340 } 8341 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 8342 mIPackageManager.addCrossProfileIntentFilter( 8343 filter, who.getPackageName(), callingUserId, parent.id, 0); 8344 } 8345 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 8346 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 8347 parent.id, callingUserId, 0); 8348 } 8349 } catch (RemoteException re) { 8350 // Shouldn't happen 8351 } finally { 8352 mInjector.binderRestoreCallingIdentity(id); 8353 } 8354 } 8355 } 8356 8357 @Override 8358 public void clearCrossProfileIntentFilters(ComponentName who) { 8359 Preconditions.checkNotNull(who, "ComponentName is null"); 8360 int callingUserId = UserHandle.getCallingUserId(); 8361 synchronized (getLockObject()) { 8362 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8363 long id = mInjector.binderClearCallingIdentity(); 8364 try { 8365 UserInfo parent = mUserManager.getProfileParent(callingUserId); 8366 if (parent == null) { 8367 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 8368 + "parent"); 8369 return; 8370 } 8371 // Removing those that go from the managed profile to the parent. 8372 mIPackageManager.clearCrossProfileIntentFilters( 8373 callingUserId, who.getPackageName()); 8374 // And those that go from the parent to the managed profile. 8375 // If we want to support multiple managed profiles, we will have to only remove 8376 // those that have callingUserId as their target. 8377 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 8378 } catch (RemoteException re) { 8379 // Shouldn't happen 8380 } finally { 8381 mInjector.binderRestoreCallingIdentity(id); 8382 } 8383 } 8384 } 8385 8386 /** 8387 * @return true if all packages in enabledPackages are either in the list 8388 * permittedList or are a system app. 8389 */ 8390 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 8391 List<String> permittedList, int userIdToCheck) { 8392 long id = mInjector.binderClearCallingIdentity(); 8393 try { 8394 // If we have an enabled packages list for a managed profile the packages 8395 // we should check are installed for the parent user. 8396 UserInfo user = getUserInfo(userIdToCheck); 8397 if (user.isManagedProfile()) { 8398 userIdToCheck = user.profileGroupId; 8399 } 8400 8401 for (String enabledPackage : enabledPackages) { 8402 boolean systemService = false; 8403 try { 8404 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 8405 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 8406 userIdToCheck); 8407 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 8408 } catch (RemoteException e) { 8409 Log.i(LOG_TAG, "Can't talk to package managed", e); 8410 } 8411 if (!systemService && !permittedList.contains(enabledPackage)) { 8412 return false; 8413 } 8414 } 8415 } finally { 8416 mInjector.binderRestoreCallingIdentity(id); 8417 } 8418 return true; 8419 } 8420 8421 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 8422 // Not using AccessibilityManager.getInstance because that guesses 8423 // at the user you require based on callingUid and caches for a given 8424 // process. 8425 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 8426 IAccessibilityManager service = iBinder == null 8427 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 8428 return new AccessibilityManager(mContext, service, userId); 8429 } 8430 8431 @Override 8432 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 8433 if (!mHasFeature) { 8434 return false; 8435 } 8436 Preconditions.checkNotNull(who, "ComponentName is null"); 8437 8438 if (packageList != null) { 8439 int userId = UserHandle.getCallingUserId(); 8440 List<AccessibilityServiceInfo> enabledServices = null; 8441 long id = mInjector.binderClearCallingIdentity(); 8442 try { 8443 UserInfo user = getUserInfo(userId); 8444 if (user.isManagedProfile()) { 8445 userId = user.profileGroupId; 8446 } 8447 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 8448 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 8449 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 8450 } finally { 8451 mInjector.binderRestoreCallingIdentity(id); 8452 } 8453 8454 if (enabledServices != null) { 8455 List<String> enabledPackages = new ArrayList<String>(); 8456 for (AccessibilityServiceInfo service : enabledServices) { 8457 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 8458 } 8459 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 8460 userId)) { 8461 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 8462 + "because it contains already enabled accesibility services."); 8463 return false; 8464 } 8465 } 8466 } 8467 8468 synchronized (getLockObject()) { 8469 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8470 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8471 admin.permittedAccessiblityServices = packageList; 8472 saveSettingsLocked(UserHandle.getCallingUserId()); 8473 } 8474 return true; 8475 } 8476 8477 @Override 8478 public List getPermittedAccessibilityServices(ComponentName who) { 8479 if (!mHasFeature) { 8480 return null; 8481 } 8482 Preconditions.checkNotNull(who, "ComponentName is null"); 8483 8484 synchronized (getLockObject()) { 8485 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8486 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8487 return admin.permittedAccessiblityServices; 8488 } 8489 } 8490 8491 @Override 8492 public List getPermittedAccessibilityServicesForUser(int userId) { 8493 if (!mHasFeature) { 8494 return null; 8495 } 8496 enforceManageUsers(); 8497 synchronized (getLockObject()) { 8498 List<String> result = null; 8499 // If we have multiple profiles we return the intersection of the 8500 // permitted lists. This can happen in cases where we have a device 8501 // and profile owner. 8502 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 8503 for (int profileId : profileIds) { 8504 // Just loop though all admins, only device or profiles 8505 // owners can have permitted lists set. 8506 DevicePolicyData policy = getUserDataUnchecked(profileId); 8507 final int N = policy.mAdminList.size(); 8508 for (int j = 0; j < N; j++) { 8509 ActiveAdmin admin = policy.mAdminList.get(j); 8510 List<String> fromAdmin = admin.permittedAccessiblityServices; 8511 if (fromAdmin != null) { 8512 if (result == null) { 8513 result = new ArrayList<>(fromAdmin); 8514 } else { 8515 result.retainAll(fromAdmin); 8516 } 8517 } 8518 } 8519 } 8520 8521 // If we have a permitted list add all system accessibility services. 8522 if (result != null) { 8523 long id = mInjector.binderClearCallingIdentity(); 8524 try { 8525 UserInfo user = getUserInfo(userId); 8526 if (user.isManagedProfile()) { 8527 userId = user.profileGroupId; 8528 } 8529 AccessibilityManager accessibilityManager = 8530 getAccessibilityManagerForUser(userId); 8531 List<AccessibilityServiceInfo> installedServices = 8532 accessibilityManager.getInstalledAccessibilityServiceList(); 8533 8534 if (installedServices != null) { 8535 for (AccessibilityServiceInfo service : installedServices) { 8536 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 8537 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 8538 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8539 result.add(serviceInfo.packageName); 8540 } 8541 } 8542 } 8543 } finally { 8544 mInjector.binderRestoreCallingIdentity(id); 8545 } 8546 } 8547 8548 return result; 8549 } 8550 } 8551 8552 @Override 8553 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 8554 int userHandle) { 8555 if (!mHasFeature) { 8556 return true; 8557 } 8558 Preconditions.checkNotNull(who, "ComponentName is null"); 8559 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 8560 if (!isCallerWithSystemUid()){ 8561 throw new SecurityException( 8562 "Only the system can query if an accessibility service is disabled by admin"); 8563 } 8564 synchronized (getLockObject()) { 8565 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 8566 if (admin == null) { 8567 return false; 8568 } 8569 if (admin.permittedAccessiblityServices == null) { 8570 return true; 8571 } 8572 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 8573 admin.permittedAccessiblityServices, userHandle); 8574 } 8575 } 8576 8577 private boolean checkCallerIsCurrentUserOrProfile() { 8578 final int callingUserId = UserHandle.getCallingUserId(); 8579 final long token = mInjector.binderClearCallingIdentity(); 8580 try { 8581 UserInfo currentUser; 8582 UserInfo callingUser = getUserInfo(callingUserId); 8583 try { 8584 currentUser = mInjector.getIActivityManager().getCurrentUser(); 8585 } catch (RemoteException e) { 8586 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 8587 return false; 8588 } 8589 8590 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 8591 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 8592 + "of a user that isn't the foreground user."); 8593 return false; 8594 } 8595 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 8596 Slog.e(LOG_TAG, "Cannot set permitted input methods " 8597 + "of a user that isn't the foreground user."); 8598 return false; 8599 } 8600 } finally { 8601 mInjector.binderRestoreCallingIdentity(token); 8602 } 8603 return true; 8604 } 8605 8606 @Override 8607 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 8608 if (!mHasFeature) { 8609 return false; 8610 } 8611 Preconditions.checkNotNull(who, "ComponentName is null"); 8612 8613 // TODO When InputMethodManager supports per user calls remove 8614 // this restriction. 8615 if (!checkCallerIsCurrentUserOrProfile()) { 8616 return false; 8617 } 8618 8619 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8620 if (packageList != null) { 8621 // InputMethodManager fetches input methods for current user. 8622 // So this can only be set when calling user is the current user 8623 // or parent is current user in case of managed profiles. 8624 InputMethodManager inputMethodManager = 8625 mContext.getSystemService(InputMethodManager.class); 8626 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList(); 8627 8628 if (enabledImes != null) { 8629 List<String> enabledPackages = new ArrayList<String>(); 8630 for (InputMethodInfo ime : enabledImes) { 8631 enabledPackages.add(ime.getPackageName()); 8632 } 8633 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 8634 callingUserId)) { 8635 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 8636 + "because it contains already enabled input method."); 8637 return false; 8638 } 8639 } 8640 } 8641 8642 synchronized (getLockObject()) { 8643 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8644 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8645 admin.permittedInputMethods = packageList; 8646 saveSettingsLocked(callingUserId); 8647 } 8648 return true; 8649 } 8650 8651 @Override 8652 public List getPermittedInputMethods(ComponentName who) { 8653 if (!mHasFeature) { 8654 return null; 8655 } 8656 Preconditions.checkNotNull(who, "ComponentName is null"); 8657 8658 synchronized (getLockObject()) { 8659 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8660 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8661 return admin.permittedInputMethods; 8662 } 8663 } 8664 8665 @Override 8666 public List getPermittedInputMethodsForCurrentUser() { 8667 enforceManageUsers(); 8668 UserInfo currentUser; 8669 try { 8670 currentUser = mInjector.getIActivityManager().getCurrentUser(); 8671 } catch (RemoteException e) { 8672 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e); 8673 // Activity managed is dead, just allow all IMEs 8674 return null; 8675 } 8676 8677 int userId = currentUser.id; 8678 synchronized (getLockObject()) { 8679 List<String> result = null; 8680 // If we have multiple profiles we return the intersection of the 8681 // permitted lists. This can happen in cases where we have a device 8682 // and profile owner. 8683 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 8684 for (int profileId : profileIds) { 8685 // Just loop though all admins, only device or profiles 8686 // owners can have permitted lists set. 8687 DevicePolicyData policy = getUserDataUnchecked(profileId); 8688 final int N = policy.mAdminList.size(); 8689 for (int j = 0; j < N; j++) { 8690 ActiveAdmin admin = policy.mAdminList.get(j); 8691 List<String> fromAdmin = admin.permittedInputMethods; 8692 if (fromAdmin != null) { 8693 if (result == null) { 8694 result = new ArrayList<String>(fromAdmin); 8695 } else { 8696 result.retainAll(fromAdmin); 8697 } 8698 } 8699 } 8700 } 8701 8702 // If we have a permitted list add all system input methods. 8703 if (result != null) { 8704 InputMethodManager inputMethodManager = 8705 mContext.getSystemService(InputMethodManager.class); 8706 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList(); 8707 long id = mInjector.binderClearCallingIdentity(); 8708 try { 8709 if (imes != null) { 8710 for (InputMethodInfo ime : imes) { 8711 ServiceInfo serviceInfo = ime.getServiceInfo(); 8712 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 8713 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8714 result.add(serviceInfo.packageName); 8715 } 8716 } 8717 } 8718 } finally { 8719 mInjector.binderRestoreCallingIdentity(id); 8720 } 8721 } 8722 return result; 8723 } 8724 } 8725 8726 @Override 8727 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 8728 int userHandle) { 8729 if (!mHasFeature) { 8730 return true; 8731 } 8732 Preconditions.checkNotNull(who, "ComponentName is null"); 8733 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 8734 if (!isCallerWithSystemUid()) { 8735 throw new SecurityException( 8736 "Only the system can query if an input method is disabled by admin"); 8737 } 8738 synchronized (getLockObject()) { 8739 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 8740 if (admin == null) { 8741 return false; 8742 } 8743 if (admin.permittedInputMethods == null) { 8744 return true; 8745 } 8746 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 8747 admin.permittedInputMethods, userHandle); 8748 } 8749 } 8750 8751 @Override 8752 public boolean setPermittedCrossProfileNotificationListeners( 8753 ComponentName who, List<String> packageList) { 8754 if (!mHasFeature) { 8755 return false; 8756 } 8757 Preconditions.checkNotNull(who, "ComponentName is null"); 8758 8759 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8760 if (!isManagedProfile(callingUserId)) { 8761 return false; 8762 } 8763 8764 synchronized (getLockObject()) { 8765 ActiveAdmin admin = getActiveAdminForCallerLocked( 8766 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8767 admin.permittedNotificationListeners = packageList; 8768 saveSettingsLocked(callingUserId); 8769 } 8770 return true; 8771 } 8772 8773 @Override 8774 public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) { 8775 if (!mHasFeature) { 8776 return null; 8777 } 8778 Preconditions.checkNotNull(who, "ComponentName is null"); 8779 8780 synchronized (getLockObject()) { 8781 ActiveAdmin admin = getActiveAdminForCallerLocked( 8782 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8783 return admin.permittedNotificationListeners; 8784 } 8785 } 8786 8787 @Override 8788 public boolean isNotificationListenerServicePermitted(String packageName, int userId) { 8789 if (!mHasFeature) { 8790 return true; 8791 } 8792 8793 Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty"); 8794 if (!isCallerWithSystemUid()) { 8795 throw new SecurityException( 8796 "Only the system can query if a notification listener service is permitted"); 8797 } 8798 synchronized (getLockObject()) { 8799 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 8800 if (profileOwner == null || profileOwner.permittedNotificationListeners == null) { 8801 return true; 8802 } 8803 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 8804 profileOwner.permittedNotificationListeners, userId); 8805 8806 } 8807 } 8808 8809 private void maybeSendAdminEnabledBroadcastLocked(int userHandle) { 8810 DevicePolicyData policyData = getUserData(userHandle); 8811 if (policyData.mAdminBroadcastPending) { 8812 // Send the initialization data to profile owner and delete the data 8813 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 8814 boolean clearInitBundle = true; 8815 if (admin != null) { 8816 PersistableBundle initBundle = policyData.mInitBundle; 8817 clearInitBundle = sendAdminCommandLocked(admin, 8818 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 8819 initBundle == null ? null : new Bundle(initBundle), 8820 null /* result receiver */, 8821 true /* send in foreground */); 8822 } 8823 if (clearInitBundle) { 8824 // If there's no admin or we've successfully called the admin, clear the init bundle 8825 // otherwise, keep it around 8826 policyData.mInitBundle = null; 8827 policyData.mAdminBroadcastPending = false; 8828 saveSettingsLocked(userHandle); 8829 } 8830 } 8831 } 8832 8833 @Override 8834 public UserHandle createAndManageUser(ComponentName admin, String name, 8835 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 8836 Preconditions.checkNotNull(admin, "admin is null"); 8837 Preconditions.checkNotNull(profileOwner, "profileOwner is null"); 8838 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 8839 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 8840 + admin + " are not in the same package"); 8841 } 8842 // Only allow the system user to use this method 8843 if (!mInjector.binderGetCallingUserHandle().isSystem()) { 8844 throw new SecurityException("createAndManageUser was called from non-system user"); 8845 } 8846 final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0; 8847 final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0 8848 && UserManager.isDeviceInDemoMode(mContext); 8849 final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0; 8850 final int targetSdkVersion; 8851 8852 // Create user. 8853 UserHandle user = null; 8854 synchronized (getLockObject()) { 8855 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8856 8857 final int callingUid = mInjector.binderGetCallingUid(); 8858 final long id = mInjector.binderClearCallingIdentity(); 8859 try { 8860 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion( 8861 callingUid); 8862 8863 // Return detail error code for checks inside 8864 // UserManagerService.createUserInternalUnchecked. 8865 DeviceStorageMonitorInternal deviceStorageMonitorInternal = 8866 LocalServices.getService(DeviceStorageMonitorInternal.class); 8867 if (deviceStorageMonitorInternal.isMemoryLow()) { 8868 if (targetSdkVersion >= Build.VERSION_CODES.P) { 8869 throw new ServiceSpecificException( 8870 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage"); 8871 } else { 8872 return null; 8873 } 8874 } 8875 if (!mUserManager.canAddMoreUsers()) { 8876 if (targetSdkVersion >= Build.VERSION_CODES.P) { 8877 throw new ServiceSpecificException( 8878 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached"); 8879 } else { 8880 return null; 8881 } 8882 } 8883 8884 int userInfoFlags = 0; 8885 if (ephemeral) { 8886 userInfoFlags |= UserInfo.FLAG_EPHEMERAL; 8887 } 8888 if (demo) { 8889 userInfoFlags |= UserInfo.FLAG_DEMO; 8890 } 8891 String[] disallowedPackages = null; 8892 if (!leaveAllSystemAppsEnabled) { 8893 disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin, 8894 UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray( 8895 new String[0]); 8896 } 8897 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 8898 userInfoFlags, disallowedPackages); 8899 if (userInfo != null) { 8900 user = userInfo.getUserHandle(); 8901 } 8902 } finally { 8903 mInjector.binderRestoreCallingIdentity(id); 8904 } 8905 } 8906 if (user == null) { 8907 if (targetSdkVersion >= Build.VERSION_CODES.P) { 8908 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN, 8909 "failed to create user"); 8910 } else { 8911 return null; 8912 } 8913 } 8914 8915 final int userHandle = user.getIdentifier(); 8916 final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED) 8917 .putExtra(Intent.EXTRA_USER_HANDLE, userHandle) 8918 .putExtra( 8919 DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED, 8920 leaveAllSystemAppsEnabled) 8921 .setPackage(getManagedProvisioningPackage(mContext)) 8922 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8923 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM); 8924 8925 final long id = mInjector.binderClearCallingIdentity(); 8926 try { 8927 final String adminPkg = admin.getPackageName(); 8928 try { 8929 // Install the profile owner if not present. 8930 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) { 8931 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle, 8932 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 8933 } 8934 } catch (RemoteException e) { 8935 // Does not happen, same process 8936 } 8937 8938 // Set admin. 8939 setActiveAdmin(profileOwner, true, userHandle); 8940 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier()); 8941 setProfileOwner(profileOwner, ownerName, userHandle); 8942 8943 synchronized (getLockObject()) { 8944 DevicePolicyData policyData = getUserData(userHandle); 8945 policyData.mInitBundle = adminExtras; 8946 policyData.mAdminBroadcastPending = true; 8947 saveSettingsLocked(userHandle); 8948 } 8949 8950 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 8951 Settings.Secure.putIntForUser(mContext.getContentResolver(), 8952 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 8953 } 8954 8955 return user; 8956 } catch (Throwable re) { 8957 mUserManager.removeUser(userHandle); 8958 if (targetSdkVersion >= Build.VERSION_CODES.P) { 8959 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN, 8960 re.getMessage()); 8961 } else { 8962 return null; 8963 } 8964 } finally { 8965 mInjector.binderRestoreCallingIdentity(id); 8966 } 8967 } 8968 8969 @Override 8970 public boolean removeUser(ComponentName who, UserHandle userHandle) { 8971 Preconditions.checkNotNull(who, "ComponentName is null"); 8972 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 8973 8974 synchronized (getLockObject()) { 8975 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8976 } 8977 8978 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8979 final long id = mInjector.binderClearCallingIdentity(); 8980 try { 8981 String restriction = isManagedProfile(userHandle.getIdentifier()) 8982 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 8983 : UserManager.DISALLOW_REMOVE_USER; 8984 if (isAdminAffectedByRestriction(who, restriction, callingUserId)) { 8985 Log.w(LOG_TAG, "The device owner cannot remove a user because " 8986 + restriction + " is enabled, and was not set by the device owner"); 8987 return false; 8988 } 8989 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 8990 } finally { 8991 mInjector.binderRestoreCallingIdentity(id); 8992 } 8993 } 8994 8995 private boolean isAdminAffectedByRestriction( 8996 ComponentName admin, String userRestriction, int userId) { 8997 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 8998 case UserManager.RESTRICTION_NOT_SET: 8999 return false; 9000 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 9001 return !isDeviceOwner(admin, userId); 9002 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 9003 return !isProfileOwner(admin, userId); 9004 default: 9005 return true; 9006 } 9007 } 9008 9009 @Override 9010 public boolean switchUser(ComponentName who, UserHandle userHandle) { 9011 Preconditions.checkNotNull(who, "ComponentName is null"); 9012 9013 synchronized (getLockObject()) { 9014 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9015 9016 long id = mInjector.binderClearCallingIdentity(); 9017 try { 9018 int userId = UserHandle.USER_SYSTEM; 9019 if (userHandle != null) { 9020 userId = userHandle.getIdentifier(); 9021 } 9022 return mInjector.getIActivityManager().switchUser(userId); 9023 } catch (RemoteException e) { 9024 Log.e(LOG_TAG, "Couldn't switch user", e); 9025 return false; 9026 } finally { 9027 mInjector.binderRestoreCallingIdentity(id); 9028 } 9029 } 9030 } 9031 9032 @Override 9033 public int startUserInBackground(ComponentName who, UserHandle userHandle) { 9034 Preconditions.checkNotNull(who, "ComponentName is null"); 9035 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 9036 9037 synchronized (getLockObject()) { 9038 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9039 } 9040 9041 final int userId = userHandle.getIdentifier(); 9042 if (isManagedProfile(userId)) { 9043 Log.w(LOG_TAG, "Managed profile cannot be started in background"); 9044 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9045 } 9046 9047 final long id = mInjector.binderClearCallingIdentity(); 9048 try { 9049 if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) { 9050 Log.w(LOG_TAG, "Cannot start more users in background"); 9051 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS; 9052 } 9053 9054 if (mInjector.getIActivityManager().startUserInBackground(userId)) { 9055 return UserManager.USER_OPERATION_SUCCESS; 9056 } else { 9057 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9058 } 9059 } catch (RemoteException e) { 9060 // Same process, should not happen. 9061 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9062 } finally { 9063 mInjector.binderRestoreCallingIdentity(id); 9064 } 9065 } 9066 9067 @Override 9068 public int stopUser(ComponentName who, UserHandle userHandle) { 9069 Preconditions.checkNotNull(who, "ComponentName is null"); 9070 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 9071 9072 synchronized (getLockObject()) { 9073 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9074 } 9075 9076 final int userId = userHandle.getIdentifier(); 9077 if (isManagedProfile(userId)) { 9078 Log.w(LOG_TAG, "Managed profile cannot be stopped"); 9079 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9080 } 9081 9082 return stopUserUnchecked(userId); 9083 } 9084 9085 @Override 9086 public int logoutUser(ComponentName who) { 9087 Preconditions.checkNotNull(who, "ComponentName is null"); 9088 9089 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9090 synchronized (getLockObject()) { 9091 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9092 if (!isUserAffiliatedWithDeviceLocked(callingUserId)) { 9093 throw new SecurityException("Admin " + who + 9094 " is neither the device owner or affiliated user's profile owner."); 9095 } 9096 } 9097 9098 if (isManagedProfile(callingUserId)) { 9099 Log.w(LOG_TAG, "Managed profile cannot be logout"); 9100 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9101 } 9102 9103 final long id = mInjector.binderClearCallingIdentity(); 9104 try { 9105 if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) { 9106 Log.w(LOG_TAG, "Failed to switch to primary user"); 9107 // This should never happen as target user is UserHandle.USER_SYSTEM 9108 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9109 } 9110 } catch (RemoteException e) { 9111 // Same process, should not happen. 9112 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9113 } finally { 9114 mInjector.binderRestoreCallingIdentity(id); 9115 } 9116 9117 return stopUserUnchecked(callingUserId); 9118 } 9119 9120 private int stopUserUnchecked(int userId) { 9121 final long id = mInjector.binderClearCallingIdentity(); 9122 try { 9123 switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) { 9124 case ActivityManager.USER_OP_SUCCESS: 9125 return UserManager.USER_OPERATION_SUCCESS; 9126 case ActivityManager.USER_OP_IS_CURRENT: 9127 return UserManager.USER_OPERATION_ERROR_CURRENT_USER; 9128 default: 9129 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9130 } 9131 } catch (RemoteException e) { 9132 // Same process, should not happen. 9133 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9134 } finally { 9135 mInjector.binderRestoreCallingIdentity(id); 9136 } 9137 } 9138 9139 @Override 9140 public List<UserHandle> getSecondaryUsers(ComponentName who) { 9141 Preconditions.checkNotNull(who, "ComponentName is null"); 9142 synchronized (getLockObject()) { 9143 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9144 } 9145 9146 final long id = mInjector.binderClearCallingIdentity(); 9147 try { 9148 final List<UserInfo> userInfos = mInjector.getUserManager().getUsers(true 9149 /*excludeDying*/); 9150 final List<UserHandle> userHandles = new ArrayList<>(); 9151 for (UserInfo userInfo : userInfos) { 9152 UserHandle userHandle = userInfo.getUserHandle(); 9153 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) { 9154 userHandles.add(userInfo.getUserHandle()); 9155 } 9156 } 9157 return userHandles; 9158 } finally { 9159 mInjector.binderRestoreCallingIdentity(id); 9160 } 9161 } 9162 9163 @Override 9164 public boolean isEphemeralUser(ComponentName who) { 9165 Preconditions.checkNotNull(who, "ComponentName is null"); 9166 synchronized (getLockObject()) { 9167 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9168 } 9169 9170 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9171 final long id = mInjector.binderClearCallingIdentity(); 9172 try { 9173 return mInjector.getUserManager().isUserEphemeral(callingUserId); 9174 } finally { 9175 mInjector.binderRestoreCallingIdentity(id); 9176 } 9177 } 9178 9179 @Override 9180 public Bundle getApplicationRestrictions(ComponentName who, String callerPackage, 9181 String packageName) { 9182 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9183 DELEGATION_APP_RESTRICTIONS); 9184 9185 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 9186 final long id = mInjector.binderClearCallingIdentity(); 9187 try { 9188 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 9189 // if no restrictions were saved, mUserManager.getApplicationRestrictions 9190 // returns null, but DPM method should return an empty Bundle as per JavaDoc 9191 return bundle != null ? bundle : Bundle.EMPTY; 9192 } finally { 9193 mInjector.binderRestoreCallingIdentity(id); 9194 } 9195 } 9196 9197 @Override 9198 public String[] setPackagesSuspended(ComponentName who, String callerPackage, 9199 String[] packageNames, boolean suspended) { 9200 int callingUserId = UserHandle.getCallingUserId(); 9201 synchronized (getLockObject()) { 9202 // Ensure the caller is a DO/PO or a package access delegate. 9203 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9204 DELEGATION_PACKAGE_ACCESS); 9205 9206 long id = mInjector.binderClearCallingIdentity(); 9207 try { 9208 return mIPackageManager.setPackagesSuspendedAsUser(packageNames, suspended, 9209 null, null, null, PLATFORM_PACKAGE_NAME, callingUserId); 9210 } catch (RemoteException re) { 9211 // Shouldn't happen. 9212 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 9213 } finally { 9214 mInjector.binderRestoreCallingIdentity(id); 9215 } 9216 return packageNames; 9217 } 9218 } 9219 9220 @Override 9221 public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) { 9222 int callingUserId = UserHandle.getCallingUserId(); 9223 synchronized (getLockObject()) { 9224 // Ensure the caller is a DO/PO or a package access delegate. 9225 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9226 DELEGATION_PACKAGE_ACCESS); 9227 9228 long id = mInjector.binderClearCallingIdentity(); 9229 try { 9230 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId); 9231 } catch (RemoteException re) { 9232 // Shouldn't happen. 9233 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 9234 } finally { 9235 mInjector.binderRestoreCallingIdentity(id); 9236 } 9237 return false; 9238 } 9239 } 9240 9241 @Override 9242 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) { 9243 Preconditions.checkNotNull(who, "ComponentName is null"); 9244 if (!UserRestrictionsUtils.isValidRestriction(key)) { 9245 return; 9246 } 9247 9248 final int userHandle = mInjector.userHandleGetCallingUserId(); 9249 synchronized (getLockObject()) { 9250 final ActiveAdmin activeAdmin = 9251 getActiveAdminForCallerLocked(who, 9252 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9253 final boolean isDeviceOwner = isDeviceOwner(who, userHandle); 9254 if (isDeviceOwner) { 9255 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 9256 throw new SecurityException("Device owner cannot set user restriction " + key); 9257 } 9258 } else { // profile owner 9259 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) { 9260 throw new SecurityException("Profile owner cannot set user restriction " + key); 9261 } 9262 } 9263 9264 // Save the restriction to ActiveAdmin. 9265 final Bundle restrictions = activeAdmin.ensureUserRestrictions(); 9266 if (enabledFromThisOwner) { 9267 restrictions.putBoolean(key, true); 9268 } else { 9269 restrictions.remove(key); 9270 } 9271 saveUserRestrictionsLocked(userHandle); 9272 } 9273 if (SecurityLog.isLoggingEnabled()) { 9274 final int eventTag = enabledFromThisOwner 9275 ? SecurityLog.TAG_USER_RESTRICTION_ADDED 9276 : SecurityLog.TAG_USER_RESTRICTION_REMOVED; 9277 SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key); 9278 } 9279 } 9280 9281 private void saveUserRestrictionsLocked(int userId) { 9282 saveSettingsLocked(userId); 9283 pushUserRestrictions(userId); 9284 sendChangedNotification(userId); 9285 } 9286 9287 private void pushUserRestrictions(int userId) { 9288 synchronized (getLockObject()) { 9289 final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId); 9290 final Bundle userRestrictions; 9291 // Whether device owner enforces camera restriction. 9292 boolean disallowCameraGlobally = false; 9293 9294 if (isDeviceOwner) { 9295 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 9296 if (deviceOwner == null) { 9297 return; // Shouldn't happen. 9298 } 9299 userRestrictions = deviceOwner.userRestrictions; 9300 // DO can disable camera globally. 9301 disallowCameraGlobally = deviceOwner.disableCamera; 9302 } else { 9303 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 9304 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null; 9305 } 9306 9307 // Whether any admin enforces camera restriction. 9308 final int cameraRestrictionScope = 9309 getCameraRestrictionScopeLocked(userId, disallowCameraGlobally); 9310 9311 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions, 9312 isDeviceOwner, cameraRestrictionScope); 9313 } 9314 } 9315 9316 /** 9317 * Get the scope of camera restriction for a given user if any. 9318 */ 9319 private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) { 9320 if (disallowCameraGlobally) { 9321 return UserManagerInternal.CAMERA_DISABLED_GLOBALLY; 9322 } else if (getCameraDisabled( 9323 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) { 9324 return UserManagerInternal.CAMERA_DISABLED_LOCALLY; 9325 } 9326 return UserManagerInternal.CAMERA_NOT_DISABLED; 9327 } 9328 9329 @Override 9330 public Bundle getUserRestrictions(ComponentName who) { 9331 if (!mHasFeature) { 9332 return null; 9333 } 9334 Preconditions.checkNotNull(who, "ComponentName is null"); 9335 synchronized (getLockObject()) { 9336 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who, 9337 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9338 return activeAdmin.userRestrictions; 9339 } 9340 } 9341 9342 @Override 9343 public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName, 9344 boolean hidden) { 9345 int callingUserId = UserHandle.getCallingUserId(); 9346 synchronized (getLockObject()) { 9347 // Ensure the caller is a DO/PO or a package access delegate. 9348 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9349 DELEGATION_PACKAGE_ACCESS); 9350 9351 long id = mInjector.binderClearCallingIdentity(); 9352 try { 9353 return mIPackageManager.setApplicationHiddenSettingAsUser( 9354 packageName, hidden, callingUserId); 9355 } catch (RemoteException re) { 9356 // shouldn't happen 9357 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 9358 } finally { 9359 mInjector.binderRestoreCallingIdentity(id); 9360 } 9361 return false; 9362 } 9363 } 9364 9365 @Override 9366 public boolean isApplicationHidden(ComponentName who, String callerPackage, 9367 String packageName) { 9368 int callingUserId = UserHandle.getCallingUserId(); 9369 synchronized (getLockObject()) { 9370 // Ensure the caller is a DO/PO or a package access delegate. 9371 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9372 DELEGATION_PACKAGE_ACCESS); 9373 9374 long id = mInjector.binderClearCallingIdentity(); 9375 try { 9376 return mIPackageManager.getApplicationHiddenSettingAsUser( 9377 packageName, callingUserId); 9378 } catch (RemoteException re) { 9379 // shouldn't happen 9380 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 9381 } finally { 9382 mInjector.binderRestoreCallingIdentity(id); 9383 } 9384 return false; 9385 } 9386 } 9387 9388 @Override 9389 public void enableSystemApp(ComponentName who, String callerPackage, String packageName) { 9390 synchronized (getLockObject()) { 9391 // Ensure the caller is a DO/PO or an enable system app delegate. 9392 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9393 DELEGATION_ENABLE_SYSTEM_APP); 9394 9395 final boolean isDemo = isCurrentUserDemo(); 9396 9397 int userId = UserHandle.getCallingUserId(); 9398 long id = mInjector.binderClearCallingIdentity(); 9399 9400 try { 9401 if (VERBOSE_LOG) { 9402 Slog.v(LOG_TAG, "installing " + packageName + " for " 9403 + userId); 9404 } 9405 9406 int parentUserId = getProfileParentId(userId); 9407 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) { 9408 throw new IllegalArgumentException("Only system apps can be enabled this way."); 9409 } 9410 9411 // Install the app. 9412 mIPackageManager.installExistingPackageAsUser(packageName, userId, 9413 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 9414 if (isDemo) { 9415 // Ensure the app is also ENABLED for demo users. 9416 mIPackageManager.setApplicationEnabledSetting(packageName, 9417 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 9418 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 9419 } 9420 } catch (RemoteException re) { 9421 // shouldn't happen 9422 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 9423 } finally { 9424 mInjector.binderRestoreCallingIdentity(id); 9425 } 9426 } 9427 } 9428 9429 @Override 9430 public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) { 9431 synchronized (getLockObject()) { 9432 // Ensure the caller is a DO/PO or an enable system app delegate. 9433 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9434 DELEGATION_ENABLE_SYSTEM_APP); 9435 9436 int userId = UserHandle.getCallingUserId(); 9437 long id = mInjector.binderClearCallingIdentity(); 9438 9439 try { 9440 int parentUserId = getProfileParentId(userId); 9441 List<ResolveInfo> activitiesToEnable = mIPackageManager 9442 .queryIntentActivities(intent, 9443 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 9444 PackageManager.MATCH_DIRECT_BOOT_AWARE 9445 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 9446 parentUserId) 9447 .getList(); 9448 9449 if (VERBOSE_LOG) { 9450 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 9451 } 9452 int numberOfAppsInstalled = 0; 9453 if (activitiesToEnable != null) { 9454 for (ResolveInfo info : activitiesToEnable) { 9455 if (info.activityInfo != null) { 9456 String packageName = info.activityInfo.packageName; 9457 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 9458 numberOfAppsInstalled++; 9459 mIPackageManager.installExistingPackageAsUser(packageName, userId, 9460 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 9461 } else { 9462 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 9463 + " system app"); 9464 } 9465 } 9466 } 9467 } 9468 return numberOfAppsInstalled; 9469 } catch (RemoteException e) { 9470 // shouldn't happen 9471 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 9472 return 0; 9473 } finally { 9474 mInjector.binderRestoreCallingIdentity(id); 9475 } 9476 } 9477 } 9478 9479 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 9480 throws RemoteException { 9481 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 9482 userId); 9483 if (appInfo == null) { 9484 throw new IllegalArgumentException("The application " + packageName + 9485 " is not present on this device"); 9486 } 9487 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9488 } 9489 9490 @Override 9491 public boolean installExistingPackage(ComponentName who, String callerPackage, 9492 String packageName) { 9493 synchronized (getLockObject()) { 9494 // Ensure the caller is a PO or an install existing package delegate 9495 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9496 DELEGATION_INSTALL_EXISTING_PACKAGE); 9497 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9498 if (!isUserAffiliatedWithDeviceLocked(callingUserId)) { 9499 throw new SecurityException("Admin " + who + 9500 " is neither the device owner or affiliated user's profile owner."); 9501 } 9502 9503 final long id = mInjector.binderClearCallingIdentity(); 9504 try { 9505 if (VERBOSE_LOG) { 9506 Slog.v(LOG_TAG, "installing " + packageName + " for " 9507 + callingUserId); 9508 } 9509 9510 // Install the package. 9511 return mIPackageManager.installExistingPackageAsUser(packageName, callingUserId, 9512 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY) 9513 == PackageManager.INSTALL_SUCCEEDED; 9514 } catch (RemoteException re) { 9515 // shouldn't happen 9516 return false; 9517 } finally { 9518 mInjector.binderRestoreCallingIdentity(id); 9519 } 9520 } 9521 } 9522 9523 @Override 9524 public void setAccountManagementDisabled(ComponentName who, String accountType, 9525 boolean disabled) { 9526 if (!mHasFeature) { 9527 return; 9528 } 9529 Preconditions.checkNotNull(who, "ComponentName is null"); 9530 synchronized (getLockObject()) { 9531 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 9532 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9533 if (disabled) { 9534 ap.accountTypesWithManagementDisabled.add(accountType); 9535 } else { 9536 ap.accountTypesWithManagementDisabled.remove(accountType); 9537 } 9538 saveSettingsLocked(UserHandle.getCallingUserId()); 9539 } 9540 } 9541 9542 @Override 9543 public String[] getAccountTypesWithManagementDisabled() { 9544 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 9545 } 9546 9547 @Override 9548 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 9549 enforceFullCrossUsersPermission(userId); 9550 if (!mHasFeature) { 9551 return null; 9552 } 9553 synchronized (getLockObject()) { 9554 DevicePolicyData policy = getUserData(userId); 9555 final int N = policy.mAdminList.size(); 9556 ArraySet<String> resultSet = new ArraySet<>(); 9557 for (int i = 0; i < N; i++) { 9558 ActiveAdmin admin = policy.mAdminList.get(i); 9559 resultSet.addAll(admin.accountTypesWithManagementDisabled); 9560 } 9561 return resultSet.toArray(new String[resultSet.size()]); 9562 } 9563 } 9564 9565 @Override 9566 public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName, 9567 boolean uninstallBlocked) { 9568 final int userId = UserHandle.getCallingUserId(); 9569 synchronized (getLockObject()) { 9570 // Ensure the caller is a DO/PO or a block uninstall delegate 9571 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9572 DELEGATION_BLOCK_UNINSTALL); 9573 9574 long id = mInjector.binderClearCallingIdentity(); 9575 try { 9576 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 9577 } catch (RemoteException re) { 9578 // Shouldn't happen. 9579 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 9580 } finally { 9581 mInjector.binderRestoreCallingIdentity(id); 9582 } 9583 } 9584 } 9585 9586 @Override 9587 public boolean isUninstallBlocked(ComponentName who, String packageName) { 9588 // This function should return true if and only if the package is blocked by 9589 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 9590 // when the package is a system app, or when it is an active device admin. 9591 final int userId = UserHandle.getCallingUserId(); 9592 9593 synchronized (getLockObject()) { 9594 if (who != null) { 9595 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9596 } 9597 9598 long id = mInjector.binderClearCallingIdentity(); 9599 try { 9600 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 9601 } catch (RemoteException re) { 9602 // Shouldn't happen. 9603 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 9604 } finally { 9605 mInjector.binderRestoreCallingIdentity(id); 9606 } 9607 } 9608 return false; 9609 } 9610 9611 @Override 9612 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 9613 if (!mHasFeature) { 9614 return; 9615 } 9616 Preconditions.checkNotNull(who, "ComponentName is null"); 9617 synchronized (getLockObject()) { 9618 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9619 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9620 if (admin.disableCallerId != disabled) { 9621 admin.disableCallerId = disabled; 9622 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 9623 } 9624 } 9625 } 9626 9627 @Override 9628 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 9629 if (!mHasFeature) { 9630 return false; 9631 } 9632 Preconditions.checkNotNull(who, "ComponentName is null"); 9633 synchronized (getLockObject()) { 9634 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9635 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9636 return admin.disableCallerId; 9637 } 9638 } 9639 9640 @Override 9641 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 9642 enforceCrossUsersPermission(userId); 9643 synchronized (getLockObject()) { 9644 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9645 return (admin != null) ? admin.disableCallerId : false; 9646 } 9647 } 9648 9649 @Override 9650 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 9651 if (!mHasFeature) { 9652 return; 9653 } 9654 Preconditions.checkNotNull(who, "ComponentName is null"); 9655 synchronized (getLockObject()) { 9656 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9657 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9658 if (admin.disableContactsSearch != disabled) { 9659 admin.disableContactsSearch = disabled; 9660 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 9661 } 9662 } 9663 } 9664 9665 @Override 9666 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 9667 if (!mHasFeature) { 9668 return false; 9669 } 9670 Preconditions.checkNotNull(who, "ComponentName is null"); 9671 synchronized (getLockObject()) { 9672 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9673 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9674 return admin.disableContactsSearch; 9675 } 9676 } 9677 9678 @Override 9679 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 9680 enforceCrossUsersPermission(userId); 9681 synchronized (getLockObject()) { 9682 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9683 return (admin != null) ? admin.disableContactsSearch : false; 9684 } 9685 } 9686 9687 @Override 9688 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 9689 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 9690 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 9691 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 9692 final int callingUserId = UserHandle.getCallingUserId(); 9693 9694 final long ident = mInjector.binderClearCallingIdentity(); 9695 try { 9696 synchronized (getLockObject()) { 9697 final int managedUserId = getManagedUserId(callingUserId); 9698 if (managedUserId < 0) { 9699 return; 9700 } 9701 if (isCrossProfileQuickContactDisabled(managedUserId)) { 9702 if (VERBOSE_LOG) { 9703 Log.v(LOG_TAG, 9704 "Cross-profile contacts access disabled for user " + managedUserId); 9705 } 9706 return; 9707 } 9708 ContactsInternal.startQuickContactWithErrorToastForUser( 9709 mContext, intent, new UserHandle(managedUserId)); 9710 } 9711 } finally { 9712 mInjector.binderRestoreCallingIdentity(ident); 9713 } 9714 } 9715 9716 /** 9717 * @return true if cross-profile QuickContact is disabled 9718 */ 9719 private boolean isCrossProfileQuickContactDisabled(int userId) { 9720 return getCrossProfileCallerIdDisabledForUser(userId) 9721 && getCrossProfileContactsSearchDisabledForUser(userId); 9722 } 9723 9724 /** 9725 * @return the user ID of the managed user that is linked to the current user, if any. 9726 * Otherwise -1. 9727 */ 9728 public int getManagedUserId(int callingUserId) { 9729 if (VERBOSE_LOG) { 9730 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 9731 } 9732 9733 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 9734 if (ui.id == callingUserId || !ui.isManagedProfile()) { 9735 continue; // Caller user self, or not a managed profile. Skip. 9736 } 9737 if (VERBOSE_LOG) { 9738 Log.v(LOG_TAG, "Managed user=" + ui.id); 9739 } 9740 return ui.id; 9741 } 9742 if (VERBOSE_LOG) { 9743 Log.v(LOG_TAG, "Managed user not found."); 9744 } 9745 return -1; 9746 } 9747 9748 @Override 9749 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 9750 if (!mHasFeature) { 9751 return; 9752 } 9753 Preconditions.checkNotNull(who, "ComponentName is null"); 9754 synchronized (getLockObject()) { 9755 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9756 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9757 if (admin.disableBluetoothContactSharing != disabled) { 9758 admin.disableBluetoothContactSharing = disabled; 9759 saveSettingsLocked(UserHandle.getCallingUserId()); 9760 } 9761 } 9762 } 9763 9764 @Override 9765 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 9766 if (!mHasFeature) { 9767 return false; 9768 } 9769 Preconditions.checkNotNull(who, "ComponentName is null"); 9770 synchronized (getLockObject()) { 9771 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9772 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9773 return admin.disableBluetoothContactSharing; 9774 } 9775 } 9776 9777 @Override 9778 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 9779 // TODO: Should there be a check to make sure this relationship is 9780 // within a profile group? 9781 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 9782 synchronized (getLockObject()) { 9783 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9784 return (admin != null) ? admin.disableBluetoothContactSharing : false; 9785 } 9786 } 9787 9788 @Override 9789 public void setLockTaskPackages(ComponentName who, String[] packages) 9790 throws SecurityException { 9791 Preconditions.checkNotNull(who, "ComponentName is null"); 9792 Preconditions.checkNotNull(packages, "packages is null"); 9793 9794 synchronized (getLockObject()) { 9795 enforceCanCallLockTaskLocked(who); 9796 final int userHandle = mInjector.userHandleGetCallingUserId(); 9797 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 9798 } 9799 } 9800 9801 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 9802 DevicePolicyData policy = getUserData(userHandle); 9803 policy.mLockTaskPackages = packages; 9804 9805 // Store the settings persistently. 9806 saveSettingsLocked(userHandle); 9807 updateLockTaskPackagesLocked(packages, userHandle); 9808 } 9809 9810 @Override 9811 public String[] getLockTaskPackages(ComponentName who) { 9812 Preconditions.checkNotNull(who, "ComponentName is null"); 9813 9814 final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 9815 synchronized (getLockObject()) { 9816 enforceCanCallLockTaskLocked(who); 9817 final List<String> packages = getUserData(userHandle).mLockTaskPackages; 9818 return packages.toArray(new String[packages.size()]); 9819 } 9820 } 9821 9822 @Override 9823 public boolean isLockTaskPermitted(String pkg) { 9824 final int userHandle = mInjector.userHandleGetCallingUserId(); 9825 synchronized (getLockObject()) { 9826 return getUserData(userHandle).mLockTaskPackages.contains(pkg); 9827 } 9828 } 9829 9830 @Override 9831 public void setLockTaskFeatures(ComponentName who, int flags) { 9832 Preconditions.checkNotNull(who, "ComponentName is null"); 9833 9834 // Throw if Overview is used without Home. 9835 boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0; 9836 boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0; 9837 Preconditions.checkArgument(hasHome || !hasOverview, 9838 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME"); 9839 boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0; 9840 Preconditions.checkArgument(hasHome || !hasNotification, 9841 "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME"); 9842 9843 final int userHandle = mInjector.userHandleGetCallingUserId(); 9844 synchronized (getLockObject()) { 9845 enforceCanCallLockTaskLocked(who); 9846 setLockTaskFeaturesLocked(userHandle, flags); 9847 } 9848 } 9849 9850 private void setLockTaskFeaturesLocked(int userHandle, int flags) { 9851 DevicePolicyData policy = getUserData(userHandle); 9852 policy.mLockTaskFeatures = flags; 9853 saveSettingsLocked(userHandle); 9854 updateLockTaskFeaturesLocked(flags, userHandle); 9855 } 9856 9857 @Override 9858 public int getLockTaskFeatures(ComponentName who) { 9859 Preconditions.checkNotNull(who, "ComponentName is null"); 9860 final int userHandle = mInjector.userHandleGetCallingUserId(); 9861 synchronized (getLockObject()) { 9862 enforceCanCallLockTaskLocked(who); 9863 return getUserData(userHandle).mLockTaskFeatures; 9864 } 9865 } 9866 9867 private void maybeClearLockTaskPolicyLocked() { 9868 final long ident = mInjector.binderClearCallingIdentity(); 9869 try { 9870 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 9871 for (int i = userInfos.size() - 1; i >= 0; i--) { 9872 int userId = userInfos.get(i).id; 9873 if (canUserUseLockTaskLocked(userId)) { 9874 continue; 9875 } 9876 9877 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages; 9878 if (!lockTaskPackages.isEmpty()) { 9879 Slog.d(LOG_TAG, 9880 "User id " + userId + " not affiliated. Clearing lock task packages"); 9881 setLockTaskPackagesLocked(userId, Collections.<String>emptyList()); 9882 } 9883 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures; 9884 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){ 9885 Slog.d(LOG_TAG, 9886 "User id " + userId + " not affiliated. Clearing lock task features"); 9887 setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE); 9888 } 9889 } 9890 } finally { 9891 mInjector.binderRestoreCallingIdentity(ident); 9892 } 9893 } 9894 9895 @Override 9896 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 9897 if (!isCallerWithSystemUid()) { 9898 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 9899 } 9900 synchronized (getLockObject()) { 9901 final DevicePolicyData policy = getUserData(userHandle); 9902 9903 if (policy.mStatusBarDisabled) { 9904 // Status bar is managed by LockTaskController during LockTask, so we cancel this 9905 // policy when LockTask starts, and reapply it when LockTask ends 9906 setStatusBarDisabledInternal(!isEnabled, userHandle); 9907 } 9908 9909 Bundle adminExtras = new Bundle(); 9910 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 9911 for (ActiveAdmin admin : policy.mAdminList) { 9912 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 9913 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 9914 if (ownsDevice || ownsProfile) { 9915 if (isEnabled) { 9916 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 9917 adminExtras, null); 9918 } else { 9919 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 9920 } 9921 } 9922 } 9923 } 9924 } 9925 9926 @Override 9927 public void setGlobalSetting(ComponentName who, String setting, String value) { 9928 Preconditions.checkNotNull(who, "ComponentName is null"); 9929 9930 synchronized (getLockObject()) { 9931 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9932 9933 // Some settings are no supported any more. However we do not want to throw a 9934 // SecurityException to avoid breaking apps. 9935 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 9936 Log.i(LOG_TAG, "Global setting no longer supported: " + setting); 9937 return; 9938 } 9939 9940 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting) 9941 && !UserManager.isDeviceInDemoMode(mContext)) { 9942 throw new SecurityException(String.format( 9943 "Permission denial: device owners cannot update %1$s", setting)); 9944 } 9945 9946 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 9947 // ignore if it contradicts an existing policy 9948 long timeMs = getMaximumTimeToLock( 9949 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 9950 if (timeMs > 0 && timeMs < Long.MAX_VALUE) { 9951 return; 9952 } 9953 } 9954 9955 long id = mInjector.binderClearCallingIdentity(); 9956 try { 9957 mInjector.settingsGlobalPutString(setting, value); 9958 } finally { 9959 mInjector.binderRestoreCallingIdentity(id); 9960 } 9961 } 9962 } 9963 9964 @Override 9965 public void setSystemSetting(ComponentName who, String setting, String value) { 9966 Preconditions.checkNotNull(who, "ComponentName is null"); 9967 Preconditions.checkStringNotEmpty(setting, "String setting is null or empty"); 9968 9969 synchronized (getLockObject()) { 9970 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9971 9972 if (!SYSTEM_SETTINGS_WHITELIST.contains(setting)) { 9973 throw new SecurityException(String.format( 9974 "Permission denial: device owners cannot update %1$s", setting)); 9975 } 9976 9977 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9978 9979 mInjector.binderWithCleanCallingIdentity(() -> 9980 mInjector.settingsSystemPutStringForUser(setting, value, callingUserId)); 9981 } 9982 } 9983 9984 @Override 9985 public boolean setTime(ComponentName who, long millis) { 9986 Preconditions.checkNotNull(who, "ComponentName is null in setTime"); 9987 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9988 // Don't allow set time when auto time is on. 9989 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) { 9990 return false; 9991 } 9992 mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis)); 9993 return true; 9994 } 9995 9996 @Override 9997 public boolean setTimeZone(ComponentName who, String timeZone) { 9998 Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone"); 9999 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10000 // Don't allow set timezone when auto timezone is on. 10001 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) { 10002 return false; 10003 } 10004 mInjector.binderWithCleanCallingIdentity(() -> 10005 mInjector.getAlarmManager().setTimeZone(timeZone)); 10006 return true; 10007 } 10008 10009 @Override 10010 public void setSecureSetting(ComponentName who, String setting, String value) { 10011 Preconditions.checkNotNull(who, "ComponentName is null"); 10012 int callingUserId = mInjector.userHandleGetCallingUserId(); 10013 10014 synchronized (getLockObject()) { 10015 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10016 10017 if (isDeviceOwner(who, callingUserId)) { 10018 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting) 10019 && !isCurrentUserDemo()) { 10020 throw new SecurityException(String.format( 10021 "Permission denial: Device owners cannot update %1$s", setting)); 10022 } 10023 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) { 10024 throw new SecurityException(String.format( 10025 "Permission denial: Profile owners cannot update %1$s", setting)); 10026 } 10027 if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) { 10028 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) { 10029 throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS 10030 + " is deprecated. Please use the user restriction " 10031 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead."); 10032 } 10033 if (!mUserManager.isManagedProfile(callingUserId)) { 10034 Slog.e(LOG_TAG, "Ignoring setSecureSetting request for " 10035 + setting + ". User restriction " 10036 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES 10037 + " should be used instead."); 10038 } else { 10039 try { 10040 setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 10041 (Integer.parseInt(value) == 0) ? true : false); 10042 } catch (NumberFormatException exc) { 10043 Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting); 10044 } 10045 } 10046 return; 10047 } 10048 long id = mInjector.binderClearCallingIdentity(); 10049 try { 10050 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) { 10051 final String currentValue = mInjector.settingsSecureGetStringForUser( 10052 Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId); 10053 if (!TextUtils.equals(currentValue, value)) { 10054 // Tell the content observer that the next change will be due to the owner 10055 // changing the value. There is a small race condition here that we cannot 10056 // avoid: Change notifications are sent asynchronously, so it is possible 10057 // that there are prior notifications queued up before the one we are about 10058 // to trigger. This is a corner case that will have no impact in practice. 10059 mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId); 10060 } 10061 getUserData(callingUserId).mCurrentInputMethodSet = true; 10062 saveSettingsLocked(callingUserId); 10063 } 10064 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 10065 } finally { 10066 mInjector.binderRestoreCallingIdentity(id); 10067 } 10068 } 10069 } 10070 10071 @Override 10072 public void setMasterVolumeMuted(ComponentName who, boolean on) { 10073 Preconditions.checkNotNull(who, "ComponentName is null"); 10074 synchronized (getLockObject()) { 10075 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10076 setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on); 10077 } 10078 } 10079 10080 @Override 10081 public boolean isMasterVolumeMuted(ComponentName who) { 10082 Preconditions.checkNotNull(who, "ComponentName is null"); 10083 synchronized (getLockObject()) { 10084 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10085 10086 AudioManager audioManager = 10087 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 10088 return audioManager.isMasterMute(); 10089 } 10090 } 10091 10092 @Override 10093 public void setUserIcon(ComponentName who, Bitmap icon) { 10094 synchronized (getLockObject()) { 10095 Preconditions.checkNotNull(who, "ComponentName is null"); 10096 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10097 10098 int userId = UserHandle.getCallingUserId(); 10099 long id = mInjector.binderClearCallingIdentity(); 10100 try { 10101 mUserManagerInternal.setUserIcon(userId, icon); 10102 } finally { 10103 mInjector.binderRestoreCallingIdentity(id); 10104 } 10105 } 10106 } 10107 10108 @Override 10109 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 10110 Preconditions.checkNotNull(who, "ComponentName is null"); 10111 final int userId = mInjector.userHandleGetCallingUserId(); 10112 synchronized (getLockObject()) { 10113 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10114 if (!isUserAffiliatedWithDeviceLocked(userId)) { 10115 throw new SecurityException("Admin " + who + 10116 " is neither the device owner or affiliated user's profile owner."); 10117 } 10118 } 10119 if (isManagedProfile(userId)) { 10120 throw new SecurityException("Managed profile cannot disable keyguard"); 10121 } 10122 10123 long ident = mInjector.binderClearCallingIdentity(); 10124 try { 10125 // disallow disabling the keyguard if a password is currently set 10126 if (disabled && mLockPatternUtils.isSecure(userId)) { 10127 return false; 10128 } 10129 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 10130 mInjector.getIWindowManager().dismissKeyguard(null /* callback */, null /* message */); 10131 } catch (RemoteException e) { 10132 // Same process, does not happen. 10133 } finally { 10134 mInjector.binderRestoreCallingIdentity(ident); 10135 } 10136 return true; 10137 } 10138 10139 @Override 10140 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 10141 int userId = UserHandle.getCallingUserId(); 10142 synchronized (getLockObject()) { 10143 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10144 if (!isUserAffiliatedWithDeviceLocked(userId)) { 10145 throw new SecurityException("Admin " + who + 10146 " is neither the device owner or affiliated user's profile owner."); 10147 } 10148 if (isManagedProfile(userId)) { 10149 throw new SecurityException("Managed profile cannot disable status bar"); 10150 } 10151 DevicePolicyData policy = getUserData(userId); 10152 if (policy.mStatusBarDisabled != disabled) { 10153 boolean isLockTaskMode = false; 10154 try { 10155 isLockTaskMode = mInjector.getIActivityManager().getLockTaskModeState() 10156 != LOCK_TASK_MODE_NONE; 10157 } catch (RemoteException e) { 10158 Slog.e(LOG_TAG, "Failed to get LockTask mode"); 10159 } 10160 if (!isLockTaskMode) { 10161 if (!setStatusBarDisabledInternal(disabled, userId)) { 10162 return false; 10163 } 10164 } 10165 policy.mStatusBarDisabled = disabled; 10166 saveSettingsLocked(userId); 10167 } 10168 } 10169 return true; 10170 } 10171 10172 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 10173 long ident = mInjector.binderClearCallingIdentity(); 10174 try { 10175 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 10176 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 10177 if (statusBarService != null) { 10178 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 10179 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 10180 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 10181 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 10182 return true; 10183 } 10184 } catch (RemoteException e) { 10185 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 10186 } finally { 10187 mInjector.binderRestoreCallingIdentity(ident); 10188 } 10189 return false; 10190 } 10191 10192 /** 10193 * We need to update the internal state of whether a user has completed setup or a 10194 * device has paired once. After that, we ignore any changes that reset the 10195 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 10196 * as we don't trust any apps that might try to reset them. 10197 * <p> 10198 * Unfortunately, we don't know which user's setup state was changed, so we write all of 10199 * them. 10200 */ 10201 void updateUserSetupCompleteAndPaired() { 10202 List<UserInfo> users = mUserManager.getUsers(true); 10203 final int N = users.size(); 10204 for (int i = 0; i < N; i++) { 10205 int userHandle = users.get(i).id; 10206 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 10207 userHandle) != 0) { 10208 DevicePolicyData policy = getUserData(userHandle); 10209 if (!policy.mUserSetupComplete) { 10210 policy.mUserSetupComplete = true; 10211 synchronized (getLockObject()) { 10212 saveSettingsLocked(userHandle); 10213 } 10214 } 10215 } 10216 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 10217 userHandle) != 0) { 10218 DevicePolicyData policy = getUserData(userHandle); 10219 if (!policy.mPaired) { 10220 policy.mPaired = true; 10221 synchronized (getLockObject()) { 10222 saveSettingsLocked(userHandle); 10223 } 10224 } 10225 } 10226 } 10227 } 10228 10229 private class SetupContentObserver extends ContentObserver { 10230 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 10231 Settings.Secure.USER_SETUP_COMPLETE); 10232 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 10233 Settings.Global.DEVICE_PROVISIONED); 10234 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 10235 private final Uri mDefaultImeChanged = Settings.Secure.getUriFor( 10236 Settings.Secure.DEFAULT_INPUT_METHOD); 10237 10238 @GuardedBy("getLockObject()") 10239 private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>(); 10240 10241 public SetupContentObserver(Handler handler) { 10242 super(handler); 10243 } 10244 10245 void register() { 10246 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 10247 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 10248 if (mIsWatch) { 10249 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 10250 } 10251 mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL); 10252 } 10253 10254 @GuardedBy("getLockObject()") 10255 private void addPendingChangeByOwnerLocked(int userId) { 10256 mUserIdsWithPendingChangesByOwner.add(userId); 10257 } 10258 10259 @Override 10260 public void onChange(boolean selfChange, Uri uri, int userId) { 10261 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 10262 updateUserSetupCompleteAndPaired(); 10263 } else if (mDeviceProvisioned.equals(uri)) { 10264 synchronized (getLockObject()) { 10265 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 10266 // is delayed until device is marked as provisioned. 10267 setDeviceOwnerSystemPropertyLocked(); 10268 } 10269 } else if (mDefaultImeChanged.equals(uri)) { 10270 synchronized (getLockObject()) { 10271 if (mUserIdsWithPendingChangesByOwner.contains(userId)) { 10272 // This change notification was triggered by the owner changing the current 10273 // IME. Ignore it. 10274 mUserIdsWithPendingChangesByOwner.remove(userId); 10275 } else { 10276 // This change notification was triggered by the user manually changing the 10277 // current IME. 10278 getUserData(userId).mCurrentInputMethodSet = false; 10279 saveSettingsLocked(userId); 10280 } 10281 } 10282 } 10283 } 10284 } 10285 10286 @VisibleForTesting 10287 final class LocalService extends DevicePolicyManagerInternal { 10288 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 10289 10290 @Override 10291 public List<String> getCrossProfileWidgetProviders(int profileId) { 10292 synchronized (getLockObject()) { 10293 if (mOwners == null) { 10294 return Collections.emptyList(); 10295 } 10296 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 10297 if (ownerComponent == null) { 10298 return Collections.emptyList(); 10299 } 10300 10301 DevicePolicyData policy = getUserDataUnchecked(profileId); 10302 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 10303 10304 if (admin == null || admin.crossProfileWidgetProviders == null 10305 || admin.crossProfileWidgetProviders.isEmpty()) { 10306 return Collections.emptyList(); 10307 } 10308 10309 return admin.crossProfileWidgetProviders; 10310 } 10311 } 10312 10313 @Override 10314 public void addOnCrossProfileWidgetProvidersChangeListener( 10315 OnCrossProfileWidgetProvidersChangeListener listener) { 10316 synchronized (getLockObject()) { 10317 if (mWidgetProviderListeners == null) { 10318 mWidgetProviderListeners = new ArrayList<>(); 10319 } 10320 if (!mWidgetProviderListeners.contains(listener)) { 10321 mWidgetProviderListeners.add(listener); 10322 } 10323 } 10324 } 10325 10326 @Override 10327 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 10328 synchronized (getLockObject()) { 10329 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 10330 } 10331 } 10332 10333 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 10334 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 10335 synchronized (getLockObject()) { 10336 listeners = new ArrayList<>(mWidgetProviderListeners); 10337 } 10338 final int listenerCount = listeners.size(); 10339 for (int i = 0; i < listenerCount; i++) { 10340 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 10341 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 10342 } 10343 } 10344 10345 @Override 10346 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 10347 // This method is called from AM with its lock held, so don't take the DPMS lock. 10348 // b/29242568 10349 10350 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 10351 if (profileOwner != null) { 10352 return DevicePolicyManagerService.this 10353 .createShowAdminSupportIntent(profileOwner, userId); 10354 } 10355 10356 final Pair<Integer, ComponentName> deviceOwner = 10357 mOwners.getDeviceOwnerUserIdAndComponent(); 10358 if (deviceOwner != null && deviceOwner.first == userId) { 10359 return DevicePolicyManagerService.this 10360 .createShowAdminSupportIntent(deviceOwner.second, userId); 10361 } 10362 10363 // We're not specifying the device admin because there isn't one. 10364 if (useDefaultIfNoAdmin) { 10365 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 10366 } 10367 return null; 10368 } 10369 10370 @Override 10371 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 10372 int source; 10373 long ident = mInjector.binderClearCallingIdentity(); 10374 try { 10375 source = mUserManager.getUserRestrictionSource(userRestriction, 10376 UserHandle.of(userId)); 10377 } finally { 10378 mInjector.binderRestoreCallingIdentity(ident); 10379 } 10380 if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) { 10381 /* 10382 * In this case, the user restriction is enforced by the system. 10383 * So we won't show an admin support intent, even if it is also 10384 * enforced by a profile/device owner. 10385 */ 10386 return null; 10387 } 10388 boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0; 10389 boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0; 10390 if (enforcedByDo && enforcedByPo) { 10391 // In this case, we'll show an admin support dialog that does not 10392 // specify the admin. 10393 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 10394 } else if (enforcedByPo) { 10395 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 10396 if (profileOwner != null) { 10397 return DevicePolicyManagerService.this 10398 .createShowAdminSupportIntent(profileOwner, userId); 10399 } 10400 // This could happen if another thread has changed the profile owner since we called 10401 // getUserRestrictionSource 10402 return null; 10403 } else if (enforcedByDo) { 10404 final Pair<Integer, ComponentName> deviceOwner 10405 = mOwners.getDeviceOwnerUserIdAndComponent(); 10406 if (deviceOwner != null) { 10407 return DevicePolicyManagerService.this 10408 .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first); 10409 } 10410 // This could happen if another thread has changed the device owner since we called 10411 // getUserRestrictionSource 10412 return null; 10413 } 10414 return null; 10415 } 10416 10417 @Override 10418 public boolean isUserAffiliatedWithDevice(int userId) { 10419 return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId); 10420 } 10421 10422 @Override 10423 public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) { 10424 synchronized (getLockObject()) { 10425 updateMaximumTimeToLockLocked(userId); 10426 } 10427 } 10428 10429 @Override 10430 public boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) { 10431 return DevicePolicyManagerService.this.canUserHaveUntrustedCredentialReset(userId); 10432 } 10433 10434 @Override 10435 public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) { 10436 synchronized (getLockObject()) { 10437 DevicePolicyData policy = getUserData(userId); 10438 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING, 10439 UserHandle.of(userId))) { 10440 Log.e(LOG_TAG, "printing is enabled"); 10441 return null; 10442 } 10443 String ownerPackage = mOwners.getProfileOwnerPackage(userId); 10444 if (ownerPackage == null) { 10445 ownerPackage = mOwners.getDeviceOwnerPackageName(); 10446 } 10447 PackageManager pm = mInjector.getPackageManager(); 10448 PackageInfo packageInfo; 10449 try { 10450 packageInfo = pm.getPackageInfo(ownerPackage, 0); 10451 } catch (NameNotFoundException e) { 10452 Log.e(LOG_TAG, "getPackageInfo error", e); 10453 return null; 10454 } 10455 if (packageInfo == null) { 10456 Log.e(LOG_TAG, "packageInfo is inexplicably null"); 10457 return null; 10458 } 10459 ApplicationInfo appInfo = packageInfo.applicationInfo; 10460 if (appInfo == null) { 10461 Log.e(LOG_TAG, "appInfo is inexplicably null"); 10462 return null; 10463 } 10464 CharSequence appLabel = pm.getApplicationLabel(appInfo); 10465 if (appLabel == null) { 10466 Log.e(LOG_TAG, "appLabel is inexplicably null"); 10467 return null; 10468 } 10469 return ((Context) ActivityThread.currentActivityThread().getSystemUiContext()) 10470 .getResources().getString(R.string.printing_disabled_by, appLabel); 10471 } 10472 } 10473 10474 @Override 10475 protected DevicePolicyCache getDevicePolicyCache() { 10476 return mPolicyCache; 10477 } 10478 } 10479 10480 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) { 10481 // This method is called with AMS lock held, so don't take DPMS lock 10482 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 10483 intent.putExtra(Intent.EXTRA_USER_ID, userId); 10484 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin); 10485 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 10486 return intent; 10487 } 10488 10489 @Override 10490 public Intent createAdminSupportIntent(String restriction) { 10491 Preconditions.checkNotNull(restriction); 10492 final int uid = mInjector.binderGetCallingUid(); 10493 final int userId = UserHandle.getUserId(uid); 10494 Intent intent = null; 10495 if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) || 10496 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction) || 10497 DevicePolicyManager.POLICY_MANDATORY_BACKUPS.equals(restriction)) { 10498 synchronized (getLockObject()) { 10499 final DevicePolicyData policy = getUserData(userId); 10500 final int N = policy.mAdminList.size(); 10501 for (int i = 0; i < N; i++) { 10502 final ActiveAdmin admin = policy.mAdminList.get(i); 10503 if ((admin.disableCamera && 10504 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) || 10505 (admin.disableScreenCapture && DevicePolicyManager 10506 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) || 10507 (admin.mandatoryBackupTransport != null && DevicePolicyManager 10508 .POLICY_MANDATORY_BACKUPS.equals(restriction))) { 10509 intent = createShowAdminSupportIntent(admin.info.getComponent(), userId); 10510 break; 10511 } 10512 } 10513 // For the camera, a device owner on a different user can disable it globally, 10514 // so we need an additional check. 10515 if (intent == null 10516 && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) { 10517 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 10518 if (admin != null && admin.disableCamera) { 10519 intent = createShowAdminSupportIntent(admin.info.getComponent(), 10520 mOwners.getDeviceOwnerUserId()); 10521 } 10522 } 10523 } 10524 } else { 10525 // if valid, |restriction| can only be a user restriction 10526 intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction); 10527 } 10528 if (intent != null) { 10529 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction); 10530 } 10531 return intent; 10532 } 10533 10534 /** 10535 * Returns true if specified admin is allowed to limit passwords and has a 10536 * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality} 10537 */ 10538 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 10539 if (admin.minimumPasswordMetrics.quality < minPasswordQuality) { 10540 return false; 10541 } 10542 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 10543 } 10544 10545 @Override 10546 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 10547 if (policy != null) { 10548 // throws exception if policy type is invalid 10549 policy.validateType(); 10550 // throws exception if freeze period is invalid 10551 policy.validateFreezePeriods(); 10552 Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 10553 // throws exception if freeze period is incompatible with previous freeze period record 10554 policy.validateAgainstPreviousFreezePeriod(record.first, record.second, 10555 LocalDate.now()); 10556 } 10557 synchronized (getLockObject()) { 10558 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10559 if (policy == null) { 10560 mOwners.clearSystemUpdatePolicy(); 10561 } else { 10562 mOwners.setSystemUpdatePolicy(policy); 10563 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false); 10564 } 10565 mOwners.writeDeviceOwner(); 10566 } 10567 mContext.sendBroadcastAsUser( 10568 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 10569 UserHandle.SYSTEM); 10570 } 10571 10572 @Override 10573 public SystemUpdatePolicy getSystemUpdatePolicy() { 10574 synchronized (getLockObject()) { 10575 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 10576 if (policy != null && !policy.isValid()) { 10577 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 10578 return null; 10579 } 10580 return policy; 10581 } 10582 } 10583 10584 private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) { 10585 return (!date.isBefore(range.first) && !date.isAfter(range.second)); 10586 } 10587 10588 /** 10589 * keeps track of the last continuous period when the system is under OTA freeze. 10590 * 10591 * DPMS keeps track of the previous dates during which OTA was freezed as a result of an 10592 * system update policy with freeze periods in effect. This is needed to make robust 10593 * validation on new system update polices, for example to prevent the OTA from being 10594 * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period 10595 * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting 10596 * a new freeze period after a few days. 10597 * 10598 * @param saveIfChanged whether to persist the result on disk if freeze period record is 10599 * updated. This should only be set to {@code false} if there is a guaranteed 10600 * mOwners.writeDeviceOwner() later in the control flow to reduce the number of 10601 * disk writes. Otherwise you risk inconsistent on-disk state. 10602 * 10603 * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod 10604 */ 10605 private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) { 10606 Slog.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord"); 10607 synchronized (getLockObject()) { 10608 final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 10609 if (policy == null) { 10610 return; 10611 } 10612 final LocalDate now = LocalDate.now(); 10613 final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now); 10614 if (currentPeriod == null) { 10615 return; 10616 } 10617 final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 10618 final LocalDate start = record.first; 10619 final LocalDate end = record.second; 10620 final boolean changed; 10621 if (end == null || start == null) { 10622 // Start a new period if there is none at the moment 10623 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 10624 } else if (now.equals(end.plusDays(1))) { 10625 // Extend the existing period 10626 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 10627 } else if (now.isAfter(end.plusDays(1))) { 10628 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) { 10629 // The device might be off for some period. If the past freeze record 10630 // is within range of the current freeze period, assume the device was off 10631 // during the period [end, now] and extend the freeze record to [start, now]. 10632 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 10633 } else { 10634 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 10635 } 10636 } else if (now.isBefore(start)) { 10637 // Systm clock was adjusted backwards, restart record 10638 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 10639 } else /* start <= now <= end */ { 10640 changed = false; 10641 } 10642 if (changed && saveIfChanged) { 10643 mOwners.writeDeviceOwner(); 10644 } 10645 } 10646 } 10647 10648 @Override 10649 public void clearSystemUpdatePolicyFreezePeriodRecord() { 10650 enforceShell("clearSystemUpdatePolicyFreezePeriodRecord"); 10651 synchronized (getLockObject()) { 10652 // Print out current record to help diagnosed CTS failures 10653 Slog.i(LOG_TAG, "Clear freeze period record: " 10654 + mOwners.getSystemUpdateFreezePeriodRecordAsString()); 10655 if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) { 10656 mOwners.writeDeviceOwner(); 10657 } 10658 } 10659 } 10660 10661 /** 10662 * Checks if the caller of the method is the device owner app. 10663 * 10664 * @param callerUid UID of the caller. 10665 * @return true if the caller is the device owner app 10666 */ 10667 @VisibleForTesting 10668 boolean isCallerDeviceOwner(int callerUid) { 10669 synchronized (getLockObject()) { 10670 if (!mOwners.hasDeviceOwner()) { 10671 return false; 10672 } 10673 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 10674 return false; 10675 } 10676 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 10677 .getPackageName(); 10678 try { 10679 String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid); 10680 for (String pkg : pkgs) { 10681 if (deviceOwnerPackageName.equals(pkg)) { 10682 return true; 10683 } 10684 } 10685 } catch (RemoteException e) { 10686 return false; 10687 } 10688 } 10689 10690 return false; 10691 } 10692 10693 @Override 10694 public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) { 10695 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 10696 "Only the system update service can broadcast update information"); 10697 10698 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 10699 Slog.w(LOG_TAG, "Only the system update service in the system user " + 10700 "can broadcast update information."); 10701 return; 10702 } 10703 10704 if (!mOwners.saveSystemUpdateInfo(info)) { 10705 // Pending system update hasn't changed, don't send duplicate notification. 10706 return; 10707 } 10708 10709 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE) 10710 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 10711 info == null ? -1 : info.getReceivedTime()); 10712 10713 final long ident = mInjector.binderClearCallingIdentity(); 10714 try { 10715 synchronized (getLockObject()) { 10716 // Broadcast to device owner first if there is one. 10717 if (mOwners.hasDeviceOwner()) { 10718 final UserHandle deviceOwnerUser = 10719 UserHandle.of(mOwners.getDeviceOwnerUserId()); 10720 intent.setComponent(mOwners.getDeviceOwnerComponent()); 10721 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 10722 } 10723 } 10724 // Get running users. 10725 final int runningUserIds[]; 10726 try { 10727 runningUserIds = mInjector.getIActivityManager().getRunningUserIds(); 10728 } catch (RemoteException e) { 10729 // Shouldn't happen. 10730 Log.e(LOG_TAG, "Could not retrieve the list of running users", e); 10731 return; 10732 } 10733 // Send broadcasts to corresponding profile owners if any. 10734 for (final int userId : runningUserIds) { 10735 synchronized (getLockObject()) { 10736 final ComponentName profileOwnerPackage = 10737 mOwners.getProfileOwnerComponent(userId); 10738 if (profileOwnerPackage != null) { 10739 intent.setComponent(profileOwnerPackage); 10740 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 10741 } 10742 } 10743 } 10744 } finally { 10745 mInjector.binderRestoreCallingIdentity(ident); 10746 } 10747 } 10748 10749 @Override 10750 public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) { 10751 Preconditions.checkNotNull(admin, "ComponentName is null"); 10752 enforceProfileOrDeviceOwner(admin); 10753 10754 return mOwners.getSystemUpdateInfo(); 10755 } 10756 10757 @Override 10758 public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) 10759 throws RemoteException { 10760 int userId = UserHandle.getCallingUserId(); 10761 synchronized (getLockObject()) { 10762 // Ensure the caller is a DO/PO or a permission grant state delegate. 10763 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10764 DELEGATION_PERMISSION_GRANT); 10765 DevicePolicyData userPolicy = getUserData(userId); 10766 if (userPolicy.mPermissionPolicy != policy) { 10767 userPolicy.mPermissionPolicy = policy; 10768 saveSettingsLocked(userId); 10769 } 10770 } 10771 } 10772 10773 @Override 10774 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 10775 int userId = UserHandle.getCallingUserId(); 10776 synchronized (getLockObject()) { 10777 DevicePolicyData userPolicy = getUserData(userId); 10778 return userPolicy.mPermissionPolicy; 10779 } 10780 } 10781 10782 @Override 10783 public boolean setPermissionGrantState(ComponentName admin, String callerPackage, 10784 String packageName, String permission, int grantState) throws RemoteException { 10785 UserHandle user = mInjector.binderGetCallingUserHandle(); 10786 synchronized (getLockObject()) { 10787 // Ensure the caller is a DO/PO or a permission grant state delegate. 10788 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10789 DELEGATION_PERMISSION_GRANT); 10790 long ident = mInjector.binderClearCallingIdentity(); 10791 try { 10792 if (getTargetSdk(packageName, user.getIdentifier()) 10793 < android.os.Build.VERSION_CODES.M) { 10794 return false; 10795 } 10796 if (!isRuntimePermission(permission)) { 10797 return false; 10798 } 10799 final PackageManager packageManager = mInjector.getPackageManager(); 10800 switch (grantState) { 10801 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: { 10802 mInjector.getPackageManagerInternal().grantRuntimePermission(packageName, 10803 permission, user.getIdentifier(), true /* override policy */); 10804 packageManager.updatePermissionFlags(permission, packageName, 10805 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 10806 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 10807 } break; 10808 10809 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: { 10810 mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName, 10811 permission, user.getIdentifier(), true /* override policy */); 10812 packageManager.updatePermissionFlags(permission, packageName, 10813 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 10814 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 10815 } break; 10816 10817 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: { 10818 packageManager.updatePermissionFlags(permission, packageName, 10819 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user); 10820 } break; 10821 } 10822 return true; 10823 } catch (SecurityException se) { 10824 return false; 10825 } catch (NameNotFoundException e) { 10826 return false; 10827 } finally { 10828 mInjector.binderRestoreCallingIdentity(ident); 10829 } 10830 } 10831 } 10832 10833 @Override 10834 public int getPermissionGrantState(ComponentName admin, String callerPackage, 10835 String packageName, String permission) throws RemoteException { 10836 PackageManager packageManager = mInjector.getPackageManager(); 10837 10838 UserHandle user = mInjector.binderGetCallingUserHandle(); 10839 if (!isCallerWithSystemUid()) { 10840 // Ensure the caller is a DO/PO or a permission grant state delegate. 10841 enforceCanManageScope(admin, callerPackage, 10842 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT); 10843 } 10844 synchronized (getLockObject()) { 10845 long ident = mInjector.binderClearCallingIdentity(); 10846 try { 10847 int granted = mIPackageManager.checkPermission(permission, 10848 packageName, user.getIdentifier()); 10849 int permFlags = packageManager.getPermissionFlags(permission, packageName, user); 10850 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 10851 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 10852 // Not controlled by policy 10853 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 10854 } else { 10855 // Policy controlled so return result based on permission grant state 10856 return granted == PackageManager.PERMISSION_GRANTED 10857 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 10858 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 10859 } 10860 } finally { 10861 mInjector.binderRestoreCallingIdentity(ident); 10862 } 10863 } 10864 } 10865 10866 boolean isPackageInstalledForUser(String packageName, int userHandle) { 10867 try { 10868 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 10869 userHandle); 10870 return (pi != null) && (pi.applicationInfo.flags != 0); 10871 } catch (RemoteException re) { 10872 throw new RuntimeException("Package manager has died", re); 10873 } 10874 } 10875 10876 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException { 10877 final PackageManager packageManager = mInjector.getPackageManager(); 10878 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0); 10879 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 10880 == PermissionInfo.PROTECTION_DANGEROUS; 10881 } 10882 10883 @Override 10884 public boolean isProvisioningAllowed(String action, String packageName) { 10885 Preconditions.checkNotNull(packageName); 10886 10887 final int callingUid = mInjector.binderGetCallingUid(); 10888 final long ident = mInjector.binderClearCallingIdentity(); 10889 try { 10890 final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser( 10891 packageName, UserHandle.getUserId(callingUid)); 10892 Preconditions.checkArgument(callingUid == uidForPackage, 10893 "Caller uid doesn't match the one for the provided package."); 10894 } catch (NameNotFoundException e) { 10895 throw new IllegalArgumentException("Invalid package provided " + packageName, e); 10896 } finally { 10897 mInjector.binderRestoreCallingIdentity(ident); 10898 } 10899 10900 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK; 10901 } 10902 10903 @Override 10904 public int checkProvisioningPreCondition(String action, String packageName) { 10905 Preconditions.checkNotNull(packageName); 10906 enforceCanManageProfileAndDeviceOwners(); 10907 return checkProvisioningPreConditionSkipPermission(action, packageName); 10908 } 10909 10910 private int checkProvisioningPreConditionSkipPermission(String action, String packageName) { 10911 if (!mHasFeature) { 10912 return CODE_DEVICE_ADMIN_NOT_SUPPORTED; 10913 } 10914 10915 final int callingUserId = mInjector.userHandleGetCallingUserId(); 10916 if (action != null) { 10917 switch (action) { 10918 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 10919 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 10920 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 10921 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 10922 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER: 10923 return checkManagedUserProvisioningPreCondition(callingUserId); 10924 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE: 10925 return checkManagedShareableDeviceProvisioningPreCondition(callingUserId); 10926 } 10927 } 10928 throw new IllegalArgumentException("Unknown provisioning action " + action); 10929 } 10930 10931 /** 10932 * The device owner can only be set before the setup phase of the primary user has completed, 10933 * except for adb command if no accounts or additional users are present on the device. 10934 */ 10935 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 10936 int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) { 10937 if (mOwners.hasDeviceOwner()) { 10938 return CODE_HAS_DEVICE_OWNER; 10939 } 10940 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 10941 return CODE_USER_HAS_PROFILE_OWNER; 10942 } 10943 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 10944 return CODE_USER_NOT_RUNNING; 10945 } 10946 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 10947 return CODE_HAS_PAIRED; 10948 } 10949 if (isAdb) { 10950 // if shell command runs after user setup completed check device status. Otherwise, OK. 10951 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 10952 if (!mInjector.userManagerIsSplitSystemUser()) { 10953 if (mUserManager.getUserCount() > 1) { 10954 return CODE_NONSYSTEM_USER_EXISTS; 10955 } 10956 if (hasIncompatibleAccountsOrNonAdb) { 10957 return CODE_ACCOUNTS_NOT_EMPTY; 10958 } 10959 } else { 10960 // STOPSHIP Do proper check in split user mode 10961 } 10962 } 10963 return CODE_OK; 10964 } else { 10965 if (!mInjector.userManagerIsSplitSystemUser()) { 10966 // In non-split user mode, DO has to be user 0 10967 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 10968 return CODE_NOT_SYSTEM_USER; 10969 } 10970 // In non-split user mode, only provision DO before setup wizard completes 10971 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 10972 return CODE_USER_SETUP_COMPLETED; 10973 } 10974 } else { 10975 // STOPSHIP Do proper check in split user mode 10976 } 10977 return CODE_OK; 10978 } 10979 } 10980 10981 private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) { 10982 synchronized (getLockObject()) { 10983 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb. 10984 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 10985 deviceOwnerUserId, /* isAdb= */ false, 10986 /* hasIncompatibleAccountsOrNonAdb=*/ true); 10987 } 10988 } 10989 10990 private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) { 10991 if (!hasFeatureManagedUsers()) { 10992 return CODE_MANAGED_USERS_NOT_SUPPORTED; 10993 } 10994 if (callingUserId == UserHandle.USER_SYSTEM 10995 && mInjector.userManagerIsSplitSystemUser()) { 10996 // Managed-profiles cannot be setup on the system user. 10997 return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 10998 } 10999 if (getProfileOwner(callingUserId) != null) { 11000 // Managed user cannot have a managed profile. 11001 return CODE_USER_HAS_PROFILE_OWNER; 11002 } 11003 11004 final long ident = mInjector.binderClearCallingIdentity(); 11005 try { 11006 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 11007 final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId); 11008 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, 11009 callingUserHandle)) { 11010 // An admin can initiate provisioning if it has set the restriction. 11011 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 11012 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) { 11013 return CODE_ADD_MANAGED_PROFILE_DISALLOWED; 11014 } 11015 } 11016 boolean canRemoveProfile = true; 11017 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 11018 callingUserHandle)) { 11019 // We can remove a profile if the admin itself has set the restriction. 11020 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 11021 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 11022 callingUserId)) { 11023 canRemoveProfile = false; 11024 } 11025 } 11026 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) { 11027 return CODE_CANNOT_ADD_MANAGED_PROFILE; 11028 } 11029 } finally { 11030 mInjector.binderRestoreCallingIdentity(ident); 11031 } 11032 return CODE_OK; 11033 } 11034 11035 private ComponentName getOwnerComponent(String packageName, int userId) { 11036 if (isDeviceOwnerPackage(packageName, userId)) { 11037 return mOwners.getDeviceOwnerComponent(); 11038 } 11039 if (isProfileOwnerPackage(packageName, userId)) { 11040 return mOwners.getProfileOwnerComponent(userId); 11041 } 11042 return null; 11043 } 11044 11045 /** 11046 * Return device owner or profile owner set on a given user. 11047 */ 11048 private @Nullable ComponentName getOwnerComponent(int userId) { 11049 synchronized (getLockObject()) { 11050 if (mOwners.getDeviceOwnerUserId() == userId) { 11051 return mOwners.getDeviceOwnerComponent(); 11052 } 11053 if (mOwners.hasProfileOwner(userId)) { 11054 return mOwners.getProfileOwnerComponent(userId); 11055 } 11056 } 11057 return null; 11058 } 11059 11060 private int checkManagedUserProvisioningPreCondition(int callingUserId) { 11061 if (!hasFeatureManagedUsers()) { 11062 return CODE_MANAGED_USERS_NOT_SUPPORTED; 11063 } 11064 if (!mInjector.userManagerIsSplitSystemUser()) { 11065 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems. 11066 return CODE_NOT_SYSTEM_USER_SPLIT; 11067 } 11068 if (callingUserId == UserHandle.USER_SYSTEM) { 11069 // System user cannot be a managed user. 11070 return CODE_SYSTEM_USER; 11071 } 11072 if (hasUserSetupCompleted(callingUserId)) { 11073 return CODE_USER_SETUP_COMPLETED; 11074 } 11075 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 11076 return CODE_HAS_PAIRED; 11077 } 11078 return CODE_OK; 11079 } 11080 11081 private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) { 11082 if (!mInjector.userManagerIsSplitSystemUser()) { 11083 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems. 11084 return CODE_NOT_SYSTEM_USER_SPLIT; 11085 } 11086 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 11087 } 11088 11089 private boolean hasFeatureManagedUsers() { 11090 try { 11091 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 11092 } catch (RemoteException e) { 11093 return false; 11094 } 11095 } 11096 11097 @Override 11098 public String getWifiMacAddress(ComponentName admin) { 11099 // Make sure caller has DO. 11100 synchronized (getLockObject()) { 11101 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11102 } 11103 11104 final long ident = mInjector.binderClearCallingIdentity(); 11105 try { 11106 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo(); 11107 if (wifiInfo == null) { 11108 return null; 11109 } 11110 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null; 11111 } finally { 11112 mInjector.binderRestoreCallingIdentity(ident); 11113 } 11114 } 11115 11116 /** 11117 * Returns the target sdk version number that the given packageName was built for 11118 * in the given user. 11119 */ 11120 private int getTargetSdk(String packageName, int userId) { 11121 final ApplicationInfo ai; 11122 try { 11123 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 11124 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion; 11125 return targetSdkVersion; 11126 } catch (RemoteException e) { 11127 // Shouldn't happen 11128 return 0; 11129 } 11130 } 11131 11132 @Override 11133 public boolean isManagedProfile(ComponentName admin) { 11134 enforceProfileOrDeviceOwner(admin); 11135 return isManagedProfile(mInjector.userHandleGetCallingUserId()); 11136 } 11137 11138 @Override 11139 public boolean isSystemOnlyUser(ComponentName admin) { 11140 synchronized (getLockObject()) { 11141 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11142 } 11143 final int callingUserId = mInjector.userHandleGetCallingUserId(); 11144 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM; 11145 } 11146 11147 @Override 11148 public void reboot(ComponentName admin) { 11149 Preconditions.checkNotNull(admin); 11150 // Make sure caller has DO. 11151 synchronized (getLockObject()) { 11152 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11153 } 11154 long ident = mInjector.binderClearCallingIdentity(); 11155 try { 11156 // Make sure there are no ongoing calls on the device. 11157 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 11158 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 11159 } 11160 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 11161 } finally { 11162 mInjector.binderRestoreCallingIdentity(ident); 11163 } 11164 } 11165 11166 @Override 11167 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 11168 if (!mHasFeature) { 11169 return; 11170 } 11171 Preconditions.checkNotNull(who, "ComponentName is null"); 11172 final int userHandle = mInjector.userHandleGetCallingUserId(); 11173 synchronized (getLockObject()) { 11174 ActiveAdmin admin = getActiveAdminForUidLocked(who, 11175 mInjector.binderGetCallingUid()); 11176 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 11177 admin.shortSupportMessage = message; 11178 saveSettingsLocked(userHandle); 11179 } 11180 } 11181 } 11182 11183 @Override 11184 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 11185 if (!mHasFeature) { 11186 return null; 11187 } 11188 Preconditions.checkNotNull(who, "ComponentName is null"); 11189 synchronized (getLockObject()) { 11190 ActiveAdmin admin = getActiveAdminForUidLocked(who, 11191 mInjector.binderGetCallingUid()); 11192 return admin.shortSupportMessage; 11193 } 11194 } 11195 11196 @Override 11197 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 11198 if (!mHasFeature) { 11199 return; 11200 } 11201 Preconditions.checkNotNull(who, "ComponentName is null"); 11202 final int userHandle = mInjector.userHandleGetCallingUserId(); 11203 synchronized (getLockObject()) { 11204 ActiveAdmin admin = getActiveAdminForUidLocked(who, 11205 mInjector.binderGetCallingUid()); 11206 if (!TextUtils.equals(admin.longSupportMessage, message)) { 11207 admin.longSupportMessage = message; 11208 saveSettingsLocked(userHandle); 11209 } 11210 } 11211 } 11212 11213 @Override 11214 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 11215 if (!mHasFeature) { 11216 return null; 11217 } 11218 Preconditions.checkNotNull(who, "ComponentName is null"); 11219 synchronized (getLockObject()) { 11220 ActiveAdmin admin = getActiveAdminForUidLocked(who, 11221 mInjector.binderGetCallingUid()); 11222 return admin.longSupportMessage; 11223 } 11224 } 11225 11226 @Override 11227 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 11228 if (!mHasFeature) { 11229 return null; 11230 } 11231 Preconditions.checkNotNull(who, "ComponentName is null"); 11232 if (!isCallerWithSystemUid()) { 11233 throw new SecurityException("Only the system can query support message for user"); 11234 } 11235 synchronized (getLockObject()) { 11236 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 11237 if (admin != null) { 11238 return admin.shortSupportMessage; 11239 } 11240 } 11241 return null; 11242 } 11243 11244 @Override 11245 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 11246 if (!mHasFeature) { 11247 return null; 11248 } 11249 Preconditions.checkNotNull(who, "ComponentName is null"); 11250 if (!isCallerWithSystemUid()) { 11251 throw new SecurityException("Only the system can query support message for user"); 11252 } 11253 synchronized (getLockObject()) { 11254 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 11255 if (admin != null) { 11256 return admin.longSupportMessage; 11257 } 11258 } 11259 return null; 11260 } 11261 11262 @Override 11263 public void setOrganizationColor(@NonNull ComponentName who, int color) { 11264 if (!mHasFeature) { 11265 return; 11266 } 11267 Preconditions.checkNotNull(who, "ComponentName is null"); 11268 final int userHandle = mInjector.userHandleGetCallingUserId(); 11269 enforceManagedProfile(userHandle, "set organization color"); 11270 synchronized (getLockObject()) { 11271 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11272 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11273 admin.organizationColor = color; 11274 saveSettingsLocked(userHandle); 11275 } 11276 } 11277 11278 @Override 11279 public void setOrganizationColorForUser(int color, int userId) { 11280 if (!mHasFeature) { 11281 return; 11282 } 11283 enforceFullCrossUsersPermission(userId); 11284 enforceManageUsers(); 11285 enforceManagedProfile(userId, "set organization color"); 11286 synchronized (getLockObject()) { 11287 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 11288 admin.organizationColor = color; 11289 saveSettingsLocked(userId); 11290 } 11291 } 11292 11293 @Override 11294 public int getOrganizationColor(@NonNull ComponentName who) { 11295 if (!mHasFeature) { 11296 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 11297 } 11298 Preconditions.checkNotNull(who, "ComponentName is null"); 11299 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color"); 11300 synchronized (getLockObject()) { 11301 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11302 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11303 return admin.organizationColor; 11304 } 11305 } 11306 11307 @Override 11308 public int getOrganizationColorForUser(int userHandle) { 11309 if (!mHasFeature) { 11310 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 11311 } 11312 enforceFullCrossUsersPermission(userHandle); 11313 enforceManagedProfile(userHandle, "get organization color"); 11314 synchronized (getLockObject()) { 11315 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 11316 return (profileOwner != null) 11317 ? profileOwner.organizationColor 11318 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 11319 } 11320 } 11321 11322 @Override 11323 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 11324 if (!mHasFeature) { 11325 return; 11326 } 11327 Preconditions.checkNotNull(who, "ComponentName is null"); 11328 final int userHandle = mInjector.userHandleGetCallingUserId(); 11329 11330 synchronized (getLockObject()) { 11331 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11332 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11333 if (!TextUtils.equals(admin.organizationName, text)) { 11334 admin.organizationName = (text == null || text.length() == 0) 11335 ? null : text.toString(); 11336 saveSettingsLocked(userHandle); 11337 } 11338 } 11339 } 11340 11341 @Override 11342 public CharSequence getOrganizationName(@NonNull ComponentName who) { 11343 if (!mHasFeature) { 11344 return null; 11345 } 11346 Preconditions.checkNotNull(who, "ComponentName is null"); 11347 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name"); 11348 synchronized (getLockObject()) { 11349 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11350 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11351 return admin.organizationName; 11352 } 11353 } 11354 11355 @Override 11356 public CharSequence getDeviceOwnerOrganizationName() { 11357 if (!mHasFeature) { 11358 return null; 11359 } 11360 enforceDeviceOwnerOrManageUsers(); 11361 synchronized (getLockObject()) { 11362 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 11363 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 11364 } 11365 } 11366 11367 @Override 11368 public CharSequence getOrganizationNameForUser(int userHandle) { 11369 if (!mHasFeature) { 11370 return null; 11371 } 11372 enforceFullCrossUsersPermission(userHandle); 11373 enforceManagedProfile(userHandle, "get organization name"); 11374 synchronized (getLockObject()) { 11375 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 11376 return (profileOwner != null) 11377 ? profileOwner.organizationName 11378 : null; 11379 } 11380 } 11381 11382 @Override 11383 public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) { 11384 Preconditions.checkNotNull(who); 11385 Preconditions.checkNotNull(packageNames); 11386 11387 if (!mHasFeature) { 11388 return packageNames; 11389 } 11390 synchronized (getLockObject()) { 11391 final ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11392 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11393 final int callingUserId = mInjector.userHandleGetCallingUserId(); 11394 final long identity = mInjector.binderClearCallingIdentity(); 11395 try { 11396 final List<String> excludedPkgs 11397 = removeInvalidPkgsForMeteredDataRestriction(callingUserId, packageNames); 11398 admin.meteredDisabledPackages = packageNames; 11399 pushMeteredDisabledPackagesLocked(callingUserId); 11400 saveSettingsLocked(callingUserId); 11401 return excludedPkgs; 11402 } finally { 11403 mInjector.binderRestoreCallingIdentity(identity); 11404 } 11405 } 11406 } 11407 11408 private List<String> removeInvalidPkgsForMeteredDataRestriction( 11409 int userId, List<String> pkgNames) { 11410 final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId); 11411 final List<String> excludedPkgs = new ArrayList<>(); 11412 for (int i = pkgNames.size() - 1; i >= 0; --i) { 11413 final String pkgName = pkgNames.get(i); 11414 // If the package is an active admin, don't restrict it. 11415 if (activeAdmins.contains(pkgName)) { 11416 excludedPkgs.add(pkgName); 11417 continue; 11418 } 11419 // If the package doesn't exist, don't restrict it. 11420 try { 11421 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) { 11422 excludedPkgs.add(pkgName); 11423 } 11424 } catch (RemoteException e) { 11425 // Should not happen 11426 } 11427 } 11428 pkgNames.removeAll(excludedPkgs); 11429 return excludedPkgs; 11430 } 11431 11432 @Override 11433 public List<String> getMeteredDataDisabledPackages(ComponentName who) { 11434 Preconditions.checkNotNull(who); 11435 11436 if (!mHasFeature) { 11437 return new ArrayList<>(); 11438 } 11439 synchronized (getLockObject()) { 11440 final ActiveAdmin admin = getActiveAdminForCallerLocked(who, 11441 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11442 return admin.meteredDisabledPackages == null 11443 ? new ArrayList<>() : admin.meteredDisabledPackages; 11444 } 11445 } 11446 11447 @Override 11448 public boolean isMeteredDataDisabledPackageForUser(ComponentName who, 11449 String packageName, int userId) { 11450 Preconditions.checkNotNull(who); 11451 11452 if (!mHasFeature) { 11453 return false; 11454 } 11455 if (!isCallerWithSystemUid()) { 11456 throw new SecurityException( 11457 "Only the system can query restricted pkgs for a specific user"); 11458 } 11459 synchronized (getLockObject()) { 11460 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 11461 if (admin != null && admin.meteredDisabledPackages != null) { 11462 return admin.meteredDisabledPackages.contains(packageName); 11463 } 11464 } 11465 return false; 11466 } 11467 11468 private void pushMeteredDisabledPackagesLocked(int userId) { 11469 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages( 11470 getMeteredDisabledPackagesLocked(userId), userId); 11471 } 11472 11473 private Set<String> getMeteredDisabledPackagesLocked(int userId) { 11474 final ComponentName who = getOwnerComponent(userId); 11475 final Set<String> restrictedPkgs = new ArraySet<>(); 11476 if (who != null) { 11477 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 11478 if (admin != null && admin.meteredDisabledPackages != null) { 11479 restrictedPkgs.addAll(admin.meteredDisabledPackages); 11480 } 11481 } 11482 return restrictedPkgs; 11483 } 11484 11485 @Override 11486 public void setAffiliationIds(ComponentName admin, List<String> ids) { 11487 if (!mHasFeature) { 11488 return; 11489 } 11490 if (ids == null) { 11491 throw new IllegalArgumentException("ids must not be null"); 11492 } 11493 for (String id : ids) { 11494 if (TextUtils.isEmpty(id)) { 11495 throw new IllegalArgumentException("ids must not contain empty string"); 11496 } 11497 } 11498 11499 final Set<String> affiliationIds = new ArraySet<>(ids); 11500 final int callingUserId = mInjector.userHandleGetCallingUserId(); 11501 synchronized (getLockObject()) { 11502 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11503 getUserData(callingUserId).mAffiliationIds = affiliationIds; 11504 saveSettingsLocked(callingUserId); 11505 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 11506 // Affiliation ids specified by the device owner are additionally stored in 11507 // UserHandle.USER_SYSTEM's DevicePolicyData. 11508 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 11509 saveSettingsLocked(UserHandle.USER_SYSTEM); 11510 } 11511 11512 // Affiliation status for any user, not just the calling user, might have changed. 11513 // The device owner user will still be affiliated after changing its affiliation ids, 11514 // but as a result of that other users might become affiliated or un-affiliated. 11515 maybePauseDeviceWideLoggingLocked(); 11516 maybeResumeDeviceWideLoggingLocked(); 11517 maybeClearLockTaskPolicyLocked(); 11518 } 11519 } 11520 11521 @Override 11522 public List<String> getAffiliationIds(ComponentName admin) { 11523 if (!mHasFeature) { 11524 return Collections.emptyList(); 11525 } 11526 11527 Preconditions.checkNotNull(admin); 11528 synchronized (getLockObject()) { 11529 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11530 return new ArrayList<String>( 11531 getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds); 11532 } 11533 } 11534 11535 @Override 11536 public boolean isAffiliatedUser() { 11537 if (!mHasFeature) { 11538 return false; 11539 } 11540 11541 synchronized (getLockObject()) { 11542 return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId()); 11543 } 11544 } 11545 11546 private boolean isUserAffiliatedWithDeviceLocked(int userId) { 11547 if (!mOwners.hasDeviceOwner()) { 11548 return false; 11549 } 11550 if (userId == mOwners.getDeviceOwnerUserId()) { 11551 // The user that the DO is installed on is always affiliated with the device. 11552 return true; 11553 } 11554 if (userId == UserHandle.USER_SYSTEM) { 11555 // The system user is always affiliated in a DO device, even if the DO is set on a 11556 // different user. This could be the case if the DO is set in the primary user 11557 // of a split user device. 11558 return true; 11559 } 11560 11561 final ComponentName profileOwner = getProfileOwner(userId); 11562 if (profileOwner == null) { 11563 return false; 11564 } 11565 11566 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 11567 final Set<String> deviceAffiliationIds = 11568 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 11569 for (String id : userAffiliationIds) { 11570 if (deviceAffiliationIds.contains(id)) { 11571 return true; 11572 } 11573 } 11574 return false; 11575 } 11576 11577 private boolean areAllUsersAffiliatedWithDeviceLocked() { 11578 final long ident = mInjector.binderClearCallingIdentity(); 11579 try { 11580 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 11581 for (int i = 0; i < userInfos.size(); i++) { 11582 int userId = userInfos.get(i).id; 11583 if (!isUserAffiliatedWithDeviceLocked(userId)) { 11584 Slog.d(LOG_TAG, "User id " + userId + " not affiliated."); 11585 return false; 11586 } 11587 } 11588 } finally { 11589 mInjector.binderRestoreCallingIdentity(ident); 11590 } 11591 11592 return true; 11593 } 11594 11595 @Override 11596 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) { 11597 if (!mHasFeature) { 11598 return; 11599 } 11600 Preconditions.checkNotNull(admin); 11601 11602 synchronized (getLockObject()) { 11603 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11604 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 11605 return; 11606 } 11607 mInjector.securityLogSetLoggingEnabledProperty(enabled); 11608 if (enabled) { 11609 mSecurityLogMonitor.start(); 11610 maybePauseDeviceWideLoggingLocked(); 11611 } else { 11612 mSecurityLogMonitor.stop(); 11613 } 11614 } 11615 } 11616 11617 @Override 11618 public boolean isSecurityLoggingEnabled(ComponentName admin) { 11619 if (!mHasFeature) { 11620 return false; 11621 } 11622 11623 synchronized (getLockObject()) { 11624 if (!isCallerWithSystemUid()) { 11625 Preconditions.checkNotNull(admin); 11626 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11627 } 11628 return mInjector.securityLogGetLoggingEnabledProperty(); 11629 } 11630 } 11631 11632 private void recordSecurityLogRetrievalTime() { 11633 synchronized (getLockObject()) { 11634 final long currentTime = System.currentTimeMillis(); 11635 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 11636 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 11637 policyData.mLastSecurityLogRetrievalTime = currentTime; 11638 saveSettingsLocked(UserHandle.USER_SYSTEM); 11639 } 11640 } 11641 } 11642 11643 @Override 11644 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) { 11645 if (!mHasFeature) { 11646 return null; 11647 } 11648 11649 Preconditions.checkNotNull(admin); 11650 ensureDeviceOwnerAndAllUsersAffiliated(admin); 11651 11652 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs) 11653 || !mInjector.securityLogGetLoggingEnabledProperty()) { 11654 return null; 11655 } 11656 11657 recordSecurityLogRetrievalTime(); 11658 11659 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 11660 try { 11661 SecurityLog.readPreviousEvents(output); 11662 return new ParceledListSlice<SecurityEvent>(output); 11663 } catch (IOException e) { 11664 Slog.w(LOG_TAG, "Fail to read previous events" , e); 11665 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 11666 } 11667 } 11668 11669 @Override 11670 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) { 11671 if (!mHasFeature) { 11672 return null; 11673 } 11674 11675 Preconditions.checkNotNull(admin); 11676 ensureDeviceOwnerAndAllUsersAffiliated(admin); 11677 11678 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 11679 return null; 11680 } 11681 11682 recordSecurityLogRetrievalTime(); 11683 11684 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 11685 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 11686 } 11687 11688 @Override 11689 public long forceSecurityLogs() { 11690 enforceShell("forceSecurityLogs"); 11691 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 11692 throw new IllegalStateException("logging is not available"); 11693 } 11694 return mSecurityLogMonitor.forceLogs(); 11695 } 11696 11697 private void enforceCanManageDeviceAdmin() { 11698 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS, 11699 null); 11700 } 11701 11702 private void enforceCanManageProfileAndDeviceOwners() { 11703 mContext.enforceCallingOrSelfPermission( 11704 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 11705 } 11706 11707 private void enforceCallerSystemUserHandle() { 11708 final int callingUid = mInjector.binderGetCallingUid(); 11709 final int userId = UserHandle.getUserId(callingUid); 11710 if (userId != UserHandle.USER_SYSTEM) { 11711 throw new SecurityException("Caller has to be in user 0"); 11712 } 11713 } 11714 11715 @Override 11716 public boolean isUninstallInQueue(final String packageName) { 11717 enforceCanManageDeviceAdmin(); 11718 final int userId = mInjector.userHandleGetCallingUserId(); 11719 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 11720 synchronized (getLockObject()) { 11721 return mPackagesToRemove.contains(packageUserPair); 11722 } 11723 } 11724 11725 @Override 11726 public void uninstallPackageWithActiveAdmins(final String packageName) { 11727 enforceCanManageDeviceAdmin(); 11728 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 11729 11730 final int userId = mInjector.userHandleGetCallingUserId(); 11731 11732 enforceUserUnlocked(userId); 11733 11734 final ComponentName profileOwner = getProfileOwner(userId); 11735 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 11736 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 11737 } 11738 11739 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 11740 if (getDeviceOwnerUserId() == userId && deviceOwner != null 11741 && packageName.equals(deviceOwner.getPackageName())) { 11742 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 11743 } 11744 11745 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 11746 synchronized (getLockObject()) { 11747 mPackagesToRemove.add(packageUserPair); 11748 } 11749 11750 // All active admins on the user. 11751 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 11752 11753 // Active admins in the target package. 11754 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 11755 if (allActiveAdmins != null) { 11756 for (ComponentName activeAdmin : allActiveAdmins) { 11757 if (packageName.equals(activeAdmin.getPackageName())) { 11758 packageActiveAdmins.add(activeAdmin); 11759 removeActiveAdmin(activeAdmin, userId); 11760 } 11761 } 11762 } 11763 if (packageActiveAdmins.size() == 0) { 11764 startUninstallIntent(packageName, userId); 11765 } else { 11766 mHandler.postDelayed(new Runnable() { 11767 @Override 11768 public void run() { 11769 for (ComponentName activeAdmin : packageActiveAdmins) { 11770 removeAdminArtifacts(activeAdmin, userId); 11771 } 11772 startUninstallIntent(packageName, userId); 11773 } 11774 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 11775 } 11776 } 11777 11778 @Override 11779 public boolean isDeviceProvisioned() { 11780 enforceManageUsers(); 11781 synchronized (getLockObject()) { 11782 return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete; 11783 } 11784 } 11785 11786 private boolean isCurrentUserDemo() { 11787 if (UserManager.isDeviceInDemoMode(mContext)) { 11788 final int userId = mInjector.userHandleGetCallingUserId(); 11789 final long callingIdentity = mInjector.binderClearCallingIdentity(); 11790 try { 11791 return mUserManager.getUserInfo(userId).isDemo(); 11792 } finally { 11793 mInjector.binderRestoreCallingIdentity(callingIdentity); 11794 } 11795 } 11796 return false; 11797 } 11798 11799 private void removePackageIfRequired(final String packageName, final int userId) { 11800 if (!packageHasActiveAdmins(packageName, userId)) { 11801 // Will not do anything if uninstall was not requested or was already started. 11802 startUninstallIntent(packageName, userId); 11803 } 11804 } 11805 11806 private void startUninstallIntent(final String packageName, final int userId) { 11807 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 11808 synchronized (getLockObject()) { 11809 if (!mPackagesToRemove.contains(packageUserPair)) { 11810 // Do nothing if uninstall was not requested or was already started. 11811 return; 11812 } 11813 mPackagesToRemove.remove(packageUserPair); 11814 } 11815 try { 11816 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) { 11817 // Package does not exist. Nothing to do. 11818 return; 11819 } 11820 } catch (RemoteException re) { 11821 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info"); 11822 } 11823 11824 try { // force stop the package before uninstalling 11825 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 11826 } catch (RemoteException re) { 11827 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 11828 } 11829 final Uri packageURI = Uri.parse("package:" + packageName); 11830 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 11831 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 11832 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 11833 } 11834 11835 /** 11836 * Removes the admin from the policy. Ideally called after the admin's 11837 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 11838 * 11839 * @param adminReceiver The admin to remove 11840 * @param userHandle The user for which this admin has to be removed. 11841 */ 11842 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 11843 synchronized (getLockObject()) { 11844 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 11845 if (admin == null) { 11846 return; 11847 } 11848 final DevicePolicyData policy = getUserData(userHandle); 11849 final boolean doProxyCleanup = admin.info.usesPolicy( 11850 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 11851 policy.mAdminList.remove(admin); 11852 policy.mAdminMap.remove(adminReceiver); 11853 validatePasswordOwnerLocked(policy); 11854 if (doProxyCleanup) { 11855 resetGlobalProxyLocked(policy); 11856 } 11857 pushActiveAdminPackagesLocked(userHandle); 11858 pushMeteredDisabledPackagesLocked(userHandle); 11859 saveSettingsLocked(userHandle); 11860 updateMaximumTimeToLockLocked(userHandle); 11861 policy.mRemovingAdmins.remove(adminReceiver); 11862 11863 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 11864 } 11865 // The removed admin might have disabled camera, so update user 11866 // restrictions. 11867 pushUserRestrictions(userHandle); 11868 } 11869 11870 @Override 11871 public void setDeviceProvisioningConfigApplied() { 11872 enforceManageUsers(); 11873 synchronized (getLockObject()) { 11874 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 11875 policy.mDeviceProvisioningConfigApplied = true; 11876 saveSettingsLocked(UserHandle.USER_SYSTEM); 11877 } 11878 } 11879 11880 @Override 11881 public boolean isDeviceProvisioningConfigApplied() { 11882 enforceManageUsers(); 11883 synchronized (getLockObject()) { 11884 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 11885 return policy.mDeviceProvisioningConfigApplied; 11886 } 11887 } 11888 11889 /** 11890 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 11891 * 11892 * It's added for testing only. Please use this API carefully if it's used by other system app 11893 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 11894 * apps. 11895 */ 11896 @Override 11897 public void forceUpdateUserSetupComplete() { 11898 enforceCanManageProfileAndDeviceOwners(); 11899 enforceCallerSystemUserHandle(); 11900 // no effect if it's called from user build 11901 if (!mInjector.isBuildDebuggable()) { 11902 return; 11903 } 11904 final int userId = UserHandle.USER_SYSTEM; 11905 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 11906 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 11907 DevicePolicyData policy = getUserData(userId); 11908 policy.mUserSetupComplete = isUserCompleted; 11909 synchronized (getLockObject()) { 11910 saveSettingsLocked(userId); 11911 } 11912 } 11913 11914 // TODO(b/22388012): When backup is available for secondary users and profiles, consider 11915 // whether there are any privacy/security implications of enabling the backup service here 11916 // if there are other users or profiles unmanaged or managed by a different entity (i.e. not 11917 // affiliated). 11918 @Override 11919 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 11920 if (!mHasFeature) { 11921 return; 11922 } 11923 Preconditions.checkNotNull(admin); 11924 synchronized (getLockObject()) { 11925 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked( 11926 admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11927 if (!enabled) { 11928 activeAdmin.mandatoryBackupTransport = null; 11929 saveSettingsLocked(UserHandle.USER_SYSTEM); 11930 } 11931 } 11932 11933 final long ident = mInjector.binderClearCallingIdentity(); 11934 try { 11935 IBackupManager ibm = mInjector.getIBackupManager(); 11936 if (ibm != null) { 11937 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled); 11938 } 11939 } catch (RemoteException e) { 11940 throw new IllegalStateException( 11941 "Failed " + (enabled ? "" : "de") + "activating backup service.", e); 11942 } finally { 11943 mInjector.binderRestoreCallingIdentity(ident); 11944 } 11945 } 11946 11947 @Override 11948 public boolean isBackupServiceEnabled(ComponentName admin) { 11949 Preconditions.checkNotNull(admin); 11950 if (!mHasFeature) { 11951 return true; 11952 } 11953 synchronized (getLockObject()) { 11954 try { 11955 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11956 IBackupManager ibm = mInjector.getIBackupManager(); 11957 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM); 11958 } catch (RemoteException e) { 11959 throw new IllegalStateException("Failed requesting backup service state.", e); 11960 } 11961 } 11962 } 11963 11964 @Override 11965 public boolean setMandatoryBackupTransport( 11966 ComponentName admin, 11967 ComponentName backupTransportComponent) { 11968 if (!mHasFeature) { 11969 return false; 11970 } 11971 Preconditions.checkNotNull(admin); 11972 synchronized (getLockObject()) { 11973 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11974 } 11975 11976 final int callingUid = mInjector.binderGetCallingUid(); 11977 final AtomicBoolean success = new AtomicBoolean(false); 11978 final CountDownLatch countDownLatch = new CountDownLatch(1); 11979 final ISelectBackupTransportCallback selectBackupTransportCallbackInternal = 11980 new ISelectBackupTransportCallback.Stub() { 11981 public void onSuccess(String transportName) { 11982 saveMandatoryBackupTransport(admin, callingUid, backupTransportComponent); 11983 success.set(true); 11984 countDownLatch.countDown(); 11985 } 11986 11987 public void onFailure(int reason) { 11988 countDownLatch.countDown(); 11989 } 11990 }; 11991 final long identity = mInjector.binderClearCallingIdentity(); 11992 try { 11993 IBackupManager ibm = mInjector.getIBackupManager(); 11994 if (ibm != null && backupTransportComponent != null) { 11995 if (!ibm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11996 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, true); 11997 } 11998 ibm.selectBackupTransportAsync( 11999 backupTransportComponent, selectBackupTransportCallbackInternal); 12000 countDownLatch.await(); 12001 if (success.get()) { 12002 ibm.setBackupEnabled(true); 12003 } 12004 } else if (backupTransportComponent == null) { 12005 saveMandatoryBackupTransport(admin, callingUid, backupTransportComponent); 12006 success.set(true); 12007 } 12008 } catch (RemoteException e) { 12009 throw new IllegalStateException("Failed to set mandatory backup transport.", e); 12010 } catch (InterruptedException e) { 12011 throw new IllegalStateException("Failed to set mandatory backup transport.", e); 12012 } finally { 12013 mInjector.binderRestoreCallingIdentity(identity); 12014 } 12015 return success.get(); 12016 } 12017 12018 private void saveMandatoryBackupTransport( 12019 ComponentName admin, int callingUid, ComponentName backupTransportComponent) { 12020 synchronized (getLockObject()) { 12021 ActiveAdmin activeAdmin = 12022 getActiveAdminWithPolicyForUidLocked( 12023 admin, 12024 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 12025 callingUid); 12026 if (!Objects.equals(backupTransportComponent, 12027 activeAdmin.mandatoryBackupTransport)) { 12028 activeAdmin.mandatoryBackupTransport = 12029 backupTransportComponent; 12030 saveSettingsLocked(UserHandle.USER_SYSTEM); 12031 } 12032 } 12033 } 12034 12035 @Override 12036 public ComponentName getMandatoryBackupTransport() { 12037 if (!mHasFeature) { 12038 return null; 12039 } 12040 synchronized (getLockObject()) { 12041 ActiveAdmin activeAdmin = getDeviceOwnerAdminLocked(); 12042 return activeAdmin == null ? null : activeAdmin.mandatoryBackupTransport; 12043 } 12044 } 12045 12046 12047 @Override 12048 public boolean bindDeviceAdminServiceAsUser( 12049 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 12050 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 12051 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 12052 if (!mHasFeature) { 12053 return false; 12054 } 12055 Preconditions.checkNotNull(admin); 12056 Preconditions.checkNotNull(caller); 12057 Preconditions.checkNotNull(serviceIntent); 12058 Preconditions.checkArgument( 12059 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 12060 "Service intent must be explicit (with a package name or component): " 12061 + serviceIntent); 12062 Preconditions.checkNotNull(connection); 12063 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 12064 "target user id must be different from the calling user id"); 12065 12066 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 12067 throw new SecurityException("Not allowed to bind to target user id"); 12068 } 12069 12070 final String targetPackage; 12071 synchronized (getLockObject()) { 12072 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 12073 } 12074 12075 final long callingIdentity = mInjector.binderClearCallingIdentity(); 12076 try { 12077 // Validate and sanitize the incoming service intent. 12078 final Intent sanitizedIntent = 12079 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 12080 if (sanitizedIntent == null) { 12081 // Fail, cannot lookup the target service. 12082 return false; 12083 } 12084 // Ask ActivityManager to bind it. Notice that we are binding the service with the 12085 // caller app instead of DevicePolicyManagerService. 12086 return mInjector.getIActivityManager().bindService( 12087 caller, activtiyToken, serviceIntent, 12088 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 12089 connection, flags, mContext.getOpPackageName(), 12090 targetUserId) != 0; 12091 } catch (RemoteException ex) { 12092 // Same process, should not happen. 12093 } finally { 12094 mInjector.binderRestoreCallingIdentity(callingIdentity); 12095 } 12096 12097 // Failed to bind. 12098 return false; 12099 } 12100 12101 @Override 12102 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 12103 if (!mHasFeature) { 12104 return Collections.emptyList(); 12105 } 12106 Preconditions.checkNotNull(admin); 12107 12108 synchronized (getLockObject()) { 12109 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12110 12111 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12112 final long callingIdentity = mInjector.binderClearCallingIdentity(); 12113 try { 12114 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 12115 if (!isDeviceOwner(admin, callingUserId)) { 12116 // Profile owners can only bind to the device owner. 12117 if (canUserBindToDeviceOwnerLocked(callingUserId)) { 12118 targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId())); 12119 } 12120 } else { 12121 // Caller is the device owner: Look for profile owners that it can bind to. 12122 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 12123 for (int i = 0; i < userInfos.size(); i++) { 12124 final int userId = userInfos.get(i).id; 12125 if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) { 12126 targetUsers.add(UserHandle.of(userId)); 12127 } 12128 } 12129 } 12130 12131 return targetUsers; 12132 } finally { 12133 mInjector.binderRestoreCallingIdentity(callingIdentity); 12134 } 12135 } 12136 } 12137 12138 private boolean canUserBindToDeviceOwnerLocked(int userId) { 12139 // There has to be a device owner, under another user id. 12140 if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) { 12141 return false; 12142 } 12143 12144 // The user must have a profile owner that belongs to the same package as the device owner. 12145 if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals( 12146 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) { 12147 return false; 12148 } 12149 12150 // The user must be affiliated. 12151 return isUserAffiliatedWithDeviceLocked(userId); 12152 } 12153 12154 /** 12155 * Return true if a given user has any accounts that'll prevent installing a device or profile 12156 * owner {@code owner}. 12157 * - If the user has no accounts, then return false. 12158 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 12159 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 12160 * ..._DISALLOWED, return true. 12161 * - Otherwise return false. 12162 * 12163 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used 12164 * when the caller is not ADB. 12165 * 12166 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 12167 */ 12168 private boolean hasIncompatibleAccountsOrNonAdbNoLock( 12169 int userId, @Nullable ComponentName owner) { 12170 if (!isAdb()) { 12171 return true; 12172 } 12173 wtfIfInLock(); 12174 12175 final long token = mInjector.binderClearCallingIdentity(); 12176 try { 12177 final AccountManager am = AccountManager.get(mContext); 12178 final Account accounts[] = am.getAccountsAsUser(userId); 12179 if (accounts.length == 0) { 12180 return false; 12181 } 12182 synchronized (getLockObject()) { 12183 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 12184 Log.w(LOG_TAG, 12185 "Non test-only owner can't be installed with existing accounts."); 12186 return true; 12187 } 12188 } 12189 12190 final String[] feature_allow = 12191 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 12192 final String[] feature_disallow = 12193 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 12194 12195 boolean compatible = true; 12196 for (Account account : accounts) { 12197 if (hasAccountFeatures(am, account, feature_disallow)) { 12198 Log.e(LOG_TAG, account + " has " + feature_disallow[0]); 12199 compatible = false; 12200 break; 12201 } 12202 if (!hasAccountFeatures(am, account, feature_allow)) { 12203 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]); 12204 compatible = false; 12205 break; 12206 } 12207 } 12208 if (compatible) { 12209 Log.w(LOG_TAG, "All accounts are compatible"); 12210 } else { 12211 Log.e(LOG_TAG, "Found incompatible accounts"); 12212 } 12213 return !compatible; 12214 } finally { 12215 mInjector.binderRestoreCallingIdentity(token); 12216 } 12217 } 12218 12219 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 12220 try { 12221 return am.hasFeatures(account, features, null, null).getResult(); 12222 } catch (Exception e) { 12223 Log.w(LOG_TAG, "Failed to get account feature", e); 12224 return false; 12225 } 12226 } 12227 12228 private boolean isAdb() { 12229 final int callingUid = mInjector.binderGetCallingUid(); 12230 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 12231 } 12232 12233 @Override 12234 public void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) { 12235 if (!mHasFeature) { 12236 return; 12237 } 12238 synchronized (getLockObject()) { 12239 Preconditions.checkNotNull(admin); 12240 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12241 12242 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 12243 // already in the requested state 12244 return; 12245 } 12246 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 12247 deviceOwner.isNetworkLoggingEnabled = enabled; 12248 if (!enabled) { 12249 deviceOwner.numNetworkLoggingNotifications = 0; 12250 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 12251 } 12252 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 12253 12254 setNetworkLoggingActiveInternal(enabled); 12255 } 12256 } 12257 12258 private void setNetworkLoggingActiveInternal(boolean active) { 12259 synchronized (getLockObject()) { 12260 final long callingIdentity = mInjector.binderClearCallingIdentity(); 12261 try { 12262 if (active) { 12263 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal()); 12264 if (!mNetworkLogger.startNetworkLogging()) { 12265 mNetworkLogger = null; 12266 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging" 12267 + " service not being available yet."); 12268 } 12269 maybePauseDeviceWideLoggingLocked(); 12270 sendNetworkLoggingNotificationLocked(); 12271 } else { 12272 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 12273 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 12274 + " service not being available yet."); 12275 } 12276 mNetworkLogger = null; 12277 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING); 12278 } 12279 } finally { 12280 mInjector.binderRestoreCallingIdentity(callingIdentity); 12281 } 12282 } 12283 } 12284 12285 /** Pauses security and network logging if there are unaffiliated users on the device */ 12286 private void maybePauseDeviceWideLoggingLocked() { 12287 if (!areAllUsersAffiliatedWithDeviceLocked()) { 12288 Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be " 12289 + "paused if enabled."); 12290 mSecurityLogMonitor.pause(); 12291 if (mNetworkLogger != null) { 12292 mNetworkLogger.pause(); 12293 } 12294 } 12295 } 12296 12297 /** Resumes security and network logging (if they are enabled) if all users are affiliated */ 12298 private void maybeResumeDeviceWideLoggingLocked() { 12299 if (areAllUsersAffiliatedWithDeviceLocked()) { 12300 final long ident = mInjector.binderClearCallingIdentity(); 12301 try { 12302 mSecurityLogMonitor.resume(); 12303 if (mNetworkLogger != null) { 12304 mNetworkLogger.resume(); 12305 } 12306 } finally { 12307 mInjector.binderRestoreCallingIdentity(ident); 12308 } 12309 } 12310 } 12311 12312 /** Deletes any security and network logs that might have been collected so far */ 12313 private void discardDeviceWideLogsLocked() { 12314 mSecurityLogMonitor.discardLogs(); 12315 if (mNetworkLogger != null) { 12316 mNetworkLogger.discardLogs(); 12317 } 12318 // TODO: We should discard pre-boot security logs here too, as otherwise those 12319 // logs (which might contain data from the user just removed) will be 12320 // available after next boot. 12321 } 12322 12323 @Override 12324 public boolean isNetworkLoggingEnabled(ComponentName admin) { 12325 if (!mHasFeature) { 12326 return false; 12327 } 12328 synchronized (getLockObject()) { 12329 enforceDeviceOwnerOrManageUsers(); 12330 return isNetworkLoggingEnabledInternalLocked(); 12331 } 12332 } 12333 12334 private boolean isNetworkLoggingEnabledInternalLocked() { 12335 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 12336 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled; 12337 } 12338 12339 /* 12340 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 12341 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 12342 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 12343 * 12344 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 12345 */ 12346 @Override 12347 public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) { 12348 if (!mHasFeature) { 12349 return null; 12350 } 12351 Preconditions.checkNotNull(admin); 12352 ensureDeviceOwnerAndAllUsersAffiliated(admin); 12353 12354 synchronized (getLockObject()) { 12355 if (mNetworkLogger == null 12356 || !isNetworkLoggingEnabledInternalLocked()) { 12357 return null; 12358 } 12359 12360 final long currentTime = System.currentTimeMillis(); 12361 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 12362 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 12363 policyData.mLastNetworkLogsRetrievalTime = currentTime; 12364 saveSettingsLocked(UserHandle.USER_SYSTEM); 12365 } 12366 return mNetworkLogger.retrieveLogs(batchToken); 12367 } 12368 } 12369 12370 private void sendNetworkLoggingNotificationLocked() { 12371 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 12372 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 12373 return; 12374 } 12375 if (deviceOwner.numNetworkLoggingNotifications >= 12376 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 12377 return; 12378 } 12379 final long now = System.currentTimeMillis(); 12380 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 12381 return; 12382 } 12383 deviceOwner.numNetworkLoggingNotifications++; 12384 if (deviceOwner.numNetworkLoggingNotifications 12385 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 12386 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 12387 } else { 12388 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 12389 } 12390 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 12391 intent.setPackage("com.android.systemui"); 12392 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0, 12393 UserHandle.CURRENT); 12394 Notification notification = 12395 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 12396 .setSmallIcon(R.drawable.ic_info_outline) 12397 .setContentTitle(mContext.getString(R.string.network_logging_notification_title)) 12398 .setContentText(mContext.getString(R.string.network_logging_notification_text)) 12399 .setTicker(mContext.getString(R.string.network_logging_notification_title)) 12400 .setShowWhen(true) 12401 .setContentIntent(pendingIntent) 12402 .setStyle(new Notification.BigTextStyle() 12403 .bigText(mContext.getString(R.string.network_logging_notification_text))) 12404 .build(); 12405 mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification); 12406 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 12407 } 12408 12409 /** 12410 * Return the package name of owner in a given user. 12411 */ 12412 private String getOwnerPackageNameForUserLocked(int userId) { 12413 return mOwners.getDeviceOwnerUserId() == userId 12414 ? mOwners.getDeviceOwnerPackageName() 12415 : mOwners.getProfileOwnerPackage(userId); 12416 } 12417 12418 /** 12419 * @param rawIntent Original service intent specified by caller. It must be explicit. 12420 * @param expectedPackageName The expected package name of the resolved service. 12421 * @return Intent that have component explicitly set. {@code null} if no service is resolved 12422 * with the given intent. 12423 * @throws SecurityException if the intent is resolved to an invalid service. 12424 */ 12425 private Intent createCrossUserServiceIntent( 12426 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 12427 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 12428 ResolveInfo info = mIPackageManager.resolveService( 12429 rawIntent, 12430 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 12431 0, // flags 12432 targetUserId); 12433 if (info == null || info.serviceInfo == null) { 12434 Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent 12435 + " or user " + targetUserId + " is not running"); 12436 return null; 12437 } 12438 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 12439 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 12440 } 12441 // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release. 12442 if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) { 12443 throw new SecurityException( 12444 "Service must be protected by BIND_DEVICE_ADMIN permission"); 12445 } 12446 // It is the system server to bind the service, it would be extremely dangerous if it 12447 // can be exploited to bind any service. Set the component explicitly to make sure we 12448 // do not bind anything accidentally. 12449 rawIntent.setComponent(info.serviceInfo.getComponentName()); 12450 return rawIntent; 12451 } 12452 12453 @Override 12454 public long getLastSecurityLogRetrievalTime() { 12455 enforceDeviceOwnerOrManageUsers(); 12456 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 12457 } 12458 12459 @Override 12460 public long getLastBugReportRequestTime() { 12461 enforceDeviceOwnerOrManageUsers(); 12462 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 12463 } 12464 12465 @Override 12466 public long getLastNetworkLogRetrievalTime() { 12467 enforceDeviceOwnerOrManageUsers(); 12468 return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime; 12469 } 12470 12471 @Override 12472 public boolean setResetPasswordToken(ComponentName admin, byte[] token) { 12473 if (!mHasFeature) { 12474 return false; 12475 } 12476 if (token == null || token.length < 32) { 12477 throw new IllegalArgumentException("token must be at least 32-byte long"); 12478 } 12479 synchronized (getLockObject()) { 12480 final int userHandle = mInjector.userHandleGetCallingUserId(); 12481 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12482 12483 DevicePolicyData policy = getUserData(userHandle); 12484 long ident = mInjector.binderClearCallingIdentity(); 12485 try { 12486 if (policy.mPasswordTokenHandle != 0) { 12487 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle); 12488 } 12489 12490 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle); 12491 saveSettingsLocked(userHandle); 12492 return policy.mPasswordTokenHandle != 0; 12493 } finally { 12494 mInjector.binderRestoreCallingIdentity(ident); 12495 } 12496 } 12497 } 12498 12499 @Override 12500 public boolean clearResetPasswordToken(ComponentName admin) { 12501 if (!mHasFeature) { 12502 return false; 12503 } 12504 synchronized (getLockObject()) { 12505 final int userHandle = mInjector.userHandleGetCallingUserId(); 12506 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12507 12508 DevicePolicyData policy = getUserData(userHandle); 12509 if (policy.mPasswordTokenHandle != 0) { 12510 long ident = mInjector.binderClearCallingIdentity(); 12511 try { 12512 boolean result = mLockPatternUtils.removeEscrowToken( 12513 policy.mPasswordTokenHandle, userHandle); 12514 policy.mPasswordTokenHandle = 0; 12515 saveSettingsLocked(userHandle); 12516 return result; 12517 } finally { 12518 mInjector.binderRestoreCallingIdentity(ident); 12519 } 12520 } 12521 } 12522 return false; 12523 } 12524 12525 @Override 12526 public boolean isResetPasswordTokenActive(ComponentName admin) { 12527 synchronized (getLockObject()) { 12528 final int userHandle = mInjector.userHandleGetCallingUserId(); 12529 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12530 12531 DevicePolicyData policy = getUserData(userHandle); 12532 if (policy.mPasswordTokenHandle != 0) { 12533 long ident = mInjector.binderClearCallingIdentity(); 12534 try { 12535 return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle, 12536 userHandle); 12537 } finally { 12538 mInjector.binderRestoreCallingIdentity(ident); 12539 } 12540 } 12541 } 12542 return false; 12543 } 12544 12545 @Override 12546 public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, 12547 int flags) { 12548 Preconditions.checkNotNull(token); 12549 synchronized (getLockObject()) { 12550 final int userHandle = mInjector.userHandleGetCallingUserId(); 12551 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12552 12553 DevicePolicyData policy = getUserData(userHandle); 12554 if (policy.mPasswordTokenHandle != 0) { 12555 final String password = passwordOrNull != null ? passwordOrNull : ""; 12556 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token, 12557 flags, mInjector.binderGetCallingUid(), userHandle); 12558 } else { 12559 Slog.w(LOG_TAG, "No saved token handle"); 12560 } 12561 } 12562 return false; 12563 } 12564 12565 @Override 12566 public boolean isCurrentInputMethodSetByOwner() { 12567 enforceProfileOwnerOrSystemUser(); 12568 return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet; 12569 } 12570 12571 @Override 12572 public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) { 12573 final int userId = user.getIdentifier(); 12574 enforceProfileOwnerOrFullCrossUsersPermission(userId); 12575 synchronized (getLockObject()) { 12576 return new StringParceledListSlice( 12577 new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts)); 12578 } 12579 } 12580 12581 @Override 12582 public void clearApplicationUserData(ComponentName admin, String packageName, 12583 IPackageDataObserver callback) { 12584 Preconditions.checkNotNull(admin, "ComponentName is null"); 12585 Preconditions.checkNotNull(packageName, "packageName is null"); 12586 Preconditions.checkNotNull(callback, "callback is null"); 12587 synchronized (getLockObject()) { 12588 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12589 } 12590 final int userId = UserHandle.getCallingUserId(); 12591 12592 long ident = mInjector.binderClearCallingIdentity(); 12593 try { 12594 ActivityManager.getService().clearApplicationUserData(packageName, false, callback, 12595 userId); 12596 } catch(RemoteException re) { 12597 // Same process, should not happen. 12598 } catch (SecurityException se) { 12599 // This can happen e.g. for device admin packages, do not throw out the exception, 12600 // because callers have no means to know beforehand for which packages this might 12601 // happen. If so, we send back that removal failed. 12602 Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName, 12603 se); 12604 try { 12605 callback.onRemoveCompleted(packageName, false); 12606 } catch (RemoteException re) { 12607 // Caller is no longer available, ignore 12608 } 12609 } finally { 12610 mInjector.binderRestoreCallingIdentity(ident); 12611 } 12612 } 12613 12614 @Override 12615 public void setLogoutEnabled(ComponentName admin, boolean enabled) { 12616 if (!mHasFeature) { 12617 return; 12618 } 12619 Preconditions.checkNotNull(admin); 12620 12621 synchronized (getLockObject()) { 12622 ActiveAdmin deviceOwner = 12623 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12624 12625 if (deviceOwner.isLogoutEnabled == enabled) { 12626 // already in the requested state 12627 return; 12628 } 12629 deviceOwner.isLogoutEnabled = enabled; 12630 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 12631 } 12632 } 12633 12634 @Override 12635 public boolean isLogoutEnabled() { 12636 if (!mHasFeature) { 12637 return false; 12638 } 12639 synchronized (getLockObject()) { 12640 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 12641 return (deviceOwner != null) && deviceOwner.isLogoutEnabled; 12642 } 12643 } 12644 12645 @Override 12646 public List<String> getDisallowedSystemApps(ComponentName admin, int userId, 12647 String provisioningAction) throws RemoteException { 12648 enforceCanManageProfileAndDeviceOwners(); 12649 return new ArrayList<>( 12650 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction)); 12651 } 12652 12653 @Override 12654 public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target, 12655 @Nullable PersistableBundle bundle) { 12656 if (!mHasFeature) { 12657 return; 12658 } 12659 12660 Preconditions.checkNotNull(admin, "Admin cannot be null."); 12661 Preconditions.checkNotNull(target, "Target cannot be null."); 12662 12663 enforceProfileOrDeviceOwner(admin); 12664 12665 if (admin.equals(target)) { 12666 throw new IllegalArgumentException("Provided administrator and target are " 12667 + "the same object."); 12668 } 12669 12670 if (admin.getPackageName().equals(target.getPackageName())) { 12671 throw new IllegalArgumentException("Provided administrator and target have " 12672 + "the same package name."); 12673 } 12674 12675 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12676 final DevicePolicyData policy = getUserData(callingUserId); 12677 final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId, 12678 /* throwForMissingPermission= */ true); 12679 checkActiveAdminPrecondition(target, incomingDeviceInfo, policy); 12680 if (!incomingDeviceInfo.supportsTransferOwnership()) { 12681 throw new IllegalArgumentException("Provided target does not support " 12682 + "ownership transfer."); 12683 } 12684 12685 final long id = mInjector.binderClearCallingIdentity(); 12686 try { 12687 synchronized (getLockObject()) { 12688 /* 12689 * We must ensure the whole process is atomic to prevent the device from ending up 12690 * in an invalid state (e.g. no active admin). This could happen if the device 12691 * is rebooted or work mode is turned off mid-transfer. 12692 * In order to guarantee atomicity, we: 12693 * 12694 * 1. Save an atomic journal file describing the transfer process 12695 * 2. Perform the transfer itself 12696 * 3. Delete the journal file 12697 * 12698 * That way if the journal file exists on device boot, we know that the transfer 12699 * must be reverted back to the original administrator. This logic is implemented in 12700 * revertTransferOwnershipIfNecessaryLocked. 12701 * */ 12702 if (bundle == null) { 12703 bundle = new PersistableBundle(); 12704 } 12705 if (isProfileOwner(admin, callingUserId)) { 12706 prepareTransfer(admin, target, bundle, callingUserId, 12707 ADMIN_TYPE_PROFILE_OWNER); 12708 transferProfileOwnershipLocked(admin, target, callingUserId); 12709 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 12710 getTransferOwnershipAdminExtras(bundle), callingUserId); 12711 postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId); 12712 if (isUserAffiliatedWithDeviceLocked(callingUserId)) { 12713 notifyAffiliatedProfileTransferOwnershipComplete(callingUserId); 12714 } 12715 } else if (isDeviceOwner(admin, callingUserId)) { 12716 prepareTransfer(admin, target, bundle, callingUserId, 12717 ADMIN_TYPE_DEVICE_OWNER); 12718 transferDeviceOwnershipLocked(admin, target, callingUserId); 12719 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 12720 getTransferOwnershipAdminExtras(bundle)); 12721 postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId); 12722 } 12723 } 12724 } finally { 12725 mInjector.binderRestoreCallingIdentity(id); 12726 } 12727 } 12728 12729 private void prepareTransfer(ComponentName admin, ComponentName target, 12730 PersistableBundle bundle, int callingUserId, String adminType) { 12731 saveTransferOwnershipBundleLocked(bundle, callingUserId); 12732 mTransferOwnershipMetadataManager.saveMetadataFile( 12733 new TransferOwnershipMetadataManager.Metadata(admin, target, 12734 callingUserId, adminType)); 12735 } 12736 12737 private void postTransfer(String broadcast, int callingUserId) { 12738 deleteTransferOwnershipMetadataFileLocked(); 12739 sendOwnerChangedBroadcast(broadcast, callingUserId); 12740 } 12741 12742 private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) { 12743 final Bundle extras = new Bundle(); 12744 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId)); 12745 sendDeviceOwnerCommand( 12746 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras); 12747 } 12748 12749 /** 12750 * Transfers the profile owner for user with id profileOwnerUserId from admin to target. 12751 */ 12752 private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target, 12753 int profileOwnerUserId) { 12754 transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId); 12755 mOwners.transferProfileOwner(target, profileOwnerUserId); 12756 Slog.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId); 12757 mOwners.writeProfileOwner(profileOwnerUserId); 12758 mDeviceAdminServiceController.startServiceForOwner( 12759 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner"); 12760 } 12761 12762 /** 12763 * Transfers the device owner for user with id userId from admin to target. 12764 */ 12765 private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) { 12766 transferActiveAdminUncheckedLocked(target, admin, userId); 12767 mOwners.transferDeviceOwnership(target); 12768 Slog.i(LOG_TAG, "Device owner set: " + target + " on user " + userId); 12769 mOwners.writeDeviceOwner(); 12770 mDeviceAdminServiceController.startServiceForOwner( 12771 target.getPackageName(), userId, "transfer-device-owner"); 12772 } 12773 12774 private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) { 12775 Bundle extras = new Bundle(); 12776 if (bundle != null) { 12777 extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle); 12778 } 12779 return extras; 12780 } 12781 12782 @Override 12783 public void setStartUserSessionMessage( 12784 ComponentName admin, CharSequence startUserSessionMessage) { 12785 if (!mHasFeature) { 12786 return; 12787 } 12788 Preconditions.checkNotNull(admin); 12789 12790 final String startUserSessionMessageString = 12791 startUserSessionMessage != null ? startUserSessionMessage.toString() : null; 12792 12793 synchronized (getLockObject()) { 12794 final ActiveAdmin deviceOwner = 12795 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12796 12797 if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) { 12798 return; 12799 } 12800 deviceOwner.startUserSessionMessage = startUserSessionMessageString; 12801 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 12802 } 12803 12804 mInjector.getActivityManagerInternal() 12805 .setSwitchingFromSystemUserMessage(startUserSessionMessageString); 12806 } 12807 12808 @Override 12809 public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) { 12810 if (!mHasFeature) { 12811 return; 12812 } 12813 Preconditions.checkNotNull(admin); 12814 12815 final String endUserSessionMessageString = 12816 endUserSessionMessage != null ? endUserSessionMessage.toString() : null; 12817 12818 synchronized (getLockObject()) { 12819 final ActiveAdmin deviceOwner = 12820 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12821 12822 if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) { 12823 return; 12824 } 12825 deviceOwner.endUserSessionMessage = endUserSessionMessageString; 12826 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 12827 } 12828 12829 mInjector.getActivityManagerInternal() 12830 .setSwitchingToSystemUserMessage(endUserSessionMessageString); 12831 } 12832 12833 @Override 12834 public String getStartUserSessionMessage(ComponentName admin) { 12835 if (!mHasFeature) { 12836 return null; 12837 } 12838 Preconditions.checkNotNull(admin); 12839 12840 synchronized (getLockObject()) { 12841 final ActiveAdmin deviceOwner = 12842 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12843 return deviceOwner.startUserSessionMessage; 12844 } 12845 } 12846 12847 @Override 12848 public String getEndUserSessionMessage(ComponentName admin) { 12849 if (!mHasFeature) { 12850 return null; 12851 } 12852 Preconditions.checkNotNull(admin); 12853 12854 synchronized (getLockObject()) { 12855 final ActiveAdmin deviceOwner = 12856 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12857 return deviceOwner.endUserSessionMessage; 12858 } 12859 } 12860 12861 private void deleteTransferOwnershipMetadataFileLocked() { 12862 mTransferOwnershipMetadataManager.deleteMetadataFile(); 12863 } 12864 12865 @Override 12866 @Nullable 12867 public PersistableBundle getTransferOwnershipBundle() { 12868 synchronized (getLockObject()) { 12869 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12870 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12871 final File bundleFile = new File( 12872 mInjector.environmentGetUserSystemDirectory(callingUserId), 12873 TRANSFER_OWNERSHIP_PARAMETERS_XML); 12874 if (!bundleFile.exists()) { 12875 return null; 12876 } 12877 try (FileInputStream stream = new FileInputStream(bundleFile)) { 12878 XmlPullParser parser = Xml.newPullParser(); 12879 parser.setInput(stream, null); 12880 parser.next(); 12881 return PersistableBundle.restoreFromXml(parser); 12882 } catch (IOException | XmlPullParserException | IllegalArgumentException e) { 12883 Slog.e(LOG_TAG, "Caught exception while trying to load the " 12884 + "owner transfer parameters from file " + bundleFile, e); 12885 return null; 12886 } 12887 } 12888 } 12889 12890 @Override 12891 public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) { 12892 if (!mHasFeature) { 12893 return -1; 12894 } 12895 Preconditions.checkNotNull(who, "ComponentName is null in addOverrideApn"); 12896 Preconditions.checkNotNull(apnSetting, "ApnSetting is null in addOverrideApn"); 12897 synchronized (getLockObject()) { 12898 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12899 } 12900 12901 int operatedId = -1; 12902 Uri resultUri; 12903 final long id = mInjector.binderClearCallingIdentity(); 12904 try { 12905 resultUri = mContext.getContentResolver().insert(DPC_URI, apnSetting.toContentValues()); 12906 } finally { 12907 mInjector.binderRestoreCallingIdentity(id); 12908 } 12909 if (resultUri != null) { 12910 try { 12911 operatedId = Integer.parseInt(resultUri.getLastPathSegment()); 12912 } catch (NumberFormatException e) { 12913 Slog.e(LOG_TAG, "Failed to parse inserted override APN id.", e); 12914 } 12915 } 12916 12917 return operatedId; 12918 } 12919 12920 @Override 12921 public boolean updateOverrideApn(@NonNull ComponentName who, int apnId, 12922 @NonNull ApnSetting apnSetting) { 12923 if (!mHasFeature) { 12924 return false; 12925 } 12926 Preconditions.checkNotNull(who, "ComponentName is null in updateOverrideApn"); 12927 Preconditions.checkNotNull(apnSetting, "ApnSetting is null in updateOverrideApn"); 12928 synchronized (getLockObject()) { 12929 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12930 } 12931 12932 if (apnId < 0) { 12933 return false; 12934 } 12935 final long id = mInjector.binderClearCallingIdentity(); 12936 try { 12937 return mContext.getContentResolver().update( 12938 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), 12939 apnSetting.toContentValues(), null, null) > 0; 12940 } finally { 12941 mInjector.binderRestoreCallingIdentity(id); 12942 } 12943 } 12944 12945 @Override 12946 public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) { 12947 if (!mHasFeature) { 12948 return false; 12949 } 12950 Preconditions.checkNotNull(who, "ComponentName is null in removeOverrideApn"); 12951 synchronized (getLockObject()) { 12952 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12953 } 12954 12955 return removeOverrideApnUnchecked(apnId); 12956 } 12957 12958 private boolean removeOverrideApnUnchecked(int apnId) { 12959 if(apnId < 0) { 12960 return false; 12961 } 12962 int numDeleted = 0; 12963 final long id = mInjector.binderClearCallingIdentity(); 12964 try { 12965 numDeleted = mContext.getContentResolver().delete( 12966 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null); 12967 } finally { 12968 mInjector.binderRestoreCallingIdentity(id); 12969 } 12970 return numDeleted > 0; 12971 } 12972 12973 @Override 12974 public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) { 12975 if (!mHasFeature) { 12976 return Collections.emptyList(); 12977 } 12978 Preconditions.checkNotNull(who, "ComponentName is null in getOverrideApns"); 12979 synchronized (getLockObject()) { 12980 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12981 } 12982 12983 return getOverrideApnsUnchecked(); 12984 } 12985 12986 private List<ApnSetting> getOverrideApnsUnchecked() { 12987 final Cursor cursor; 12988 final long id = mInjector.binderClearCallingIdentity(); 12989 try { 12990 cursor = mContext.getContentResolver().query(DPC_URI, null, null, null, null); 12991 } finally { 12992 mInjector.binderRestoreCallingIdentity(id); 12993 } 12994 12995 if (cursor == null) { 12996 return Collections.emptyList(); 12997 } 12998 try { 12999 List<ApnSetting> apnList = new ArrayList<ApnSetting>(); 13000 cursor.moveToPosition(-1); 13001 while (cursor.moveToNext()) { 13002 ApnSetting apn = ApnSetting.makeApnSetting(cursor); 13003 apnList.add(apn); 13004 } 13005 return apnList; 13006 } finally { 13007 cursor.close(); 13008 } 13009 } 13010 13011 @Override 13012 public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) { 13013 if (!mHasFeature) { 13014 return; 13015 } 13016 Preconditions.checkNotNull(who, "ComponentName is null in setOverrideApnEnabled"); 13017 synchronized (getLockObject()) { 13018 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 13019 } 13020 13021 setOverrideApnsEnabledUnchecked(enabled); 13022 } 13023 13024 private void setOverrideApnsEnabledUnchecked(boolean enabled) { 13025 ContentValues value = new ContentValues(); 13026 value.put(ENFORCE_KEY, enabled); 13027 final long id = mInjector.binderClearCallingIdentity(); 13028 try { 13029 mContext.getContentResolver().update( 13030 ENFORCE_MANAGED_URI, value, null, null); 13031 } finally { 13032 mInjector.binderRestoreCallingIdentity(id); 13033 } 13034 } 13035 13036 @Override 13037 public boolean isOverrideApnEnabled(@NonNull ComponentName who) { 13038 if (!mHasFeature) { 13039 return false; 13040 } 13041 Preconditions.checkNotNull(who, "ComponentName is null in isOverrideApnEnabled"); 13042 synchronized (getLockObject()) { 13043 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 13044 } 13045 13046 Cursor enforceCursor; 13047 final long id = mInjector.binderClearCallingIdentity(); 13048 try { 13049 enforceCursor = mContext.getContentResolver().query( 13050 ENFORCE_MANAGED_URI, null, null, null, null); 13051 } finally { 13052 mInjector.binderRestoreCallingIdentity(id); 13053 } 13054 13055 if (enforceCursor == null) { 13056 return false; 13057 } 13058 try { 13059 if (enforceCursor.moveToFirst()) { 13060 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1; 13061 } 13062 } catch (IllegalArgumentException e) { 13063 Slog.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain " 13064 + "correct info.", e); 13065 } finally { 13066 enforceCursor.close(); 13067 } 13068 return false; 13069 } 13070 13071 @VisibleForTesting 13072 void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) { 13073 final File parametersFile = new File( 13074 mInjector.environmentGetUserSystemDirectory(userId), 13075 TRANSFER_OWNERSHIP_PARAMETERS_XML); 13076 final AtomicFile atomicFile = new AtomicFile(parametersFile); 13077 FileOutputStream stream = null; 13078 try { 13079 stream = atomicFile.startWrite(); 13080 final XmlSerializer serializer = new FastXmlSerializer(); 13081 serializer.setOutput(stream, StandardCharsets.UTF_8.name()); 13082 serializer.startDocument(null, true); 13083 serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 13084 bundle.saveToXml(serializer); 13085 serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 13086 serializer.endDocument(); 13087 atomicFile.finishWrite(stream); 13088 } catch (IOException | XmlPullParserException e) { 13089 Slog.e(LOG_TAG, "Caught exception while trying to save the " 13090 + "owner transfer parameters to file " + parametersFile, e); 13091 parametersFile.delete(); 13092 atomicFile.failWrite(stream); 13093 } 13094 } 13095 13096 void deleteTransferOwnershipBundleLocked(int userId) { 13097 final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId), 13098 TRANSFER_OWNERSHIP_PARAMETERS_XML); 13099 parametersFile.delete(); 13100 } 13101 13102 private void maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent, 13103 PasswordMetrics metrics) { 13104 if (SecurityLog.isLoggingEnabled()) { 13105 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 13106 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(), 13107 userId, affectedUserId, metrics.length, metrics.quality, metrics.letters, 13108 metrics.nonLetter, metrics.numeric, metrics.upperCase, metrics.lowerCase, 13109 metrics.symbols); 13110 } 13111 } 13112 13113 private static String getManagedProvisioningPackage(Context context) { 13114 return context.getResources().getString(R.string.config_managed_provisioning_package); 13115 } 13116} 13117