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