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