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