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