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