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