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