DevicePolicyManagerService.java revision a902e5c255619a21dce3733019e45bfa5359a8c5
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 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) { 2394 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 2395 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i)); 2396 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 2397 } 2398 2399 for (int i=0; i<policy.mLockTaskPackages.size(); i++) { 2400 String component = policy.mLockTaskPackages.get(i); 2401 out.startTag(null, TAG_LOCK_TASK_COMPONENTS); 2402 out.attribute(null, "name", component); 2403 out.endTag(null, TAG_LOCK_TASK_COMPONENTS); 2404 } 2405 2406 if (policy.mStatusBarDisabled) { 2407 out.startTag(null, TAG_STATUS_BAR); 2408 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled)); 2409 out.endTag(null, TAG_STATUS_BAR); 2410 } 2411 2412 if (policy.doNotAskCredentialsOnBoot) { 2413 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 2414 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 2415 } 2416 2417 for (String id : policy.mAffiliationIds) { 2418 out.startTag(null, TAG_AFFILIATION_ID); 2419 out.attribute(null, ATTR_ID, id); 2420 out.endTag(null, TAG_AFFILIATION_ID); 2421 } 2422 2423 if (policy.mLastSecurityLogRetrievalTime >= 0) { 2424 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 2425 out.attribute(null, ATTR_VALUE, 2426 Long.toString(policy.mLastSecurityLogRetrievalTime)); 2427 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 2428 } 2429 2430 if (policy.mLastBugReportRequestTime >= 0) { 2431 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST); 2432 out.attribute(null, ATTR_VALUE, 2433 Long.toString(policy.mLastBugReportRequestTime)); 2434 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST); 2435 } 2436 2437 if (policy.mLastNetworkLogsRetrievalTime >= 0) { 2438 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 2439 out.attribute(null, ATTR_VALUE, 2440 Long.toString(policy.mLastNetworkLogsRetrievalTime)); 2441 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 2442 } 2443 2444 if (policy.mAdminBroadcastPending) { 2445 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING); 2446 out.attribute(null, ATTR_VALUE, 2447 Boolean.toString(policy.mAdminBroadcastPending)); 2448 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING); 2449 } 2450 2451 if (policy.mInitBundle != null) { 2452 out.startTag(null, TAG_INITIALIZATION_BUNDLE); 2453 policy.mInitBundle.saveToXml(out); 2454 out.endTag(null, TAG_INITIALIZATION_BUNDLE); 2455 } 2456 2457 out.endTag(null, "policies"); 2458 2459 out.endDocument(); 2460 stream.flush(); 2461 FileUtils.sync(stream); 2462 stream.close(); 2463 journal.commit(); 2464 sendChangedNotification(userHandle); 2465 } catch (XmlPullParserException | IOException e) { 2466 Slog.w(LOG_TAG, "failed writing file", e); 2467 try { 2468 if (stream != null) { 2469 stream.close(); 2470 } 2471 } catch (IOException ex) { 2472 // Ignore 2473 } 2474 journal.rollback(); 2475 } 2476 } 2477 2478 private void sendChangedNotification(int userHandle) { 2479 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 2480 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 2481 long ident = mInjector.binderClearCallingIdentity(); 2482 try { 2483 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle)); 2484 } finally { 2485 mInjector.binderRestoreCallingIdentity(ident); 2486 } 2487 } 2488 2489 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) { 2490 JournaledFile journal = makeJournaledFile(userHandle); 2491 FileInputStream stream = null; 2492 File file = journal.chooseForRead(); 2493 boolean needsRewrite = false; 2494 try { 2495 stream = new FileInputStream(file); 2496 XmlPullParser parser = Xml.newPullParser(); 2497 parser.setInput(stream, StandardCharsets.UTF_8.name()); 2498 2499 int type; 2500 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 2501 && type != XmlPullParser.START_TAG) { 2502 } 2503 String tag = parser.getName(); 2504 if (!"policies".equals(tag)) { 2505 throw new XmlPullParserException( 2506 "Settings do not start with policies tag: found " + tag); 2507 } 2508 2509 // Extract the permission provider component name if available 2510 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER); 2511 if (permissionProvider != null) { 2512 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider); 2513 } 2514 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE); 2515 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) { 2516 policy.mUserSetupComplete = true; 2517 } 2518 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED); 2519 if (paired != null && Boolean.toString(true).equals(paired)) { 2520 policy.mPaired = true; 2521 } 2522 String deviceProvisioningConfigApplied = parser.getAttributeValue(null, 2523 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED); 2524 if (deviceProvisioningConfigApplied != null 2525 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) { 2526 policy.mDeviceProvisioningConfigApplied = true; 2527 } 2528 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE); 2529 if (!TextUtils.isEmpty(provisioningState)) { 2530 policy.mUserProvisioningState = Integer.parseInt(provisioningState); 2531 } 2532 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY); 2533 if (!TextUtils.isEmpty(permissionPolicy)) { 2534 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy); 2535 } 2536 policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null, 2537 ATTR_DELEGATED_CERT_INSTALLER); 2538 policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null, 2539 ATTR_APPLICATION_RESTRICTIONS_MANAGER); 2540 2541 type = parser.next(); 2542 int outerDepth = parser.getDepth(); 2543 policy.mLockTaskPackages.clear(); 2544 policy.mAdminList.clear(); 2545 policy.mAdminMap.clear(); 2546 policy.mAffiliationIds.clear(); 2547 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 2548 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2549 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 2550 continue; 2551 } 2552 tag = parser.getName(); 2553 if ("admin".equals(tag)) { 2554 String name = parser.getAttributeValue(null, "name"); 2555 try { 2556 DeviceAdminInfo dai = findAdmin( 2557 ComponentName.unflattenFromString(name), userHandle, 2558 /* throwForMissionPermission= */ false); 2559 if (VERBOSE_LOG 2560 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid) 2561 != userHandle)) { 2562 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid " 2563 + dai.getActivityInfo().applicationInfo.uid + " for user " 2564 + userHandle); 2565 } 2566 if (dai != null) { 2567 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false); 2568 ap.readFromXml(parser); 2569 policy.mAdminMap.put(ap.info.getComponent(), ap); 2570 } 2571 } catch (RuntimeException e) { 2572 Slog.w(LOG_TAG, "Failed loading admin " + name, e); 2573 } 2574 } else if ("failed-password-attempts".equals(tag)) { 2575 policy.mFailedPasswordAttempts = Integer.parseInt( 2576 parser.getAttributeValue(null, "value")); 2577 } else if ("password-owner".equals(tag)) { 2578 policy.mPasswordOwner = Integer.parseInt( 2579 parser.getAttributeValue(null, "value")); 2580 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) { 2581 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME)); 2582 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) { 2583 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name")); 2584 } else if (TAG_STATUS_BAR.equals(tag)) { 2585 policy.mStatusBarDisabled = Boolean.parseBoolean( 2586 parser.getAttributeValue(null, ATTR_DISABLED)); 2587 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) { 2588 policy.doNotAskCredentialsOnBoot = true; 2589 } else if (TAG_AFFILIATION_ID.equals(tag)) { 2590 policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID)); 2591 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) { 2592 policy.mLastSecurityLogRetrievalTime = Long.parseLong( 2593 parser.getAttributeValue(null, ATTR_VALUE)); 2594 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) { 2595 policy.mLastBugReportRequestTime = Long.parseLong( 2596 parser.getAttributeValue(null, ATTR_VALUE)); 2597 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) { 2598 policy.mLastNetworkLogsRetrievalTime = Long.parseLong( 2599 parser.getAttributeValue(null, ATTR_VALUE)); 2600 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) { 2601 String pending = parser.getAttributeValue(null, ATTR_VALUE); 2602 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending); 2603 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) { 2604 policy.mInitBundle = PersistableBundle.restoreFromXml(parser); 2605 } else if ("active-password".equals(tag)) { 2606 needsRewrite = true; 2607 } else { 2608 Slog.w(LOG_TAG, "Unknown tag: " + tag); 2609 XmlUtils.skipCurrentTag(parser); 2610 } 2611 } 2612 } catch (FileNotFoundException e) { 2613 // Don't be noisy, this is normal if we haven't defined any policies. 2614 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException 2615 | IndexOutOfBoundsException e) { 2616 Slog.w(LOG_TAG, "failed parsing " + file, e); 2617 } 2618 try { 2619 if (stream != null) { 2620 stream.close(); 2621 } 2622 } catch (IOException e) { 2623 // Ignore 2624 } 2625 2626 // Might need to upgrade the file by rewriting it 2627 if (needsRewrite) { 2628 saveSettingsLocked(userHandle); 2629 } 2630 2631 // Generate a list of admins from the admin map 2632 policy.mAdminList.addAll(policy.mAdminMap.values()); 2633 2634 validatePasswordOwnerLocked(policy); 2635 updateMaximumTimeToLockLocked(userHandle); 2636 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle); 2637 if (policy.mStatusBarDisabled) { 2638 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle); 2639 } 2640 } 2641 2642 private void updateLockTaskPackagesLocked(List<String> packages, int userId) { 2643 long ident = mInjector.binderClearCallingIdentity(); 2644 try { 2645 mInjector.getIActivityManager() 2646 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()])); 2647 } catch (RemoteException e) { 2648 // Not gonna happen. 2649 } finally { 2650 mInjector.binderRestoreCallingIdentity(ident); 2651 } 2652 } 2653 2654 private void updateDeviceOwnerLocked() { 2655 long ident = mInjector.binderClearCallingIdentity(); 2656 try { 2657 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the 2658 // user id and also protect all other DAs too. 2659 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 2660 if (deviceOwnerComponent != null) { 2661 mInjector.getIActivityManager() 2662 .updateDeviceOwner(deviceOwnerComponent.getPackageName()); 2663 } 2664 } catch (RemoteException e) { 2665 // Not gonna happen. 2666 } finally { 2667 mInjector.binderRestoreCallingIdentity(ident); 2668 } 2669 } 2670 2671 static void validateQualityConstant(int quality) { 2672 switch (quality) { 2673 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED: 2674 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK: 2675 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: 2676 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: 2677 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX: 2678 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: 2679 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: 2680 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX: 2681 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED: 2682 return; 2683 } 2684 throw new IllegalArgumentException("Invalid quality constant: 0x" 2685 + Integer.toHexString(quality)); 2686 } 2687 2688 void validatePasswordOwnerLocked(DevicePolicyData policy) { 2689 if (policy.mPasswordOwner >= 0) { 2690 boolean haveOwner = false; 2691 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 2692 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) { 2693 haveOwner = true; 2694 break; 2695 } 2696 } 2697 if (!haveOwner) { 2698 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner 2699 + " no longer active; disabling"); 2700 policy.mPasswordOwner = -1; 2701 } 2702 } 2703 } 2704 2705 @VisibleForTesting 2706 void systemReady(int phase) { 2707 if (!mHasFeature) { 2708 return; 2709 } 2710 switch (phase) { 2711 case SystemService.PHASE_LOCK_SETTINGS_READY: 2712 onLockSettingsReady(); 2713 break; 2714 case SystemService.PHASE_BOOT_COMPLETED: 2715 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this. 2716 break; 2717 } 2718 } 2719 2720 private void onLockSettingsReady() { 2721 getUserData(UserHandle.USER_SYSTEM); 2722 loadOwners(); 2723 cleanUpOldUsers(); 2724 2725 onStartUser(UserHandle.USER_SYSTEM); 2726 2727 // Register an observer for watching for user setup complete. 2728 new SetupContentObserver(mHandler).register(); 2729 // Initialize the user setup state, to handle the upgrade case. 2730 updateUserSetupCompleteAndPaired(); 2731 2732 List<String> packageList; 2733 synchronized (this) { 2734 packageList = getKeepUninstalledPackagesLocked(); 2735 } 2736 if (packageList != null) { 2737 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 2738 } 2739 2740 synchronized (this) { 2741 // push the force-ephemeral-users policy to the user manager. 2742 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 2743 if (deviceOwner != null) { 2744 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers); 2745 } 2746 } 2747 } 2748 2749 private void ensureDeviceOwnerUserStarted() { 2750 final int userId; 2751 synchronized (this) { 2752 if (!mOwners.hasDeviceOwner()) { 2753 return; 2754 } 2755 userId = mOwners.getDeviceOwnerUserId(); 2756 } 2757 if (VERBOSE_LOG) { 2758 Log.v(LOG_TAG, "Starting non-system DO user: " + userId); 2759 } 2760 if (userId != UserHandle.USER_SYSTEM) { 2761 try { 2762 mInjector.getIActivityManager().startUserInBackground(userId); 2763 2764 // STOPSHIP Prevent the DO user from being killed. 2765 2766 } catch (RemoteException e) { 2767 Slog.w(LOG_TAG, "Exception starting user", e); 2768 } 2769 } 2770 } 2771 2772 private void onStartUser(int userId) { 2773 updateScreenCaptureDisabledInWindowManager(userId, 2774 getScreenCaptureDisabled(null, userId)); 2775 pushUserRestrictions(userId); 2776 } 2777 2778 private void cleanUpOldUsers() { 2779 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled 2780 // before reboot 2781 Set<Integer> usersWithProfileOwners; 2782 Set<Integer> usersWithData; 2783 synchronized(this) { 2784 usersWithProfileOwners = mOwners.getProfileOwnerKeys(); 2785 usersWithData = new ArraySet<>(); 2786 for (int i = 0; i < mUserData.size(); i++) { 2787 usersWithData.add(mUserData.keyAt(i)); 2788 } 2789 } 2790 List<UserInfo> allUsers = mUserManager.getUsers(); 2791 2792 Set<Integer> deletedUsers = new ArraySet<>(); 2793 deletedUsers.addAll(usersWithProfileOwners); 2794 deletedUsers.addAll(usersWithData); 2795 for (UserInfo userInfo : allUsers) { 2796 deletedUsers.remove(userInfo.id); 2797 } 2798 for (Integer userId : deletedUsers) { 2799 removeUserData(userId); 2800 } 2801 } 2802 2803 private void handlePasswordExpirationNotification(int userHandle) { 2804 synchronized (this) { 2805 final long now = System.currentTimeMillis(); 2806 2807 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 2808 userHandle, /* parent */ false); 2809 final int N = admins.size(); 2810 for (int i = 0; i < N; i++) { 2811 ActiveAdmin admin = admins.get(i); 2812 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD) 2813 && admin.passwordExpirationTimeout > 0L 2814 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS 2815 && admin.passwordExpirationDate > 0L) { 2816 sendAdminCommandLocked(admin, 2817 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING); 2818 } 2819 } 2820 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false); 2821 } 2822 } 2823 2824 private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> { 2825 @Override 2826 protected Void doInBackground(Integer... params) { 2827 int userHandle = params[0]; 2828 2829 if (userHandle == UserHandle.USER_ALL) { 2830 for (UserInfo userInfo : mUserManager.getUsers(true)) { 2831 manageNotification(userInfo.getUserHandle()); 2832 } 2833 } else { 2834 manageNotification(UserHandle.of(userHandle)); 2835 } 2836 return null; 2837 } 2838 2839 private void manageNotification(UserHandle userHandle) { 2840 if (!mUserManager.isUserUnlocked(userHandle)) { 2841 return; 2842 } 2843 2844 // Call out to KeyChain to check for CAs which are waiting for approval. 2845 final List<String> pendingCertificates; 2846 try { 2847 pendingCertificates = getInstalledCaCertificates(userHandle); 2848 } catch (RemoteException | RuntimeException e) { 2849 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e); 2850 return; 2851 } 2852 2853 synchronized (DevicePolicyManagerService.this) { 2854 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 2855 2856 // Remove deleted certificates. Flush xml if necessary. 2857 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) { 2858 saveSettingsLocked(userHandle.getIdentifier()); 2859 } 2860 // Trim to approved certificates. 2861 pendingCertificates.removeAll(policy.mAcceptedCaCertificates); 2862 } 2863 2864 if (pendingCertificates.isEmpty()) { 2865 mInjector.getNotificationManager().cancelAsUser( 2866 null, MONITORING_CERT_NOTIFICATION_ID, userHandle); 2867 return; 2868 } 2869 2870 // Build and show a warning notification 2871 int smallIconId; 2872 String contentText; 2873 int parentUserId = userHandle.getIdentifier(); 2874 if (getProfileOwner(userHandle.getIdentifier()) != null) { 2875 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, 2876 getProfileOwnerName(userHandle.getIdentifier())); 2877 smallIconId = R.drawable.stat_sys_certificate_info; 2878 parentUserId = getProfileParentId(userHandle.getIdentifier()); 2879 } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) { 2880 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, 2881 getDeviceOwnerName()); 2882 smallIconId = R.drawable.stat_sys_certificate_info; 2883 } else { 2884 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown); 2885 smallIconId = android.R.drawable.stat_sys_warning; 2886 } 2887 2888 final int numberOfCertificates = pendingCertificates.size(); 2889 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO); 2890 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 2891 dialogIntent.setPackage("com.android.settings"); 2892 dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates); 2893 dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier()); 2894 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0, 2895 dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, 2896 new UserHandle(parentUserId)); 2897 2898 final Context userContext; 2899 try { 2900 final String packageName = mContext.getPackageName(); 2901 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle); 2902 } catch (PackageManager.NameNotFoundException e) { 2903 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e); 2904 return; 2905 } 2906 final Notification noti = new Notification.Builder(userContext) 2907 .setSmallIcon(smallIconId) 2908 .setContentTitle(mContext.getResources().getQuantityText( 2909 R.plurals.ssl_ca_cert_warning, numberOfCertificates)) 2910 .setContentText(contentText) 2911 .setContentIntent(notifyIntent) 2912 .setPriority(Notification.PRIORITY_HIGH) 2913 .setShowWhen(false) 2914 .setColor(mContext.getColor( 2915 com.android.internal.R.color.system_notification_accent_color)) 2916 .build(); 2917 2918 mInjector.getNotificationManager().notifyAsUser( 2919 null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle); 2920 } 2921 2922 private List<String> getInstalledCaCertificates(UserHandle userHandle) 2923 throws RemoteException, RuntimeException { 2924 KeyChainConnection conn = null; 2925 try { 2926 conn = KeyChain.bindAsUser(mContext, userHandle); 2927 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList(); 2928 List<String> result = new ArrayList<>(aliases.size()); 2929 for (int i = 0; i < aliases.size(); i++) { 2930 result.add(aliases.get(i).string); 2931 } 2932 return result; 2933 } catch (InterruptedException e) { 2934 Thread.currentThread().interrupt(); 2935 return null; 2936 } catch (AssertionError e) { 2937 throw new RuntimeException(e); 2938 } finally { 2939 if (conn != null) { 2940 conn.close(); 2941 } 2942 } 2943 } 2944 } 2945 2946 /** 2947 * @param adminReceiver The admin to add 2948 * @param refreshing true = update an active admin, no error 2949 */ 2950 @Override 2951 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) { 2952 if (!mHasFeature) { 2953 return; 2954 } 2955 setActiveAdmin(adminReceiver, refreshing, userHandle, null); 2956 } 2957 2958 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, 2959 Bundle onEnableData) { 2960 mContext.enforceCallingOrSelfPermission( 2961 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 2962 enforceFullCrossUsersPermission(userHandle); 2963 2964 DevicePolicyData policy = getUserData(userHandle); 2965 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle, 2966 /* throwForMissionPermission= */ true); 2967 if (info == null) { 2968 throw new IllegalArgumentException("Bad admin: " + adminReceiver); 2969 } 2970 if (!info.getActivityInfo().applicationInfo.isInternal()) { 2971 throw new IllegalArgumentException("Only apps in internal storage can be active admin: " 2972 + adminReceiver); 2973 } 2974 synchronized (this) { 2975 long ident = mInjector.binderClearCallingIdentity(); 2976 try { 2977 final ActiveAdmin existingAdmin 2978 = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 2979 if (!refreshing && existingAdmin != null) { 2980 throw new IllegalArgumentException("Admin is already added"); 2981 } 2982 if (policy.mRemovingAdmins.contains(adminReceiver)) { 2983 throw new IllegalArgumentException( 2984 "Trying to set an admin which is being removed"); 2985 } 2986 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false); 2987 newAdmin.testOnlyAdmin = 2988 (existingAdmin != null) ? existingAdmin.testOnlyAdmin 2989 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle); 2990 policy.mAdminMap.put(adminReceiver, newAdmin); 2991 int replaceIndex = -1; 2992 final int N = policy.mAdminList.size(); 2993 for (int i=0; i < N; i++) { 2994 ActiveAdmin oldAdmin = policy.mAdminList.get(i); 2995 if (oldAdmin.info.getComponent().equals(adminReceiver)) { 2996 replaceIndex = i; 2997 break; 2998 } 2999 } 3000 if (replaceIndex == -1) { 3001 policy.mAdminList.add(newAdmin); 3002 enableIfNecessary(info.getPackageName(), userHandle); 3003 } else { 3004 policy.mAdminList.set(replaceIndex, newAdmin); 3005 } 3006 saveSettingsLocked(userHandle); 3007 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3008 onEnableData, null); 3009 } finally { 3010 mInjector.binderRestoreCallingIdentity(ident); 3011 } 3012 } 3013 } 3014 3015 @Override 3016 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) { 3017 if (!mHasFeature) { 3018 return false; 3019 } 3020 enforceFullCrossUsersPermission(userHandle); 3021 synchronized (this) { 3022 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null; 3023 } 3024 } 3025 3026 @Override 3027 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) { 3028 if (!mHasFeature) { 3029 return false; 3030 } 3031 enforceFullCrossUsersPermission(userHandle); 3032 synchronized (this) { 3033 DevicePolicyData policyData = getUserData(userHandle); 3034 return policyData.mRemovingAdmins.contains(adminReceiver); 3035 } 3036 } 3037 3038 @Override 3039 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) { 3040 if (!mHasFeature) { 3041 return false; 3042 } 3043 enforceFullCrossUsersPermission(userHandle); 3044 synchronized (this) { 3045 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3046 if (administrator == null) { 3047 throw new SecurityException("No active admin " + adminReceiver); 3048 } 3049 return administrator.info.usesPolicy(policyId); 3050 } 3051 } 3052 3053 @Override 3054 @SuppressWarnings("unchecked") 3055 public List<ComponentName> getActiveAdmins(int userHandle) { 3056 if (!mHasFeature) { 3057 return Collections.EMPTY_LIST; 3058 } 3059 3060 enforceFullCrossUsersPermission(userHandle); 3061 synchronized (this) { 3062 DevicePolicyData policy = getUserData(userHandle); 3063 final int N = policy.mAdminList.size(); 3064 if (N <= 0) { 3065 return null; 3066 } 3067 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N); 3068 for (int i=0; i<N; i++) { 3069 res.add(policy.mAdminList.get(i).info.getComponent()); 3070 } 3071 return res; 3072 } 3073 } 3074 3075 @Override 3076 public boolean packageHasActiveAdmins(String packageName, int userHandle) { 3077 if (!mHasFeature) { 3078 return false; 3079 } 3080 enforceFullCrossUsersPermission(userHandle); 3081 synchronized (this) { 3082 DevicePolicyData policy = getUserData(userHandle); 3083 final int N = policy.mAdminList.size(); 3084 for (int i=0; i<N; i++) { 3085 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) { 3086 return true; 3087 } 3088 } 3089 return false; 3090 } 3091 } 3092 3093 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) { 3094 if (!mHasFeature) { 3095 return; 3096 } 3097 Preconditions.checkNotNull(adminReceiver, "ComponentName is null"); 3098 enforceShell("forceRemoveActiveAdmin"); 3099 long ident = mInjector.binderClearCallingIdentity(); 3100 try { 3101 synchronized (this) { 3102 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) { 3103 throw new SecurityException("Attempt to remove non-test admin " 3104 + adminReceiver + " " + userHandle); 3105 } 3106 3107 // If admin is a device or profile owner tidy that up first. 3108 if (isDeviceOwner(adminReceiver, userHandle)) { 3109 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle); 3110 clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userHandle)); 3111 } 3112 if (isProfileOwner(adminReceiver, userHandle)) { 3113 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, 3114 userHandle, /* parent */ false); 3115 clearProfileOwnerLocked(admin, userHandle); 3116 } 3117 } 3118 // Remove the admin skipping sending the broadcast. 3119 removeAdminArtifacts(adminReceiver, userHandle); 3120 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle); 3121 } finally { 3122 mInjector.binderRestoreCallingIdentity(ident); 3123 } 3124 } 3125 3126 // It's temporary solution to clear DISALLOW_ADD_USER after CTS 3127 // TODO: b/31952368 when the restriction is moved from system to the device owner, 3128 // it can be removed. 3129 private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) { 3130 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) { 3131 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle); 3132 } 3133 } 3134 3135 /** 3136 * Return if a given package has testOnly="true", in which case we'll relax certain rules 3137 * for CTS. 3138 * 3139 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked} 3140 * to check wehter an active admin is test-only or not. 3141 * 3142 * The system allows this flag to be changed when an app is updated, which is not good 3143 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed, 3144 * and used the persisted version in actual checks. (See b/31382361 and b/28928996) 3145 */ 3146 private boolean isPackageTestOnly(String packageName, int userHandle) { 3147 final ApplicationInfo ai; 3148 try { 3149 ai = mIPackageManager.getApplicationInfo(packageName, 3150 (PackageManager.MATCH_DIRECT_BOOT_AWARE 3151 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle); 3152 } catch (RemoteException e) { 3153 throw new IllegalStateException(e); 3154 } 3155 if (ai == null) { 3156 throw new IllegalStateException("Couldn't find package: " 3157 + packageName + " on user " + userHandle); 3158 } 3159 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0; 3160 } 3161 3162 /** 3163 * See {@link #isPackageTestOnly}. 3164 */ 3165 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) { 3166 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3167 return (admin != null) && admin.testOnlyAdmin; 3168 } 3169 3170 private void enforceShell(String method) { 3171 final int callingUid = Binder.getCallingUid(); 3172 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) { 3173 throw new SecurityException("Non-shell user attempted to call " + method); 3174 } 3175 } 3176 3177 @Override 3178 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) { 3179 if (!mHasFeature) { 3180 return; 3181 } 3182 enforceFullCrossUsersPermission(userHandle); 3183 enforceUserUnlocked(userHandle); 3184 synchronized (this) { 3185 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3186 if (admin == null) { 3187 return; 3188 } 3189 // Active device/profile owners must remain active admins. 3190 if (isDeviceOwner(adminReceiver, userHandle) 3191 || isProfileOwner(adminReceiver, userHandle)) { 3192 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" + 3193 adminReceiver); 3194 return; 3195 } 3196 if (admin.getUid() != mInjector.binderGetCallingUid()) { 3197 mContext.enforceCallingOrSelfPermission( 3198 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 3199 } 3200 long ident = mInjector.binderClearCallingIdentity(); 3201 try { 3202 removeActiveAdminLocked(adminReceiver, userHandle); 3203 } finally { 3204 mInjector.binderRestoreCallingIdentity(ident); 3205 } 3206 } 3207 } 3208 3209 @Override 3210 public boolean isSeparateProfileChallengeAllowed(int userHandle) { 3211 ComponentName profileOwner = getProfileOwner(userHandle); 3212 // Profile challenge is supported on N or newer release. 3213 return profileOwner != null && 3214 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M; 3215 } 3216 3217 @Override 3218 public void setPasswordQuality(ComponentName who, int quality, boolean parent) { 3219 if (!mHasFeature) { 3220 return; 3221 } 3222 Preconditions.checkNotNull(who, "ComponentName is null"); 3223 validateQualityConstant(quality); 3224 3225 synchronized (this) { 3226 ActiveAdmin ap = getActiveAdminForCallerLocked( 3227 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3228 if (ap.minimumPasswordMetrics.quality != quality) { 3229 ap.minimumPasswordMetrics.quality = quality; 3230 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3231 } 3232 } 3233 } 3234 3235 @Override 3236 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) { 3237 if (!mHasFeature) { 3238 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 3239 } 3240 enforceFullCrossUsersPermission(userHandle); 3241 synchronized (this) { 3242 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 3243 3244 if (who != null) { 3245 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3246 return admin != null ? admin.minimumPasswordMetrics.quality : mode; 3247 } 3248 3249 // Return the strictest policy across all participating admins. 3250 List<ActiveAdmin> admins = 3251 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3252 final int N = admins.size(); 3253 for (int i = 0; i < N; i++) { 3254 ActiveAdmin admin = admins.get(i); 3255 if (mode < admin.minimumPasswordMetrics.quality) { 3256 mode = admin.minimumPasswordMetrics.quality; 3257 } 3258 } 3259 return mode; 3260 } 3261 } 3262 3263 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked( 3264 int userHandle, boolean parent) { 3265 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) { 3266 // If this user has a separate challenge, only return its restrictions. 3267 return getUserDataUnchecked(userHandle).mAdminList; 3268 } else { 3269 // Return all admins for this user and the profiles that are visible from this 3270 // user that do not use a separate work challenge. 3271 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>(); 3272 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 3273 DevicePolicyData policy = getUserData(userInfo.id); 3274 if (!userInfo.isManagedProfile()) { 3275 admins.addAll(policy.mAdminList); 3276 } else { 3277 // For managed profiles, we always include the policies set on the parent 3278 // profile. Additionally, we include the ones set on the managed profile 3279 // if no separate challenge is in place. 3280 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id); 3281 final int N = policy.mAdminList.size(); 3282 for (int i = 0; i < N; i++) { 3283 ActiveAdmin admin = policy.mAdminList.get(i); 3284 if (admin.hasParentActiveAdmin()) { 3285 admins.add(admin.getParentActiveAdmin()); 3286 } 3287 if (!hasSeparateChallenge) { 3288 admins.add(admin); 3289 } 3290 } 3291 } 3292 } 3293 return admins; 3294 } 3295 } 3296 3297 private boolean isSeparateProfileChallengeEnabled(int userHandle) { 3298 long ident = mInjector.binderClearCallingIdentity(); 3299 try { 3300 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle); 3301 } finally { 3302 mInjector.binderRestoreCallingIdentity(ident); 3303 } 3304 } 3305 3306 @Override 3307 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) { 3308 if (!mHasFeature) { 3309 return; 3310 } 3311 Preconditions.checkNotNull(who, "ComponentName is null"); 3312 synchronized (this) { 3313 ActiveAdmin ap = getActiveAdminForCallerLocked( 3314 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3315 if (ap.minimumPasswordMetrics.length != length) { 3316 ap.minimumPasswordMetrics.length = length; 3317 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3318 } 3319 } 3320 } 3321 3322 @Override 3323 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) { 3324 if (!mHasFeature) { 3325 return 0; 3326 } 3327 enforceFullCrossUsersPermission(userHandle); 3328 synchronized (this) { 3329 int length = 0; 3330 3331 if (who != null) { 3332 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3333 return admin != null ? admin.minimumPasswordMetrics.length : length; 3334 } 3335 3336 // Return the strictest policy across all participating admins. 3337 List<ActiveAdmin> admins = 3338 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3339 final int N = admins.size(); 3340 for (int i = 0; i < N; i++) { 3341 ActiveAdmin admin = admins.get(i); 3342 if (length < admin.minimumPasswordMetrics.length) { 3343 length = admin.minimumPasswordMetrics.length; 3344 } 3345 } 3346 return length; 3347 } 3348 } 3349 3350 @Override 3351 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) { 3352 if (!mHasFeature) { 3353 return; 3354 } 3355 Preconditions.checkNotNull(who, "ComponentName is null"); 3356 synchronized (this) { 3357 ActiveAdmin ap = getActiveAdminForCallerLocked( 3358 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3359 if (ap.passwordHistoryLength != length) { 3360 ap.passwordHistoryLength = length; 3361 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3362 } 3363 } 3364 } 3365 3366 @Override 3367 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) { 3368 if (!mHasFeature) { 3369 return 0; 3370 } 3371 enforceFullCrossUsersPermission(userHandle); 3372 synchronized (this) { 3373 int length = 0; 3374 3375 if (who != null) { 3376 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3377 return admin != null ? admin.passwordHistoryLength : length; 3378 } 3379 3380 // Return the strictest policy across all participating admins. 3381 List<ActiveAdmin> admins = 3382 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3383 final int N = admins.size(); 3384 for (int i = 0; i < N; i++) { 3385 ActiveAdmin admin = admins.get(i); 3386 if (length < admin.passwordHistoryLength) { 3387 length = admin.passwordHistoryLength; 3388 } 3389 } 3390 3391 return length; 3392 } 3393 } 3394 3395 @Override 3396 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) { 3397 if (!mHasFeature) { 3398 return; 3399 } 3400 Preconditions.checkNotNull(who, "ComponentName is null"); 3401 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms"); 3402 final int userHandle = mInjector.userHandleGetCallingUserId(); 3403 synchronized (this) { 3404 ActiveAdmin ap = getActiveAdminForCallerLocked( 3405 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent); 3406 // Calling this API automatically bumps the expiration date 3407 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 3408 ap.passwordExpirationDate = expiration; 3409 ap.passwordExpirationTimeout = timeout; 3410 if (timeout > 0L) { 3411 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 3412 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 3413 .format(new Date(expiration))); 3414 } 3415 saveSettingsLocked(userHandle); 3416 3417 // in case this is the first one, set the alarm on the appropriate user. 3418 setExpirationAlarmCheckLocked(mContext, userHandle, parent); 3419 } 3420 } 3421 3422 /** 3423 * Return a single admin's expiration cycle time, or the min of all cycle times. 3424 * Returns 0 if not configured. 3425 */ 3426 @Override 3427 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) { 3428 if (!mHasFeature) { 3429 return 0L; 3430 } 3431 enforceFullCrossUsersPermission(userHandle); 3432 synchronized (this) { 3433 long timeout = 0L; 3434 3435 if (who != null) { 3436 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3437 return admin != null ? admin.passwordExpirationTimeout : timeout; 3438 } 3439 3440 // Return the strictest policy across all participating admins. 3441 List<ActiveAdmin> admins = 3442 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3443 final int N = admins.size(); 3444 for (int i = 0; i < N; i++) { 3445 ActiveAdmin admin = admins.get(i); 3446 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 3447 && timeout > admin.passwordExpirationTimeout)) { 3448 timeout = admin.passwordExpirationTimeout; 3449 } 3450 } 3451 return timeout; 3452 } 3453 } 3454 3455 @Override 3456 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { 3457 final int userId = UserHandle.getCallingUserId(); 3458 List<String> changedProviders = null; 3459 3460 synchronized (this) { 3461 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 3462 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3463 if (activeAdmin.crossProfileWidgetProviders == null) { 3464 activeAdmin.crossProfileWidgetProviders = new ArrayList<>(); 3465 } 3466 List<String> providers = activeAdmin.crossProfileWidgetProviders; 3467 if (!providers.contains(packageName)) { 3468 providers.add(packageName); 3469 changedProviders = new ArrayList<>(providers); 3470 saveSettingsLocked(userId); 3471 } 3472 } 3473 3474 if (changedProviders != null) { 3475 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 3476 return true; 3477 } 3478 3479 return false; 3480 } 3481 3482 @Override 3483 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { 3484 final int userId = UserHandle.getCallingUserId(); 3485 List<String> changedProviders = null; 3486 3487 synchronized (this) { 3488 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 3489 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3490 if (activeAdmin.crossProfileWidgetProviders == null 3491 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 3492 return false; 3493 } 3494 List<String> providers = activeAdmin.crossProfileWidgetProviders; 3495 if (providers.remove(packageName)) { 3496 changedProviders = new ArrayList<>(providers); 3497 saveSettingsLocked(userId); 3498 } 3499 } 3500 3501 if (changedProviders != null) { 3502 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 3503 return true; 3504 } 3505 3506 return false; 3507 } 3508 3509 @Override 3510 public List<String> getCrossProfileWidgetProviders(ComponentName admin) { 3511 synchronized (this) { 3512 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 3513 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3514 if (activeAdmin.crossProfileWidgetProviders == null 3515 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 3516 return null; 3517 } 3518 if (mInjector.binderIsCallingUidMyUid()) { 3519 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders); 3520 } else { 3521 return activeAdmin.crossProfileWidgetProviders; 3522 } 3523 } 3524 } 3525 3526 /** 3527 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 3528 * Returns 0 if not configured. 3529 */ 3530 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) { 3531 long timeout = 0L; 3532 3533 if (who != null) { 3534 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3535 return admin != null ? admin.passwordExpirationDate : timeout; 3536 } 3537 3538 // Return the strictest policy across all participating admins. 3539 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3540 final int N = admins.size(); 3541 for (int i = 0; i < N; i++) { 3542 ActiveAdmin admin = admins.get(i); 3543 if (timeout == 0L || (admin.passwordExpirationDate != 0 3544 && timeout > admin.passwordExpirationDate)) { 3545 timeout = admin.passwordExpirationDate; 3546 } 3547 } 3548 return timeout; 3549 } 3550 3551 @Override 3552 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) { 3553 if (!mHasFeature) { 3554 return 0L; 3555 } 3556 enforceFullCrossUsersPermission(userHandle); 3557 synchronized (this) { 3558 return getPasswordExpirationLocked(who, userHandle, parent); 3559 } 3560 } 3561 3562 @Override 3563 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) { 3564 if (!mHasFeature) { 3565 return; 3566 } 3567 Preconditions.checkNotNull(who, "ComponentName is null"); 3568 synchronized (this) { 3569 ActiveAdmin ap = getActiveAdminForCallerLocked( 3570 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3571 if (ap.minimumPasswordMetrics.upperCase != length) { 3572 ap.minimumPasswordMetrics.upperCase = length; 3573 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3574 } 3575 } 3576 } 3577 3578 @Override 3579 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) { 3580 if (!mHasFeature) { 3581 return 0; 3582 } 3583 enforceFullCrossUsersPermission(userHandle); 3584 synchronized (this) { 3585 int length = 0; 3586 3587 if (who != null) { 3588 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3589 return admin != null ? admin.minimumPasswordMetrics.upperCase : length; 3590 } 3591 3592 // Return the strictest policy across all participating admins. 3593 List<ActiveAdmin> admins = 3594 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3595 final int N = admins.size(); 3596 for (int i = 0; i < N; i++) { 3597 ActiveAdmin admin = admins.get(i); 3598 if (length < admin.minimumPasswordMetrics.upperCase) { 3599 length = admin.minimumPasswordMetrics.upperCase; 3600 } 3601 } 3602 return length; 3603 } 3604 } 3605 3606 @Override 3607 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) { 3608 Preconditions.checkNotNull(who, "ComponentName is null"); 3609 synchronized (this) { 3610 ActiveAdmin ap = getActiveAdminForCallerLocked( 3611 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3612 if (ap.minimumPasswordMetrics.lowerCase != length) { 3613 ap.minimumPasswordMetrics.lowerCase = length; 3614 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3615 } 3616 } 3617 } 3618 3619 @Override 3620 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) { 3621 if (!mHasFeature) { 3622 return 0; 3623 } 3624 enforceFullCrossUsersPermission(userHandle); 3625 synchronized (this) { 3626 int length = 0; 3627 3628 if (who != null) { 3629 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3630 return admin != null ? admin.minimumPasswordMetrics.lowerCase : length; 3631 } 3632 3633 // Return the strictest policy across all participating admins. 3634 List<ActiveAdmin> admins = 3635 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3636 final int N = admins.size(); 3637 for (int i = 0; i < N; i++) { 3638 ActiveAdmin admin = admins.get(i); 3639 if (length < admin.minimumPasswordMetrics.lowerCase) { 3640 length = admin.minimumPasswordMetrics.lowerCase; 3641 } 3642 } 3643 return length; 3644 } 3645 } 3646 3647 @Override 3648 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) { 3649 if (!mHasFeature) { 3650 return; 3651 } 3652 Preconditions.checkNotNull(who, "ComponentName is null"); 3653 synchronized (this) { 3654 ActiveAdmin ap = getActiveAdminForCallerLocked( 3655 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3656 if (ap.minimumPasswordMetrics.letters != length) { 3657 ap.minimumPasswordMetrics.letters = length; 3658 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3659 } 3660 } 3661 } 3662 3663 @Override 3664 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) { 3665 if (!mHasFeature) { 3666 return 0; 3667 } 3668 enforceFullCrossUsersPermission(userHandle); 3669 synchronized (this) { 3670 int length = 0; 3671 3672 if (who != null) { 3673 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3674 return admin != null ? admin.minimumPasswordMetrics.letters : length; 3675 } 3676 3677 // Return the strictest policy across all participating admins. 3678 List<ActiveAdmin> admins = 3679 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3680 final int N = admins.size(); 3681 for (int i = 0; i < N; i++) { 3682 ActiveAdmin admin = admins.get(i); 3683 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 3684 continue; 3685 } 3686 if (length < admin.minimumPasswordMetrics.letters) { 3687 length = admin.minimumPasswordMetrics.letters; 3688 } 3689 } 3690 return length; 3691 } 3692 } 3693 3694 @Override 3695 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) { 3696 if (!mHasFeature) { 3697 return; 3698 } 3699 Preconditions.checkNotNull(who, "ComponentName is null"); 3700 synchronized (this) { 3701 ActiveAdmin ap = getActiveAdminForCallerLocked( 3702 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3703 if (ap.minimumPasswordMetrics.numeric != length) { 3704 ap.minimumPasswordMetrics.numeric = length; 3705 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3706 } 3707 } 3708 } 3709 3710 @Override 3711 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) { 3712 if (!mHasFeature) { 3713 return 0; 3714 } 3715 enforceFullCrossUsersPermission(userHandle); 3716 synchronized (this) { 3717 int length = 0; 3718 3719 if (who != null) { 3720 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3721 return admin != null ? admin.minimumPasswordMetrics.numeric : length; 3722 } 3723 3724 // Return the strictest policy across all participating admins. 3725 List<ActiveAdmin> admins = 3726 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3727 final int N = admins.size(); 3728 for (int i = 0; i < N; i++) { 3729 ActiveAdmin admin = admins.get(i); 3730 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 3731 continue; 3732 } 3733 if (length < admin.minimumPasswordMetrics.numeric) { 3734 length = admin.minimumPasswordMetrics.numeric; 3735 } 3736 } 3737 return length; 3738 } 3739 } 3740 3741 @Override 3742 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) { 3743 if (!mHasFeature) { 3744 return; 3745 } 3746 Preconditions.checkNotNull(who, "ComponentName is null"); 3747 synchronized (this) { 3748 ActiveAdmin ap = getActiveAdminForCallerLocked( 3749 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3750 if (ap.minimumPasswordMetrics.symbols != length) { 3751 ap.minimumPasswordMetrics.symbols = length; 3752 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3753 } 3754 } 3755 } 3756 3757 @Override 3758 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) { 3759 if (!mHasFeature) { 3760 return 0; 3761 } 3762 enforceFullCrossUsersPermission(userHandle); 3763 synchronized (this) { 3764 int length = 0; 3765 3766 if (who != null) { 3767 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3768 return admin != null ? admin.minimumPasswordMetrics.symbols : length; 3769 } 3770 3771 // Return the strictest policy across all participating admins. 3772 List<ActiveAdmin> admins = 3773 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3774 final int N = admins.size(); 3775 for (int i = 0; i < N; i++) { 3776 ActiveAdmin admin = admins.get(i); 3777 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 3778 continue; 3779 } 3780 if (length < admin.minimumPasswordMetrics.symbols) { 3781 length = admin.minimumPasswordMetrics.symbols; 3782 } 3783 } 3784 return length; 3785 } 3786 } 3787 3788 @Override 3789 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) { 3790 if (!mHasFeature) { 3791 return; 3792 } 3793 Preconditions.checkNotNull(who, "ComponentName is null"); 3794 synchronized (this) { 3795 ActiveAdmin ap = getActiveAdminForCallerLocked( 3796 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3797 if (ap.minimumPasswordMetrics.nonLetter != length) { 3798 ap.minimumPasswordMetrics.nonLetter = length; 3799 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3800 } 3801 } 3802 } 3803 3804 @Override 3805 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) { 3806 if (!mHasFeature) { 3807 return 0; 3808 } 3809 enforceFullCrossUsersPermission(userHandle); 3810 synchronized (this) { 3811 int length = 0; 3812 3813 if (who != null) { 3814 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3815 return admin != null ? admin.minimumPasswordMetrics.nonLetter : length; 3816 } 3817 3818 // Return the strictest policy across all participating admins. 3819 List<ActiveAdmin> admins = 3820 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3821 final int N = admins.size(); 3822 for (int i = 0; i < N; i++) { 3823 ActiveAdmin admin = admins.get(i); 3824 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 3825 continue; 3826 } 3827 if (length < admin.minimumPasswordMetrics.nonLetter) { 3828 length = admin.minimumPasswordMetrics.nonLetter; 3829 } 3830 } 3831 return length; 3832 } 3833 } 3834 3835 @Override 3836 public boolean isActivePasswordSufficient(int userHandle, boolean parent) { 3837 if (!mHasFeature) { 3838 return true; 3839 } 3840 enforceFullCrossUsersPermission(userHandle); 3841 3842 synchronized (this) { 3843 // This API can only be called by an active device admin, 3844 // so try to retrieve it to check that the caller is one. 3845 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3846 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 3847 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent); 3848 } 3849 } 3850 3851 @Override 3852 public boolean isProfileActivePasswordSufficientForParent(int userHandle) { 3853 if (!mHasFeature) { 3854 return true; 3855 } 3856 enforceFullCrossUsersPermission(userHandle); 3857 enforceManagedProfile(userHandle, "call APIs refering to the parent profile"); 3858 3859 synchronized (this) { 3860 int targetUser = getProfileParentId(userHandle); 3861 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false)); 3862 return isActivePasswordSufficientForUserLocked(policy, targetUser, false); 3863 } 3864 } 3865 3866 private boolean isActivePasswordSufficientForUserLocked( 3867 DevicePolicyData policy, int userHandle, boolean parent) { 3868 enforceUserUnlocked(userHandle, parent); 3869 3870 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent); 3871 if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) { 3872 return false; 3873 } 3874 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC 3875 && policy.mActivePasswordMetrics.length < getPasswordMinimumLength( 3876 null, userHandle, parent)) { 3877 return false; 3878 } 3879 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 3880 return true; 3881 } 3882 return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase( 3883 null, userHandle, parent) 3884 && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase( 3885 null, userHandle, parent) 3886 && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters( 3887 null, userHandle, parent) 3888 && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric( 3889 null, userHandle, parent) 3890 && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols( 3891 null, userHandle, parent) 3892 && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter( 3893 null, userHandle, parent); 3894 } 3895 3896 @Override 3897 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) { 3898 enforceFullCrossUsersPermission(userHandle); 3899 synchronized (this) { 3900 if (!isCallerWithSystemUid()) { 3901 // This API can only be called by an active device admin, 3902 // so try to retrieve it to check that the caller is one. 3903 getActiveAdminForCallerLocked( 3904 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 3905 } 3906 3907 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 3908 3909 return policy.mFailedPasswordAttempts; 3910 } 3911 } 3912 3913 @Override 3914 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) { 3915 if (!mHasFeature) { 3916 return; 3917 } 3918 Preconditions.checkNotNull(who, "ComponentName is null"); 3919 synchronized (this) { 3920 // This API can only be called by an active device admin, 3921 // so try to retrieve it to check that the caller is one. 3922 getActiveAdminForCallerLocked( 3923 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent); 3924 ActiveAdmin ap = getActiveAdminForCallerLocked( 3925 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 3926 if (ap.maximumFailedPasswordsForWipe != num) { 3927 ap.maximumFailedPasswordsForWipe = num; 3928 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3929 } 3930 } 3931 } 3932 3933 @Override 3934 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) { 3935 if (!mHasFeature) { 3936 return 0; 3937 } 3938 enforceFullCrossUsersPermission(userHandle); 3939 synchronized (this) { 3940 ActiveAdmin admin = (who != null) 3941 ? getActiveAdminUncheckedLocked(who, userHandle, parent) 3942 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent); 3943 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 3944 } 3945 } 3946 3947 @Override 3948 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) { 3949 if (!mHasFeature) { 3950 return UserHandle.USER_NULL; 3951 } 3952 enforceFullCrossUsersPermission(userHandle); 3953 synchronized (this) { 3954 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked( 3955 userHandle, parent); 3956 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL; 3957 } 3958 } 3959 3960 /** 3961 * Returns the admin with the strictest policy on maximum failed passwords for: 3962 * <ul> 3963 * <li>this user if it has a separate profile challenge, or 3964 * <li>this user and all profiles that don't have their own challenge otherwise. 3965 * </ul> 3966 * <p>If the policy for the primary and any other profile are equal, it returns the admin for 3967 * the primary profile. 3968 * Returns {@code null} if no participating admin has that policy set. 3969 */ 3970 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked( 3971 int userHandle, boolean parent) { 3972 int count = 0; 3973 ActiveAdmin strictestAdmin = null; 3974 3975 // Return the strictest policy across all participating admins. 3976 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3977 final int N = admins.size(); 3978 for (int i = 0; i < N; i++) { 3979 ActiveAdmin admin = admins.get(i); 3980 if (admin.maximumFailedPasswordsForWipe == 3981 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 3982 continue; // No max number of failed passwords policy set for this profile. 3983 } 3984 3985 // We always favor the primary profile if several profiles have the same value set. 3986 int userId = admin.getUserHandle().getIdentifier(); 3987 if (count == 0 || 3988 count > admin.maximumFailedPasswordsForWipe || 3989 (count == admin.maximumFailedPasswordsForWipe && 3990 getUserInfo(userId).isPrimary())) { 3991 count = admin.maximumFailedPasswordsForWipe; 3992 strictestAdmin = admin; 3993 } 3994 } 3995 return strictestAdmin; 3996 } 3997 3998 private UserInfo getUserInfo(@UserIdInt int userId) { 3999 final long token = mInjector.binderClearCallingIdentity(); 4000 try { 4001 return mUserManager.getUserInfo(userId); 4002 } finally { 4003 mInjector.binderRestoreCallingIdentity(token); 4004 } 4005 } 4006 4007 @Override 4008 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException { 4009 if (!mHasFeature) { 4010 return false; 4011 } 4012 final int callingUid = mInjector.binderGetCallingUid(); 4013 final int userHandle = mInjector.userHandleGetCallingUserId(); 4014 4015 String password = passwordOrNull != null ? passwordOrNull : ""; 4016 4017 // Password resetting to empty/null is not allowed for managed profiles. 4018 if (TextUtils.isEmpty(password)) { 4019 enforceNotManagedProfile(userHandle, "clear the active password"); 4020 } 4021 4022 int quality; 4023 synchronized (this) { 4024 // If caller has PO (or DO) it can change the password, so see if that's the case first. 4025 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked( 4026 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid); 4027 final boolean preN; 4028 if (admin != null) { 4029 preN = getTargetSdk(admin.info.getPackageName(), 4030 userHandle) <= android.os.Build.VERSION_CODES.M; 4031 } else { 4032 // Otherwise, make sure the caller has any active admin with the right policy. 4033 admin = getActiveAdminForCallerLocked(null, 4034 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD); 4035 preN = getTargetSdk(admin.info.getPackageName(), 4036 userHandle) <= android.os.Build.VERSION_CODES.M; 4037 4038 // As of N, password resetting to empty/null is not allowed anymore. 4039 // TODO Should we allow DO/PO to set an empty password? 4040 if (TextUtils.isEmpty(password)) { 4041 if (!preN) { 4042 throw new SecurityException("Cannot call with null password"); 4043 } else { 4044 Slog.e(LOG_TAG, "Cannot call with null password"); 4045 return false; 4046 } 4047 } 4048 // As of N, password cannot be changed by the admin if it is already set. 4049 if (isLockScreenSecureUnchecked(userHandle)) { 4050 if (!preN) { 4051 throw new SecurityException("Admin cannot change current password"); 4052 } else { 4053 Slog.e(LOG_TAG, "Admin cannot change current password"); 4054 return false; 4055 } 4056 } 4057 } 4058 // Do not allow to reset password when current user has a managed profile 4059 if (!isManagedProfile(userHandle)) { 4060 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4061 if (userInfo.isManagedProfile()) { 4062 if (!preN) { 4063 throw new IllegalStateException( 4064 "Cannot reset password on user has managed profile"); 4065 } else { 4066 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile"); 4067 return false; 4068 } 4069 } 4070 } 4071 } 4072 // Do not allow to reset password when user is locked 4073 if (!mUserManager.isUserUnlocked(userHandle)) { 4074 if (!preN) { 4075 throw new IllegalStateException("Cannot reset password when user is locked"); 4076 } else { 4077 Slog.e(LOG_TAG, "Cannot reset password when user is locked"); 4078 return false; 4079 } 4080 } 4081 4082 quality = getPasswordQuality(null, userHandle, /* parent */ false); 4083 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) { 4084 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 4085 } 4086 final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password); 4087 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 4088 final int realQuality = metrics.quality; 4089 if (realQuality < quality 4090 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4091 Slog.w(LOG_TAG, "resetPassword: password quality 0x" 4092 + Integer.toHexString(realQuality) 4093 + " does not meet required quality 0x" 4094 + Integer.toHexString(quality)); 4095 return false; 4096 } 4097 quality = Math.max(realQuality, quality); 4098 } 4099 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false); 4100 if (password.length() < length) { 4101 Slog.w(LOG_TAG, "resetPassword: password length " + password.length() 4102 + " does not meet required length " + length); 4103 return false; 4104 } 4105 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4106 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false); 4107 if(metrics.letters < neededLetters) { 4108 Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters 4109 + " does not meet required number of letters " + neededLetters); 4110 return false; 4111 } 4112 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false); 4113 if (metrics.numeric < neededNumeric) { 4114 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric 4115 + " does not meet required number of numerical digits " 4116 + neededNumeric); 4117 return false; 4118 } 4119 int neededLowerCase = getPasswordMinimumLowerCase( 4120 null, userHandle, /* parent */ false); 4121 if (metrics.lowerCase < neededLowerCase) { 4122 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " 4123 + metrics.lowerCase 4124 + " does not meet required number of lowercase letters " 4125 + neededLowerCase); 4126 return false; 4127 } 4128 int neededUpperCase = getPasswordMinimumUpperCase( 4129 null, userHandle, /* parent */ false); 4130 if (metrics.upperCase < neededUpperCase) { 4131 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " 4132 + metrics.upperCase 4133 + " does not meet required number of uppercase letters " 4134 + neededUpperCase); 4135 return false; 4136 } 4137 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false); 4138 if (metrics.symbols < neededSymbols) { 4139 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols 4140 + " does not meet required number of special symbols " + neededSymbols); 4141 return false; 4142 } 4143 int neededNonLetter = getPasswordMinimumNonLetter( 4144 null, userHandle, /* parent */ false); 4145 if (metrics.nonLetter < neededNonLetter) { 4146 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " 4147 + metrics.nonLetter 4148 + " does not meet required number of non-letter characters " 4149 + neededNonLetter); 4150 return false; 4151 } 4152 } 4153 } 4154 4155 DevicePolicyData policy = getUserData(userHandle); 4156 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 4157 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 4158 return false; 4159 } 4160 4161 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid); 4162 boolean doNotAskCredentialsOnBoot = 4163 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 4164 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 4165 setDoNotAskCredentialsOnBoot(); 4166 } 4167 4168 // Don't do this with the lock held, because it is going to call 4169 // back in to the service. 4170 final long ident = mInjector.binderClearCallingIdentity(); 4171 try { 4172 if (!TextUtils.isEmpty(password)) { 4173 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle); 4174 } else { 4175 mLockPatternUtils.clearLock(userHandle); 4176 } 4177 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 4178 if (requireEntry) { 4179 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, 4180 UserHandle.USER_ALL); 4181 } 4182 synchronized (this) { 4183 int newOwner = requireEntry ? callingUid : -1; 4184 if (policy.mPasswordOwner != newOwner) { 4185 policy.mPasswordOwner = newOwner; 4186 saveSettingsLocked(userHandle); 4187 } 4188 } 4189 } finally { 4190 mInjector.binderRestoreCallingIdentity(ident); 4191 } 4192 4193 return true; 4194 } 4195 4196 private boolean isLockScreenSecureUnchecked(int userId) { 4197 long ident = mInjector.binderClearCallingIdentity(); 4198 try { 4199 return mLockPatternUtils.isSecure(userId); 4200 } finally { 4201 mInjector.binderRestoreCallingIdentity(ident); 4202 } 4203 } 4204 4205 private void setDoNotAskCredentialsOnBoot() { 4206 synchronized (this) { 4207 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4208 if (!policyData.doNotAskCredentialsOnBoot) { 4209 policyData.doNotAskCredentialsOnBoot = true; 4210 saveSettingsLocked(UserHandle.USER_SYSTEM); 4211 } 4212 } 4213 } 4214 4215 @Override 4216 public boolean getDoNotAskCredentialsOnBoot() { 4217 mContext.enforceCallingOrSelfPermission( 4218 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null); 4219 synchronized (this) { 4220 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4221 return policyData.doNotAskCredentialsOnBoot; 4222 } 4223 } 4224 4225 @Override 4226 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) { 4227 if (!mHasFeature) { 4228 return; 4229 } 4230 Preconditions.checkNotNull(who, "ComponentName is null"); 4231 final int userHandle = mInjector.userHandleGetCallingUserId(); 4232 synchronized (this) { 4233 ActiveAdmin ap = getActiveAdminForCallerLocked( 4234 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 4235 if (ap.maximumTimeToUnlock != timeMs) { 4236 ap.maximumTimeToUnlock = timeMs; 4237 saveSettingsLocked(userHandle); 4238 updateMaximumTimeToLockLocked(userHandle); 4239 } 4240 } 4241 } 4242 4243 void updateMaximumTimeToLockLocked(int userHandle) { 4244 // Calculate the min timeout for all profiles - including the ones with a separate 4245 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that 4246 // challenge only and keep the screen on. However there is no easy way of doing that at the 4247 // moment so we set the screen off timeout regardless of whether it affects the parent user 4248 // or the profile challenge only. 4249 long timeMs = Long.MAX_VALUE; 4250 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle); 4251 for (int profileId : profileIds) { 4252 DevicePolicyData policy = getUserDataUnchecked(profileId); 4253 final int N = policy.mAdminList.size(); 4254 for (int i = 0; i < N; i++) { 4255 ActiveAdmin admin = policy.mAdminList.get(i); 4256 if (admin.maximumTimeToUnlock > 0 4257 && timeMs > admin.maximumTimeToUnlock) { 4258 timeMs = admin.maximumTimeToUnlock; 4259 } 4260 // If userInfo.id is a managed profile, we also need to look at 4261 // the policies set on the parent. 4262 if (admin.hasParentActiveAdmin()) { 4263 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin(); 4264 if (parentAdmin.maximumTimeToUnlock > 0 4265 && timeMs > parentAdmin.maximumTimeToUnlock) { 4266 timeMs = parentAdmin.maximumTimeToUnlock; 4267 } 4268 } 4269 } 4270 } 4271 4272 // We only store the last maximum time to lock on the parent profile. So if calling from a 4273 // managed profile, retrieve the policy for the parent. 4274 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle)); 4275 if (policy.mLastMaximumTimeToLock == timeMs) { 4276 return; 4277 } 4278 policy.mLastMaximumTimeToLock = timeMs; 4279 4280 final long ident = mInjector.binderClearCallingIdentity(); 4281 try { 4282 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) { 4283 // Make sure KEEP_SCREEN_ON is disabled, since that 4284 // would allow bypassing of the maximum time to lock. 4285 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 4286 } 4287 4288 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 4289 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE)); 4290 } finally { 4291 mInjector.binderRestoreCallingIdentity(ident); 4292 } 4293 } 4294 4295 @Override 4296 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) { 4297 if (!mHasFeature) { 4298 return 0; 4299 } 4300 enforceFullCrossUsersPermission(userHandle); 4301 synchronized (this) { 4302 if (who != null) { 4303 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4304 return admin != null ? admin.maximumTimeToUnlock : 0; 4305 } 4306 // Return the strictest policy across all participating admins. 4307 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4308 userHandle, parent); 4309 return getMaximumTimeToLockPolicyFromAdmins(admins); 4310 } 4311 } 4312 4313 @Override 4314 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) { 4315 if (!mHasFeature) { 4316 return 0; 4317 } 4318 enforceFullCrossUsersPermission(userHandle); 4319 synchronized (this) { 4320 // All admins for this user. 4321 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>(); 4322 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4323 DevicePolicyData policy = getUserData(userInfo.id); 4324 admins.addAll(policy.mAdminList); 4325 // If it is a managed profile, it may have parent active admins 4326 if (userInfo.isManagedProfile()) { 4327 for (ActiveAdmin admin : policy.mAdminList) { 4328 if (admin.hasParentActiveAdmin()) { 4329 admins.add(admin.getParentActiveAdmin()); 4330 } 4331 } 4332 } 4333 } 4334 return getMaximumTimeToLockPolicyFromAdmins(admins); 4335 } 4336 } 4337 4338 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) { 4339 long time = 0; 4340 final int N = admins.size(); 4341 for (int i = 0; i < N; i++) { 4342 ActiveAdmin admin = admins.get(i); 4343 if (time == 0) { 4344 time = admin.maximumTimeToUnlock; 4345 } else if (admin.maximumTimeToUnlock != 0 4346 && time > admin.maximumTimeToUnlock) { 4347 time = admin.maximumTimeToUnlock; 4348 } 4349 } 4350 return time; 4351 } 4352 4353 @Override 4354 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, 4355 boolean parent) { 4356 if (!mHasFeature) { 4357 return; 4358 } 4359 Preconditions.checkNotNull(who, "ComponentName is null"); 4360 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number."); 4361 // timeoutMs with value 0 means that the admin doesn't participate 4362 // timeoutMs is clamped to the interval in case the internal constants change in the future 4363 if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) { 4364 timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS; 4365 } 4366 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 4367 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4368 } 4369 4370 final int userHandle = mInjector.userHandleGetCallingUserId(); 4371 synchronized (this) { 4372 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 4373 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent); 4374 if (ap.strongAuthUnlockTimeout != timeoutMs) { 4375 ap.strongAuthUnlockTimeout = timeoutMs; 4376 saveSettingsLocked(userHandle); 4377 } 4378 } 4379 } 4380 4381 /** 4382 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all 4383 * admins if who is null. 4384 * Returns 0 if not configured for the provided admin. 4385 */ 4386 @Override 4387 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) { 4388 if (!mHasFeature) { 4389 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4390 } 4391 enforceFullCrossUsersPermission(userId); 4392 synchronized (this) { 4393 if (who != null) { 4394 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent); 4395 return admin != null ? admin.strongAuthUnlockTimeout : 0; 4396 } 4397 4398 // Return the strictest policy across all participating admins. 4399 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent); 4400 4401 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4402 for (int i = 0; i < admins.size(); i++) { 4403 final long timeout = admins.get(i).strongAuthUnlockTimeout; 4404 if (timeout != 0) { // take only participating admins into account 4405 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout); 4406 } 4407 } 4408 return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS); 4409 } 4410 } 4411 4412 @Override 4413 public void lockNow(int flags, boolean parent) { 4414 if (!mHasFeature) { 4415 return; 4416 } 4417 4418 final int callingUserId = mInjector.userHandleGetCallingUserId(); 4419 synchronized (this) { 4420 // This API can only be called by an active device admin, 4421 // so try to retrieve it to check that the caller is one. 4422 final ActiveAdmin admin = getActiveAdminForCallerLocked( 4423 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 4424 4425 final long ident = mInjector.binderClearCallingIdentity(); 4426 try { 4427 // Evict key 4428 if ((flags & DevicePolicyManager.FLAG_EVICT_CE_KEY) != 0) { 4429 enforceManagedProfile(callingUserId, "set FLAG_EVICT_CE_KEY"); 4430 if (!isProfileOwner(admin.info.getComponent(), callingUserId)) { 4431 throw new SecurityException( 4432 "Only profile owner admins can set FLAG_EVICT_CE_KEY"); 4433 } 4434 if (parent) { 4435 throw new IllegalArgumentException( 4436 "Cannot set FLAG_EVICT_CE_KEY for the parent"); 4437 } 4438 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 4439 throw new UnsupportedOperationException( 4440 "FLAG_EVICT_CE_KEY only applies to FBE devices"); 4441 } 4442 mUserManager.evictCredentialEncryptionKey(callingUserId); 4443 } 4444 4445 // Lock all users unless this is a managed profile with a separate challenge 4446 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId) 4447 ? UserHandle.USER_ALL : callingUserId); 4448 mLockPatternUtils.requireStrongAuth( 4449 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock); 4450 4451 // Require authentication for the device or profile 4452 if (userToLock == UserHandle.USER_ALL) { 4453 // Power off the display 4454 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(), 4455 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 4456 mInjector.getIWindowManager().lockNow(null); 4457 } else { 4458 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true); 4459 } 4460 } catch (RemoteException e) { 4461 } finally { 4462 mInjector.binderRestoreCallingIdentity(ident); 4463 } 4464 } 4465 } 4466 4467 @Override 4468 public void enforceCanManageCaCerts(ComponentName who) { 4469 if (who == null) { 4470 if (!isCallerDelegatedCertInstaller()) { 4471 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 4472 } 4473 } else { 4474 synchronized (this) { 4475 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4476 } 4477 } 4478 } 4479 4480 private void enforceCanManageInstalledKeys(ComponentName who) { 4481 if (who == null) { 4482 if (!isCallerDelegatedCertInstaller()) { 4483 throw new SecurityException("who == null, but caller is not cert installer"); 4484 } 4485 } else { 4486 synchronized (this) { 4487 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4488 } 4489 } 4490 } 4491 4492 private boolean isCallerDelegatedCertInstaller() { 4493 final int callingUid = mInjector.binderGetCallingUid(); 4494 final int userHandle = UserHandle.getUserId(callingUid); 4495 synchronized (this) { 4496 final DevicePolicyData policy = getUserData(userHandle); 4497 if (policy.mDelegatedCertInstallerPackage == null) { 4498 return false; 4499 } 4500 4501 try { 4502 int uid = mInjector.getPackageManager().getPackageUidAsUser( 4503 policy.mDelegatedCertInstallerPackage, userHandle); 4504 return uid == callingUid; 4505 } catch (NameNotFoundException e) { 4506 return false; 4507 } 4508 } 4509 } 4510 4511 @Override 4512 public boolean approveCaCert(String alias, int userId, boolean approval) { 4513 enforceManageUsers(); 4514 synchronized (this) { 4515 Set<String> certs = getUserData(userId).mAcceptedCaCertificates; 4516 boolean changed = (approval ? certs.add(alias) : certs.remove(alias)); 4517 if (!changed) { 4518 return false; 4519 } 4520 saveSettingsLocked(userId); 4521 } 4522 new MonitoringCertNotificationTask().execute(userId); 4523 return true; 4524 } 4525 4526 @Override 4527 public boolean isCaCertApproved(String alias, int userId) { 4528 enforceManageUsers(); 4529 synchronized (this) { 4530 return getUserData(userId).mAcceptedCaCertificates.contains(alias); 4531 } 4532 } 4533 4534 private void removeCaApprovalsIfNeeded(int userId) { 4535 for (UserInfo userInfo : mUserManager.getProfiles(userId)) { 4536 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id); 4537 if (userInfo.isManagedProfile()){ 4538 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id)); 4539 } 4540 if (!isSecure) { 4541 synchronized (this) { 4542 getUserData(userInfo.id).mAcceptedCaCertificates.clear(); 4543 saveSettingsLocked(userInfo.id); 4544 } 4545 4546 new MonitoringCertNotificationTask().execute(userInfo.id); 4547 } 4548 } 4549 } 4550 4551 @Override 4552 public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException { 4553 enforceCanManageCaCerts(admin); 4554 4555 byte[] pemCert; 4556 try { 4557 X509Certificate cert = parseCert(certBuffer); 4558 pemCert = Credentials.convertToPem(cert); 4559 } catch (CertificateException ce) { 4560 Log.e(LOG_TAG, "Problem converting cert", ce); 4561 return false; 4562 } catch (IOException ioe) { 4563 Log.e(LOG_TAG, "Problem reading cert", ioe); 4564 return false; 4565 } 4566 4567 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 4568 final long id = mInjector.binderClearCallingIdentity(); 4569 try { 4570 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 4571 try { 4572 keyChainConnection.getService().installCaCertificate(pemCert); 4573 return true; 4574 } catch (RemoteException e) { 4575 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e); 4576 } finally { 4577 keyChainConnection.close(); 4578 } 4579 } catch (InterruptedException e1) { 4580 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1); 4581 Thread.currentThread().interrupt(); 4582 } finally { 4583 mInjector.binderRestoreCallingIdentity(id); 4584 } 4585 return false; 4586 } 4587 4588 private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException { 4589 CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 4590 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream( 4591 certBuffer)); 4592 } 4593 4594 @Override 4595 public void uninstallCaCerts(ComponentName admin, String[] aliases) { 4596 enforceCanManageCaCerts(admin); 4597 4598 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 4599 final long id = mInjector.binderClearCallingIdentity(); 4600 try { 4601 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 4602 try { 4603 for (int i = 0 ; i < aliases.length; i++) { 4604 keyChainConnection.getService().deleteCaCertificate(aliases[i]); 4605 } 4606 } catch (RemoteException e) { 4607 Log.e(LOG_TAG, "from CaCertUninstaller: ", e); 4608 } finally { 4609 keyChainConnection.close(); 4610 } 4611 } catch (InterruptedException ie) { 4612 Log.w(LOG_TAG, "CaCertUninstaller: ", ie); 4613 Thread.currentThread().interrupt(); 4614 } finally { 4615 mInjector.binderRestoreCallingIdentity(id); 4616 } 4617 } 4618 4619 @Override 4620 public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain, 4621 String alias, boolean requestAccess) { 4622 enforceCanManageInstalledKeys(who); 4623 4624 final int callingUid = mInjector.binderGetCallingUid(); 4625 final long id = mInjector.binderClearCallingIdentity(); 4626 try { 4627 final KeyChainConnection keyChainConnection = 4628 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid)); 4629 try { 4630 IKeyChainService keyChain = keyChainConnection.getService(); 4631 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) { 4632 return false; 4633 } 4634 if (requestAccess) { 4635 keyChain.setGrant(callingUid, alias, true); 4636 } 4637 return true; 4638 } catch (RemoteException e) { 4639 Log.e(LOG_TAG, "Installing certificate", e); 4640 } finally { 4641 keyChainConnection.close(); 4642 } 4643 } catch (InterruptedException e) { 4644 Log.w(LOG_TAG, "Interrupted while installing certificate", e); 4645 Thread.currentThread().interrupt(); 4646 } finally { 4647 mInjector.binderRestoreCallingIdentity(id); 4648 } 4649 return false; 4650 } 4651 4652 @Override 4653 public boolean removeKeyPair(ComponentName who, String alias) { 4654 enforceCanManageInstalledKeys(who); 4655 4656 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 4657 final long id = Binder.clearCallingIdentity(); 4658 try { 4659 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 4660 try { 4661 IKeyChainService keyChain = keyChainConnection.getService(); 4662 return keyChain.removeKeyPair(alias); 4663 } catch (RemoteException e) { 4664 Log.e(LOG_TAG, "Removing keypair", e); 4665 } finally { 4666 keyChainConnection.close(); 4667 } 4668 } catch (InterruptedException e) { 4669 Log.w(LOG_TAG, "Interrupted while removing keypair", e); 4670 Thread.currentThread().interrupt(); 4671 } finally { 4672 Binder.restoreCallingIdentity(id); 4673 } 4674 return false; 4675 } 4676 4677 @Override 4678 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, 4679 final IBinder response) { 4680 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers. 4681 if (!isCallerWithSystemUid()) { 4682 return; 4683 } 4684 4685 final UserHandle caller = mInjector.binderGetCallingUserHandle(); 4686 // If there is a profile owner, redirect to that; otherwise query the device owner. 4687 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier()); 4688 if (aliasChooser == null && caller.isSystem()) { 4689 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 4690 if (deviceOwnerAdmin != null) { 4691 aliasChooser = deviceOwnerAdmin.info.getComponent(); 4692 } 4693 } 4694 if (aliasChooser == null) { 4695 sendPrivateKeyAliasResponse(null, response); 4696 return; 4697 } 4698 4699 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 4700 intent.setComponent(aliasChooser); 4701 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 4702 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri); 4703 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 4704 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 4705 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 4706 4707 final long id = mInjector.binderClearCallingIdentity(); 4708 try { 4709 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() { 4710 @Override 4711 public void onReceive(Context context, Intent intent) { 4712 final String chosenAlias = getResultData(); 4713 sendPrivateKeyAliasResponse(chosenAlias, response); 4714 } 4715 }, null, Activity.RESULT_OK, null, null); 4716 } finally { 4717 mInjector.binderRestoreCallingIdentity(id); 4718 } 4719 } 4720 4721 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 4722 final IKeyChainAliasCallback keyChainAliasResponse = 4723 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 4724 new AsyncTask<Void, Void, Void>() { 4725 @Override 4726 protected Void doInBackground(Void... unused) { 4727 try { 4728 keyChainAliasResponse.alias(alias); 4729 } catch (Exception e) { 4730 // Catch everything (not just RemoteException): caller could throw a 4731 // RuntimeException back across processes. 4732 Log.e(LOG_TAG, "error while responding to callback", e); 4733 } 4734 return null; 4735 } 4736 }.execute(); 4737 } 4738 4739 @Override 4740 public void setCertInstallerPackage(ComponentName who, String installerPackage) 4741 throws SecurityException { 4742 int userHandle = UserHandle.getCallingUserId(); 4743 synchronized (this) { 4744 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4745 if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) { 4746 if (installerPackage != null && 4747 !isPackageInstalledForUser(installerPackage, userHandle)) { 4748 throw new IllegalArgumentException("Package " + installerPackage 4749 + " is not installed on the current user"); 4750 } 4751 } 4752 DevicePolicyData policy = getUserData(userHandle); 4753 policy.mDelegatedCertInstallerPackage = installerPackage; 4754 saveSettingsLocked(userHandle); 4755 } 4756 } 4757 4758 @Override 4759 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 4760 int userHandle = UserHandle.getCallingUserId(); 4761 synchronized (this) { 4762 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4763 DevicePolicyData policy = getUserData(userHandle); 4764 return policy.mDelegatedCertInstallerPackage; 4765 } 4766 } 4767 4768 /** 4769 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is 4770 * not installed and therefore not available. 4771 * 4772 * @throws SecurityException if the caller is not a profile or device owner. 4773 * @throws UnsupportedOperationException if the package does not support being set as always-on. 4774 */ 4775 @Override 4776 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown) 4777 throws SecurityException { 4778 synchronized (this) { 4779 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4780 } 4781 4782 final int userId = mInjector.userHandleGetCallingUserId(); 4783 final long token = mInjector.binderClearCallingIdentity(); 4784 try { 4785 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) { 4786 return false; 4787 } 4788 ConnectivityManager connectivityManager = (ConnectivityManager) 4789 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 4790 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) { 4791 throw new UnsupportedOperationException(); 4792 } 4793 } finally { 4794 mInjector.binderRestoreCallingIdentity(token); 4795 } 4796 return true; 4797 } 4798 4799 @Override 4800 public String getAlwaysOnVpnPackage(ComponentName admin) 4801 throws SecurityException { 4802 synchronized (this) { 4803 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4804 } 4805 4806 final int userId = mInjector.userHandleGetCallingUserId(); 4807 final long token = mInjector.binderClearCallingIdentity(); 4808 try{ 4809 ConnectivityManager connectivityManager = (ConnectivityManager) 4810 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 4811 return connectivityManager.getAlwaysOnVpnPackageForUser(userId); 4812 } finally { 4813 mInjector.binderRestoreCallingIdentity(token); 4814 } 4815 } 4816 4817 private void wipeDataNoLock(boolean wipeExtRequested, String reason, boolean force) { 4818 wtfIfInLock(); 4819 4820 if (wipeExtRequested) { 4821 StorageManager sm = (StorageManager) mContext.getSystemService( 4822 Context.STORAGE_SERVICE); 4823 sm.wipeAdoptableDisks(); 4824 } 4825 try { 4826 RecoverySystem.rebootWipeUserData(mContext, false /* shutdown */, reason, force); 4827 } catch (IOException | SecurityException e) { 4828 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 4829 } 4830 } 4831 4832 @Override 4833 public void wipeData(int flags) { 4834 if (!mHasFeature) { 4835 return; 4836 } 4837 final int userHandle = mInjector.userHandleGetCallingUserId(); 4838 enforceFullCrossUsersPermission(userHandle); 4839 4840 final String source; 4841 synchronized (this) { 4842 // This API can only be called by an active device admin, 4843 // so try to retrieve it to check that the caller is one. 4844 final ActiveAdmin admin = getActiveAdminForCallerLocked(null, 4845 DeviceAdminInfo.USES_POLICY_WIPE_DATA); 4846 source = admin.info.getComponent().flattenToShortString(); 4847 4848 long ident = mInjector.binderClearCallingIdentity(); 4849 try { 4850 final String restriction; 4851 if (userHandle == UserHandle.USER_SYSTEM) { 4852 restriction = UserManager.DISALLOW_FACTORY_RESET; 4853 } else if (isManagedProfile(userHandle)) { 4854 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 4855 } else { 4856 restriction = UserManager.DISALLOW_REMOVE_USER; 4857 } 4858 if (isAdminAffectedByRestriction( 4859 admin.info.getComponent(), restriction, userHandle)) { 4860 throw new SecurityException("Cannot wipe data. " + restriction 4861 + " restriction is set for user " + userHandle); 4862 } 4863 4864 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 4865 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) { 4866 throw new SecurityException( 4867 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA"); 4868 } 4869 PersistentDataBlockManager manager = (PersistentDataBlockManager) 4870 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 4871 if (manager != null) { 4872 manager.wipe(); 4873 } 4874 } 4875 4876 } finally { 4877 mInjector.binderRestoreCallingIdentity(ident); 4878 } 4879 } 4880 final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0; 4881 wipeDeviceNoLock(wipeExtRequested, userHandle, 4882 "DevicePolicyManager.wipeData() from " + source, /*force=*/ true); 4883 } 4884 4885 private void wipeDeviceNoLock( 4886 boolean wipeExtRequested, final int userHandle, String reason, boolean force) { 4887 wtfIfInLock(); 4888 4889 long ident = mInjector.binderClearCallingIdentity(); 4890 try { 4891 // TODO If split user is enabled and the device owner is set in the primary user (rather 4892 // than system), we should probably trigger factory reset. Current code just remove 4893 // that user (but still clears FRP...) 4894 if (userHandle == UserHandle.USER_SYSTEM) { 4895 wipeDataNoLock(wipeExtRequested, reason, force); 4896 } else { 4897 try { 4898 IActivityManager am = mInjector.getIActivityManager(); 4899 if (am.getCurrentUser().id == userHandle) { 4900 am.switchUser(UserHandle.USER_SYSTEM); 4901 } 4902 4903 boolean userRemoved = force 4904 ? mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle) 4905 : mUserManager.removeUser(userHandle); 4906 if (!userRemoved) { 4907 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle); 4908 } else if (isManagedProfile(userHandle)) { 4909 sendWipeProfileNotification(); 4910 } 4911 } catch (RemoteException re) { 4912 // Shouldn't happen 4913 } 4914 } 4915 } finally { 4916 mInjector.binderRestoreCallingIdentity(ident); 4917 } 4918 } 4919 4920 private void sendWipeProfileNotification() { 4921 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe); 4922 Notification notification = new Notification.Builder(mContext) 4923 .setSmallIcon(android.R.drawable.stat_sys_warning) 4924 .setContentTitle(mContext.getString(R.string.work_profile_deleted)) 4925 .setContentText(contentText) 4926 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 4927 .setStyle(new Notification.BigTextStyle().bigText(contentText)) 4928 .build(); 4929 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification); 4930 } 4931 4932 private void clearWipeProfileNotification() { 4933 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID); 4934 } 4935 4936 @Override 4937 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 4938 if (!mHasFeature) { 4939 return; 4940 } 4941 enforceFullCrossUsersPermission(userHandle); 4942 mContext.enforceCallingOrSelfPermission( 4943 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 4944 4945 synchronized (this) { 4946 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 4947 if (admin == null) { 4948 result.sendResult(null); 4949 return; 4950 } 4951 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 4952 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 4953 intent.setComponent(admin.info.getComponent()); 4954 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 4955 null, new BroadcastReceiver() { 4956 @Override 4957 public void onReceive(Context context, Intent intent) { 4958 result.sendResult(getResultExtras(false)); 4959 } 4960 }, null, Activity.RESULT_OK, null, null); 4961 } 4962 } 4963 4964 @Override 4965 public void setActivePasswordState(PasswordMetrics metrics, int userHandle) { 4966 if (!mHasFeature) { 4967 return; 4968 } 4969 enforceFullCrossUsersPermission(userHandle); 4970 mContext.enforceCallingOrSelfPermission( 4971 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 4972 4973 // If the managed profile doesn't have a separate password, set the metrics to default 4974 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 4975 metrics = new PasswordMetrics(); 4976 } 4977 4978 validateQualityConstant(metrics.quality); 4979 DevicePolicyData policy = getUserData(userHandle); 4980 synchronized (this) { 4981 policy.mActivePasswordMetrics = metrics; 4982 } 4983 } 4984 4985 @Override 4986 public void reportPasswordChanged(@UserIdInt int userId) { 4987 if (!mHasFeature) { 4988 return; 4989 } 4990 enforceFullCrossUsersPermission(userId); 4991 4992 // Managed Profile password can only be changed when it has a separate challenge. 4993 if (!isSeparateProfileChallengeEnabled(userId)) { 4994 enforceNotManagedProfile(userId, "set the active password"); 4995 } 4996 4997 mContext.enforceCallingOrSelfPermission( 4998 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 4999 5000 DevicePolicyData policy = getUserData(userId); 5001 5002 long ident = mInjector.binderClearCallingIdentity(); 5003 try { 5004 synchronized (this) { 5005 policy.mFailedPasswordAttempts = 0; 5006 saveSettingsLocked(userId); 5007 updatePasswordExpirationsLocked(userId); 5008 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 5009 5010 // Send a broadcast to each profile using this password as its primary unlock. 5011 sendAdminCommandForLockscreenPoliciesLocked( 5012 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 5013 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 5014 } 5015 removeCaApprovalsIfNeeded(userId); 5016 } finally { 5017 mInjector.binderRestoreCallingIdentity(ident); 5018 } 5019 } 5020 5021 /** 5022 * Called any time the device password is updated. Resets all password expiration clocks. 5023 */ 5024 private void updatePasswordExpirationsLocked(int userHandle) { 5025 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>(); 5026 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5027 userHandle, /* parent */ false); 5028 final int N = admins.size(); 5029 for (int i = 0; i < N; i++) { 5030 ActiveAdmin admin = admins.get(i); 5031 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 5032 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 5033 long timeout = admin.passwordExpirationTimeout; 5034 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 5035 admin.passwordExpirationDate = expiration; 5036 } 5037 } 5038 for (int affectedUserId : affectedUserIds) { 5039 saveSettingsLocked(affectedUserId); 5040 } 5041 } 5042 5043 @Override 5044 public void reportFailedPasswordAttempt(int userHandle) { 5045 enforceFullCrossUsersPermission(userHandle); 5046 if (!isSeparateProfileChallengeEnabled(userHandle)) { 5047 enforceNotManagedProfile(userHandle, 5048 "report failed password attempt if separate profile challenge is not in place"); 5049 } 5050 mContext.enforceCallingOrSelfPermission( 5051 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5052 5053 final long ident = mInjector.binderClearCallingIdentity(); 5054 try { 5055 boolean wipeData = false; 5056 int identifier = 0; 5057 synchronized (this) { 5058 DevicePolicyData policy = getUserData(userHandle); 5059 policy.mFailedPasswordAttempts++; 5060 saveSettingsLocked(userHandle); 5061 if (mHasFeature) { 5062 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 5063 userHandle, /* parent */ false); 5064 int max = strictestAdmin != null 5065 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 5066 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 5067 // Wipe the user/profile associated with the policy that was violated. This 5068 // is not necessarily calling user: if the policy that fired was from a 5069 // managed profile rather than the main user profile, we wipe former only. 5070 wipeData = true; 5071 identifier = strictestAdmin.getUserHandle().getIdentifier(); 5072 } 5073 5074 sendAdminCommandForLockscreenPoliciesLocked( 5075 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 5076 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 5077 } 5078 } 5079 if (wipeData) { 5080 // Call without holding lock. 5081 wipeDeviceNoLock(false, identifier, "reportFailedPasswordAttempt()", false); 5082 } 5083 } finally { 5084 mInjector.binderRestoreCallingIdentity(ident); 5085 } 5086 5087 if (mInjector.securityLogIsLoggingEnabled()) { 5088 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 5089 /*method strength*/ 1); 5090 } 5091 } 5092 5093 @Override 5094 public void reportSuccessfulPasswordAttempt(int userHandle) { 5095 enforceFullCrossUsersPermission(userHandle); 5096 mContext.enforceCallingOrSelfPermission( 5097 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5098 5099 synchronized (this) { 5100 DevicePolicyData policy = getUserData(userHandle); 5101 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 5102 long ident = mInjector.binderClearCallingIdentity(); 5103 try { 5104 policy.mFailedPasswordAttempts = 0; 5105 policy.mPasswordOwner = -1; 5106 saveSettingsLocked(userHandle); 5107 if (mHasFeature) { 5108 sendAdminCommandForLockscreenPoliciesLocked( 5109 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 5110 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 5111 } 5112 } finally { 5113 mInjector.binderRestoreCallingIdentity(ident); 5114 } 5115 } 5116 } 5117 5118 if (mInjector.securityLogIsLoggingEnabled()) { 5119 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 5120 /*method strength*/ 1); 5121 } 5122 } 5123 5124 @Override 5125 public void reportFailedFingerprintAttempt(int userHandle) { 5126 enforceFullCrossUsersPermission(userHandle); 5127 mContext.enforceCallingOrSelfPermission( 5128 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5129 if (mInjector.securityLogIsLoggingEnabled()) { 5130 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 5131 /*method strength*/ 0); 5132 } 5133 } 5134 5135 @Override 5136 public void reportSuccessfulFingerprintAttempt(int userHandle) { 5137 enforceFullCrossUsersPermission(userHandle); 5138 mContext.enforceCallingOrSelfPermission( 5139 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5140 if (mInjector.securityLogIsLoggingEnabled()) { 5141 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 5142 /*method strength*/ 0); 5143 } 5144 } 5145 5146 @Override 5147 public void reportKeyguardDismissed(int userHandle) { 5148 enforceFullCrossUsersPermission(userHandle); 5149 mContext.enforceCallingOrSelfPermission( 5150 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5151 5152 if (mInjector.securityLogIsLoggingEnabled()) { 5153 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 5154 } 5155 } 5156 5157 @Override 5158 public void reportKeyguardSecured(int userHandle) { 5159 enforceFullCrossUsersPermission(userHandle); 5160 mContext.enforceCallingOrSelfPermission( 5161 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5162 5163 if (mInjector.securityLogIsLoggingEnabled()) { 5164 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 5165 } 5166 } 5167 5168 @Override 5169 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 5170 String exclusionList) { 5171 if (!mHasFeature) { 5172 return null; 5173 } 5174 synchronized(this) { 5175 Preconditions.checkNotNull(who, "ComponentName is null"); 5176 5177 // Only check if system user has set global proxy. We don't allow other users to set it. 5178 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5179 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5180 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 5181 5182 // Scan through active admins and find if anyone has already 5183 // set the global proxy. 5184 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 5185 for (ComponentName component : compSet) { 5186 ActiveAdmin ap = policy.mAdminMap.get(component); 5187 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 5188 // Another admin already sets the global proxy 5189 // Return it to the caller. 5190 return component; 5191 } 5192 } 5193 5194 // If the user is not system, don't set the global proxy. Fail silently. 5195 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 5196 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 5197 + UserHandle.getCallingUserId() + " is not permitted."); 5198 return null; 5199 } 5200 if (proxySpec == null) { 5201 admin.specifiesGlobalProxy = false; 5202 admin.globalProxySpec = null; 5203 admin.globalProxyExclusionList = null; 5204 } else { 5205 5206 admin.specifiesGlobalProxy = true; 5207 admin.globalProxySpec = proxySpec; 5208 admin.globalProxyExclusionList = exclusionList; 5209 } 5210 5211 // Reset the global proxy accordingly 5212 // Do this using system permissions, as apps cannot write to secure settings 5213 long origId = mInjector.binderClearCallingIdentity(); 5214 try { 5215 resetGlobalProxyLocked(policy); 5216 } finally { 5217 mInjector.binderRestoreCallingIdentity(origId); 5218 } 5219 return null; 5220 } 5221 } 5222 5223 @Override 5224 public ComponentName getGlobalProxyAdmin(int userHandle) { 5225 if (!mHasFeature) { 5226 return null; 5227 } 5228 enforceFullCrossUsersPermission(userHandle); 5229 synchronized(this) { 5230 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5231 // Scan through active admins and find if anyone has already 5232 // set the global proxy. 5233 final int N = policy.mAdminList.size(); 5234 for (int i = 0; i < N; i++) { 5235 ActiveAdmin ap = policy.mAdminList.get(i); 5236 if (ap.specifiesGlobalProxy) { 5237 // Device admin sets the global proxy 5238 // Return it to the caller. 5239 return ap.info.getComponent(); 5240 } 5241 } 5242 } 5243 // No device admin sets the global proxy. 5244 return null; 5245 } 5246 5247 @Override 5248 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 5249 synchronized (this) { 5250 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5251 } 5252 long token = mInjector.binderClearCallingIdentity(); 5253 try { 5254 ConnectivityManager connectivityManager = (ConnectivityManager) 5255 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5256 connectivityManager.setGlobalProxy(proxyInfo); 5257 } finally { 5258 mInjector.binderRestoreCallingIdentity(token); 5259 } 5260 } 5261 5262 private void resetGlobalProxyLocked(DevicePolicyData policy) { 5263 final int N = policy.mAdminList.size(); 5264 for (int i = 0; i < N; i++) { 5265 ActiveAdmin ap = policy.mAdminList.get(i); 5266 if (ap.specifiesGlobalProxy) { 5267 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 5268 return; 5269 } 5270 } 5271 // No device admins defining global proxies - reset global proxy settings to none 5272 saveGlobalProxyLocked(null, null); 5273 } 5274 5275 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 5276 if (exclusionList == null) { 5277 exclusionList = ""; 5278 } 5279 if (proxySpec == null) { 5280 proxySpec = ""; 5281 } 5282 // Remove white spaces 5283 proxySpec = proxySpec.trim(); 5284 String data[] = proxySpec.split(":"); 5285 int proxyPort = 8080; 5286 if (data.length > 1) { 5287 try { 5288 proxyPort = Integer.parseInt(data[1]); 5289 } catch (NumberFormatException e) {} 5290 } 5291 exclusionList = exclusionList.trim(); 5292 5293 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 5294 if (!proxyProperties.isValid()) { 5295 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 5296 return; 5297 } 5298 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 5299 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 5300 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 5301 exclusionList); 5302 } 5303 5304 /** 5305 * Set the storage encryption request for a single admin. Returns the new total request 5306 * status (for all admins). 5307 */ 5308 @Override 5309 public int setStorageEncryption(ComponentName who, boolean encrypt) { 5310 if (!mHasFeature) { 5311 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5312 } 5313 Preconditions.checkNotNull(who, "ComponentName is null"); 5314 final int userHandle = UserHandle.getCallingUserId(); 5315 synchronized (this) { 5316 // Check for permissions 5317 // Only system user can set storage encryption 5318 if (userHandle != UserHandle.USER_SYSTEM) { 5319 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User " 5320 + UserHandle.getCallingUserId() + " is not permitted."); 5321 return 0; 5322 } 5323 5324 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5325 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 5326 5327 // Quick exit: If the filesystem does not support encryption, we can exit early. 5328 if (!isEncryptionSupported()) { 5329 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5330 } 5331 5332 // (1) Record the value for the admin so it's sticky 5333 if (ap.encryptionRequested != encrypt) { 5334 ap.encryptionRequested = encrypt; 5335 saveSettingsLocked(userHandle); 5336 } 5337 5338 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5339 // (2) Compute "max" for all admins 5340 boolean newRequested = false; 5341 final int N = policy.mAdminList.size(); 5342 for (int i = 0; i < N; i++) { 5343 newRequested |= policy.mAdminList.get(i).encryptionRequested; 5344 } 5345 5346 // Notify OS of new request 5347 setEncryptionRequested(newRequested); 5348 5349 // Return the new global request status 5350 return newRequested 5351 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 5352 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 5353 } 5354 } 5355 5356 /** 5357 * Get the current storage encryption request status for a given admin, or aggregate of all 5358 * active admins. 5359 */ 5360 @Override 5361 public boolean getStorageEncryption(ComponentName who, int userHandle) { 5362 if (!mHasFeature) { 5363 return false; 5364 } 5365 enforceFullCrossUsersPermission(userHandle); 5366 synchronized (this) { 5367 // Check for permissions if a particular caller is specified 5368 if (who != null) { 5369 // When checking for a single caller, status is based on caller's request 5370 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 5371 return ap != null ? ap.encryptionRequested : false; 5372 } 5373 5374 // If no particular caller is specified, return the aggregate set of requests. 5375 // This is short circuited by returning true on the first hit. 5376 DevicePolicyData policy = getUserData(userHandle); 5377 final int N = policy.mAdminList.size(); 5378 for (int i = 0; i < N; i++) { 5379 if (policy.mAdminList.get(i).encryptionRequested) { 5380 return true; 5381 } 5382 } 5383 return false; 5384 } 5385 } 5386 5387 /** 5388 * Get the current encryption status of the device. 5389 */ 5390 @Override 5391 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 5392 if (!mHasFeature) { 5393 // Ok to return current status. 5394 } 5395 enforceFullCrossUsersPermission(userHandle); 5396 5397 // It's not critical here, but let's make sure the package name is correct, in case 5398 // we start using it for different purposes. 5399 ensureCallerPackage(callerPackage); 5400 5401 final ApplicationInfo ai; 5402 try { 5403 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 5404 } catch (RemoteException e) { 5405 throw new SecurityException(e); 5406 } 5407 5408 boolean legacyApp = false; 5409 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 5410 legacyApp = true; 5411 } 5412 5413 final int rawStatus = getEncryptionStatus(); 5414 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 5415 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 5416 } 5417 return rawStatus; 5418 } 5419 5420 /** 5421 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 5422 */ 5423 private boolean isEncryptionSupported() { 5424 // Note, this can be implemented as 5425 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5426 // But is provided as a separate internal method if there's a faster way to do a 5427 // simple check for supported-or-not. 5428 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5429 } 5430 5431 /** 5432 * Hook to low-levels: Reporting the current status of encryption. 5433 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 5434 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 5435 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 5436 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or 5437 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 5438 */ 5439 private int getEncryptionStatus() { 5440 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5441 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 5442 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) { 5443 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 5444 } else if (mInjector.storageManagerIsEncrypted()) { 5445 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 5446 } else if (mInjector.storageManagerIsEncryptable()) { 5447 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 5448 } else { 5449 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5450 } 5451 } 5452 5453 /** 5454 * Hook to low-levels: If needed, record the new admin setting for encryption. 5455 */ 5456 private void setEncryptionRequested(boolean encrypt) { 5457 } 5458 5459 /** 5460 * Set whether the screen capture is disabled for the user managed by the specified admin. 5461 */ 5462 @Override 5463 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) { 5464 if (!mHasFeature) { 5465 return; 5466 } 5467 Preconditions.checkNotNull(who, "ComponentName is null"); 5468 final int userHandle = UserHandle.getCallingUserId(); 5469 synchronized (this) { 5470 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5471 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5472 if (ap.disableScreenCapture != disabled) { 5473 ap.disableScreenCapture = disabled; 5474 saveSettingsLocked(userHandle); 5475 updateScreenCaptureDisabledInWindowManager(userHandle, disabled); 5476 } 5477 } 5478 } 5479 5480 /** 5481 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 5482 * active admin (if given admin is null). 5483 */ 5484 @Override 5485 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) { 5486 if (!mHasFeature) { 5487 return false; 5488 } 5489 synchronized (this) { 5490 if (who != null) { 5491 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 5492 return (admin != null) ? admin.disableScreenCapture : false; 5493 } 5494 5495 DevicePolicyData policy = getUserData(userHandle); 5496 final int N = policy.mAdminList.size(); 5497 for (int i = 0; i < N; i++) { 5498 ActiveAdmin admin = policy.mAdminList.get(i); 5499 if (admin.disableScreenCapture) { 5500 return true; 5501 } 5502 } 5503 return false; 5504 } 5505 } 5506 5507 private void updateScreenCaptureDisabledInWindowManager(final int userHandle, 5508 final boolean disabled) { 5509 mHandler.post(new Runnable() { 5510 @Override 5511 public void run() { 5512 try { 5513 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled); 5514 } catch (RemoteException e) { 5515 Log.w(LOG_TAG, "Unable to notify WindowManager.", e); 5516 } 5517 } 5518 }); 5519 } 5520 5521 /** 5522 * Set whether auto time is required by the specified admin (must be device owner). 5523 */ 5524 @Override 5525 public void setAutoTimeRequired(ComponentName who, boolean required) { 5526 if (!mHasFeature) { 5527 return; 5528 } 5529 Preconditions.checkNotNull(who, "ComponentName is null"); 5530 final int userHandle = UserHandle.getCallingUserId(); 5531 synchronized (this) { 5532 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5533 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5534 if (admin.requireAutoTime != required) { 5535 admin.requireAutoTime = required; 5536 saveSettingsLocked(userHandle); 5537 } 5538 } 5539 5540 // Turn AUTO_TIME on in settings if it is required 5541 if (required) { 5542 long ident = mInjector.binderClearCallingIdentity(); 5543 try { 5544 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */); 5545 } finally { 5546 mInjector.binderRestoreCallingIdentity(ident); 5547 } 5548 } 5549 } 5550 5551 /** 5552 * Returns whether or not auto time is required by the device owner. 5553 */ 5554 @Override 5555 public boolean getAutoTimeRequired() { 5556 if (!mHasFeature) { 5557 return false; 5558 } 5559 synchronized (this) { 5560 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 5561 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false; 5562 } 5563 } 5564 5565 @Override 5566 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 5567 if (!mHasFeature) { 5568 return; 5569 } 5570 Preconditions.checkNotNull(who, "ComponentName is null"); 5571 // Allow setting this policy to true only if there is a split system user. 5572 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) { 5573 throw new UnsupportedOperationException( 5574 "Cannot force ephemeral users on systems without split system user."); 5575 } 5576 boolean removeAllUsers = false; 5577 synchronized (this) { 5578 final ActiveAdmin deviceOwner = 5579 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5580 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) { 5581 deviceOwner.forceEphemeralUsers = forceEphemeralUsers; 5582 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 5583 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers); 5584 removeAllUsers = forceEphemeralUsers; 5585 } 5586 } 5587 if (removeAllUsers) { 5588 long identitity = mInjector.binderClearCallingIdentity(); 5589 try { 5590 mUserManagerInternal.removeAllUsers(); 5591 } finally { 5592 mInjector.binderRestoreCallingIdentity(identitity); 5593 } 5594 } 5595 } 5596 5597 @Override 5598 public boolean getForceEphemeralUsers(ComponentName who) { 5599 if (!mHasFeature) { 5600 return false; 5601 } 5602 Preconditions.checkNotNull(who, "ComponentName is null"); 5603 synchronized (this) { 5604 final ActiveAdmin deviceOwner = 5605 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5606 return deviceOwner.forceEphemeralUsers; 5607 } 5608 } 5609 5610 private boolean isDeviceOwnerManagedSingleUserDevice() { 5611 synchronized (this) { 5612 if (!mOwners.hasDeviceOwner()) { 5613 return false; 5614 } 5615 } 5616 final long callingIdentity = mInjector.binderClearCallingIdentity(); 5617 try { 5618 if (mInjector.userManagerIsSplitSystemUser()) { 5619 // In split system user mode, only allow the case where the device owner is managing 5620 // the only non-system user of the device 5621 return (mUserManager.getUserCount() == 2 5622 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM); 5623 } else { 5624 return mUserManager.getUserCount() == 1; 5625 } 5626 } finally { 5627 mInjector.binderRestoreCallingIdentity(callingIdentity); 5628 } 5629 } 5630 5631 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException { 5632 synchronized (this) { 5633 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5634 } 5635 if (!isDeviceOwnerManagedSingleUserDevice()) { 5636 throw new SecurityException( 5637 "There should only be one user, managed by Device Owner"); 5638 } 5639 } 5640 5641 @Override 5642 public boolean requestBugreport(ComponentName who) { 5643 if (!mHasFeature) { 5644 return false; 5645 } 5646 Preconditions.checkNotNull(who, "ComponentName is null"); 5647 ensureDeviceOwnerManagingSingleUser(who); 5648 5649 if (mRemoteBugreportServiceIsActive.get() 5650 || (getDeviceOwnerRemoteBugreportUri() != null)) { 5651 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running."); 5652 return false; 5653 } 5654 5655 final long currentTime = System.currentTimeMillis(); 5656 synchronized (this) { 5657 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 5658 if (currentTime > policyData.mLastBugReportRequestTime) { 5659 policyData.mLastBugReportRequestTime = currentTime; 5660 saveSettingsLocked(UserHandle.USER_SYSTEM); 5661 } 5662 } 5663 5664 final long callingIdentity = mInjector.binderClearCallingIdentity(); 5665 try { 5666 mInjector.getIActivityManager().requestBugReport( 5667 ActivityManager.BUGREPORT_OPTION_REMOTE); 5668 5669 mRemoteBugreportServiceIsActive.set(true); 5670 mRemoteBugreportSharingAccepted.set(false); 5671 registerRemoteBugreportReceivers(); 5672 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 5673 RemoteBugreportUtils.buildNotification(mContext, 5674 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL); 5675 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable, 5676 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS); 5677 return true; 5678 } catch (RemoteException re) { 5679 // should never happen 5680 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re); 5681 return false; 5682 } finally { 5683 mInjector.binderRestoreCallingIdentity(callingIdentity); 5684 } 5685 } 5686 5687 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) { 5688 Intent intent = new Intent(action); 5689 intent.setComponent(mOwners.getDeviceOwnerComponent()); 5690 if (extras != null) { 5691 intent.putExtras(extras); 5692 } 5693 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 5694 } 5695 5696 private synchronized String getDeviceOwnerRemoteBugreportUri() { 5697 return mOwners.getDeviceOwnerRemoteBugreportUri(); 5698 } 5699 5700 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, 5701 String bugreportHash) { 5702 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 5703 } 5704 5705 private void registerRemoteBugreportReceivers() { 5706 try { 5707 IntentFilter filterFinished = new IntentFilter( 5708 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH, 5709 RemoteBugreportUtils.BUGREPORT_MIMETYPE); 5710 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished); 5711 } catch (IntentFilter.MalformedMimeTypeException e) { 5712 // should never happen, as setting a constant 5713 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e); 5714 } 5715 IntentFilter filterConsent = new IntentFilter(); 5716 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 5717 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 5718 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 5719 } 5720 5721 private void onBugreportFinished(Intent intent) { 5722 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 5723 mRemoteBugreportServiceIsActive.set(false); 5724 Uri bugreportUri = intent.getData(); 5725 String bugreportUriString = null; 5726 if (bugreportUri != null) { 5727 bugreportUriString = bugreportUri.toString(); 5728 } 5729 String bugreportHash = intent.getStringExtra( 5730 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH); 5731 if (mRemoteBugreportSharingAccepted.get()) { 5732 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 5733 mInjector.getNotificationManager().cancel(LOG_TAG, 5734 RemoteBugreportUtils.NOTIFICATION_ID); 5735 } else { 5736 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash); 5737 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 5738 RemoteBugreportUtils.buildNotification(mContext, 5739 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 5740 UserHandle.ALL); 5741 } 5742 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 5743 } 5744 5745 private void onBugreportFailed() { 5746 mRemoteBugreportServiceIsActive.set(false); 5747 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 5748 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 5749 mRemoteBugreportSharingAccepted.set(false); 5750 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 5751 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID); 5752 Bundle extras = new Bundle(); 5753 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 5754 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING); 5755 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 5756 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 5757 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 5758 } 5759 5760 private void onBugreportSharingAccepted() { 5761 mRemoteBugreportSharingAccepted.set(true); 5762 String bugreportUriString = null; 5763 String bugreportHash = null; 5764 synchronized (this) { 5765 bugreportUriString = getDeviceOwnerRemoteBugreportUri(); 5766 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash(); 5767 } 5768 if (bugreportUriString != null) { 5769 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 5770 } else if (mRemoteBugreportServiceIsActive.get()) { 5771 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 5772 RemoteBugreportUtils.buildNotification(mContext, 5773 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED), 5774 UserHandle.ALL); 5775 } 5776 } 5777 5778 private void onBugreportSharingDeclined() { 5779 if (mRemoteBugreportServiceIsActive.get()) { 5780 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 5781 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 5782 mRemoteBugreportServiceIsActive.set(false); 5783 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 5784 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 5785 } 5786 mRemoteBugreportSharingAccepted.set(false); 5787 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 5788 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null); 5789 } 5790 5791 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, 5792 String bugreportHash) { 5793 ParcelFileDescriptor pfd = null; 5794 try { 5795 if (bugreportUriString == null) { 5796 throw new FileNotFoundException(); 5797 } 5798 Uri bugreportUri = Uri.parse(bugreportUriString); 5799 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r"); 5800 5801 synchronized (this) { 5802 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 5803 intent.setComponent(mOwners.getDeviceOwnerComponent()); 5804 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE); 5805 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 5806 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(), 5807 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); 5808 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 5809 } 5810 } catch (FileNotFoundException e) { 5811 Bundle extras = new Bundle(); 5812 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 5813 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE); 5814 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 5815 } finally { 5816 try { 5817 if (pfd != null) { 5818 pfd.close(); 5819 } 5820 } catch (IOException ex) { 5821 // Ignore 5822 } 5823 mRemoteBugreportSharingAccepted.set(false); 5824 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 5825 } 5826 } 5827 5828 /** 5829 * Disables all device cameras according to the specified admin. 5830 */ 5831 @Override 5832 public void setCameraDisabled(ComponentName who, boolean disabled) { 5833 if (!mHasFeature) { 5834 return; 5835 } 5836 Preconditions.checkNotNull(who, "ComponentName is null"); 5837 final int userHandle = mInjector.userHandleGetCallingUserId(); 5838 synchronized (this) { 5839 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5840 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 5841 if (ap.disableCamera != disabled) { 5842 ap.disableCamera = disabled; 5843 saveSettingsLocked(userHandle); 5844 } 5845 } 5846 // Tell the user manager that the restrictions have changed. 5847 pushUserRestrictions(userHandle); 5848 } 5849 5850 /** 5851 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 5852 * active admins. 5853 */ 5854 @Override 5855 public boolean getCameraDisabled(ComponentName who, int userHandle) { 5856 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true); 5857 } 5858 5859 private boolean getCameraDisabled(ComponentName who, int userHandle, 5860 boolean mergeDeviceOwnerRestriction) { 5861 if (!mHasFeature) { 5862 return false; 5863 } 5864 synchronized (this) { 5865 if (who != null) { 5866 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 5867 return (admin != null) ? admin.disableCamera : false; 5868 } 5869 // First, see if DO has set it. If so, it's device-wide. 5870 if (mergeDeviceOwnerRestriction) { 5871 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 5872 if (deviceOwner != null && deviceOwner.disableCamera) { 5873 return true; 5874 } 5875 } 5876 5877 // Then check each device admin on the user. 5878 DevicePolicyData policy = getUserData(userHandle); 5879 // Determine whether or not the device camera is disabled for any active admins. 5880 final int N = policy.mAdminList.size(); 5881 for (int i = 0; i < N; i++) { 5882 ActiveAdmin admin = policy.mAdminList.get(i); 5883 if (admin.disableCamera) { 5884 return true; 5885 } 5886 } 5887 return false; 5888 } 5889 } 5890 5891 @Override 5892 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 5893 if (!mHasFeature) { 5894 return; 5895 } 5896 Preconditions.checkNotNull(who, "ComponentName is null"); 5897 final int userHandle = mInjector.userHandleGetCallingUserId(); 5898 if (isManagedProfile(userHandle)) { 5899 if (parent) { 5900 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 5901 } else { 5902 which = which & PROFILE_KEYGUARD_FEATURES; 5903 } 5904 } 5905 synchronized (this) { 5906 ActiveAdmin ap = getActiveAdminForCallerLocked( 5907 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 5908 if (ap.disabledKeyguardFeatures != which) { 5909 ap.disabledKeyguardFeatures = which; 5910 saveSettingsLocked(userHandle); 5911 } 5912 } 5913 } 5914 5915 /** 5916 * Gets the disabled state for features in keyguard for the given admin, 5917 * or the aggregate of all active admins if who is null. 5918 */ 5919 @Override 5920 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 5921 if (!mHasFeature) { 5922 return 0; 5923 } 5924 enforceFullCrossUsersPermission(userHandle); 5925 final long ident = mInjector.binderClearCallingIdentity(); 5926 try { 5927 synchronized (this) { 5928 if (who != null) { 5929 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 5930 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 5931 } 5932 5933 final List<ActiveAdmin> admins; 5934 if (!parent && isManagedProfile(userHandle)) { 5935 // If we are being asked about a managed profile, just return keyguard features 5936 // disabled by admins in the profile. 5937 admins = getUserDataUnchecked(userHandle).mAdminList; 5938 } else { 5939 // Otherwise return those set by admins in the user and its profiles. 5940 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 5941 } 5942 5943 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 5944 final int N = admins.size(); 5945 for (int i = 0; i < N; i++) { 5946 ActiveAdmin admin = admins.get(i); 5947 int userId = admin.getUserHandle().getIdentifier(); 5948 boolean isRequestedUser = !parent && (userId == userHandle); 5949 if (isRequestedUser || !isManagedProfile(userId)) { 5950 // If we are being asked explicitly about this user 5951 // return all disabled features even if its a managed profile. 5952 which |= admin.disabledKeyguardFeatures; 5953 } else { 5954 // Otherwise a managed profile is only allowed to disable 5955 // some features on the parent user. 5956 which |= (admin.disabledKeyguardFeatures 5957 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 5958 } 5959 } 5960 return which; 5961 } 5962 } finally { 5963 mInjector.binderRestoreCallingIdentity(ident); 5964 } 5965 } 5966 5967 @Override 5968 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) { 5969 if (!mHasFeature) { 5970 return; 5971 } 5972 Preconditions.checkNotNull(who, "ComponentName is null"); 5973 Preconditions.checkNotNull(packageList, "packageList is null"); 5974 final int userHandle = UserHandle.getCallingUserId(); 5975 synchronized (this) { 5976 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5977 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5978 admin.keepUninstalledPackages = packageList; 5979 saveSettingsLocked(userHandle); 5980 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 5981 } 5982 } 5983 5984 @Override 5985 public List<String> getKeepUninstalledPackages(ComponentName who) { 5986 Preconditions.checkNotNull(who, "ComponentName is null"); 5987 if (!mHasFeature) { 5988 return null; 5989 } 5990 // TODO In split system user mode, allow apps on user 0 to query the list 5991 synchronized (this) { 5992 // Check if this is the device owner who is calling 5993 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5994 return getKeepUninstalledPackagesLocked(); 5995 } 5996 } 5997 5998 private List<String> getKeepUninstalledPackagesLocked() { 5999 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6000 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 6001 } 6002 6003 @Override 6004 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) { 6005 if (!mHasFeature) { 6006 return false; 6007 } 6008 if (admin == null 6009 || !isPackageInstalledForUser(admin.getPackageName(), userId)) { 6010 throw new IllegalArgumentException("Invalid component " + admin 6011 + " for device owner"); 6012 } 6013 final boolean hasIncompatibleAccountsOrNonAdb = 6014 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin); 6015 synchronized (this) { 6016 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb); 6017 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 6018 if (activeAdmin == null 6019 || getUserData(userId).mRemovingAdmins.contains(admin)) { 6020 throw new IllegalArgumentException("Not active admin: " + admin); 6021 } 6022 6023 // Shutting down backup manager service permanently. 6024 long ident = mInjector.binderClearCallingIdentity(); 6025 try { 6026 if (mInjector.getIBackupManager() != null) { 6027 mInjector.getIBackupManager() 6028 .setBackupServiceActive(UserHandle.USER_SYSTEM, false); 6029 } 6030 } catch (RemoteException e) { 6031 throw new IllegalStateException("Failed deactivating backup service.", e); 6032 } finally { 6033 mInjector.binderRestoreCallingIdentity(ident); 6034 } 6035 6036 if (isAdb()) { 6037 // Log device owner provisioning was started using adb. 6038 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 6039 } 6040 6041 mOwners.setDeviceOwner(admin, ownerName, userId); 6042 mOwners.writeDeviceOwner(); 6043 updateDeviceOwnerLocked(); 6044 setDeviceOwnerSystemPropertyLocked(); 6045 6046 final Set<String> restrictions = 6047 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner(); 6048 if (!restrictions.isEmpty()) { 6049 for (String restriction : restrictions) { 6050 activeAdmin.ensureUserRestrictions().putBoolean(restriction, true); 6051 } 6052 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions); 6053 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions); 6054 6055 saveUserRestrictionsLocked(userId); 6056 } 6057 6058 ident = mInjector.binderClearCallingIdentity(); 6059 try { 6060 // TODO Send to system too? 6061 mContext.sendBroadcastAsUser( 6062 new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 6063 UserHandle.of(userId)); 6064 } finally { 6065 mInjector.binderRestoreCallingIdentity(ident); 6066 } 6067 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 6068 return true; 6069 } 6070 } 6071 6072 @Override 6073 public boolean hasDeviceOwner() { 6074 enforceDeviceOwnerOrManageUsers(); 6075 return mOwners.hasDeviceOwner(); 6076 } 6077 6078 boolean isDeviceOwner(ActiveAdmin admin) { 6079 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 6080 } 6081 6082 public boolean isDeviceOwner(ComponentName who, int userId) { 6083 synchronized (this) { 6084 return mOwners.hasDeviceOwner() 6085 && mOwners.getDeviceOwnerUserId() == userId 6086 && mOwners.getDeviceOwnerComponent().equals(who); 6087 } 6088 } 6089 6090 private boolean isDeviceOwnerPackage(String packageName, int userId) { 6091 synchronized (this) { 6092 return mOwners.hasDeviceOwner() 6093 && mOwners.getDeviceOwnerUserId() == userId 6094 && mOwners.getDeviceOwnerPackageName().equals(packageName); 6095 } 6096 } 6097 6098 public boolean isProfileOwner(ComponentName who, int userId) { 6099 final ComponentName profileOwner = getProfileOwner(userId); 6100 return who != null && who.equals(profileOwner); 6101 } 6102 6103 @Override 6104 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 6105 if (!mHasFeature) { 6106 return null; 6107 } 6108 if (!callingUserOnly) { 6109 enforceManageUsers(); 6110 } 6111 synchronized (this) { 6112 if (!mOwners.hasDeviceOwner()) { 6113 return null; 6114 } 6115 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 6116 mOwners.getDeviceOwnerUserId()) { 6117 return null; 6118 } 6119 return mOwners.getDeviceOwnerComponent(); 6120 } 6121 } 6122 6123 @Override 6124 public int getDeviceOwnerUserId() { 6125 if (!mHasFeature) { 6126 return UserHandle.USER_NULL; 6127 } 6128 enforceManageUsers(); 6129 synchronized (this) { 6130 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 6131 } 6132 } 6133 6134 /** 6135 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 6136 * MANAGE_USERS. 6137 */ 6138 @Override 6139 public String getDeviceOwnerName() { 6140 if (!mHasFeature) { 6141 return null; 6142 } 6143 enforceManageUsers(); 6144 synchronized (this) { 6145 if (!mOwners.hasDeviceOwner()) { 6146 return null; 6147 } 6148 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 6149 // Should setDeviceOwner/ProfileOwner still take a name? 6150 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 6151 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 6152 } 6153 } 6154 6155 /** Returns the active device owner or {@code null} if there is no device owner. */ 6156 @VisibleForTesting 6157 ActiveAdmin getDeviceOwnerAdminLocked() { 6158 ComponentName component = mOwners.getDeviceOwnerComponent(); 6159 if (component == null) { 6160 return null; 6161 } 6162 6163 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 6164 final int n = policy.mAdminList.size(); 6165 for (int i = 0; i < n; i++) { 6166 ActiveAdmin admin = policy.mAdminList.get(i); 6167 if (component.equals(admin.info.getComponent())) { 6168 return admin; 6169 } 6170 } 6171 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 6172 return null; 6173 } 6174 6175 @Override 6176 public void clearDeviceOwner(String packageName) { 6177 Preconditions.checkNotNull(packageName, "packageName is null"); 6178 final int callingUid = mInjector.binderGetCallingUid(); 6179 try { 6180 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 6181 UserHandle.getUserId(callingUid)); 6182 if (uid != callingUid) { 6183 throw new SecurityException("Invalid packageName"); 6184 } 6185 } catch (NameNotFoundException e) { 6186 throw new SecurityException(e); 6187 } 6188 synchronized (this) { 6189 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 6190 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 6191 if (!mOwners.hasDeviceOwner() 6192 || !deviceOwnerComponent.getPackageName().equals(packageName) 6193 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) { 6194 throw new SecurityException( 6195 "clearDeviceOwner can only be called by the device owner"); 6196 } 6197 enforceUserUnlocked(deviceOwnerUserId); 6198 6199 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 6200 long ident = mInjector.binderClearCallingIdentity(); 6201 try { 6202 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 6203 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 6204 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED); 6205 mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId)); 6206 } finally { 6207 mInjector.binderRestoreCallingIdentity(ident); 6208 } 6209 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 6210 } 6211 } 6212 6213 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 6214 if (admin != null) { 6215 admin.disableCamera = false; 6216 admin.userRestrictions = null; 6217 admin.defaultEnabledRestrictionsAlreadySet.clear(); 6218 admin.forceEphemeralUsers = false; 6219 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 6220 final DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 6221 policyData.mLastSecurityLogRetrievalTime = -1; 6222 policyData.mLastBugReportRequestTime = -1; 6223 policyData.mLastNetworkLogsRetrievalTime = -1; 6224 saveSettingsLocked(UserHandle.USER_SYSTEM); 6225 } 6226 clearUserPoliciesLocked(userId); 6227 6228 mOwners.clearDeviceOwner(); 6229 mOwners.writeDeviceOwner(); 6230 updateDeviceOwnerLocked(); 6231 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded(); 6232 try { 6233 if (mInjector.getIBackupManager() != null) { 6234 // Reactivate backup service. 6235 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true); 6236 } 6237 } catch (RemoteException e) { 6238 throw new IllegalStateException("Failed reactivating backup service.", e); 6239 } 6240 } 6241 6242 @Override 6243 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 6244 if (!mHasFeature) { 6245 return false; 6246 } 6247 if (who == null 6248 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) { 6249 throw new IllegalArgumentException("Component " + who 6250 + " not installed for userId:" + userHandle); 6251 } 6252 final boolean hasIncompatibleAccountsOrNonAdb = 6253 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who); 6254 synchronized (this) { 6255 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb); 6256 6257 if (getActiveAdminUncheckedLocked(who, userHandle) == null 6258 || getUserData(userHandle).mRemovingAdmins.contains(who)) { 6259 throw new IllegalArgumentException("Not active admin: " + who); 6260 } 6261 6262 if (isAdb()) { 6263 // Log profile owner provisioning was started using adb. 6264 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 6265 } 6266 6267 mOwners.setProfileOwner(who, ownerName, userHandle); 6268 mOwners.writeProfileOwner(userHandle); 6269 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 6270 6271 return true; 6272 } 6273 } 6274 6275 @Override 6276 public void clearProfileOwner(ComponentName who) { 6277 if (!mHasFeature) { 6278 return; 6279 } 6280 final UserHandle callingUser = mInjector.binderGetCallingUserHandle(); 6281 final int userId = callingUser.getIdentifier(); 6282 enforceNotManagedProfile(userId, "clear profile owner"); 6283 enforceUserUnlocked(userId); 6284 // Check if this is the profile owner who is calling 6285 final ActiveAdmin admin = 6286 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6287 synchronized (this) { 6288 final long ident = mInjector.binderClearCallingIdentity(); 6289 try { 6290 clearProfileOwnerLocked(admin, userId); 6291 removeActiveAdminLocked(who, userId); 6292 } finally { 6293 mInjector.binderRestoreCallingIdentity(ident); 6294 } 6295 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 6296 } 6297 } 6298 6299 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 6300 if (admin != null) { 6301 admin.disableCamera = false; 6302 admin.userRestrictions = null; 6303 admin.defaultEnabledRestrictionsAlreadySet.clear(); 6304 } 6305 clearUserPoliciesLocked(userId); 6306 mOwners.removeProfileOwner(userId); 6307 mOwners.writeProfileOwner(userId); 6308 } 6309 6310 @Override 6311 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 6312 Preconditions.checkNotNull(who, "ComponentName is null"); 6313 if (!mHasFeature) { 6314 return; 6315 } 6316 6317 synchronized (this) { 6318 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6319 long token = mInjector.binderClearCallingIdentity(); 6320 try { 6321 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null); 6322 } finally { 6323 mInjector.binderRestoreCallingIdentity(token); 6324 } 6325 } 6326 } 6327 6328 @Override 6329 public CharSequence getDeviceOwnerLockScreenInfo() { 6330 return mLockPatternUtils.getDeviceOwnerInfo(); 6331 } 6332 6333 private void clearUserPoliciesLocked(int userId) { 6334 // Reset some of the user-specific policies 6335 DevicePolicyData policy = getUserData(userId); 6336 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 6337 policy.mDelegatedCertInstallerPackage = null; 6338 policy.mApplicationRestrictionsManagingPackage = null; 6339 policy.mStatusBarDisabled = false; 6340 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 6341 saveSettingsLocked(userId); 6342 6343 try { 6344 mIPackageManager.updatePermissionFlagsForAllApps( 6345 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 6346 0 /* flagValues */, userId); 6347 pushUserRestrictions(userId); 6348 } catch (RemoteException re) { 6349 // Shouldn't happen. 6350 } 6351 } 6352 6353 @Override 6354 public boolean hasUserSetupCompleted() { 6355 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 6356 } 6357 6358 // This checks only if the Setup Wizard has run. Since Wear devices pair before 6359 // completing Setup Wizard, and pairing involves transferring user data, calling 6360 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). 6361 private boolean hasUserSetupCompleted(int userHandle) { 6362 if (!mHasFeature) { 6363 return true; 6364 } 6365 return getUserData(userHandle).mUserSetupComplete; 6366 } 6367 6368 private boolean hasPaired(int userHandle) { 6369 if (!mHasFeature) { 6370 return true; 6371 } 6372 return getUserData(userHandle).mPaired; 6373 } 6374 6375 @Override 6376 public int getUserProvisioningState() { 6377 if (!mHasFeature) { 6378 return DevicePolicyManager.STATE_USER_UNMANAGED; 6379 } 6380 int userHandle = mInjector.userHandleGetCallingUserId(); 6381 return getUserProvisioningState(userHandle); 6382 } 6383 6384 private int getUserProvisioningState(int userHandle) { 6385 return getUserData(userHandle).mUserProvisioningState; 6386 } 6387 6388 @Override 6389 public void setUserProvisioningState(int newState, int userHandle) { 6390 if (!mHasFeature) { 6391 return; 6392 } 6393 6394 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle) 6395 && getManagedUserId(userHandle) == -1) { 6396 // No managed device, user or profile, so setting provisioning state makes no sense. 6397 throw new IllegalStateException("Not allowed to change provisioning state unless a " 6398 + "device or profile owner is set."); 6399 } 6400 6401 synchronized (this) { 6402 boolean transitionCheckNeeded = true; 6403 6404 // Calling identity/permission checks. 6405 if (isAdb()) { 6406 // ADB shell can only move directly from un-managed to finalized as part of directly 6407 // setting profile-owner or device-owner. 6408 if (getUserProvisioningState(userHandle) != 6409 DevicePolicyManager.STATE_USER_UNMANAGED 6410 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 6411 throw new IllegalStateException("Not allowed to change provisioning state " 6412 + "unless current provisioning state is unmanaged, and new state is " 6413 + "finalized."); 6414 } 6415 transitionCheckNeeded = false; 6416 } else { 6417 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS. 6418 enforceCanManageProfileAndDeviceOwners(); 6419 } 6420 6421 final DevicePolicyData policyData = getUserData(userHandle); 6422 if (transitionCheckNeeded) { 6423 // Optional state transition check for non-ADB case. 6424 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState); 6425 } 6426 policyData.mUserProvisioningState = newState; 6427 saveSettingsLocked(userHandle); 6428 } 6429 } 6430 6431 private void checkUserProvisioningStateTransition(int currentState, int newState) { 6432 // Valid transitions for normal use-cases. 6433 switch (currentState) { 6434 case DevicePolicyManager.STATE_USER_UNMANAGED: 6435 // Can move to any state from unmanaged (except itself as an edge case).. 6436 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 6437 return; 6438 } 6439 break; 6440 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 6441 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 6442 // Can only move to finalized from these states. 6443 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 6444 return; 6445 } 6446 break; 6447 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 6448 // Current user has a managed-profile, but current user is not managed, so 6449 // rather than moving to finalized state, go back to unmanaged once 6450 // profile provisioning is complete. 6451 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 6452 return; 6453 } 6454 break; 6455 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED: 6456 // Cannot transition out of finalized. 6457 break; 6458 } 6459 6460 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 6461 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 6462 + "from state [" + currentState + "]"); 6463 } 6464 6465 @Override 6466 public void setProfileEnabled(ComponentName who) { 6467 if (!mHasFeature) { 6468 return; 6469 } 6470 Preconditions.checkNotNull(who, "ComponentName is null"); 6471 synchronized (this) { 6472 // Check if this is the profile owner who is calling 6473 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6474 final int userId = UserHandle.getCallingUserId(); 6475 enforceManagedProfile(userId, "enable the profile"); 6476 // Check if the profile is already enabled. 6477 UserInfo managedProfile = getUserInfo(userId); 6478 if (managedProfile.isEnabled()) { 6479 Slog.e(LOG_TAG, 6480 "setProfileEnabled is called when the profile is already enabled"); 6481 return; 6482 } 6483 long id = mInjector.binderClearCallingIdentity(); 6484 try { 6485 mUserManager.setUserEnabled(userId); 6486 UserInfo parent = mUserManager.getProfileParent(userId); 6487 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 6488 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 6489 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 6490 Intent.FLAG_RECEIVER_FOREGROUND); 6491 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id)); 6492 } finally { 6493 mInjector.binderRestoreCallingIdentity(id); 6494 } 6495 } 6496 } 6497 6498 @Override 6499 public void setProfileName(ComponentName who, String profileName) { 6500 Preconditions.checkNotNull(who, "ComponentName is null"); 6501 int userId = UserHandle.getCallingUserId(); 6502 // Check if this is the profile owner (includes device owner). 6503 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6504 6505 long id = mInjector.binderClearCallingIdentity(); 6506 try { 6507 mUserManager.setUserName(userId, profileName); 6508 } finally { 6509 mInjector.binderRestoreCallingIdentity(id); 6510 } 6511 } 6512 6513 @Override 6514 public ComponentName getProfileOwner(int userHandle) { 6515 if (!mHasFeature) { 6516 return null; 6517 } 6518 6519 synchronized (this) { 6520 return mOwners.getProfileOwnerComponent(userHandle); 6521 } 6522 } 6523 6524 // Returns the active profile owner for this user or null if the current user has no 6525 // profile owner. 6526 @VisibleForTesting 6527 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 6528 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 6529 if (profileOwner == null) { 6530 return null; 6531 } 6532 DevicePolicyData policy = getUserData(userHandle); 6533 final int n = policy.mAdminList.size(); 6534 for (int i = 0; i < n; i++) { 6535 ActiveAdmin admin = policy.mAdminList.get(i); 6536 if (profileOwner.equals(admin.info.getComponent())) { 6537 return admin; 6538 } 6539 } 6540 return null; 6541 } 6542 6543 @Override 6544 public String getProfileOwnerName(int userHandle) { 6545 if (!mHasFeature) { 6546 return null; 6547 } 6548 enforceManageUsers(); 6549 ComponentName profileOwner = getProfileOwner(userHandle); 6550 if (profileOwner == null) { 6551 return null; 6552 } 6553 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 6554 } 6555 6556 /** 6557 * Canonical name for a given package. 6558 */ 6559 private String getApplicationLabel(String packageName, int userHandle) { 6560 long token = mInjector.binderClearCallingIdentity(); 6561 try { 6562 final Context userContext; 6563 try { 6564 UserHandle handle = new UserHandle(userHandle); 6565 userContext = mContext.createPackageContextAsUser(packageName, 0, handle); 6566 } catch (PackageManager.NameNotFoundException nnfe) { 6567 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe); 6568 return null; 6569 } 6570 ApplicationInfo appInfo = userContext.getApplicationInfo(); 6571 CharSequence result = null; 6572 if (appInfo != null) { 6573 PackageManager pm = userContext.getPackageManager(); 6574 result = pm.getApplicationLabel(appInfo); 6575 } 6576 return result != null ? result.toString() : null; 6577 } finally { 6578 mInjector.binderRestoreCallingIdentity(token); 6579 } 6580 } 6581 6582 /** 6583 * Calls wtfStack() if called with the DPMS lock held. 6584 */ 6585 private void wtfIfInLock() { 6586 if (Thread.holdsLock(this)) { 6587 Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held"); 6588 } 6589 } 6590 6591 /** 6592 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 6593 * permission. 6594 * The profile owner can only be set before the user setup phase has completed, 6595 * except for: 6596 * - SYSTEM_UID 6597 * - adb unless hasIncompatibleAccountsOrNonAdb is true. 6598 */ 6599 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle, 6600 boolean hasIncompatibleAccountsOrNonAdb) { 6601 UserInfo info = getUserInfo(userHandle); 6602 if (info == null) { 6603 // User doesn't exist. 6604 throw new IllegalArgumentException( 6605 "Attempted to set profile owner for invalid userId: " + userHandle); 6606 } 6607 if (info.isGuest()) { 6608 throw new IllegalStateException("Cannot set a profile owner on a guest"); 6609 } 6610 if (mOwners.hasProfileOwner(userHandle)) { 6611 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 6612 + "is already set."); 6613 } 6614 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 6615 throw new IllegalStateException("Trying to set the profile owner, but the user " 6616 + "already has a device owner."); 6617 } 6618 if (isAdb()) { 6619 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 6620 && hasIncompatibleAccountsOrNonAdb) { 6621 throw new IllegalStateException("Not allowed to set the profile owner because " 6622 + "there are already some accounts on the profile"); 6623 } 6624 return; 6625 } 6626 enforceCanManageProfileAndDeviceOwners(); 6627 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) { 6628 throw new IllegalStateException("Cannot set the profile owner on a user which is " 6629 + "already set-up"); 6630 } 6631 } 6632 6633 /** 6634 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 6635 * permission. 6636 */ 6637 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId, 6638 boolean hasIncompatibleAccountsOrNonAdb) { 6639 if (!isAdb()) { 6640 enforceCanManageProfileAndDeviceOwners(); 6641 } 6642 6643 final int code = checkDeviceOwnerProvisioningPreConditionLocked( 6644 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb); 6645 switch (code) { 6646 case CODE_OK: 6647 return; 6648 case CODE_HAS_DEVICE_OWNER: 6649 throw new IllegalStateException( 6650 "Trying to set the device owner, but device owner is already set."); 6651 case CODE_USER_HAS_PROFILE_OWNER: 6652 throw new IllegalStateException("Trying to set the device owner, but the user " 6653 + "already has a profile owner."); 6654 case CODE_USER_NOT_RUNNING: 6655 throw new IllegalStateException("User not running: " + userId); 6656 case CODE_NOT_SYSTEM_USER: 6657 throw new IllegalStateException("User is not system user"); 6658 case CODE_USER_SETUP_COMPLETED: 6659 throw new IllegalStateException( 6660 "Cannot set the device owner if the device is already set-up"); 6661 case CODE_NONSYSTEM_USER_EXISTS: 6662 throw new IllegalStateException("Not allowed to set the device owner because there " 6663 + "are already several users on the device"); 6664 case CODE_ACCOUNTS_NOT_EMPTY: 6665 throw new IllegalStateException("Not allowed to set the device owner because there " 6666 + "are already some accounts on the device"); 6667 case CODE_HAS_PAIRED: 6668 throw new IllegalStateException("Not allowed to set the device owner because this " 6669 + "device has already paired"); 6670 default: 6671 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code); 6672 } 6673 } 6674 6675 private void enforceUserUnlocked(int userId) { 6676 // Since we're doing this operation on behalf of an app, we only 6677 // want to use the actual "unlocked" state. 6678 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 6679 "User must be running and unlocked"); 6680 } 6681 6682 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 6683 if (parent) { 6684 enforceUserUnlocked(getProfileParentId(userId)); 6685 } else { 6686 enforceUserUnlocked(userId); 6687 } 6688 } 6689 6690 private void enforceManageUsers() { 6691 final int callingUid = mInjector.binderGetCallingUid(); 6692 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 6693 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 6694 } 6695 } 6696 6697 private void enforceFullCrossUsersPermission(int userHandle) { 6698 enforceSystemUserOrPermission(userHandle, 6699 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 6700 } 6701 6702 private void enforceCrossUsersPermission(int userHandle) { 6703 enforceSystemUserOrPermission(userHandle, 6704 android.Manifest.permission.INTERACT_ACROSS_USERS); 6705 } 6706 6707 private void enforceSystemUserOrPermission(int userHandle, String permission) { 6708 if (userHandle < 0) { 6709 throw new IllegalArgumentException("Invalid userId " + userHandle); 6710 } 6711 final int callingUid = mInjector.binderGetCallingUid(); 6712 if (userHandle == UserHandle.getUserId(callingUid)) { 6713 return; 6714 } 6715 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 6716 mContext.enforceCallingOrSelfPermission(permission, 6717 "Must be system or have " + permission + " permission"); 6718 } 6719 } 6720 6721 private void enforceManagedProfile(int userHandle, String message) { 6722 if(!isManagedProfile(userHandle)) { 6723 throw new SecurityException("You can not " + message + " outside a managed profile."); 6724 } 6725 } 6726 6727 private void enforceNotManagedProfile(int userHandle, String message) { 6728 if(isManagedProfile(userHandle)) { 6729 throw new SecurityException("You can not " + message + " for a managed profile."); 6730 } 6731 } 6732 6733 private void enforceDeviceOwnerOrManageUsers() { 6734 synchronized (this) { 6735 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 6736 mInjector.binderGetCallingUid()) != null) { 6737 return; 6738 } 6739 } 6740 enforceManageUsers(); 6741 } 6742 6743 private void ensureCallerPackage(@Nullable String packageName) { 6744 if (packageName == null) { 6745 Preconditions.checkState(isCallerWithSystemUid(), 6746 "Only caller can omit package name"); 6747 } else { 6748 final int callingUid = mInjector.binderGetCallingUid(); 6749 final int userId = mInjector.userHandleGetCallingUserId(); 6750 try { 6751 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 6752 packageName, 0, userId); 6753 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name"); 6754 } catch (RemoteException e) { 6755 // Shouldn't happen 6756 } 6757 } 6758 } 6759 6760 private boolean isCallerWithSystemUid() { 6761 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID); 6762 } 6763 6764 private int getProfileParentId(int userHandle) { 6765 final long ident = mInjector.binderClearCallingIdentity(); 6766 try { 6767 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 6768 return parentUser != null ? parentUser.id : userHandle; 6769 } finally { 6770 mInjector.binderRestoreCallingIdentity(ident); 6771 } 6772 } 6773 6774 private int getCredentialOwner(int userHandle, boolean parent) { 6775 final long ident = mInjector.binderClearCallingIdentity(); 6776 try { 6777 if (parent) { 6778 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 6779 if (parentProfile != null) { 6780 userHandle = parentProfile.id; 6781 } 6782 } 6783 return mUserManager.getCredentialOwnerProfile(userHandle); 6784 } finally { 6785 mInjector.binderRestoreCallingIdentity(ident); 6786 } 6787 } 6788 6789 private boolean isManagedProfile(int userHandle) { 6790 final UserInfo user = getUserInfo(userHandle); 6791 return user != null && user.isManagedProfile(); 6792 } 6793 6794 private void enableIfNecessary(String packageName, int userId) { 6795 try { 6796 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 6797 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 6798 userId); 6799 if (ai.enabledSetting 6800 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 6801 mIPackageManager.setApplicationEnabledSetting(packageName, 6802 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 6803 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 6804 } 6805 } catch (RemoteException e) { 6806 } 6807 } 6808 6809 @Override 6810 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 6811 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 6812 != PackageManager.PERMISSION_GRANTED) { 6813 6814 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid=" 6815 + mInjector.binderGetCallingPid() 6816 + ", uid=" + mInjector.binderGetCallingUid()); 6817 return; 6818 } 6819 6820 synchronized (this) { 6821 pw.println("Current Device Policy Manager state:"); 6822 mOwners.dump(" ", pw); 6823 int userCount = mUserData.size(); 6824 for (int u = 0; u < userCount; u++) { 6825 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 6826 pw.println(); 6827 pw.println(" Enabled Device Admins (User " + policy.mUserHandle 6828 + ", provisioningState: " + policy.mUserProvisioningState + "):"); 6829 final int N = policy.mAdminList.size(); 6830 for (int i=0; i<N; i++) { 6831 ActiveAdmin ap = policy.mAdminList.get(i); 6832 if (ap != null) { 6833 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 6834 pw.println(":"); 6835 ap.dump(" ", pw); 6836 } 6837 } 6838 if (!policy.mRemovingAdmins.isEmpty()) { 6839 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 6840 + policy.mRemovingAdmins); 6841 } 6842 6843 pw.println(" "); 6844 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 6845 } 6846 pw.println(); 6847 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 6848 } 6849 } 6850 6851 private String getEncryptionStatusName(int encryptionStatus) { 6852 switch (encryptionStatus) { 6853 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 6854 return "inactive"; 6855 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 6856 return "block default key"; 6857 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 6858 return "block"; 6859 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 6860 return "per-user"; 6861 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 6862 return "unsupported"; 6863 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 6864 return "activating"; 6865 default: 6866 return "unknown"; 6867 } 6868 } 6869 6870 @Override 6871 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 6872 ComponentName activity) { 6873 Preconditions.checkNotNull(who, "ComponentName is null"); 6874 final int userHandle = UserHandle.getCallingUserId(); 6875 synchronized (this) { 6876 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6877 6878 long id = mInjector.binderClearCallingIdentity(); 6879 try { 6880 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 6881 } catch (RemoteException re) { 6882 // Shouldn't happen 6883 } finally { 6884 mInjector.binderRestoreCallingIdentity(id); 6885 } 6886 } 6887 } 6888 6889 @Override 6890 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 6891 Preconditions.checkNotNull(who, "ComponentName is null"); 6892 final int userHandle = UserHandle.getCallingUserId(); 6893 synchronized (this) { 6894 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6895 6896 long id = mInjector.binderClearCallingIdentity(); 6897 try { 6898 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 6899 } catch (RemoteException re) { 6900 // Shouldn't happen 6901 } finally { 6902 mInjector.binderRestoreCallingIdentity(id); 6903 } 6904 } 6905 } 6906 6907 @Override 6908 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 6909 String packageName) { 6910 Preconditions.checkNotNull(admin, "ComponentName is null"); 6911 6912 final int userHandle = mInjector.userHandleGetCallingUserId(); 6913 synchronized (this) { 6914 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6915 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) { 6916 return false; 6917 } 6918 DevicePolicyData policy = getUserData(userHandle); 6919 policy.mApplicationRestrictionsManagingPackage = packageName; 6920 saveSettingsLocked(userHandle); 6921 return true; 6922 } 6923 } 6924 6925 @Override 6926 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 6927 Preconditions.checkNotNull(admin, "ComponentName is null"); 6928 6929 final int userHandle = mInjector.userHandleGetCallingUserId(); 6930 synchronized (this) { 6931 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6932 DevicePolicyData policy = getUserData(userHandle); 6933 return policy.mApplicationRestrictionsManagingPackage; 6934 } 6935 } 6936 6937 @Override 6938 public boolean isCallerApplicationRestrictionsManagingPackage() { 6939 final int callingUid = mInjector.binderGetCallingUid(); 6940 final int userHandle = UserHandle.getUserId(callingUid); 6941 synchronized (this) { 6942 final DevicePolicyData policy = getUserData(userHandle); 6943 if (policy.mApplicationRestrictionsManagingPackage == null) { 6944 return false; 6945 } 6946 6947 try { 6948 int uid = mInjector.getPackageManager().getPackageUidAsUser( 6949 policy.mApplicationRestrictionsManagingPackage, userHandle); 6950 return uid == callingUid; 6951 } catch (NameNotFoundException e) { 6952 return false; 6953 } 6954 } 6955 } 6956 6957 private void enforceCanManageApplicationRestrictions(ComponentName who) { 6958 if (who != null) { 6959 synchronized (this) { 6960 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6961 } 6962 } else if (!isCallerApplicationRestrictionsManagingPackage()) { 6963 throw new SecurityException( 6964 "No admin component given, and caller cannot manage application restrictions " 6965 + "for other apps."); 6966 } 6967 } 6968 6969 @Override 6970 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) { 6971 enforceCanManageApplicationRestrictions(who); 6972 6973 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 6974 final long id = mInjector.binderClearCallingIdentity(); 6975 try { 6976 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 6977 } finally { 6978 mInjector.binderRestoreCallingIdentity(id); 6979 } 6980 } 6981 6982 @Override 6983 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 6984 PersistableBundle args, boolean parent) { 6985 if (!mHasFeature) { 6986 return; 6987 } 6988 Preconditions.checkNotNull(admin, "admin is null"); 6989 Preconditions.checkNotNull(agent, "agent is null"); 6990 final int userHandle = UserHandle.getCallingUserId(); 6991 synchronized (this) { 6992 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 6993 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 6994 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 6995 saveSettingsLocked(userHandle); 6996 } 6997 } 6998 6999 @Override 7000 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 7001 ComponentName agent, int userHandle, boolean parent) { 7002 if (!mHasFeature) { 7003 return null; 7004 } 7005 Preconditions.checkNotNull(agent, "agent null"); 7006 enforceFullCrossUsersPermission(userHandle); 7007 7008 synchronized (this) { 7009 final String componentName = agent.flattenToString(); 7010 if (admin != null) { 7011 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 7012 if (ap == null) return null; 7013 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 7014 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 7015 List<PersistableBundle> result = new ArrayList<>(); 7016 result.add(trustAgentInfo.options); 7017 return result; 7018 } 7019 7020 // Return strictest policy for this user and profiles that are visible from this user. 7021 List<PersistableBundle> result = null; 7022 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 7023 // of the options. If any admin doesn't have options, discard options for the rest 7024 // and return null. 7025 List<ActiveAdmin> admins = 7026 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 7027 boolean allAdminsHaveOptions = true; 7028 final int N = admins.size(); 7029 for (int i = 0; i < N; i++) { 7030 final ActiveAdmin active = admins.get(i); 7031 7032 final boolean disablesTrust = (active.disabledKeyguardFeatures 7033 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 7034 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 7035 if (info != null && info.options != null && !info.options.isEmpty()) { 7036 if (disablesTrust) { 7037 if (result == null) { 7038 result = new ArrayList<>(); 7039 } 7040 result.add(info.options); 7041 } else { 7042 Log.w(LOG_TAG, "Ignoring admin " + active.info 7043 + " because it has trust options but doesn't declare " 7044 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 7045 } 7046 } else if (disablesTrust) { 7047 allAdminsHaveOptions = false; 7048 break; 7049 } 7050 } 7051 return allAdminsHaveOptions ? result : null; 7052 } 7053 } 7054 7055 @Override 7056 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 7057 Preconditions.checkNotNull(who, "ComponentName is null"); 7058 synchronized (this) { 7059 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7060 7061 int userHandle = UserHandle.getCallingUserId(); 7062 DevicePolicyData userData = getUserData(userHandle); 7063 userData.mRestrictionsProvider = permissionProvider; 7064 saveSettingsLocked(userHandle); 7065 } 7066 } 7067 7068 @Override 7069 public ComponentName getRestrictionsProvider(int userHandle) { 7070 synchronized (this) { 7071 if (!isCallerWithSystemUid()) { 7072 throw new SecurityException("Only the system can query the permission provider"); 7073 } 7074 DevicePolicyData userData = getUserData(userHandle); 7075 return userData != null ? userData.mRestrictionsProvider : null; 7076 } 7077 } 7078 7079 @Override 7080 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 7081 Preconditions.checkNotNull(who, "ComponentName is null"); 7082 int callingUserId = UserHandle.getCallingUserId(); 7083 synchronized (this) { 7084 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7085 7086 long id = mInjector.binderClearCallingIdentity(); 7087 try { 7088 UserInfo parent = mUserManager.getProfileParent(callingUserId); 7089 if (parent == null) { 7090 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 7091 + "parent"); 7092 return; 7093 } 7094 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 7095 mIPackageManager.addCrossProfileIntentFilter( 7096 filter, who.getPackageName(), callingUserId, parent.id, 0); 7097 } 7098 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 7099 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 7100 parent.id, callingUserId, 0); 7101 } 7102 } catch (RemoteException re) { 7103 // Shouldn't happen 7104 } finally { 7105 mInjector.binderRestoreCallingIdentity(id); 7106 } 7107 } 7108 } 7109 7110 @Override 7111 public void clearCrossProfileIntentFilters(ComponentName who) { 7112 Preconditions.checkNotNull(who, "ComponentName is null"); 7113 int callingUserId = UserHandle.getCallingUserId(); 7114 synchronized (this) { 7115 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7116 long id = mInjector.binderClearCallingIdentity(); 7117 try { 7118 UserInfo parent = mUserManager.getProfileParent(callingUserId); 7119 if (parent == null) { 7120 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 7121 + "parent"); 7122 return; 7123 } 7124 // Removing those that go from the managed profile to the parent. 7125 mIPackageManager.clearCrossProfileIntentFilters( 7126 callingUserId, who.getPackageName()); 7127 // And those that go from the parent to the managed profile. 7128 // If we want to support multiple managed profiles, we will have to only remove 7129 // those that have callingUserId as their target. 7130 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 7131 } catch (RemoteException re) { 7132 // Shouldn't happen 7133 } finally { 7134 mInjector.binderRestoreCallingIdentity(id); 7135 } 7136 } 7137 } 7138 7139 /** 7140 * @return true if all packages in enabledPackages are either in the list 7141 * permittedList or are a system app. 7142 */ 7143 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 7144 List<String> permittedList, int userIdToCheck) { 7145 long id = mInjector.binderClearCallingIdentity(); 7146 try { 7147 // If we have an enabled packages list for a managed profile the packages 7148 // we should check are installed for the parent user. 7149 UserInfo user = getUserInfo(userIdToCheck); 7150 if (user.isManagedProfile()) { 7151 userIdToCheck = user.profileGroupId; 7152 } 7153 7154 for (String enabledPackage : enabledPackages) { 7155 boolean systemService = false; 7156 try { 7157 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 7158 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 7159 userIdToCheck); 7160 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7161 } catch (RemoteException e) { 7162 Log.i(LOG_TAG, "Can't talk to package managed", e); 7163 } 7164 if (!systemService && !permittedList.contains(enabledPackage)) { 7165 return false; 7166 } 7167 } 7168 } finally { 7169 mInjector.binderRestoreCallingIdentity(id); 7170 } 7171 return true; 7172 } 7173 7174 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 7175 // Not using AccessibilityManager.getInstance because that guesses 7176 // at the user you require based on callingUid and caches for a given 7177 // process. 7178 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 7179 IAccessibilityManager service = iBinder == null 7180 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 7181 return new AccessibilityManager(mContext, service, userId); 7182 } 7183 7184 @Override 7185 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 7186 if (!mHasFeature) { 7187 return false; 7188 } 7189 Preconditions.checkNotNull(who, "ComponentName is null"); 7190 7191 if (packageList != null) { 7192 int userId = UserHandle.getCallingUserId(); 7193 List<AccessibilityServiceInfo> enabledServices = null; 7194 long id = mInjector.binderClearCallingIdentity(); 7195 try { 7196 UserInfo user = getUserInfo(userId); 7197 if (user.isManagedProfile()) { 7198 userId = user.profileGroupId; 7199 } 7200 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 7201 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 7202 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 7203 } finally { 7204 mInjector.binderRestoreCallingIdentity(id); 7205 } 7206 7207 if (enabledServices != null) { 7208 List<String> enabledPackages = new ArrayList<String>(); 7209 for (AccessibilityServiceInfo service : enabledServices) { 7210 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 7211 } 7212 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 7213 userId)) { 7214 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 7215 + "because it contains already enabled accesibility services."); 7216 return false; 7217 } 7218 } 7219 } 7220 7221 synchronized (this) { 7222 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7223 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7224 admin.permittedAccessiblityServices = packageList; 7225 saveSettingsLocked(UserHandle.getCallingUserId()); 7226 } 7227 return true; 7228 } 7229 7230 @Override 7231 public List getPermittedAccessibilityServices(ComponentName who) { 7232 if (!mHasFeature) { 7233 return null; 7234 } 7235 Preconditions.checkNotNull(who, "ComponentName is null"); 7236 7237 synchronized (this) { 7238 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7239 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7240 return admin.permittedAccessiblityServices; 7241 } 7242 } 7243 7244 @Override 7245 public List getPermittedAccessibilityServicesForUser(int userId) { 7246 if (!mHasFeature) { 7247 return null; 7248 } 7249 synchronized (this) { 7250 List<String> result = null; 7251 // If we have multiple profiles we return the intersection of the 7252 // permitted lists. This can happen in cases where we have a device 7253 // and profile owner. 7254 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 7255 for (int profileId : profileIds) { 7256 // Just loop though all admins, only device or profiles 7257 // owners can have permitted lists set. 7258 DevicePolicyData policy = getUserDataUnchecked(profileId); 7259 final int N = policy.mAdminList.size(); 7260 for (int j = 0; j < N; j++) { 7261 ActiveAdmin admin = policy.mAdminList.get(j); 7262 List<String> fromAdmin = admin.permittedAccessiblityServices; 7263 if (fromAdmin != null) { 7264 if (result == null) { 7265 result = new ArrayList<>(fromAdmin); 7266 } else { 7267 result.retainAll(fromAdmin); 7268 } 7269 } 7270 } 7271 } 7272 7273 // If we have a permitted list add all system accessibility services. 7274 if (result != null) { 7275 long id = mInjector.binderClearCallingIdentity(); 7276 try { 7277 UserInfo user = getUserInfo(userId); 7278 if (user.isManagedProfile()) { 7279 userId = user.profileGroupId; 7280 } 7281 AccessibilityManager accessibilityManager = 7282 getAccessibilityManagerForUser(userId); 7283 List<AccessibilityServiceInfo> installedServices = 7284 accessibilityManager.getInstalledAccessibilityServiceList(); 7285 7286 if (installedServices != null) { 7287 for (AccessibilityServiceInfo service : installedServices) { 7288 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 7289 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 7290 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7291 result.add(serviceInfo.packageName); 7292 } 7293 } 7294 } 7295 } finally { 7296 mInjector.binderRestoreCallingIdentity(id); 7297 } 7298 } 7299 7300 return result; 7301 } 7302 } 7303 7304 @Override 7305 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 7306 int userHandle) { 7307 if (!mHasFeature) { 7308 return true; 7309 } 7310 Preconditions.checkNotNull(who, "ComponentName is null"); 7311 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 7312 if (!isCallerWithSystemUid()){ 7313 throw new SecurityException( 7314 "Only the system can query if an accessibility service is disabled by admin"); 7315 } 7316 synchronized (this) { 7317 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7318 if (admin == null) { 7319 return false; 7320 } 7321 if (admin.permittedAccessiblityServices == null) { 7322 return true; 7323 } 7324 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName), 7325 admin.permittedAccessiblityServices, userHandle); 7326 } 7327 } 7328 7329 private boolean checkCallerIsCurrentUserOrProfile() { 7330 int callingUserId = UserHandle.getCallingUserId(); 7331 long token = mInjector.binderClearCallingIdentity(); 7332 try { 7333 UserInfo currentUser; 7334 UserInfo callingUser = getUserInfo(callingUserId); 7335 try { 7336 currentUser = mInjector.getIActivityManager().getCurrentUser(); 7337 } catch (RemoteException e) { 7338 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 7339 return false; 7340 } 7341 7342 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 7343 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 7344 + "of a user that isn't the foreground user."); 7345 return false; 7346 } 7347 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 7348 Slog.e(LOG_TAG, "Cannot set permitted input methods " 7349 + "of a user that isn't the foreground user."); 7350 return false; 7351 } 7352 } finally { 7353 mInjector.binderRestoreCallingIdentity(token); 7354 } 7355 return true; 7356 } 7357 7358 @Override 7359 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 7360 if (!mHasFeature) { 7361 return false; 7362 } 7363 Preconditions.checkNotNull(who, "ComponentName is null"); 7364 7365 // TODO When InputMethodManager supports per user calls remove 7366 // this restriction. 7367 if (!checkCallerIsCurrentUserOrProfile()) { 7368 return false; 7369 } 7370 7371 if (packageList != null) { 7372 // InputMethodManager fetches input methods for current user. 7373 // So this can only be set when calling user is the current user 7374 // or parent is current user in case of managed profiles. 7375 InputMethodManager inputMethodManager = 7376 mContext.getSystemService(InputMethodManager.class); 7377 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList(); 7378 7379 if (enabledImes != null) { 7380 List<String> enabledPackages = new ArrayList<String>(); 7381 for (InputMethodInfo ime : enabledImes) { 7382 enabledPackages.add(ime.getPackageName()); 7383 } 7384 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 7385 mInjector.binderGetCallingUserHandle().getIdentifier())) { 7386 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 7387 + "because it contains already enabled input method."); 7388 return false; 7389 } 7390 } 7391 } 7392 7393 synchronized (this) { 7394 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7395 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7396 admin.permittedInputMethods = packageList; 7397 saveSettingsLocked(UserHandle.getCallingUserId()); 7398 } 7399 return true; 7400 } 7401 7402 @Override 7403 public List getPermittedInputMethods(ComponentName who) { 7404 if (!mHasFeature) { 7405 return null; 7406 } 7407 Preconditions.checkNotNull(who, "ComponentName is null"); 7408 7409 synchronized (this) { 7410 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7411 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7412 return admin.permittedInputMethods; 7413 } 7414 } 7415 7416 @Override 7417 public List getPermittedInputMethodsForCurrentUser() { 7418 UserInfo currentUser; 7419 try { 7420 currentUser = mInjector.getIActivityManager().getCurrentUser(); 7421 } catch (RemoteException e) { 7422 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e); 7423 // Activity managed is dead, just allow all IMEs 7424 return null; 7425 } 7426 7427 int userId = currentUser.id; 7428 synchronized (this) { 7429 List<String> result = null; 7430 // If we have multiple profiles we return the intersection of the 7431 // permitted lists. This can happen in cases where we have a device 7432 // and profile owner. 7433 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 7434 for (int profileId : profileIds) { 7435 // Just loop though all admins, only device or profiles 7436 // owners can have permitted lists set. 7437 DevicePolicyData policy = getUserDataUnchecked(profileId); 7438 final int N = policy.mAdminList.size(); 7439 for (int j = 0; j < N; j++) { 7440 ActiveAdmin admin = policy.mAdminList.get(j); 7441 List<String> fromAdmin = admin.permittedInputMethods; 7442 if (fromAdmin != null) { 7443 if (result == null) { 7444 result = new ArrayList<String>(fromAdmin); 7445 } else { 7446 result.retainAll(fromAdmin); 7447 } 7448 } 7449 } 7450 } 7451 7452 // If we have a permitted list add all system input methods. 7453 if (result != null) { 7454 InputMethodManager inputMethodManager = 7455 mContext.getSystemService(InputMethodManager.class); 7456 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList(); 7457 long id = mInjector.binderClearCallingIdentity(); 7458 try { 7459 if (imes != null) { 7460 for (InputMethodInfo ime : imes) { 7461 ServiceInfo serviceInfo = ime.getServiceInfo(); 7462 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 7463 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7464 result.add(serviceInfo.packageName); 7465 } 7466 } 7467 } 7468 } finally { 7469 mInjector.binderRestoreCallingIdentity(id); 7470 } 7471 } 7472 return result; 7473 } 7474 } 7475 7476 @Override 7477 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 7478 int userHandle) { 7479 if (!mHasFeature) { 7480 return true; 7481 } 7482 Preconditions.checkNotNull(who, "ComponentName is null"); 7483 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 7484 if (!isCallerWithSystemUid()) { 7485 throw new SecurityException( 7486 "Only the system can query if an input method is disabled by admin"); 7487 } 7488 synchronized (this) { 7489 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7490 if (admin == null) { 7491 return false; 7492 } 7493 if (admin.permittedInputMethods == null) { 7494 return true; 7495 } 7496 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName), 7497 admin.permittedInputMethods, userHandle); 7498 } 7499 } 7500 7501 private void sendAdminEnabledBroadcastLocked(int userHandle) { 7502 DevicePolicyData policyData = getUserData(userHandle); 7503 if (policyData.mAdminBroadcastPending) { 7504 // Send the initialization data to profile owner and delete the data 7505 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 7506 if (admin != null) { 7507 PersistableBundle initBundle = policyData.mInitBundle; 7508 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 7509 initBundle == null ? null : new Bundle(initBundle), null); 7510 } 7511 policyData.mInitBundle = null; 7512 policyData.mAdminBroadcastPending = false; 7513 saveSettingsLocked(userHandle); 7514 } 7515 } 7516 7517 @Override 7518 public UserHandle createAndManageUser(ComponentName admin, String name, 7519 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 7520 Preconditions.checkNotNull(admin, "admin is null"); 7521 Preconditions.checkNotNull(profileOwner, "profileOwner is null"); 7522 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 7523 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 7524 + admin + " are not in the same package"); 7525 } 7526 // Only allow the system user to use this method 7527 if (!mInjector.binderGetCallingUserHandle().isSystem()) { 7528 throw new SecurityException("createAndManageUser was called from non-system user"); 7529 } 7530 if (!mInjector.userManagerIsSplitSystemUser() 7531 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) { 7532 throw new IllegalArgumentException( 7533 "Ephemeral users are only supported on systems with a split system user."); 7534 } 7535 // Create user. 7536 UserHandle user = null; 7537 synchronized (this) { 7538 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7539 7540 final long id = mInjector.binderClearCallingIdentity(); 7541 try { 7542 int userInfoFlags = 0; 7543 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) { 7544 userInfoFlags |= UserInfo.FLAG_EPHEMERAL; 7545 } 7546 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 7547 userInfoFlags); 7548 if (userInfo != null) { 7549 user = userInfo.getUserHandle(); 7550 } 7551 } finally { 7552 mInjector.binderRestoreCallingIdentity(id); 7553 } 7554 } 7555 if (user == null) { 7556 return null; 7557 } 7558 // Set admin. 7559 final long id = mInjector.binderClearCallingIdentity(); 7560 try { 7561 final String adminPkg = admin.getPackageName(); 7562 7563 final int userHandle = user.getIdentifier(); 7564 try { 7565 // Install the profile owner if not present. 7566 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) { 7567 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle); 7568 } 7569 } catch (RemoteException e) { 7570 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, " 7571 + "removing created user", e); 7572 mUserManager.removeUser(user.getIdentifier()); 7573 return null; 7574 } 7575 7576 setActiveAdmin(profileOwner, true, userHandle); 7577 // User is not started yet, the broadcast by setActiveAdmin will not be received. 7578 // So we store adminExtras for broadcasting when the user starts for first time. 7579 synchronized(this) { 7580 DevicePolicyData policyData = getUserData(userHandle); 7581 policyData.mInitBundle = adminExtras; 7582 policyData.mAdminBroadcastPending = true; 7583 saveSettingsLocked(userHandle); 7584 } 7585 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier()); 7586 setProfileOwner(profileOwner, ownerName, userHandle); 7587 7588 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 7589 Settings.Secure.putIntForUser(mContext.getContentResolver(), 7590 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 7591 } 7592 7593 return user; 7594 } finally { 7595 mInjector.binderRestoreCallingIdentity(id); 7596 } 7597 } 7598 7599 @Override 7600 public boolean removeUser(ComponentName who, UserHandle userHandle) { 7601 Preconditions.checkNotNull(who, "ComponentName is null"); 7602 synchronized (this) { 7603 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7604 } 7605 7606 final int callingUserId = mInjector.userHandleGetCallingUserId(); 7607 final long id = mInjector.binderClearCallingIdentity(); 7608 try { 7609 String restriction = isManagedProfile(userHandle.getIdentifier()) 7610 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 7611 : UserManager.DISALLOW_REMOVE_USER; 7612 if (isAdminAffectedByRestriction(who, restriction, callingUserId)) { 7613 Log.w(LOG_TAG, "The device owner cannot remove a user because " 7614 + restriction + " is enabled, and was not set by the device owner"); 7615 return false; 7616 } 7617 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 7618 } finally { 7619 mInjector.binderRestoreCallingIdentity(id); 7620 } 7621 } 7622 7623 private boolean isAdminAffectedByRestriction( 7624 ComponentName admin, String userRestriction, int userId) { 7625 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 7626 case UserManager.RESTRICTION_NOT_SET: 7627 return false; 7628 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 7629 return !isDeviceOwner(admin, userId); 7630 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 7631 return !isProfileOwner(admin, userId); 7632 default: 7633 return true; 7634 } 7635 } 7636 7637 @Override 7638 public boolean switchUser(ComponentName who, UserHandle userHandle) { 7639 Preconditions.checkNotNull(who, "ComponentName is null"); 7640 synchronized (this) { 7641 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7642 7643 long id = mInjector.binderClearCallingIdentity(); 7644 try { 7645 int userId = UserHandle.USER_SYSTEM; 7646 if (userHandle != null) { 7647 userId = userHandle.getIdentifier(); 7648 } 7649 return mInjector.getIActivityManager().switchUser(userId); 7650 } catch (RemoteException e) { 7651 Log.e(LOG_TAG, "Couldn't switch user", e); 7652 return false; 7653 } finally { 7654 mInjector.binderRestoreCallingIdentity(id); 7655 } 7656 } 7657 } 7658 7659 @Override 7660 public Bundle getApplicationRestrictions(ComponentName who, String packageName) { 7661 enforceCanManageApplicationRestrictions(who); 7662 7663 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 7664 final long id = mInjector.binderClearCallingIdentity(); 7665 try { 7666 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 7667 // if no restrictions were saved, mUserManager.getApplicationRestrictions 7668 // returns null, but DPM method should return an empty Bundle as per JavaDoc 7669 return bundle != null ? bundle : Bundle.EMPTY; 7670 } finally { 7671 mInjector.binderRestoreCallingIdentity(id); 7672 } 7673 } 7674 7675 @Override 7676 public String[] setPackagesSuspended(ComponentName who, String[] packageNames, 7677 boolean suspended) { 7678 Preconditions.checkNotNull(who, "ComponentName is null"); 7679 int callingUserId = UserHandle.getCallingUserId(); 7680 synchronized (this) { 7681 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7682 7683 long id = mInjector.binderClearCallingIdentity(); 7684 try { 7685 return mIPackageManager.setPackagesSuspendedAsUser( 7686 packageNames, suspended, callingUserId); 7687 } catch (RemoteException re) { 7688 // Shouldn't happen. 7689 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 7690 } finally { 7691 mInjector.binderRestoreCallingIdentity(id); 7692 } 7693 return packageNames; 7694 } 7695 } 7696 7697 @Override 7698 public boolean isPackageSuspended(ComponentName who, String packageName) { 7699 Preconditions.checkNotNull(who, "ComponentName is null"); 7700 int callingUserId = UserHandle.getCallingUserId(); 7701 synchronized (this) { 7702 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7703 7704 long id = mInjector.binderClearCallingIdentity(); 7705 try { 7706 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId); 7707 } catch (RemoteException re) { 7708 // Shouldn't happen. 7709 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 7710 } finally { 7711 mInjector.binderRestoreCallingIdentity(id); 7712 } 7713 return false; 7714 } 7715 } 7716 7717 @Override 7718 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) { 7719 Preconditions.checkNotNull(who, "ComponentName is null"); 7720 if (!UserRestrictionsUtils.isValidRestriction(key)) { 7721 return; 7722 } 7723 7724 final int userHandle = mInjector.userHandleGetCallingUserId(); 7725 synchronized (this) { 7726 ActiveAdmin activeAdmin = 7727 getActiveAdminForCallerLocked(who, 7728 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7729 final boolean isDeviceOwner = isDeviceOwner(who, userHandle); 7730 if (isDeviceOwner) { 7731 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 7732 throw new SecurityException("Device owner cannot set user restriction " + key); 7733 } 7734 } else { // profile owner 7735 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) { 7736 throw new SecurityException("Profile owner cannot set user restriction " + key); 7737 } 7738 } 7739 7740 // Save the restriction to ActiveAdmin. 7741 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner); 7742 saveUserRestrictionsLocked(userHandle); 7743 } 7744 } 7745 7746 private void saveUserRestrictionsLocked(int userId) { 7747 saveSettingsLocked(userId); 7748 pushUserRestrictions(userId); 7749 sendChangedNotification(userId); 7750 } 7751 7752 private void pushUserRestrictions(int userId) { 7753 synchronized (this) { 7754 final Bundle global; 7755 final Bundle local = new Bundle(); 7756 if (mOwners.isDeviceOwnerUserId(userId)) { 7757 global = new Bundle(); 7758 7759 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7760 if (deviceOwner == null) { 7761 return; // Shouldn't happen. 7762 } 7763 7764 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions, 7765 global, local); 7766 // DO can disable camera globally. 7767 if (deviceOwner.disableCamera) { 7768 global.putBoolean(UserManager.DISALLOW_CAMERA, true); 7769 } 7770 } else { 7771 global = null; 7772 7773 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 7774 if (profileOwner != null) { 7775 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions); 7776 } 7777 } 7778 // Also merge in *local* camera restriction. 7779 if (getCameraDisabled(/* who= */ null, 7780 userId, /* mergeDeviceOwnerRestriction= */ false)) { 7781 local.putBoolean(UserManager.DISALLOW_CAMERA, true); 7782 } 7783 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global); 7784 } 7785 } 7786 7787 @Override 7788 public Bundle getUserRestrictions(ComponentName who) { 7789 if (!mHasFeature) { 7790 return null; 7791 } 7792 Preconditions.checkNotNull(who, "ComponentName is null"); 7793 synchronized (this) { 7794 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who, 7795 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7796 return activeAdmin.userRestrictions; 7797 } 7798 } 7799 7800 @Override 7801 public boolean setApplicationHidden(ComponentName who, String packageName, 7802 boolean hidden) { 7803 Preconditions.checkNotNull(who, "ComponentName is null"); 7804 int callingUserId = UserHandle.getCallingUserId(); 7805 synchronized (this) { 7806 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7807 7808 long id = mInjector.binderClearCallingIdentity(); 7809 try { 7810 return mIPackageManager.setApplicationHiddenSettingAsUser( 7811 packageName, hidden, callingUserId); 7812 } catch (RemoteException re) { 7813 // shouldn't happen 7814 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 7815 } finally { 7816 mInjector.binderRestoreCallingIdentity(id); 7817 } 7818 return false; 7819 } 7820 } 7821 7822 @Override 7823 public boolean isApplicationHidden(ComponentName who, String packageName) { 7824 Preconditions.checkNotNull(who, "ComponentName is null"); 7825 int callingUserId = UserHandle.getCallingUserId(); 7826 synchronized (this) { 7827 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7828 7829 long id = mInjector.binderClearCallingIdentity(); 7830 try { 7831 return mIPackageManager.getApplicationHiddenSettingAsUser( 7832 packageName, callingUserId); 7833 } catch (RemoteException re) { 7834 // shouldn't happen 7835 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 7836 } finally { 7837 mInjector.binderRestoreCallingIdentity(id); 7838 } 7839 return false; 7840 } 7841 } 7842 7843 @Override 7844 public void enableSystemApp(ComponentName who, String packageName) { 7845 Preconditions.checkNotNull(who, "ComponentName is null"); 7846 synchronized (this) { 7847 // This API can only be called by an active device admin, 7848 // so try to retrieve it to check that the caller is one. 7849 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7850 7851 int userId = UserHandle.getCallingUserId(); 7852 long id = mInjector.binderClearCallingIdentity(); 7853 7854 try { 7855 if (VERBOSE_LOG) { 7856 Slog.v(LOG_TAG, "installing " + packageName + " for " 7857 + userId); 7858 } 7859 7860 int parentUserId = getProfileParentId(userId); 7861 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) { 7862 throw new IllegalArgumentException("Only system apps can be enabled this way."); 7863 } 7864 7865 // Install the app. 7866 mIPackageManager.installExistingPackageAsUser(packageName, userId); 7867 7868 } catch (RemoteException re) { 7869 // shouldn't happen 7870 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 7871 } finally { 7872 mInjector.binderRestoreCallingIdentity(id); 7873 } 7874 } 7875 } 7876 7877 @Override 7878 public int enableSystemAppWithIntent(ComponentName who, Intent intent) { 7879 Preconditions.checkNotNull(who, "ComponentName is null"); 7880 synchronized (this) { 7881 // This API can only be called by an active device admin, 7882 // so try to retrieve it to check that the caller is one. 7883 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7884 7885 int userId = UserHandle.getCallingUserId(); 7886 long id = mInjector.binderClearCallingIdentity(); 7887 7888 try { 7889 int parentUserId = getProfileParentId(userId); 7890 List<ResolveInfo> activitiesToEnable = mIPackageManager 7891 .queryIntentActivities(intent, 7892 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 7893 PackageManager.MATCH_DIRECT_BOOT_AWARE 7894 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 7895 parentUserId) 7896 .getList(); 7897 7898 if (VERBOSE_LOG) { 7899 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 7900 } 7901 int numberOfAppsInstalled = 0; 7902 if (activitiesToEnable != null) { 7903 for (ResolveInfo info : activitiesToEnable) { 7904 if (info.activityInfo != null) { 7905 String packageName = info.activityInfo.packageName; 7906 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 7907 numberOfAppsInstalled++; 7908 mIPackageManager.installExistingPackageAsUser(packageName, userId); 7909 } else { 7910 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 7911 + " system app"); 7912 } 7913 } 7914 } 7915 } 7916 return numberOfAppsInstalled; 7917 } catch (RemoteException e) { 7918 // shouldn't happen 7919 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 7920 return 0; 7921 } finally { 7922 mInjector.binderRestoreCallingIdentity(id); 7923 } 7924 } 7925 } 7926 7927 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 7928 throws RemoteException { 7929 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 7930 userId); 7931 if (appInfo == null) { 7932 throw new IllegalArgumentException("The application " + packageName + 7933 " is not present on this device"); 7934 } 7935 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7936 } 7937 7938 @Override 7939 public void setAccountManagementDisabled(ComponentName who, String accountType, 7940 boolean disabled) { 7941 if (!mHasFeature) { 7942 return; 7943 } 7944 Preconditions.checkNotNull(who, "ComponentName is null"); 7945 synchronized (this) { 7946 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 7947 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7948 if (disabled) { 7949 ap.accountTypesWithManagementDisabled.add(accountType); 7950 } else { 7951 ap.accountTypesWithManagementDisabled.remove(accountType); 7952 } 7953 saveSettingsLocked(UserHandle.getCallingUserId()); 7954 } 7955 } 7956 7957 @Override 7958 public String[] getAccountTypesWithManagementDisabled() { 7959 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 7960 } 7961 7962 @Override 7963 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 7964 enforceFullCrossUsersPermission(userId); 7965 if (!mHasFeature) { 7966 return null; 7967 } 7968 synchronized (this) { 7969 DevicePolicyData policy = getUserData(userId); 7970 final int N = policy.mAdminList.size(); 7971 ArraySet<String> resultSet = new ArraySet<>(); 7972 for (int i = 0; i < N; i++) { 7973 ActiveAdmin admin = policy.mAdminList.get(i); 7974 resultSet.addAll(admin.accountTypesWithManagementDisabled); 7975 } 7976 return resultSet.toArray(new String[resultSet.size()]); 7977 } 7978 } 7979 7980 @Override 7981 public void setUninstallBlocked(ComponentName who, String packageName, 7982 boolean uninstallBlocked) { 7983 Preconditions.checkNotNull(who, "ComponentName is null"); 7984 final int userId = UserHandle.getCallingUserId(); 7985 synchronized (this) { 7986 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7987 7988 long id = mInjector.binderClearCallingIdentity(); 7989 try { 7990 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 7991 } catch (RemoteException re) { 7992 // Shouldn't happen. 7993 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 7994 } finally { 7995 mInjector.binderRestoreCallingIdentity(id); 7996 } 7997 } 7998 } 7999 8000 @Override 8001 public boolean isUninstallBlocked(ComponentName who, String packageName) { 8002 // This function should return true if and only if the package is blocked by 8003 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 8004 // when the package is a system app, or when it is an active device admin. 8005 final int userId = UserHandle.getCallingUserId(); 8006 8007 synchronized (this) { 8008 if (who != null) { 8009 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8010 } 8011 8012 long id = mInjector.binderClearCallingIdentity(); 8013 try { 8014 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 8015 } catch (RemoteException re) { 8016 // Shouldn't happen. 8017 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 8018 } finally { 8019 mInjector.binderRestoreCallingIdentity(id); 8020 } 8021 } 8022 return false; 8023 } 8024 8025 @Override 8026 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 8027 if (!mHasFeature) { 8028 return; 8029 } 8030 Preconditions.checkNotNull(who, "ComponentName is null"); 8031 synchronized (this) { 8032 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8033 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8034 if (admin.disableCallerId != disabled) { 8035 admin.disableCallerId = disabled; 8036 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 8037 } 8038 } 8039 } 8040 8041 @Override 8042 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 8043 if (!mHasFeature) { 8044 return false; 8045 } 8046 Preconditions.checkNotNull(who, "ComponentName is null"); 8047 synchronized (this) { 8048 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8049 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8050 return admin.disableCallerId; 8051 } 8052 } 8053 8054 @Override 8055 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 8056 enforceCrossUsersPermission(userId); 8057 synchronized (this) { 8058 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8059 return (admin != null) ? admin.disableCallerId : false; 8060 } 8061 } 8062 8063 @Override 8064 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 8065 if (!mHasFeature) { 8066 return; 8067 } 8068 Preconditions.checkNotNull(who, "ComponentName is null"); 8069 synchronized (this) { 8070 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8071 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8072 if (admin.disableContactsSearch != disabled) { 8073 admin.disableContactsSearch = disabled; 8074 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 8075 } 8076 } 8077 } 8078 8079 @Override 8080 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 8081 if (!mHasFeature) { 8082 return false; 8083 } 8084 Preconditions.checkNotNull(who, "ComponentName is null"); 8085 synchronized (this) { 8086 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8087 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8088 return admin.disableContactsSearch; 8089 } 8090 } 8091 8092 @Override 8093 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 8094 enforceCrossUsersPermission(userId); 8095 synchronized (this) { 8096 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8097 return (admin != null) ? admin.disableContactsSearch : false; 8098 } 8099 } 8100 8101 @Override 8102 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 8103 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 8104 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 8105 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 8106 final int callingUserId = UserHandle.getCallingUserId(); 8107 8108 final long ident = mInjector.binderClearCallingIdentity(); 8109 try { 8110 synchronized (this) { 8111 final int managedUserId = getManagedUserId(callingUserId); 8112 if (managedUserId < 0) { 8113 return; 8114 } 8115 if (isCrossProfileQuickContactDisabled(managedUserId)) { 8116 if (VERBOSE_LOG) { 8117 Log.v(LOG_TAG, 8118 "Cross-profile contacts access disabled for user " + managedUserId); 8119 } 8120 return; 8121 } 8122 ContactsInternal.startQuickContactWithErrorToastForUser( 8123 mContext, intent, new UserHandle(managedUserId)); 8124 } 8125 } finally { 8126 mInjector.binderRestoreCallingIdentity(ident); 8127 } 8128 } 8129 8130 /** 8131 * @return true if cross-profile QuickContact is disabled 8132 */ 8133 private boolean isCrossProfileQuickContactDisabled(int userId) { 8134 return getCrossProfileCallerIdDisabledForUser(userId) 8135 && getCrossProfileContactsSearchDisabledForUser(userId); 8136 } 8137 8138 /** 8139 * @return the user ID of the managed user that is linked to the current user, if any. 8140 * Otherwise -1. 8141 */ 8142 public int getManagedUserId(int callingUserId) { 8143 if (VERBOSE_LOG) { 8144 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 8145 } 8146 8147 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 8148 if (ui.id == callingUserId || !ui.isManagedProfile()) { 8149 continue; // Caller user self, or not a managed profile. Skip. 8150 } 8151 if (VERBOSE_LOG) { 8152 Log.v(LOG_TAG, "Managed user=" + ui.id); 8153 } 8154 return ui.id; 8155 } 8156 if (VERBOSE_LOG) { 8157 Log.v(LOG_TAG, "Managed user not found."); 8158 } 8159 return -1; 8160 } 8161 8162 @Override 8163 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 8164 if (!mHasFeature) { 8165 return; 8166 } 8167 Preconditions.checkNotNull(who, "ComponentName is null"); 8168 synchronized (this) { 8169 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8170 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8171 if (admin.disableBluetoothContactSharing != disabled) { 8172 admin.disableBluetoothContactSharing = disabled; 8173 saveSettingsLocked(UserHandle.getCallingUserId()); 8174 } 8175 } 8176 } 8177 8178 @Override 8179 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 8180 if (!mHasFeature) { 8181 return false; 8182 } 8183 Preconditions.checkNotNull(who, "ComponentName is null"); 8184 synchronized (this) { 8185 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8186 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8187 return admin.disableBluetoothContactSharing; 8188 } 8189 } 8190 8191 @Override 8192 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 8193 // TODO: Should there be a check to make sure this relationship is 8194 // within a profile group? 8195 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 8196 synchronized (this) { 8197 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8198 return (admin != null) ? admin.disableBluetoothContactSharing : false; 8199 } 8200 } 8201 8202 /** 8203 * Sets which packages may enter lock task mode. 8204 * 8205 * <p>This function can only be called by the device owner or alternatively by the profile owner 8206 * in case the user is affiliated. 8207 * 8208 * @param packages The list of packages allowed to enter lock task mode. 8209 */ 8210 @Override 8211 public void setLockTaskPackages(ComponentName who, String[] packages) 8212 throws SecurityException { 8213 Preconditions.checkNotNull(who, "ComponentName is null"); 8214 8215 synchronized (this) { 8216 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8217 final int userHandle = mInjector.userHandleGetCallingUserId(); 8218 if (isUserAffiliatedWithDevice(userHandle)) { 8219 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 8220 } else { 8221 throw new SecurityException("Admin " + who + 8222 " is neither the device owner or affiliated user's profile owner."); 8223 } 8224 } 8225 } 8226 8227 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 8228 DevicePolicyData policy = getUserData(userHandle); 8229 policy.mLockTaskPackages = packages; 8230 8231 // Store the settings persistently. 8232 saveSettingsLocked(userHandle); 8233 updateLockTaskPackagesLocked(packages, userHandle); 8234 } 8235 8236 /** 8237 * This function returns the list of components allowed to start the task lock mode. 8238 */ 8239 @Override 8240 public String[] getLockTaskPackages(ComponentName who) { 8241 Preconditions.checkNotNull(who, "ComponentName is null"); 8242 synchronized (this) { 8243 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8244 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 8245 final List<String> packages = getLockTaskPackagesLocked(userHandle); 8246 return packages.toArray(new String[packages.size()]); 8247 } 8248 } 8249 8250 private List<String> getLockTaskPackagesLocked(int userHandle) { 8251 final DevicePolicyData policy = getUserData(userHandle); 8252 return policy.mLockTaskPackages; 8253 } 8254 8255 /** 8256 * This function lets the caller know whether the given package is allowed to start the 8257 * lock task mode. 8258 * @param pkg The package to check 8259 */ 8260 @Override 8261 public boolean isLockTaskPermitted(String pkg) { 8262 // Get current user's devicepolicy 8263 int uid = mInjector.binderGetCallingUid(); 8264 int userHandle = UserHandle.getUserId(uid); 8265 DevicePolicyData policy = getUserData(userHandle); 8266 synchronized (this) { 8267 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) { 8268 String lockTaskPackage = policy.mLockTaskPackages.get(i); 8269 8270 // If the given package equals one of the packages stored our list, 8271 // we allow this package to start lock task mode. 8272 if (lockTaskPackage.equals(pkg)) { 8273 return true; 8274 } 8275 } 8276 } 8277 return false; 8278 } 8279 8280 @Override 8281 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 8282 if (!isCallerWithSystemUid()) { 8283 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 8284 } 8285 synchronized (this) { 8286 final DevicePolicyData policy = getUserData(userHandle); 8287 Bundle adminExtras = new Bundle(); 8288 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 8289 for (ActiveAdmin admin : policy.mAdminList) { 8290 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 8291 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 8292 if (ownsDevice || ownsProfile) { 8293 if (isEnabled) { 8294 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 8295 adminExtras, null); 8296 } else { 8297 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 8298 } 8299 } 8300 } 8301 } 8302 } 8303 8304 @Override 8305 public void setGlobalSetting(ComponentName who, String setting, String value) { 8306 Preconditions.checkNotNull(who, "ComponentName is null"); 8307 8308 synchronized (this) { 8309 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8310 8311 // Some settings are no supported any more. However we do not want to throw a 8312 // SecurityException to avoid breaking apps. 8313 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 8314 Log.i(LOG_TAG, "Global setting no longer supported: " + setting); 8315 return; 8316 } 8317 8318 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) { 8319 throw new SecurityException(String.format( 8320 "Permission denial: device owners cannot update %1$s", setting)); 8321 } 8322 8323 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 8324 // ignore if it contradicts an existing policy 8325 long timeMs = getMaximumTimeToLock( 8326 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 8327 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) { 8328 return; 8329 } 8330 } 8331 8332 long id = mInjector.binderClearCallingIdentity(); 8333 try { 8334 mInjector.settingsGlobalPutString(setting, value); 8335 } finally { 8336 mInjector.binderRestoreCallingIdentity(id); 8337 } 8338 } 8339 } 8340 8341 @Override 8342 public void setSecureSetting(ComponentName who, String setting, String value) { 8343 Preconditions.checkNotNull(who, "ComponentName is null"); 8344 int callingUserId = mInjector.userHandleGetCallingUserId(); 8345 8346 synchronized (this) { 8347 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8348 8349 if (isDeviceOwner(who, callingUserId)) { 8350 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) { 8351 throw new SecurityException(String.format( 8352 "Permission denial: Device owners cannot update %1$s", setting)); 8353 } 8354 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) { 8355 throw new SecurityException(String.format( 8356 "Permission denial: Profile owners cannot update %1$s", setting)); 8357 } 8358 8359 long id = mInjector.binderClearCallingIdentity(); 8360 try { 8361 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 8362 } finally { 8363 mInjector.binderRestoreCallingIdentity(id); 8364 } 8365 } 8366 } 8367 8368 @Override 8369 public void setMasterVolumeMuted(ComponentName who, boolean on) { 8370 Preconditions.checkNotNull(who, "ComponentName is null"); 8371 synchronized (this) { 8372 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8373 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on); 8374 } 8375 } 8376 8377 @Override 8378 public boolean isMasterVolumeMuted(ComponentName who) { 8379 Preconditions.checkNotNull(who, "ComponentName is null"); 8380 synchronized (this) { 8381 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8382 8383 AudioManager audioManager = 8384 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 8385 return audioManager.isMasterMute(); 8386 } 8387 } 8388 8389 @Override 8390 public void setUserIcon(ComponentName who, Bitmap icon) { 8391 synchronized (this) { 8392 Preconditions.checkNotNull(who, "ComponentName is null"); 8393 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8394 8395 int userId = UserHandle.getCallingUserId(); 8396 long id = mInjector.binderClearCallingIdentity(); 8397 try { 8398 mUserManagerInternal.setUserIcon(userId, icon); 8399 } finally { 8400 mInjector.binderRestoreCallingIdentity(id); 8401 } 8402 } 8403 } 8404 8405 @Override 8406 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 8407 Preconditions.checkNotNull(who, "ComponentName is null"); 8408 synchronized (this) { 8409 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8410 } 8411 final int userId = UserHandle.getCallingUserId(); 8412 8413 long ident = mInjector.binderClearCallingIdentity(); 8414 try { 8415 // disallow disabling the keyguard if a password is currently set 8416 if (disabled && mLockPatternUtils.isSecure(userId)) { 8417 return false; 8418 } 8419 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 8420 } finally { 8421 mInjector.binderRestoreCallingIdentity(ident); 8422 } 8423 return true; 8424 } 8425 8426 @Override 8427 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 8428 int userId = UserHandle.getCallingUserId(); 8429 synchronized (this) { 8430 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8431 DevicePolicyData policy = getUserData(userId); 8432 if (policy.mStatusBarDisabled != disabled) { 8433 if (!setStatusBarDisabledInternal(disabled, userId)) { 8434 return false; 8435 } 8436 policy.mStatusBarDisabled = disabled; 8437 saveSettingsLocked(userId); 8438 } 8439 } 8440 return true; 8441 } 8442 8443 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 8444 long ident = mInjector.binderClearCallingIdentity(); 8445 try { 8446 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 8447 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 8448 if (statusBarService != null) { 8449 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 8450 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 8451 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 8452 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 8453 return true; 8454 } 8455 } catch (RemoteException e) { 8456 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 8457 } finally { 8458 mInjector.binderRestoreCallingIdentity(ident); 8459 } 8460 return false; 8461 } 8462 8463 /** 8464 * We need to update the internal state of whether a user has completed setup or a 8465 * device has paired once. After that, we ignore any changes that reset the 8466 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 8467 * as we don't trust any apps that might try to reset them. 8468 * <p> 8469 * Unfortunately, we don't know which user's setup state was changed, so we write all of 8470 * them. 8471 */ 8472 void updateUserSetupCompleteAndPaired() { 8473 List<UserInfo> users = mUserManager.getUsers(true); 8474 final int N = users.size(); 8475 for (int i = 0; i < N; i++) { 8476 int userHandle = users.get(i).id; 8477 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 8478 userHandle) != 0) { 8479 DevicePolicyData policy = getUserData(userHandle); 8480 if (!policy.mUserSetupComplete) { 8481 policy.mUserSetupComplete = true; 8482 synchronized (this) { 8483 saveSettingsLocked(userHandle); 8484 } 8485 } 8486 } 8487 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 8488 userHandle) != 0) { 8489 DevicePolicyData policy = getUserData(userHandle); 8490 if (!policy.mPaired) { 8491 policy.mPaired = true; 8492 synchronized (this) { 8493 saveSettingsLocked(userHandle); 8494 } 8495 } 8496 } 8497 } 8498 } 8499 8500 private class SetupContentObserver extends ContentObserver { 8501 8502 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 8503 Settings.Secure.USER_SETUP_COMPLETE); 8504 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 8505 Settings.Global.DEVICE_PROVISIONED); 8506 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 8507 8508 public SetupContentObserver(Handler handler) { 8509 super(handler); 8510 } 8511 8512 void register() { 8513 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 8514 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 8515 if (mIsWatch) { 8516 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 8517 } 8518 } 8519 8520 @Override 8521 public void onChange(boolean selfChange, Uri uri) { 8522 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 8523 updateUserSetupCompleteAndPaired(); 8524 } else if (mDeviceProvisioned.equals(uri)) { 8525 synchronized (DevicePolicyManagerService.this) { 8526 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 8527 // is delayed until device is marked as provisioned. 8528 setDeviceOwnerSystemPropertyLocked(); 8529 } 8530 } 8531 } 8532 } 8533 8534 @VisibleForTesting 8535 final class LocalService extends DevicePolicyManagerInternal { 8536 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 8537 8538 @Override 8539 public List<String> getCrossProfileWidgetProviders(int profileId) { 8540 synchronized (DevicePolicyManagerService.this) { 8541 if (mOwners == null) { 8542 return Collections.emptyList(); 8543 } 8544 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 8545 if (ownerComponent == null) { 8546 return Collections.emptyList(); 8547 } 8548 8549 DevicePolicyData policy = getUserDataUnchecked(profileId); 8550 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 8551 8552 if (admin == null || admin.crossProfileWidgetProviders == null 8553 || admin.crossProfileWidgetProviders.isEmpty()) { 8554 return Collections.emptyList(); 8555 } 8556 8557 return admin.crossProfileWidgetProviders; 8558 } 8559 } 8560 8561 @Override 8562 public void addOnCrossProfileWidgetProvidersChangeListener( 8563 OnCrossProfileWidgetProvidersChangeListener listener) { 8564 synchronized (DevicePolicyManagerService.this) { 8565 if (mWidgetProviderListeners == null) { 8566 mWidgetProviderListeners = new ArrayList<>(); 8567 } 8568 if (!mWidgetProviderListeners.contains(listener)) { 8569 mWidgetProviderListeners.add(listener); 8570 } 8571 } 8572 } 8573 8574 @Override 8575 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 8576 synchronized(DevicePolicyManagerService.this) { 8577 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 8578 } 8579 } 8580 8581 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 8582 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 8583 synchronized (DevicePolicyManagerService.this) { 8584 listeners = new ArrayList<>(mWidgetProviderListeners); 8585 } 8586 final int listenerCount = listeners.size(); 8587 for (int i = 0; i < listenerCount; i++) { 8588 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 8589 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 8590 } 8591 } 8592 8593 @Override 8594 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 8595 // This method is called from AM with its lock held, so don't take the DPMS lock. 8596 // b/29242568 8597 8598 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 8599 if (profileOwner != null) { 8600 return createShowAdminSupportIntent(profileOwner, userId); 8601 } 8602 8603 final Pair<Integer, ComponentName> deviceOwner = 8604 mOwners.getDeviceOwnerUserIdAndComponent(); 8605 if (deviceOwner != null && deviceOwner.first == userId) { 8606 return createShowAdminSupportIntent(deviceOwner.second, userId); 8607 } 8608 8609 // We're not specifying the device admin because there isn't one. 8610 if (useDefaultIfNoAdmin) { 8611 return createShowAdminSupportIntent(null, userId); 8612 } 8613 return null; 8614 } 8615 8616 @Override 8617 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 8618 int source; 8619 long ident = mInjector.binderClearCallingIdentity(); 8620 try { 8621 source = mUserManager.getUserRestrictionSource(userRestriction, 8622 UserHandle.of(userId)); 8623 } finally { 8624 mInjector.binderRestoreCallingIdentity(ident); 8625 } 8626 if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) { 8627 /* 8628 * In this case, the user restriction is enforced by the system. 8629 * So we won't show an admin support intent, even if it is also 8630 * enforced by a profile/device owner. 8631 */ 8632 return null; 8633 } 8634 boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0; 8635 boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0; 8636 if (enforcedByDo && enforcedByPo) { 8637 // In this case, we'll show an admin support dialog that does not 8638 // specify the admin. 8639 return createShowAdminSupportIntent(null, userId); 8640 } else if (enforcedByPo) { 8641 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 8642 if (profileOwner != null) { 8643 return createShowAdminSupportIntent(profileOwner, userId); 8644 } 8645 // This could happen if another thread has changed the profile owner since we called 8646 // getUserRestrictionSource 8647 return null; 8648 } else if (enforcedByDo) { 8649 final Pair<Integer, ComponentName> deviceOwner 8650 = mOwners.getDeviceOwnerUserIdAndComponent(); 8651 if (deviceOwner != null) { 8652 return createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first); 8653 } 8654 // This could happen if another thread has changed the device owner since we called 8655 // getUserRestrictionSource 8656 return null; 8657 } 8658 return null; 8659 } 8660 8661 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) { 8662 // This method is called with AMS lock held, so don't take DPMS lock 8663 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 8664 intent.putExtra(Intent.EXTRA_USER_ID, userId); 8665 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin); 8666 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 8667 return intent; 8668 } 8669 } 8670 8671 /** 8672 * Returns true if specified admin is allowed to limit passwords and has a 8673 * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality} 8674 */ 8675 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 8676 if (admin.minimumPasswordMetrics.quality < minPasswordQuality) { 8677 return false; 8678 } 8679 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 8680 } 8681 8682 @Override 8683 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 8684 if (policy != null && !policy.isValid()) { 8685 throw new IllegalArgumentException("Invalid system update policy."); 8686 } 8687 synchronized (this) { 8688 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8689 if (policy == null) { 8690 mOwners.clearSystemUpdatePolicy(); 8691 } else { 8692 mOwners.setSystemUpdatePolicy(policy); 8693 } 8694 mOwners.writeDeviceOwner(); 8695 } 8696 mContext.sendBroadcastAsUser( 8697 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 8698 UserHandle.SYSTEM); 8699 } 8700 8701 @Override 8702 public SystemUpdatePolicy getSystemUpdatePolicy() { 8703 if (UserManager.isDeviceInDemoMode(mContext)) { 8704 // Pretending to have an automatic update policy when the device is in retail demo 8705 // mode. This will allow the device to download and install an ota without 8706 // any user interaction. 8707 return SystemUpdatePolicy.createAutomaticInstallPolicy(); 8708 } 8709 synchronized (this) { 8710 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 8711 if (policy != null && !policy.isValid()) { 8712 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 8713 return null; 8714 } 8715 return policy; 8716 } 8717 } 8718 8719 /** 8720 * Checks if the caller of the method is the device owner app. 8721 * 8722 * @param callerUid UID of the caller. 8723 * @return true if the caller is the device owner app 8724 */ 8725 @VisibleForTesting 8726 boolean isCallerDeviceOwner(int callerUid) { 8727 synchronized (this) { 8728 if (!mOwners.hasDeviceOwner()) { 8729 return false; 8730 } 8731 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 8732 return false; 8733 } 8734 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 8735 .getPackageName(); 8736 final String[] pkgs = mInjector.getPackageManager().getPackagesForUid(callerUid); 8737 8738 for (String pkg : pkgs) { 8739 if (deviceOwnerPackageName.equals(pkg)) { 8740 return true; 8741 } 8742 } 8743 } 8744 8745 return false; 8746 } 8747 8748 @Override 8749 public void notifyPendingSystemUpdate(long updateReceivedTime) { 8750 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 8751 "Only the system update service can broadcast update information"); 8752 8753 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 8754 Slog.w(LOG_TAG, "Only the system update service in the system user " + 8755 "can broadcast update information."); 8756 return; 8757 } 8758 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE); 8759 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 8760 updateReceivedTime); 8761 8762 final long ident = mInjector.binderClearCallingIdentity(); 8763 try { 8764 synchronized (this) { 8765 // Broadcast to device owner first if there is one. 8766 if (mOwners.hasDeviceOwner()) { 8767 final UserHandle deviceOwnerUser = 8768 UserHandle.of(mOwners.getDeviceOwnerUserId()); 8769 intent.setComponent(mOwners.getDeviceOwnerComponent()); 8770 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 8771 } 8772 } 8773 // Get running users. 8774 final int runningUserIds[]; 8775 try { 8776 runningUserIds = mInjector.getIActivityManager().getRunningUserIds(); 8777 } catch (RemoteException e) { 8778 // Shouldn't happen. 8779 Log.e(LOG_TAG, "Could not retrieve the list of running users", e); 8780 return; 8781 } 8782 // Send broadcasts to corresponding profile owners if any. 8783 for (final int userId : runningUserIds) { 8784 synchronized (this) { 8785 final ComponentName profileOwnerPackage = 8786 mOwners.getProfileOwnerComponent(userId); 8787 if (profileOwnerPackage != null) { 8788 intent.setComponent(profileOwnerPackage); 8789 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 8790 } 8791 } 8792 } 8793 } finally { 8794 mInjector.binderRestoreCallingIdentity(ident); 8795 } 8796 } 8797 8798 @Override 8799 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException { 8800 int userId = UserHandle.getCallingUserId(); 8801 synchronized (this) { 8802 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8803 DevicePolicyData userPolicy = getUserData(userId); 8804 if (userPolicy.mPermissionPolicy != policy) { 8805 userPolicy.mPermissionPolicy = policy; 8806 saveSettingsLocked(userId); 8807 } 8808 } 8809 } 8810 8811 @Override 8812 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 8813 int userId = UserHandle.getCallingUserId(); 8814 synchronized (this) { 8815 DevicePolicyData userPolicy = getUserData(userId); 8816 return userPolicy.mPermissionPolicy; 8817 } 8818 } 8819 8820 @Override 8821 public boolean setPermissionGrantState(ComponentName admin, String packageName, 8822 String permission, int grantState) throws RemoteException { 8823 UserHandle user = mInjector.binderGetCallingUserHandle(); 8824 synchronized (this) { 8825 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8826 long ident = mInjector.binderClearCallingIdentity(); 8827 try { 8828 if (getTargetSdk(packageName, user.getIdentifier()) 8829 < android.os.Build.VERSION_CODES.M) { 8830 return false; 8831 } 8832 final PackageManager packageManager = mInjector.getPackageManager(); 8833 switch (grantState) { 8834 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: { 8835 mInjector.getPackageManagerInternal().grantRuntimePermission(packageName, 8836 permission, user.getIdentifier(), true /* override policy */); 8837 packageManager.updatePermissionFlags(permission, packageName, 8838 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 8839 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 8840 } break; 8841 8842 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: { 8843 mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName, 8844 permission, user.getIdentifier(), true /* override policy */); 8845 packageManager.updatePermissionFlags(permission, packageName, 8846 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 8847 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 8848 } break; 8849 8850 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: { 8851 packageManager.updatePermissionFlags(permission, packageName, 8852 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user); 8853 } break; 8854 } 8855 return true; 8856 } catch (SecurityException se) { 8857 return false; 8858 } finally { 8859 mInjector.binderRestoreCallingIdentity(ident); 8860 } 8861 } 8862 } 8863 8864 @Override 8865 public int getPermissionGrantState(ComponentName admin, String packageName, 8866 String permission) throws RemoteException { 8867 PackageManager packageManager = mInjector.getPackageManager(); 8868 8869 UserHandle user = mInjector.binderGetCallingUserHandle(); 8870 synchronized (this) { 8871 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8872 long ident = mInjector.binderClearCallingIdentity(); 8873 try { 8874 int granted = mIPackageManager.checkPermission(permission, 8875 packageName, user.getIdentifier()); 8876 int permFlags = packageManager.getPermissionFlags(permission, packageName, user); 8877 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 8878 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 8879 // Not controlled by policy 8880 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 8881 } else { 8882 // Policy controlled so return result based on permission grant state 8883 return granted == PackageManager.PERMISSION_GRANTED 8884 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 8885 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 8886 } 8887 } finally { 8888 mInjector.binderRestoreCallingIdentity(ident); 8889 } 8890 } 8891 } 8892 8893 boolean isPackageInstalledForUser(String packageName, int userHandle) { 8894 try { 8895 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 8896 userHandle); 8897 return (pi != null) && (pi.applicationInfo.flags != 0); 8898 } catch (RemoteException re) { 8899 throw new RuntimeException("Package manager has died", re); 8900 } 8901 } 8902 8903 @Override 8904 public boolean isProvisioningAllowed(String action, String packageName) { 8905 Preconditions.checkNotNull(packageName); 8906 8907 final int callingUid = mInjector.binderGetCallingUid(); 8908 final long ident = mInjector.binderClearCallingIdentity(); 8909 try { 8910 final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser( 8911 packageName, UserHandle.getUserId(callingUid)); 8912 Preconditions.checkArgument(callingUid == uidForPackage, 8913 "Caller uid doesn't match the one for the provided package."); 8914 } catch (NameNotFoundException e) { 8915 throw new IllegalArgumentException("Invalid package provided " + packageName, e); 8916 } finally { 8917 mInjector.binderRestoreCallingIdentity(ident); 8918 } 8919 8920 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK; 8921 } 8922 8923 @Override 8924 public int checkProvisioningPreCondition(String action, String packageName) { 8925 Preconditions.checkNotNull(packageName); 8926 enforceCanManageProfileAndDeviceOwners(); 8927 return checkProvisioningPreConditionSkipPermission(action, packageName); 8928 } 8929 8930 private int checkProvisioningPreConditionSkipPermission(String action, String packageName) { 8931 if (!mHasFeature) { 8932 return CODE_DEVICE_ADMIN_NOT_SUPPORTED; 8933 } 8934 8935 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8936 if (action != null) { 8937 switch (action) { 8938 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 8939 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 8940 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 8941 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 8942 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER: 8943 return checkManagedUserProvisioningPreCondition(callingUserId); 8944 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE: 8945 return checkManagedShareableDeviceProvisioningPreCondition(callingUserId); 8946 } 8947 } 8948 throw new IllegalArgumentException("Unknown provisioning action " + action); 8949 } 8950 8951 /** 8952 * The device owner can only be set before the setup phase of the primary user has completed, 8953 * except for adb command if no accounts or additional users are present on the device. 8954 */ 8955 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 8956 int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) { 8957 if (mOwners.hasDeviceOwner()) { 8958 return CODE_HAS_DEVICE_OWNER; 8959 } 8960 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 8961 return CODE_USER_HAS_PROFILE_OWNER; 8962 } 8963 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 8964 return CODE_USER_NOT_RUNNING; 8965 } 8966 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 8967 return CODE_HAS_PAIRED; 8968 } 8969 if (isAdb) { 8970 // if shell command runs after user setup completed check device status. Otherwise, OK. 8971 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 8972 if (!mInjector.userManagerIsSplitSystemUser()) { 8973 if (mUserManager.getUserCount() > 1) { 8974 return CODE_NONSYSTEM_USER_EXISTS; 8975 } 8976 if (hasIncompatibleAccountsOrNonAdb) { 8977 return CODE_ACCOUNTS_NOT_EMPTY; 8978 } 8979 } else { 8980 // STOPSHIP Do proper check in split user mode 8981 } 8982 } 8983 return CODE_OK; 8984 } else { 8985 if (!mInjector.userManagerIsSplitSystemUser()) { 8986 // In non-split user mode, DO has to be user 0 8987 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 8988 return CODE_NOT_SYSTEM_USER; 8989 } 8990 // In non-split user mode, only provision DO before setup wizard completes 8991 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 8992 return CODE_USER_SETUP_COMPLETED; 8993 } 8994 } else { 8995 // STOPSHIP Do proper check in split user mode 8996 } 8997 return CODE_OK; 8998 } 8999 } 9000 9001 private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) { 9002 synchronized (this) { 9003 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb. 9004 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 9005 deviceOwnerUserId, /* isAdb= */ false, 9006 /* hasIncompatibleAccountsOrNonAdb=*/ true); 9007 } 9008 } 9009 9010 private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) { 9011 if (!hasFeatureManagedUsers()) { 9012 return CODE_MANAGED_USERS_NOT_SUPPORTED; 9013 } 9014 if (callingUserId == UserHandle.USER_SYSTEM 9015 && mInjector.userManagerIsSplitSystemUser()) { 9016 // Managed-profiles cannot be setup on the system user. 9017 return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 9018 } 9019 if (getProfileOwner(callingUserId) != null) { 9020 // Managed user cannot have a managed profile. 9021 return CODE_USER_HAS_PROFILE_OWNER; 9022 } 9023 9024 final long ident = mInjector.binderClearCallingIdentity(); 9025 try { 9026 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 9027 if (mUserManager.hasUserRestriction( 9028 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserHandle)) { 9029 // The DO can initiate provisioning if the restriction was set by the DO. 9030 if (!isDeviceOwnerPackage(packageName, callingUserId) 9031 || isAdminAffectedByRestriction(mOwners.getDeviceOwnerComponent(), 9032 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) { 9033 // Caller is not DO or the restriction was set by the system. 9034 return CODE_ADD_MANAGED_PROFILE_DISALLOWED; 9035 } 9036 } 9037 9038 // TODO: Allow it if the caller is the DO? DO could just call removeUser() before 9039 // provisioning, so not strictly required... 9040 boolean canRemoveProfile = !mUserManager.hasUserRestriction( 9041 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, callingUserHandle); 9042 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) { 9043 return CODE_CANNOT_ADD_MANAGED_PROFILE; 9044 } 9045 } finally { 9046 mInjector.binderRestoreCallingIdentity(ident); 9047 } 9048 return CODE_OK; 9049 } 9050 9051 private int checkManagedUserProvisioningPreCondition(int callingUserId) { 9052 if (!hasFeatureManagedUsers()) { 9053 return CODE_MANAGED_USERS_NOT_SUPPORTED; 9054 } 9055 if (!mInjector.userManagerIsSplitSystemUser()) { 9056 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems. 9057 return CODE_NOT_SYSTEM_USER_SPLIT; 9058 } 9059 if (callingUserId == UserHandle.USER_SYSTEM) { 9060 // System user cannot be a managed user. 9061 return CODE_SYSTEM_USER; 9062 } 9063 if (hasUserSetupCompleted(callingUserId)) { 9064 return CODE_USER_SETUP_COMPLETED; 9065 } 9066 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 9067 return CODE_HAS_PAIRED; 9068 } 9069 return CODE_OK; 9070 } 9071 9072 private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) { 9073 if (!mInjector.userManagerIsSplitSystemUser()) { 9074 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems. 9075 return CODE_NOT_SYSTEM_USER_SPLIT; 9076 } 9077 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 9078 } 9079 9080 private boolean hasFeatureManagedUsers() { 9081 try { 9082 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 9083 } catch (RemoteException e) { 9084 return false; 9085 } 9086 } 9087 9088 @Override 9089 public String getWifiMacAddress(ComponentName admin) { 9090 // Make sure caller has DO. 9091 synchronized (this) { 9092 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9093 } 9094 9095 final long ident = mInjector.binderClearCallingIdentity(); 9096 try { 9097 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo(); 9098 if (wifiInfo == null) { 9099 return null; 9100 } 9101 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null; 9102 } finally { 9103 mInjector.binderRestoreCallingIdentity(ident); 9104 } 9105 } 9106 9107 /** 9108 * Returns the target sdk version number that the given packageName was built for 9109 * in the given user. 9110 */ 9111 private int getTargetSdk(String packageName, int userId) { 9112 final ApplicationInfo ai; 9113 try { 9114 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 9115 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion; 9116 return targetSdkVersion; 9117 } catch (RemoteException e) { 9118 // Shouldn't happen 9119 return 0; 9120 } 9121 } 9122 9123 @Override 9124 public boolean isManagedProfile(ComponentName admin) { 9125 synchronized (this) { 9126 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9127 } 9128 return isManagedProfile(mInjector.userHandleGetCallingUserId()); 9129 } 9130 9131 @Override 9132 public boolean isSystemOnlyUser(ComponentName admin) { 9133 synchronized (this) { 9134 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9135 } 9136 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9137 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM; 9138 } 9139 9140 @Override 9141 public void reboot(ComponentName admin) { 9142 Preconditions.checkNotNull(admin); 9143 // Make sure caller has DO. 9144 synchronized (this) { 9145 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9146 } 9147 long ident = mInjector.binderClearCallingIdentity(); 9148 try { 9149 // Make sure there are no ongoing calls on the device. 9150 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 9151 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 9152 } 9153 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 9154 } finally { 9155 mInjector.binderRestoreCallingIdentity(ident); 9156 } 9157 } 9158 9159 @Override 9160 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 9161 if (!mHasFeature) { 9162 return; 9163 } 9164 Preconditions.checkNotNull(who, "ComponentName is null"); 9165 final int userHandle = mInjector.userHandleGetCallingUserId(); 9166 synchronized (this) { 9167 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9168 mInjector.binderGetCallingUid()); 9169 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 9170 admin.shortSupportMessage = message; 9171 saveSettingsLocked(userHandle); 9172 } 9173 } 9174 } 9175 9176 @Override 9177 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 9178 if (!mHasFeature) { 9179 return null; 9180 } 9181 Preconditions.checkNotNull(who, "ComponentName is null"); 9182 synchronized (this) { 9183 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9184 mInjector.binderGetCallingUid()); 9185 return admin.shortSupportMessage; 9186 } 9187 } 9188 9189 @Override 9190 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 9191 if (!mHasFeature) { 9192 return; 9193 } 9194 Preconditions.checkNotNull(who, "ComponentName is null"); 9195 final int userHandle = mInjector.userHandleGetCallingUserId(); 9196 synchronized (this) { 9197 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9198 mInjector.binderGetCallingUid()); 9199 if (!TextUtils.equals(admin.longSupportMessage, message)) { 9200 admin.longSupportMessage = message; 9201 saveSettingsLocked(userHandle); 9202 } 9203 } 9204 } 9205 9206 @Override 9207 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 9208 if (!mHasFeature) { 9209 return null; 9210 } 9211 Preconditions.checkNotNull(who, "ComponentName is null"); 9212 synchronized (this) { 9213 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9214 mInjector.binderGetCallingUid()); 9215 return admin.longSupportMessage; 9216 } 9217 } 9218 9219 @Override 9220 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 9221 if (!mHasFeature) { 9222 return null; 9223 } 9224 Preconditions.checkNotNull(who, "ComponentName is null"); 9225 if (!isCallerWithSystemUid()) { 9226 throw new SecurityException("Only the system can query support message for user"); 9227 } 9228 synchronized (this) { 9229 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 9230 if (admin != null) { 9231 return admin.shortSupportMessage; 9232 } 9233 } 9234 return null; 9235 } 9236 9237 @Override 9238 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 9239 if (!mHasFeature) { 9240 return null; 9241 } 9242 Preconditions.checkNotNull(who, "ComponentName is null"); 9243 if (!isCallerWithSystemUid()) { 9244 throw new SecurityException("Only the system can query support message for user"); 9245 } 9246 synchronized (this) { 9247 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 9248 if (admin != null) { 9249 return admin.longSupportMessage; 9250 } 9251 } 9252 return null; 9253 } 9254 9255 @Override 9256 public void setOrganizationColor(@NonNull ComponentName who, int color) { 9257 if (!mHasFeature) { 9258 return; 9259 } 9260 Preconditions.checkNotNull(who, "ComponentName is null"); 9261 final int userHandle = mInjector.userHandleGetCallingUserId(); 9262 enforceManagedProfile(userHandle, "set organization color"); 9263 synchronized (this) { 9264 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9265 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9266 admin.organizationColor = color; 9267 saveSettingsLocked(userHandle); 9268 } 9269 } 9270 9271 @Override 9272 public void setOrganizationColorForUser(int color, int userId) { 9273 if (!mHasFeature) { 9274 return; 9275 } 9276 enforceFullCrossUsersPermission(userId); 9277 enforceManageUsers(); 9278 enforceManagedProfile(userId, "set organization color"); 9279 synchronized (this) { 9280 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9281 admin.organizationColor = color; 9282 saveSettingsLocked(userId); 9283 } 9284 } 9285 9286 @Override 9287 public int getOrganizationColor(@NonNull ComponentName who) { 9288 if (!mHasFeature) { 9289 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 9290 } 9291 Preconditions.checkNotNull(who, "ComponentName is null"); 9292 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color"); 9293 synchronized (this) { 9294 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9295 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9296 return admin.organizationColor; 9297 } 9298 } 9299 9300 @Override 9301 public int getOrganizationColorForUser(int userHandle) { 9302 if (!mHasFeature) { 9303 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 9304 } 9305 enforceFullCrossUsersPermission(userHandle); 9306 enforceManagedProfile(userHandle, "get organization color"); 9307 synchronized (this) { 9308 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 9309 return (profileOwner != null) 9310 ? profileOwner.organizationColor 9311 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 9312 } 9313 } 9314 9315 @Override 9316 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 9317 if (!mHasFeature) { 9318 return; 9319 } 9320 Preconditions.checkNotNull(who, "ComponentName is null"); 9321 final int userHandle = mInjector.userHandleGetCallingUserId(); 9322 9323 synchronized (this) { 9324 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9325 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9326 if (!TextUtils.equals(admin.organizationName, text)) { 9327 admin.organizationName = (text == null || text.length() == 0) 9328 ? null : text.toString(); 9329 saveSettingsLocked(userHandle); 9330 } 9331 } 9332 } 9333 9334 @Override 9335 public CharSequence getOrganizationName(@NonNull ComponentName who) { 9336 if (!mHasFeature) { 9337 return null; 9338 } 9339 Preconditions.checkNotNull(who, "ComponentName is null"); 9340 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name"); 9341 synchronized(this) { 9342 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9343 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9344 return admin.organizationName; 9345 } 9346 } 9347 9348 @Override 9349 public CharSequence getDeviceOwnerOrganizationName() { 9350 if (!mHasFeature) { 9351 return null; 9352 } 9353 enforceDeviceOwnerOrManageUsers(); 9354 synchronized(this) { 9355 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 9356 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 9357 } 9358 } 9359 9360 @Override 9361 public CharSequence getOrganizationNameForUser(int userHandle) { 9362 if (!mHasFeature) { 9363 return null; 9364 } 9365 enforceFullCrossUsersPermission(userHandle); 9366 enforceManagedProfile(userHandle, "get organization name"); 9367 synchronized (this) { 9368 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 9369 return (profileOwner != null) 9370 ? profileOwner.organizationName 9371 : null; 9372 } 9373 } 9374 9375 @Override 9376 public void setAffiliationIds(ComponentName admin, List<String> ids) { 9377 if (!mHasFeature) { 9378 return; 9379 } 9380 9381 Preconditions.checkNotNull(admin); 9382 Preconditions.checkCollectionElementsNotNull(ids, "ids"); 9383 9384 final Set<String> affiliationIds = new ArraySet<String>(ids); 9385 Preconditions.checkArgument( 9386 !affiliationIds.contains(""), "ids must not contain empty strings"); 9387 9388 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9389 synchronized (this) { 9390 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9391 getUserData(callingUserId).mAffiliationIds = affiliationIds; 9392 saveSettingsLocked(callingUserId); 9393 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 9394 // Affiliation ids specified by the device owner are additionally stored in 9395 // UserHandle.USER_SYSTEM's DevicePolicyData. 9396 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 9397 saveSettingsLocked(UserHandle.USER_SYSTEM); 9398 } 9399 } 9400 } 9401 9402 @Override 9403 public List<String> getAffiliationIds(ComponentName admin) { 9404 if (!mHasFeature) { 9405 return Collections.emptyList(); 9406 } 9407 9408 Preconditions.checkNotNull(admin); 9409 synchronized (this) { 9410 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9411 return new ArrayList<String>( 9412 getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds); 9413 } 9414 } 9415 9416 @Override 9417 public boolean isAffiliatedUser() { 9418 return isUserAffiliatedWithDevice(mInjector.userHandleGetCallingUserId()); 9419 } 9420 9421 private boolean isUserAffiliatedWithDevice(int userId) { 9422 synchronized (this) { 9423 if (!mOwners.hasDeviceOwner()) { 9424 return false; 9425 } 9426 if (userId == mOwners.getDeviceOwnerUserId()) { 9427 // The user that the DO is installed on is always affiliated with the device. 9428 return true; 9429 } 9430 if (userId == UserHandle.USER_SYSTEM) { 9431 // The system user is always affiliated in a DO device, even if the DO is set on a 9432 // different user. This could be the case if the DO is set in the primary user 9433 // of a split user device. 9434 return true; 9435 } 9436 final ComponentName profileOwner = getProfileOwner(userId); 9437 if (profileOwner == null) { 9438 return false; 9439 } 9440 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 9441 final Set<String> deviceAffiliationIds = 9442 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 9443 for (String id : userAffiliationIds) { 9444 if (deviceAffiliationIds.contains(id)) { 9445 return true; 9446 } 9447 } 9448 } 9449 return false; 9450 } 9451 9452 private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() { 9453 final boolean isSingleUserManagedDevice = isDeviceOwnerManagedSingleUserDevice(); 9454 9455 // disable security logging if needed 9456 if (!isSingleUserManagedDevice) { 9457 mInjector.securityLogSetLoggingEnabledProperty(false); 9458 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user managed" 9459 + " device."); 9460 } 9461 9462 // disable backup service if needed 9463 // note: when clearing DO, the backup service shouldn't be disabled if it was enabled by 9464 // the device owner 9465 if (mOwners.hasDeviceOwner() && !isSingleUserManagedDevice) { 9466 setBackupServiceEnabledInternal(false); 9467 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user."); 9468 } 9469 9470 // disable network logging if needed 9471 if (!isSingleUserManagedDevice) { 9472 setNetworkLoggingActiveInternal(false); 9473 Slog.w(LOG_TAG, "Network logging turned off as it's no longer a single user managed" 9474 + " device."); 9475 // if there still is a device owner, disable logging policy, otherwise the admin 9476 // has been nuked 9477 if (mOwners.hasDeviceOwner()) { 9478 getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = false; 9479 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 9480 } 9481 } 9482 } 9483 9484 @Override 9485 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) { 9486 Preconditions.checkNotNull(admin); 9487 ensureDeviceOwnerManagingSingleUser(admin); 9488 9489 synchronized (this) { 9490 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 9491 return; 9492 } 9493 mInjector.securityLogSetLoggingEnabledProperty(enabled); 9494 if (enabled) { 9495 mSecurityLogMonitor.start(); 9496 } else { 9497 mSecurityLogMonitor.stop(); 9498 } 9499 } 9500 } 9501 9502 @Override 9503 public boolean isSecurityLoggingEnabled(ComponentName admin) { 9504 Preconditions.checkNotNull(admin); 9505 synchronized (this) { 9506 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9507 return mInjector.securityLogGetLoggingEnabledProperty(); 9508 } 9509 } 9510 9511 private synchronized void recordSecurityLogRetrievalTime() { 9512 final long currentTime = System.currentTimeMillis(); 9513 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 9514 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 9515 policyData.mLastSecurityLogRetrievalTime = currentTime; 9516 saveSettingsLocked(UserHandle.USER_SYSTEM); 9517 } 9518 } 9519 9520 @Override 9521 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) { 9522 Preconditions.checkNotNull(admin); 9523 ensureDeviceOwnerManagingSingleUser(admin); 9524 9525 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) { 9526 return null; 9527 } 9528 9529 recordSecurityLogRetrievalTime(); 9530 9531 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 9532 try { 9533 SecurityLog.readPreviousEvents(output); 9534 return new ParceledListSlice<SecurityEvent>(output); 9535 } catch (IOException e) { 9536 Slog.w(LOG_TAG, "Fail to read previous events" , e); 9537 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 9538 } 9539 } 9540 9541 @Override 9542 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) { 9543 Preconditions.checkNotNull(admin); 9544 ensureDeviceOwnerManagingSingleUser(admin); 9545 9546 recordSecurityLogRetrievalTime(); 9547 9548 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 9549 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 9550 } 9551 9552 private void enforceCanManageDeviceAdmin() { 9553 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS, 9554 null); 9555 } 9556 9557 private void enforceCanManageProfileAndDeviceOwners() { 9558 mContext.enforceCallingOrSelfPermission( 9559 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 9560 } 9561 9562 private void enforceCallerSystemUserHandle() { 9563 final int callingUid = mInjector.binderGetCallingUid(); 9564 final int userId = UserHandle.getUserId(callingUid); 9565 if (userId != UserHandle.USER_SYSTEM) { 9566 throw new SecurityException("Caller has to be in user 0"); 9567 } 9568 } 9569 9570 @Override 9571 public boolean isUninstallInQueue(final String packageName) { 9572 enforceCanManageDeviceAdmin(); 9573 final int userId = mInjector.userHandleGetCallingUserId(); 9574 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 9575 synchronized (this) { 9576 return mPackagesToRemove.contains(packageUserPair); 9577 } 9578 } 9579 9580 @Override 9581 public void uninstallPackageWithActiveAdmins(final String packageName) { 9582 enforceCanManageDeviceAdmin(); 9583 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 9584 9585 final int userId = mInjector.userHandleGetCallingUserId(); 9586 9587 enforceUserUnlocked(userId); 9588 9589 final ComponentName profileOwner = getProfileOwner(userId); 9590 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 9591 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 9592 } 9593 9594 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 9595 if (getDeviceOwnerUserId() == userId && deviceOwner != null 9596 && packageName.equals(deviceOwner.getPackageName())) { 9597 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 9598 } 9599 9600 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 9601 synchronized (this) { 9602 mPackagesToRemove.add(packageUserPair); 9603 } 9604 9605 // All active admins on the user. 9606 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 9607 9608 // Active admins in the target package. 9609 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 9610 if (allActiveAdmins != null) { 9611 for (ComponentName activeAdmin : allActiveAdmins) { 9612 if (packageName.equals(activeAdmin.getPackageName())) { 9613 packageActiveAdmins.add(activeAdmin); 9614 removeActiveAdmin(activeAdmin, userId); 9615 } 9616 } 9617 } 9618 if (packageActiveAdmins.size() == 0) { 9619 startUninstallIntent(packageName, userId); 9620 } else { 9621 mHandler.postDelayed(new Runnable() { 9622 @Override 9623 public void run() { 9624 for (ComponentName activeAdmin : packageActiveAdmins) { 9625 removeAdminArtifacts(activeAdmin, userId); 9626 } 9627 startUninstallIntent(packageName, userId); 9628 } 9629 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 9630 } 9631 } 9632 9633 @Override 9634 public boolean isDeviceProvisioned() { 9635 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT)); 9636 } 9637 9638 private void removePackageIfRequired(final String packageName, final int userId) { 9639 if (!packageHasActiveAdmins(packageName, userId)) { 9640 // Will not do anything if uninstall was not requested or was already started. 9641 startUninstallIntent(packageName, userId); 9642 } 9643 } 9644 9645 private void startUninstallIntent(final String packageName, final int userId) { 9646 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 9647 synchronized (this) { 9648 if (!mPackagesToRemove.contains(packageUserPair)) { 9649 // Do nothing if uninstall was not requested or was already started. 9650 return; 9651 } 9652 mPackagesToRemove.remove(packageUserPair); 9653 } 9654 try { 9655 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) { 9656 // Package does not exist. Nothing to do. 9657 return; 9658 } 9659 } catch (RemoteException re) { 9660 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info"); 9661 } 9662 9663 try { // force stop the package before uninstalling 9664 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 9665 } catch (RemoteException re) { 9666 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 9667 } 9668 final Uri packageURI = Uri.parse("package:" + packageName); 9669 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 9670 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 9671 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 9672 } 9673 9674 /** 9675 * Removes the admin from the policy. Ideally called after the admin's 9676 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 9677 * 9678 * @param adminReceiver The admin to remove 9679 * @param userHandle The user for which this admin has to be removed. 9680 */ 9681 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 9682 synchronized (this) { 9683 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 9684 if (admin == null) { 9685 return; 9686 } 9687 final DevicePolicyData policy = getUserData(userHandle); 9688 final boolean doProxyCleanup = admin.info.usesPolicy( 9689 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 9690 policy.mAdminList.remove(admin); 9691 policy.mAdminMap.remove(adminReceiver); 9692 validatePasswordOwnerLocked(policy); 9693 if (doProxyCleanup) { 9694 resetGlobalProxyLocked(policy); 9695 } 9696 saveSettingsLocked(userHandle); 9697 updateMaximumTimeToLockLocked(userHandle); 9698 policy.mRemovingAdmins.remove(adminReceiver); 9699 9700 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 9701 } 9702 // The removed admin might have disabled camera, so update user 9703 // restrictions. 9704 pushUserRestrictions(userHandle); 9705 } 9706 9707 @Override 9708 public void setDeviceProvisioningConfigApplied() { 9709 enforceManageUsers(); 9710 synchronized (this) { 9711 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 9712 policy.mDeviceProvisioningConfigApplied = true; 9713 saveSettingsLocked(UserHandle.USER_SYSTEM); 9714 } 9715 } 9716 9717 @Override 9718 public boolean isDeviceProvisioningConfigApplied() { 9719 enforceManageUsers(); 9720 synchronized (this) { 9721 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 9722 return policy.mDeviceProvisioningConfigApplied; 9723 } 9724 } 9725 9726 /** 9727 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 9728 * 9729 * It's added for testing only. Please use this API carefully if it's used by other system app 9730 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 9731 * apps. 9732 */ 9733 @Override 9734 public void forceUpdateUserSetupComplete() { 9735 enforceCanManageProfileAndDeviceOwners(); 9736 enforceCallerSystemUserHandle(); 9737 // no effect if it's called from user build 9738 if (!mInjector.isBuildDebuggable()) { 9739 return; 9740 } 9741 final int userId = UserHandle.USER_SYSTEM; 9742 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 9743 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 9744 DevicePolicyData policy = getUserData(userId); 9745 policy.mUserSetupComplete = isUserCompleted; 9746 synchronized (this) { 9747 saveSettingsLocked(userId); 9748 } 9749 } 9750 9751 @Override 9752 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 9753 Preconditions.checkNotNull(admin); 9754 if (!mHasFeature) { 9755 return; 9756 } 9757 ensureDeviceOwnerManagingSingleUser(admin); 9758 setBackupServiceEnabledInternal(enabled); 9759 } 9760 9761 private synchronized void setBackupServiceEnabledInternal(boolean enabled) { 9762 long ident = mInjector.binderClearCallingIdentity(); 9763 try { 9764 IBackupManager ibm = mInjector.getIBackupManager(); 9765 if (ibm != null) { 9766 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled); 9767 } 9768 } catch (RemoteException e) { 9769 throw new IllegalStateException( 9770 "Failed " + (enabled ? "" : "de") + "activating backup service.", e); 9771 } finally { 9772 mInjector.binderRestoreCallingIdentity(ident); 9773 } 9774 } 9775 9776 @Override 9777 public boolean isBackupServiceEnabled(ComponentName admin) { 9778 Preconditions.checkNotNull(admin); 9779 if (!mHasFeature) { 9780 return true; 9781 } 9782 synchronized (this) { 9783 try { 9784 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9785 IBackupManager ibm = mInjector.getIBackupManager(); 9786 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM); 9787 } catch (RemoteException e) { 9788 throw new IllegalStateException("Failed requesting backup service state.", e); 9789 } 9790 } 9791 } 9792 9793 @Override 9794 public boolean bindDeviceAdminServiceAsUser( 9795 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 9796 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 9797 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 9798 if (!mHasFeature) { 9799 return false; 9800 } 9801 Preconditions.checkNotNull(admin); 9802 Preconditions.checkNotNull(caller); 9803 Preconditions.checkNotNull(serviceIntent); 9804 Preconditions.checkArgument( 9805 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 9806 "Service intent must be explicit (with a package name or component): " 9807 + serviceIntent); 9808 Preconditions.checkNotNull(connection); 9809 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 9810 "target user id must be different from the calling user id"); 9811 9812 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 9813 throw new SecurityException("Not allowed to bind to target user id"); 9814 } 9815 9816 final String targetPackage; 9817 synchronized (this) { 9818 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 9819 } 9820 9821 final long callingIdentity = mInjector.binderClearCallingIdentity(); 9822 try { 9823 // Validate and sanitize the incoming service intent. 9824 final Intent sanitizedIntent = 9825 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 9826 if (sanitizedIntent == null) { 9827 // Fail, cannot lookup the target service. 9828 return false; 9829 } 9830 // Ask ActivityManager to bind it. Notice that we are binding the service with the 9831 // caller app instead of DevicePolicyManagerService. 9832 return mInjector.getIActivityManager().bindService( 9833 caller, activtiyToken, serviceIntent, 9834 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 9835 connection, flags, mContext.getOpPackageName(), 9836 targetUserId) != 0; 9837 } catch (RemoteException ex) { 9838 // Same process, should not happen. 9839 } finally { 9840 mInjector.binderRestoreCallingIdentity(callingIdentity); 9841 } 9842 9843 // Failed to bind. 9844 return false; 9845 } 9846 9847 @Override 9848 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 9849 if (!mHasFeature) { 9850 return Collections.emptyList(); 9851 } 9852 Preconditions.checkNotNull(admin); 9853 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 9854 9855 synchronized (this) { 9856 ActiveAdmin callingOwner = getActiveAdminForCallerLocked( 9857 admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9858 9859 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9860 final boolean isCallerDeviceOwner = isDeviceOwner(callingOwner); 9861 final boolean isCallerManagedProfile = isManagedProfile(callingUserId); 9862 if ((!isCallerDeviceOwner && !isCallerManagedProfile) 9863 || !isUserAffiliatedWithDevice(callingUserId)) { 9864 return targetUsers; 9865 } 9866 9867 final long callingIdentity = mInjector.binderClearCallingIdentity(); 9868 try { 9869 String callingOwnerPackage = callingOwner.info.getComponent().getPackageName(); 9870 for (int userId : mUserManager.getProfileIdsWithDisabled(callingUserId)) { 9871 if (userId == callingUserId) { 9872 continue; 9873 } 9874 9875 // We only allow the device owner and a managed profile owner to bind to each 9876 // other. 9877 if ((isCallerManagedProfile && userId == mOwners.getDeviceOwnerUserId()) 9878 || (isCallerDeviceOwner && isManagedProfile(userId))) { 9879 String targetOwnerPackage = getOwnerPackageNameForUserLocked(userId); 9880 9881 // Both must be the same package and be affiliated in order to bind. 9882 if (callingOwnerPackage.equals(targetOwnerPackage) 9883 && isUserAffiliatedWithDevice(userId)) { 9884 targetUsers.add(UserHandle.of(userId)); 9885 } 9886 } 9887 } 9888 } finally { 9889 mInjector.binderRestoreCallingIdentity(callingIdentity); 9890 } 9891 } 9892 9893 return targetUsers; 9894 } 9895 9896 /** 9897 * Return true if a given user has any accounts that'll prevent installing a device or profile 9898 * owner {@code owner}. 9899 * - If the user has no accounts, then return false. 9900 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 9901 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 9902 * ..._DISALLOWED, return true. 9903 * - Otherwise return false. 9904 * 9905 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used 9906 * when the caller is not ADB. 9907 * 9908 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 9909 */ 9910 private boolean hasIncompatibleAccountsOrNonAdbNoLock( 9911 int userId, @Nullable ComponentName owner) { 9912 if (!isAdb()) { 9913 return true; 9914 } 9915 wtfIfInLock(); 9916 9917 final long token = mInjector.binderClearCallingIdentity(); 9918 try { 9919 final AccountManager am = AccountManager.get(mContext); 9920 final Account accounts[] = am.getAccountsAsUser(userId); 9921 if (accounts.length == 0) { 9922 return false; 9923 } 9924 synchronized (this) { 9925 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 9926 Log.w(LOG_TAG, 9927 "Non test-only owner can't be installed with existing accounts."); 9928 return true; 9929 } 9930 } 9931 9932 final String[] feature_allow = 9933 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 9934 final String[] feature_disallow = 9935 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 9936 9937 boolean compatible = true; 9938 for (Account account : accounts) { 9939 if (hasAccountFeatures(am, account, feature_disallow)) { 9940 Log.e(LOG_TAG, account + " has " + feature_disallow[0]); 9941 compatible = false; 9942 break; 9943 } 9944 if (!hasAccountFeatures(am, account, feature_allow)) { 9945 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]); 9946 compatible = false; 9947 break; 9948 } 9949 } 9950 if (compatible) { 9951 Log.w(LOG_TAG, "All accounts are compatible"); 9952 } else { 9953 Log.e(LOG_TAG, "Found incompatible accounts"); 9954 } 9955 return !compatible; 9956 } finally { 9957 mInjector.binderRestoreCallingIdentity(token); 9958 } 9959 } 9960 9961 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 9962 try { 9963 return am.hasFeatures(account, features, null, null).getResult(); 9964 } catch (Exception e) { 9965 Log.w(LOG_TAG, "Failed to get account feature", e); 9966 return false; 9967 } 9968 } 9969 9970 private boolean isAdb() { 9971 final int callingUid = mInjector.binderGetCallingUid(); 9972 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 9973 } 9974 9975 @Override 9976 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) { 9977 if (!mHasFeature) { 9978 return; 9979 } 9980 Preconditions.checkNotNull(admin); 9981 ensureDeviceOwnerManagingSingleUser(admin); 9982 9983 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 9984 // already in the requested state 9985 return; 9986 } 9987 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 9988 deviceOwner.isNetworkLoggingEnabled = enabled; 9989 if (!enabled) { 9990 deviceOwner.numNetworkLoggingNotifications = 0; 9991 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 9992 } 9993 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 9994 9995 setNetworkLoggingActiveInternal(enabled); 9996 } 9997 9998 private synchronized void setNetworkLoggingActiveInternal(boolean active) { 9999 final long callingIdentity = mInjector.binderClearCallingIdentity(); 10000 try { 10001 if (active) { 10002 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal()); 10003 if (!mNetworkLogger.startNetworkLogging()) { 10004 mNetworkLogger = null; 10005 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging" 10006 + " service not being available yet."); 10007 } 10008 sendNetworkLoggingNotificationLocked(); 10009 } else { 10010 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 10011 mNetworkLogger = null; 10012 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 10013 + " service not being available yet."); 10014 } 10015 mNetworkLogger = null; 10016 mInjector.getNotificationManager().cancel(NETWORK_LOGGING_NOTIFICATION_ID); 10017 } 10018 } finally { 10019 mInjector.binderRestoreCallingIdentity(callingIdentity); 10020 } 10021 } 10022 10023 @Override 10024 public boolean isNetworkLoggingEnabled(ComponentName admin) { 10025 if (!mHasFeature) { 10026 return false; 10027 } 10028 synchronized (this) { 10029 enforceDeviceOwnerOrManageUsers(); 10030 return isNetworkLoggingEnabledInternalLocked(); 10031 } 10032 } 10033 10034 private boolean isNetworkLoggingEnabledInternalLocked() { 10035 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10036 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled; 10037 } 10038 10039 /* 10040 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 10041 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 10042 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 10043 * 10044 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 10045 */ 10046 @Override 10047 public synchronized List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, 10048 long batchToken) { 10049 if (!mHasFeature) { 10050 return null; 10051 } 10052 Preconditions.checkNotNull(admin); 10053 ensureDeviceOwnerManagingSingleUser(admin); 10054 10055 if (mNetworkLogger == null) { 10056 return null; 10057 } 10058 10059 if (!isNetworkLoggingEnabledInternalLocked()) { 10060 return null; 10061 } 10062 10063 final long currentTime = System.currentTimeMillis(); 10064 synchronized (this) { 10065 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 10066 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 10067 policyData.mLastNetworkLogsRetrievalTime = currentTime; 10068 saveSettingsLocked(UserHandle.USER_SYSTEM); 10069 } 10070 } 10071 10072 return mNetworkLogger.retrieveLogs(batchToken); 10073 } 10074 10075 private void sendNetworkLoggingNotificationLocked() { 10076 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10077 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 10078 return; 10079 } 10080 if (deviceOwner.numNetworkLoggingNotifications >= 10081 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 10082 return; 10083 } 10084 final long now = System.currentTimeMillis(); 10085 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 10086 return; 10087 } 10088 deviceOwner.numNetworkLoggingNotifications++; 10089 if (deviceOwner.numNetworkLoggingNotifications 10090 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 10091 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 10092 } else { 10093 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 10094 } 10095 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 10096 intent.setPackage("com.android.systemui"); 10097 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0, 10098 UserHandle.CURRENT); 10099 Notification notification = new Notification.Builder(mContext) 10100 .setSmallIcon(R.drawable.ic_qs_network_logging) 10101 .setContentTitle(mContext.getString(R.string.network_logging_notification_title)) 10102 .setContentText(mContext.getString(R.string.network_logging_notification_text)) 10103 .setTicker(mContext.getString(R.string.network_logging_notification_title)) 10104 .setShowWhen(true) 10105 .setContentIntent(pendingIntent) 10106 .build(); 10107 mInjector.getNotificationManager().notify(NETWORK_LOGGING_NOTIFICATION_ID, notification); 10108 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 10109 } 10110 10111 /** 10112 * Return the package name of owner in a given user. 10113 */ 10114 private String getOwnerPackageNameForUserLocked(int userId) { 10115 return mOwners.getDeviceOwnerUserId() == userId 10116 ? mOwners.getDeviceOwnerPackageName() 10117 : mOwners.getProfileOwnerPackage(userId); 10118 } 10119 10120 /** 10121 * @param rawIntent Original service intent specified by caller. It must be explicit. 10122 * @param expectedPackageName The expected package name of the resolved service. 10123 * @return Intent that have component explicitly set. {@code null} if no service is resolved 10124 * with the given intent. 10125 * @throws SecurityException if the intent is resolved to an invalid service. 10126 */ 10127 private Intent createCrossUserServiceIntent( 10128 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 10129 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 10130 ResolveInfo info = mIPackageManager.resolveService( 10131 rawIntent, 10132 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 10133 0, // flags 10134 targetUserId); 10135 if (info == null || info.serviceInfo == null) { 10136 Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent 10137 + " or user " + targetUserId + " is not running"); 10138 return null; 10139 } 10140 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 10141 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 10142 } 10143 if (info.serviceInfo.exported) { 10144 throw new SecurityException("The service must be unexported"); 10145 } 10146 // It is the system server to bind the service, it would be extremely dangerous if it 10147 // can be exploited to bind any service. Set the component explicitly to make sure we 10148 // do not bind anything accidentally. 10149 rawIntent.setComponent(info.serviceInfo.getComponentName()); 10150 return rawIntent; 10151 } 10152 10153 @Override 10154 public long getLastSecurityLogRetrievalTime() { 10155 enforceDeviceOwnerOrManageUsers(); 10156 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 10157 } 10158 10159 @Override 10160 public long getLastBugReportRequestTime() { 10161 enforceDeviceOwnerOrManageUsers(); 10162 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 10163 } 10164 10165 @Override 10166 public long getLastNetworkLogRetrievalTime() { 10167 enforceDeviceOwnerOrManageUsers(); 10168 return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime; 10169 } 10170} 10171