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