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