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