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