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