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