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