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