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