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