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