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