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