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