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