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