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