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