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