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