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