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