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