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