DevicePolicyManagerService.java revision 9bab1c4dd505903dbdd7403ea38d8b9d449e9be4
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 wipeDataLocked(boolean wipeExtRequested, String reason, boolean force) { 4792 if (wipeExtRequested) { 4793 StorageManager sm = (StorageManager) mContext.getSystemService( 4794 Context.STORAGE_SERVICE); 4795 sm.wipeAdoptableDisks(); 4796 } 4797 try { 4798 RecoverySystem.rebootWipeUserData(mContext, false /* shutdown */, reason, force); 4799 } catch (IOException | SecurityException e) { 4800 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 4801 } 4802 } 4803 4804 @Override 4805 public void wipeData(int flags) { 4806 if (!mHasFeature) { 4807 return; 4808 } 4809 final int userHandle = mInjector.userHandleGetCallingUserId(); 4810 enforceFullCrossUsersPermission(userHandle); 4811 synchronized (this) { 4812 // This API can only be called by an active device admin, 4813 // so try to retrieve it to check that the caller is one. 4814 final ActiveAdmin admin = getActiveAdminForCallerLocked(null, 4815 DeviceAdminInfo.USES_POLICY_WIPE_DATA); 4816 4817 final String source = admin.info.getComponent().flattenToShortString(); 4818 4819 long ident = mInjector.binderClearCallingIdentity(); 4820 try { 4821 final String restriction; 4822 if (userHandle == UserHandle.USER_SYSTEM) { 4823 restriction = UserManager.DISALLOW_FACTORY_RESET; 4824 } else if (isManagedProfile(userHandle)) { 4825 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 4826 } else { 4827 restriction = UserManager.DISALLOW_REMOVE_USER; 4828 } 4829 if (isAdminAffectedByRestriction( 4830 admin.info.getComponent(), restriction, userHandle)) { 4831 throw new SecurityException("Cannot wipe data. " + restriction 4832 + " restriction is set for user " + userHandle); 4833 } 4834 4835 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 4836 if (!isDeviceOwner(admin.info.getComponent(), userHandle)) { 4837 throw new SecurityException( 4838 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA"); 4839 } 4840 PersistentDataBlockManager manager = (PersistentDataBlockManager) 4841 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 4842 if (manager != null) { 4843 manager.wipe(); 4844 } 4845 } 4846 4847 boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0; 4848 wipeDeviceOrUserLocked(wipeExtRequested, userHandle, 4849 "DevicePolicyManager.wipeData() from " + source, /*force=*/ true); 4850 } finally { 4851 mInjector.binderRestoreCallingIdentity(ident); 4852 } 4853 } 4854 } 4855 4856 private void wipeDeviceOrUserLocked( 4857 boolean wipeExtRequested, final int userHandle, String reason, boolean force) { 4858 // TODO If split user is enabled and the device owner is set in the primary user (rather 4859 // than system), we should probably trigger factory reset. Current code just remove 4860 // that user (but still clears FRP...) 4861 if (userHandle == UserHandle.USER_SYSTEM) { 4862 wipeDataLocked(wipeExtRequested, reason, force); 4863 } else { 4864 mHandler.post(new Runnable() { 4865 @Override 4866 public void run() { 4867 try { 4868 IActivityManager am = mInjector.getIActivityManager(); 4869 if (am.getCurrentUser().id == userHandle) { 4870 am.switchUser(UserHandle.USER_SYSTEM); 4871 } 4872 4873 boolean userRemoved = force 4874 ? mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle) 4875 : mUserManager.removeUser(userHandle); 4876 if (!userRemoved) { 4877 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle); 4878 } else if (isManagedProfile(userHandle)) { 4879 sendWipeProfileNotification(); 4880 } 4881 } catch (RemoteException re) { 4882 // Shouldn't happen 4883 } 4884 } 4885 }); 4886 } 4887 } 4888 4889 private void sendWipeProfileNotification() { 4890 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe); 4891 Notification notification = new Notification.Builder(mContext) 4892 .setSmallIcon(android.R.drawable.stat_sys_warning) 4893 .setContentTitle(mContext.getString(R.string.work_profile_deleted)) 4894 .setContentText(contentText) 4895 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 4896 .setStyle(new Notification.BigTextStyle().bigText(contentText)) 4897 .build(); 4898 mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification); 4899 } 4900 4901 private void clearWipeProfileNotification() { 4902 mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID); 4903 } 4904 4905 @Override 4906 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 4907 if (!mHasFeature) { 4908 return; 4909 } 4910 enforceFullCrossUsersPermission(userHandle); 4911 mContext.enforceCallingOrSelfPermission( 4912 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 4913 4914 synchronized (this) { 4915 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 4916 if (admin == null) { 4917 result.sendResult(null); 4918 return; 4919 } 4920 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 4921 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 4922 intent.setComponent(admin.info.getComponent()); 4923 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 4924 null, new BroadcastReceiver() { 4925 @Override 4926 public void onReceive(Context context, Intent intent) { 4927 result.sendResult(getResultExtras(false)); 4928 } 4929 }, null, Activity.RESULT_OK, null, null); 4930 } 4931 } 4932 4933 @Override 4934 public void setActivePasswordState(PasswordMetrics metrics, int userHandle) { 4935 if (!mHasFeature) { 4936 return; 4937 } 4938 enforceFullCrossUsersPermission(userHandle); 4939 mContext.enforceCallingOrSelfPermission( 4940 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 4941 4942 // If the managed profile doesn't have a separate password, set the metrics to default 4943 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 4944 metrics = new PasswordMetrics(); 4945 } 4946 4947 validateQualityConstant(metrics.quality); 4948 DevicePolicyData policy = getUserData(userHandle); 4949 synchronized (this) { 4950 policy.mActivePasswordMetrics = metrics; 4951 } 4952 } 4953 4954 @Override 4955 public void reportPasswordChanged(@UserIdInt int userId) { 4956 if (!mHasFeature) { 4957 return; 4958 } 4959 enforceFullCrossUsersPermission(userId); 4960 4961 // Managed Profile password can only be changed when it has a separate challenge. 4962 if (!isSeparateProfileChallengeEnabled(userId)) { 4963 enforceNotManagedProfile(userId, "set the active password"); 4964 } 4965 4966 mContext.enforceCallingOrSelfPermission( 4967 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 4968 4969 DevicePolicyData policy = getUserData(userId); 4970 4971 long ident = mInjector.binderClearCallingIdentity(); 4972 try { 4973 synchronized (this) { 4974 policy.mFailedPasswordAttempts = 0; 4975 saveSettingsLocked(userId); 4976 updatePasswordExpirationsLocked(userId); 4977 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 4978 4979 // Send a broadcast to each profile using this password as its primary unlock. 4980 sendAdminCommandForLockscreenPoliciesLocked( 4981 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 4982 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 4983 } 4984 removeCaApprovalsIfNeeded(userId); 4985 } finally { 4986 mInjector.binderRestoreCallingIdentity(ident); 4987 } 4988 } 4989 4990 /** 4991 * Called any time the device password is updated. Resets all password expiration clocks. 4992 */ 4993 private void updatePasswordExpirationsLocked(int userHandle) { 4994 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>(); 4995 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4996 userHandle, /* parent */ false); 4997 final int N = admins.size(); 4998 for (int i = 0; i < N; i++) { 4999 ActiveAdmin admin = admins.get(i); 5000 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 5001 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 5002 long timeout = admin.passwordExpirationTimeout; 5003 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 5004 admin.passwordExpirationDate = expiration; 5005 } 5006 } 5007 for (int affectedUserId : affectedUserIds) { 5008 saveSettingsLocked(affectedUserId); 5009 } 5010 } 5011 5012 @Override 5013 public void reportFailedPasswordAttempt(int userHandle) { 5014 enforceFullCrossUsersPermission(userHandle); 5015 if (!isSeparateProfileChallengeEnabled(userHandle)) { 5016 enforceNotManagedProfile(userHandle, 5017 "report failed password attempt if separate profile challenge is not in place"); 5018 } 5019 mContext.enforceCallingOrSelfPermission( 5020 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5021 5022 final long ident = mInjector.binderClearCallingIdentity(); 5023 try { 5024 boolean wipeData = false; 5025 int identifier = 0; 5026 synchronized (this) { 5027 DevicePolicyData policy = getUserData(userHandle); 5028 policy.mFailedPasswordAttempts++; 5029 saveSettingsLocked(userHandle); 5030 if (mHasFeature) { 5031 ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 5032 userHandle, /* parent */ false); 5033 int max = strictestAdmin != null 5034 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 5035 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 5036 // Wipe the user/profile associated with the policy that was violated. This 5037 // is not necessarily calling user: if the policy that fired was from a 5038 // managed profile rather than the main user profile, we wipe former only. 5039 wipeData = true; 5040 identifier = strictestAdmin.getUserHandle().getIdentifier(); 5041 } 5042 5043 sendAdminCommandForLockscreenPoliciesLocked( 5044 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 5045 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 5046 } 5047 } 5048 if (wipeData) { 5049 // Call without holding lock. 5050 wipeDeviceOrUserLocked(false, identifier, 5051 "reportFailedPasswordAttempt()", false); 5052 } 5053 } finally { 5054 mInjector.binderRestoreCallingIdentity(ident); 5055 } 5056 5057 if (mInjector.securityLogIsLoggingEnabled()) { 5058 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 5059 /*method strength*/ 1); 5060 } 5061 } 5062 5063 @Override 5064 public void reportSuccessfulPasswordAttempt(int userHandle) { 5065 enforceFullCrossUsersPermission(userHandle); 5066 mContext.enforceCallingOrSelfPermission( 5067 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5068 5069 synchronized (this) { 5070 DevicePolicyData policy = getUserData(userHandle); 5071 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 5072 long ident = mInjector.binderClearCallingIdentity(); 5073 try { 5074 policy.mFailedPasswordAttempts = 0; 5075 policy.mPasswordOwner = -1; 5076 saveSettingsLocked(userHandle); 5077 if (mHasFeature) { 5078 sendAdminCommandForLockscreenPoliciesLocked( 5079 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 5080 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 5081 } 5082 } finally { 5083 mInjector.binderRestoreCallingIdentity(ident); 5084 } 5085 } 5086 } 5087 5088 if (mInjector.securityLogIsLoggingEnabled()) { 5089 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 5090 /*method strength*/ 1); 5091 } 5092 } 5093 5094 @Override 5095 public void reportFailedFingerprintAttempt(int userHandle) { 5096 enforceFullCrossUsersPermission(userHandle); 5097 mContext.enforceCallingOrSelfPermission( 5098 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5099 if (mInjector.securityLogIsLoggingEnabled()) { 5100 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 5101 /*method strength*/ 0); 5102 } 5103 } 5104 5105 @Override 5106 public void reportSuccessfulFingerprintAttempt(int userHandle) { 5107 enforceFullCrossUsersPermission(userHandle); 5108 mContext.enforceCallingOrSelfPermission( 5109 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5110 if (mInjector.securityLogIsLoggingEnabled()) { 5111 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 5112 /*method strength*/ 0); 5113 } 5114 } 5115 5116 @Override 5117 public void reportKeyguardDismissed(int userHandle) { 5118 enforceFullCrossUsersPermission(userHandle); 5119 mContext.enforceCallingOrSelfPermission( 5120 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5121 5122 if (mInjector.securityLogIsLoggingEnabled()) { 5123 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 5124 } 5125 } 5126 5127 @Override 5128 public void reportKeyguardSecured(int userHandle) { 5129 enforceFullCrossUsersPermission(userHandle); 5130 mContext.enforceCallingOrSelfPermission( 5131 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5132 5133 if (mInjector.securityLogIsLoggingEnabled()) { 5134 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 5135 } 5136 } 5137 5138 @Override 5139 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 5140 String exclusionList) { 5141 if (!mHasFeature) { 5142 return null; 5143 } 5144 synchronized(this) { 5145 Preconditions.checkNotNull(who, "ComponentName is null"); 5146 5147 // Only check if system user has set global proxy. We don't allow other users to set it. 5148 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5149 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5150 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 5151 5152 // Scan through active admins and find if anyone has already 5153 // set the global proxy. 5154 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 5155 for (ComponentName component : compSet) { 5156 ActiveAdmin ap = policy.mAdminMap.get(component); 5157 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 5158 // Another admin already sets the global proxy 5159 // Return it to the caller. 5160 return component; 5161 } 5162 } 5163 5164 // If the user is not system, don't set the global proxy. Fail silently. 5165 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 5166 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 5167 + UserHandle.getCallingUserId() + " is not permitted."); 5168 return null; 5169 } 5170 if (proxySpec == null) { 5171 admin.specifiesGlobalProxy = false; 5172 admin.globalProxySpec = null; 5173 admin.globalProxyExclusionList = null; 5174 } else { 5175 5176 admin.specifiesGlobalProxy = true; 5177 admin.globalProxySpec = proxySpec; 5178 admin.globalProxyExclusionList = exclusionList; 5179 } 5180 5181 // Reset the global proxy accordingly 5182 // Do this using system permissions, as apps cannot write to secure settings 5183 long origId = mInjector.binderClearCallingIdentity(); 5184 try { 5185 resetGlobalProxyLocked(policy); 5186 } finally { 5187 mInjector.binderRestoreCallingIdentity(origId); 5188 } 5189 return null; 5190 } 5191 } 5192 5193 @Override 5194 public ComponentName getGlobalProxyAdmin(int userHandle) { 5195 if (!mHasFeature) { 5196 return null; 5197 } 5198 enforceFullCrossUsersPermission(userHandle); 5199 synchronized(this) { 5200 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5201 // Scan through active admins and find if anyone has already 5202 // set the global proxy. 5203 final int N = policy.mAdminList.size(); 5204 for (int i = 0; i < N; i++) { 5205 ActiveAdmin ap = policy.mAdminList.get(i); 5206 if (ap.specifiesGlobalProxy) { 5207 // Device admin sets the global proxy 5208 // Return it to the caller. 5209 return ap.info.getComponent(); 5210 } 5211 } 5212 } 5213 // No device admin sets the global proxy. 5214 return null; 5215 } 5216 5217 @Override 5218 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 5219 synchronized (this) { 5220 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5221 } 5222 long token = mInjector.binderClearCallingIdentity(); 5223 try { 5224 ConnectivityManager connectivityManager = (ConnectivityManager) 5225 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5226 connectivityManager.setGlobalProxy(proxyInfo); 5227 } finally { 5228 mInjector.binderRestoreCallingIdentity(token); 5229 } 5230 } 5231 5232 private void resetGlobalProxyLocked(DevicePolicyData policy) { 5233 final int N = policy.mAdminList.size(); 5234 for (int i = 0; i < N; i++) { 5235 ActiveAdmin ap = policy.mAdminList.get(i); 5236 if (ap.specifiesGlobalProxy) { 5237 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 5238 return; 5239 } 5240 } 5241 // No device admins defining global proxies - reset global proxy settings to none 5242 saveGlobalProxyLocked(null, null); 5243 } 5244 5245 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 5246 if (exclusionList == null) { 5247 exclusionList = ""; 5248 } 5249 if (proxySpec == null) { 5250 proxySpec = ""; 5251 } 5252 // Remove white spaces 5253 proxySpec = proxySpec.trim(); 5254 String data[] = proxySpec.split(":"); 5255 int proxyPort = 8080; 5256 if (data.length > 1) { 5257 try { 5258 proxyPort = Integer.parseInt(data[1]); 5259 } catch (NumberFormatException e) {} 5260 } 5261 exclusionList = exclusionList.trim(); 5262 5263 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 5264 if (!proxyProperties.isValid()) { 5265 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 5266 return; 5267 } 5268 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 5269 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 5270 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 5271 exclusionList); 5272 } 5273 5274 /** 5275 * Set the storage encryption request for a single admin. Returns the new total request 5276 * status (for all admins). 5277 */ 5278 @Override 5279 public int setStorageEncryption(ComponentName who, boolean encrypt) { 5280 if (!mHasFeature) { 5281 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5282 } 5283 Preconditions.checkNotNull(who, "ComponentName is null"); 5284 final int userHandle = UserHandle.getCallingUserId(); 5285 synchronized (this) { 5286 // Check for permissions 5287 // Only system user can set storage encryption 5288 if (userHandle != UserHandle.USER_SYSTEM) { 5289 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User " 5290 + UserHandle.getCallingUserId() + " is not permitted."); 5291 return 0; 5292 } 5293 5294 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5295 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 5296 5297 // Quick exit: If the filesystem does not support encryption, we can exit early. 5298 if (!isEncryptionSupported()) { 5299 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5300 } 5301 5302 // (1) Record the value for the admin so it's sticky 5303 if (ap.encryptionRequested != encrypt) { 5304 ap.encryptionRequested = encrypt; 5305 saveSettingsLocked(userHandle); 5306 } 5307 5308 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5309 // (2) Compute "max" for all admins 5310 boolean newRequested = false; 5311 final int N = policy.mAdminList.size(); 5312 for (int i = 0; i < N; i++) { 5313 newRequested |= policy.mAdminList.get(i).encryptionRequested; 5314 } 5315 5316 // Notify OS of new request 5317 setEncryptionRequested(newRequested); 5318 5319 // Return the new global request status 5320 return newRequested 5321 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 5322 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 5323 } 5324 } 5325 5326 /** 5327 * Get the current storage encryption request status for a given admin, or aggregate of all 5328 * active admins. 5329 */ 5330 @Override 5331 public boolean getStorageEncryption(ComponentName who, int userHandle) { 5332 if (!mHasFeature) { 5333 return false; 5334 } 5335 enforceFullCrossUsersPermission(userHandle); 5336 synchronized (this) { 5337 // Check for permissions if a particular caller is specified 5338 if (who != null) { 5339 // When checking for a single caller, status is based on caller's request 5340 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 5341 return ap != null ? ap.encryptionRequested : false; 5342 } 5343 5344 // If no particular caller is specified, return the aggregate set of requests. 5345 // This is short circuited by returning true on the first hit. 5346 DevicePolicyData policy = getUserData(userHandle); 5347 final int N = policy.mAdminList.size(); 5348 for (int i = 0; i < N; i++) { 5349 if (policy.mAdminList.get(i).encryptionRequested) { 5350 return true; 5351 } 5352 } 5353 return false; 5354 } 5355 } 5356 5357 /** 5358 * Get the current encryption status of the device. 5359 */ 5360 @Override 5361 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 5362 if (!mHasFeature) { 5363 // Ok to return current status. 5364 } 5365 enforceFullCrossUsersPermission(userHandle); 5366 5367 // It's not critical here, but let's make sure the package name is correct, in case 5368 // we start using it for different purposes. 5369 ensureCallerPackage(callerPackage); 5370 5371 final ApplicationInfo ai; 5372 try { 5373 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 5374 } catch (RemoteException e) { 5375 throw new SecurityException(e); 5376 } 5377 5378 boolean legacyApp = false; 5379 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 5380 legacyApp = true; 5381 } 5382 5383 final int rawStatus = getEncryptionStatus(); 5384 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 5385 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 5386 } 5387 return rawStatus; 5388 } 5389 5390 /** 5391 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 5392 */ 5393 private boolean isEncryptionSupported() { 5394 // Note, this can be implemented as 5395 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5396 // But is provided as a separate internal method if there's a faster way to do a 5397 // simple check for supported-or-not. 5398 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5399 } 5400 5401 /** 5402 * Hook to low-levels: Reporting the current status of encryption. 5403 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 5404 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 5405 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 5406 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or 5407 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 5408 */ 5409 private int getEncryptionStatus() { 5410 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5411 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 5412 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) { 5413 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 5414 } else if (mInjector.storageManagerIsEncrypted()) { 5415 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 5416 } else if (mInjector.storageManagerIsEncryptable()) { 5417 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 5418 } else { 5419 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5420 } 5421 } 5422 5423 /** 5424 * Hook to low-levels: If needed, record the new admin setting for encryption. 5425 */ 5426 private void setEncryptionRequested(boolean encrypt) { 5427 } 5428 5429 /** 5430 * Set whether the screen capture is disabled for the user managed by the specified admin. 5431 */ 5432 @Override 5433 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) { 5434 if (!mHasFeature) { 5435 return; 5436 } 5437 Preconditions.checkNotNull(who, "ComponentName is null"); 5438 final int userHandle = UserHandle.getCallingUserId(); 5439 synchronized (this) { 5440 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5441 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5442 if (ap.disableScreenCapture != disabled) { 5443 ap.disableScreenCapture = disabled; 5444 saveSettingsLocked(userHandle); 5445 updateScreenCaptureDisabledInWindowManager(userHandle, disabled); 5446 } 5447 } 5448 } 5449 5450 /** 5451 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 5452 * active admin (if given admin is null). 5453 */ 5454 @Override 5455 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) { 5456 if (!mHasFeature) { 5457 return false; 5458 } 5459 synchronized (this) { 5460 if (who != null) { 5461 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 5462 return (admin != null) ? admin.disableScreenCapture : false; 5463 } 5464 5465 DevicePolicyData policy = getUserData(userHandle); 5466 final int N = policy.mAdminList.size(); 5467 for (int i = 0; i < N; i++) { 5468 ActiveAdmin admin = policy.mAdminList.get(i); 5469 if (admin.disableScreenCapture) { 5470 return true; 5471 } 5472 } 5473 return false; 5474 } 5475 } 5476 5477 private void updateScreenCaptureDisabledInWindowManager(final int userHandle, 5478 final boolean disabled) { 5479 mHandler.post(new Runnable() { 5480 @Override 5481 public void run() { 5482 try { 5483 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled); 5484 } catch (RemoteException e) { 5485 Log.w(LOG_TAG, "Unable to notify WindowManager.", e); 5486 } 5487 } 5488 }); 5489 } 5490 5491 /** 5492 * Set whether auto time is required by the specified admin (must be device owner). 5493 */ 5494 @Override 5495 public void setAutoTimeRequired(ComponentName who, boolean required) { 5496 if (!mHasFeature) { 5497 return; 5498 } 5499 Preconditions.checkNotNull(who, "ComponentName is null"); 5500 final int userHandle = UserHandle.getCallingUserId(); 5501 synchronized (this) { 5502 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5503 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5504 if (admin.requireAutoTime != required) { 5505 admin.requireAutoTime = required; 5506 saveSettingsLocked(userHandle); 5507 } 5508 } 5509 5510 // Turn AUTO_TIME on in settings if it is required 5511 if (required) { 5512 long ident = mInjector.binderClearCallingIdentity(); 5513 try { 5514 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */); 5515 } finally { 5516 mInjector.binderRestoreCallingIdentity(ident); 5517 } 5518 } 5519 } 5520 5521 /** 5522 * Returns whether or not auto time is required by the device owner. 5523 */ 5524 @Override 5525 public boolean getAutoTimeRequired() { 5526 if (!mHasFeature) { 5527 return false; 5528 } 5529 synchronized (this) { 5530 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 5531 return (deviceOwner != null) ? deviceOwner.requireAutoTime : false; 5532 } 5533 } 5534 5535 @Override 5536 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 5537 if (!mHasFeature) { 5538 return; 5539 } 5540 Preconditions.checkNotNull(who, "ComponentName is null"); 5541 // Allow setting this policy to true only if there is a split system user. 5542 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) { 5543 throw new UnsupportedOperationException( 5544 "Cannot force ephemeral users on systems without split system user."); 5545 } 5546 boolean removeAllUsers = false; 5547 synchronized (this) { 5548 final ActiveAdmin deviceOwner = 5549 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5550 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) { 5551 deviceOwner.forceEphemeralUsers = forceEphemeralUsers; 5552 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 5553 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers); 5554 removeAllUsers = forceEphemeralUsers; 5555 } 5556 } 5557 if (removeAllUsers) { 5558 long identitity = mInjector.binderClearCallingIdentity(); 5559 try { 5560 mUserManagerInternal.removeAllUsers(); 5561 } finally { 5562 mInjector.binderRestoreCallingIdentity(identitity); 5563 } 5564 } 5565 } 5566 5567 @Override 5568 public boolean getForceEphemeralUsers(ComponentName who) { 5569 if (!mHasFeature) { 5570 return false; 5571 } 5572 Preconditions.checkNotNull(who, "ComponentName is null"); 5573 synchronized (this) { 5574 final ActiveAdmin deviceOwner = 5575 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5576 return deviceOwner.forceEphemeralUsers; 5577 } 5578 } 5579 5580 private boolean isDeviceOwnerManagedSingleUserDevice() { 5581 synchronized (this) { 5582 if (!mOwners.hasDeviceOwner()) { 5583 return false; 5584 } 5585 } 5586 final long callingIdentity = mInjector.binderClearCallingIdentity(); 5587 try { 5588 if (mInjector.userManagerIsSplitSystemUser()) { 5589 // In split system user mode, only allow the case where the device owner is managing 5590 // the only non-system user of the device 5591 return (mUserManager.getUserCount() == 2 5592 && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM); 5593 } else { 5594 return mUserManager.getUserCount() == 1; 5595 } 5596 } finally { 5597 mInjector.binderRestoreCallingIdentity(callingIdentity); 5598 } 5599 } 5600 5601 private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException { 5602 synchronized (this) { 5603 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5604 } 5605 if (!isDeviceOwnerManagedSingleUserDevice()) { 5606 throw new SecurityException( 5607 "There should only be one user, managed by Device Owner"); 5608 } 5609 } 5610 5611 @Override 5612 public boolean requestBugreport(ComponentName who) { 5613 if (!mHasFeature) { 5614 return false; 5615 } 5616 Preconditions.checkNotNull(who, "ComponentName is null"); 5617 ensureDeviceOwnerManagingSingleUser(who); 5618 5619 if (mRemoteBugreportServiceIsActive.get() 5620 || (getDeviceOwnerRemoteBugreportUri() != null)) { 5621 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running."); 5622 return false; 5623 } 5624 5625 final long currentTime = System.currentTimeMillis(); 5626 synchronized (this) { 5627 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 5628 if (currentTime > policyData.mLastBugReportRequestTime) { 5629 policyData.mLastBugReportRequestTime = currentTime; 5630 saveSettingsLocked(UserHandle.USER_SYSTEM); 5631 } 5632 } 5633 5634 final long callingIdentity = mInjector.binderClearCallingIdentity(); 5635 try { 5636 mInjector.getIActivityManager().requestBugReport( 5637 ActivityManager.BUGREPORT_OPTION_REMOTE); 5638 5639 mRemoteBugreportServiceIsActive.set(true); 5640 mRemoteBugreportSharingAccepted.set(false); 5641 registerRemoteBugreportReceivers(); 5642 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 5643 RemoteBugreportUtils.buildNotification(mContext, 5644 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL); 5645 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable, 5646 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS); 5647 return true; 5648 } catch (RemoteException re) { 5649 // should never happen 5650 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re); 5651 return false; 5652 } finally { 5653 mInjector.binderRestoreCallingIdentity(callingIdentity); 5654 } 5655 } 5656 5657 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) { 5658 Intent intent = new Intent(action); 5659 intent.setComponent(mOwners.getDeviceOwnerComponent()); 5660 if (extras != null) { 5661 intent.putExtras(extras); 5662 } 5663 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 5664 } 5665 5666 private synchronized String getDeviceOwnerRemoteBugreportUri() { 5667 return mOwners.getDeviceOwnerRemoteBugreportUri(); 5668 } 5669 5670 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, 5671 String bugreportHash) { 5672 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 5673 } 5674 5675 private void registerRemoteBugreportReceivers() { 5676 try { 5677 IntentFilter filterFinished = new IntentFilter( 5678 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH, 5679 RemoteBugreportUtils.BUGREPORT_MIMETYPE); 5680 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished); 5681 } catch (IntentFilter.MalformedMimeTypeException e) { 5682 // should never happen, as setting a constant 5683 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e); 5684 } 5685 IntentFilter filterConsent = new IntentFilter(); 5686 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 5687 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 5688 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 5689 } 5690 5691 private void onBugreportFinished(Intent intent) { 5692 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 5693 mRemoteBugreportServiceIsActive.set(false); 5694 Uri bugreportUri = intent.getData(); 5695 String bugreportUriString = null; 5696 if (bugreportUri != null) { 5697 bugreportUriString = bugreportUri.toString(); 5698 } 5699 String bugreportHash = intent.getStringExtra( 5700 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH); 5701 if (mRemoteBugreportSharingAccepted.get()) { 5702 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 5703 mInjector.getNotificationManager().cancel(LOG_TAG, 5704 RemoteBugreportUtils.NOTIFICATION_ID); 5705 } else { 5706 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash); 5707 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 5708 RemoteBugreportUtils.buildNotification(mContext, 5709 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 5710 UserHandle.ALL); 5711 } 5712 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 5713 } 5714 5715 private void onBugreportFailed() { 5716 mRemoteBugreportServiceIsActive.set(false); 5717 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 5718 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 5719 mRemoteBugreportSharingAccepted.set(false); 5720 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 5721 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID); 5722 Bundle extras = new Bundle(); 5723 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 5724 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING); 5725 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 5726 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 5727 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 5728 } 5729 5730 private void onBugreportSharingAccepted() { 5731 mRemoteBugreportSharingAccepted.set(true); 5732 String bugreportUriString = null; 5733 String bugreportHash = null; 5734 synchronized (this) { 5735 bugreportUriString = getDeviceOwnerRemoteBugreportUri(); 5736 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash(); 5737 } 5738 if (bugreportUriString != null) { 5739 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 5740 } else if (mRemoteBugreportServiceIsActive.get()) { 5741 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 5742 RemoteBugreportUtils.buildNotification(mContext, 5743 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED), 5744 UserHandle.ALL); 5745 } 5746 } 5747 5748 private void onBugreportSharingDeclined() { 5749 if (mRemoteBugreportServiceIsActive.get()) { 5750 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 5751 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 5752 mRemoteBugreportServiceIsActive.set(false); 5753 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 5754 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 5755 } 5756 mRemoteBugreportSharingAccepted.set(false); 5757 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 5758 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null); 5759 } 5760 5761 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, 5762 String bugreportHash) { 5763 ParcelFileDescriptor pfd = null; 5764 try { 5765 if (bugreportUriString == null) { 5766 throw new FileNotFoundException(); 5767 } 5768 Uri bugreportUri = Uri.parse(bugreportUriString); 5769 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r"); 5770 5771 synchronized (this) { 5772 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 5773 intent.setComponent(mOwners.getDeviceOwnerComponent()); 5774 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE); 5775 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 5776 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(), 5777 bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); 5778 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 5779 } 5780 } catch (FileNotFoundException e) { 5781 Bundle extras = new Bundle(); 5782 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 5783 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE); 5784 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 5785 } finally { 5786 try { 5787 if (pfd != null) { 5788 pfd.close(); 5789 } 5790 } catch (IOException ex) { 5791 // Ignore 5792 } 5793 mRemoteBugreportSharingAccepted.set(false); 5794 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 5795 } 5796 } 5797 5798 /** 5799 * Disables all device cameras according to the specified admin. 5800 */ 5801 @Override 5802 public void setCameraDisabled(ComponentName who, boolean disabled) { 5803 if (!mHasFeature) { 5804 return; 5805 } 5806 Preconditions.checkNotNull(who, "ComponentName is null"); 5807 final int userHandle = mInjector.userHandleGetCallingUserId(); 5808 synchronized (this) { 5809 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5810 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 5811 if (ap.disableCamera != disabled) { 5812 ap.disableCamera = disabled; 5813 saveSettingsLocked(userHandle); 5814 } 5815 } 5816 // Tell the user manager that the restrictions have changed. 5817 pushUserRestrictions(userHandle); 5818 } 5819 5820 /** 5821 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 5822 * active admins. 5823 */ 5824 @Override 5825 public boolean getCameraDisabled(ComponentName who, int userHandle) { 5826 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true); 5827 } 5828 5829 private boolean getCameraDisabled(ComponentName who, int userHandle, 5830 boolean mergeDeviceOwnerRestriction) { 5831 if (!mHasFeature) { 5832 return false; 5833 } 5834 synchronized (this) { 5835 if (who != null) { 5836 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 5837 return (admin != null) ? admin.disableCamera : false; 5838 } 5839 // First, see if DO has set it. If so, it's device-wide. 5840 if (mergeDeviceOwnerRestriction) { 5841 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 5842 if (deviceOwner != null && deviceOwner.disableCamera) { 5843 return true; 5844 } 5845 } 5846 5847 // Then check each device admin on the user. 5848 DevicePolicyData policy = getUserData(userHandle); 5849 // Determine whether or not the device camera is disabled for any active admins. 5850 final int N = policy.mAdminList.size(); 5851 for (int i = 0; i < N; i++) { 5852 ActiveAdmin admin = policy.mAdminList.get(i); 5853 if (admin.disableCamera) { 5854 return true; 5855 } 5856 } 5857 return false; 5858 } 5859 } 5860 5861 @Override 5862 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 5863 if (!mHasFeature) { 5864 return; 5865 } 5866 Preconditions.checkNotNull(who, "ComponentName is null"); 5867 final int userHandle = mInjector.userHandleGetCallingUserId(); 5868 if (isManagedProfile(userHandle)) { 5869 if (parent) { 5870 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 5871 } else { 5872 which = which & PROFILE_KEYGUARD_FEATURES; 5873 } 5874 } 5875 synchronized (this) { 5876 ActiveAdmin ap = getActiveAdminForCallerLocked( 5877 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 5878 if (ap.disabledKeyguardFeatures != which) { 5879 ap.disabledKeyguardFeatures = which; 5880 saveSettingsLocked(userHandle); 5881 } 5882 } 5883 } 5884 5885 /** 5886 * Gets the disabled state for features in keyguard for the given admin, 5887 * or the aggregate of all active admins if who is null. 5888 */ 5889 @Override 5890 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 5891 if (!mHasFeature) { 5892 return 0; 5893 } 5894 enforceFullCrossUsersPermission(userHandle); 5895 final long ident = mInjector.binderClearCallingIdentity(); 5896 try { 5897 synchronized (this) { 5898 if (who != null) { 5899 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 5900 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 5901 } 5902 5903 final List<ActiveAdmin> admins; 5904 if (!parent && isManagedProfile(userHandle)) { 5905 // If we are being asked about a managed profile, just return keyguard features 5906 // disabled by admins in the profile. 5907 admins = getUserDataUnchecked(userHandle).mAdminList; 5908 } else { 5909 // Otherwise return those set by admins in the user and its profiles. 5910 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 5911 } 5912 5913 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 5914 final int N = admins.size(); 5915 for (int i = 0; i < N; i++) { 5916 ActiveAdmin admin = admins.get(i); 5917 int userId = admin.getUserHandle().getIdentifier(); 5918 boolean isRequestedUser = !parent && (userId == userHandle); 5919 if (isRequestedUser || !isManagedProfile(userId)) { 5920 // If we are being asked explicitly about this user 5921 // return all disabled features even if its a managed profile. 5922 which |= admin.disabledKeyguardFeatures; 5923 } else { 5924 // Otherwise a managed profile is only allowed to disable 5925 // some features on the parent user. 5926 which |= (admin.disabledKeyguardFeatures 5927 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 5928 } 5929 } 5930 return which; 5931 } 5932 } finally { 5933 mInjector.binderRestoreCallingIdentity(ident); 5934 } 5935 } 5936 5937 @Override 5938 public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) { 5939 if (!mHasFeature) { 5940 return; 5941 } 5942 Preconditions.checkNotNull(who, "ComponentName is null"); 5943 Preconditions.checkNotNull(packageList, "packageList is null"); 5944 final int userHandle = UserHandle.getCallingUserId(); 5945 synchronized (this) { 5946 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5947 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5948 admin.keepUninstalledPackages = packageList; 5949 saveSettingsLocked(userHandle); 5950 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 5951 } 5952 } 5953 5954 @Override 5955 public List<String> getKeepUninstalledPackages(ComponentName who) { 5956 Preconditions.checkNotNull(who, "ComponentName is null"); 5957 if (!mHasFeature) { 5958 return null; 5959 } 5960 // TODO In split system user mode, allow apps on user 0 to query the list 5961 synchronized (this) { 5962 // Check if this is the device owner who is calling 5963 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5964 return getKeepUninstalledPackagesLocked(); 5965 } 5966 } 5967 5968 private List<String> getKeepUninstalledPackagesLocked() { 5969 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 5970 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 5971 } 5972 5973 @Override 5974 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) { 5975 if (!mHasFeature) { 5976 return false; 5977 } 5978 if (admin == null 5979 || !isPackageInstalledForUser(admin.getPackageName(), userId)) { 5980 throw new IllegalArgumentException("Invalid component " + admin 5981 + " for device owner"); 5982 } 5983 final boolean hasIncompatibleAccounts = hasIncompatibleAccountsNoLock(userId, admin); 5984 synchronized (this) { 5985 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccounts); 5986 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 5987 if (activeAdmin == null 5988 || getUserData(userId).mRemovingAdmins.contains(admin)) { 5989 throw new IllegalArgumentException("Not active admin: " + admin); 5990 } 5991 5992 // Shutting down backup manager service permanently. 5993 long ident = mInjector.binderClearCallingIdentity(); 5994 try { 5995 if (mInjector.getIBackupManager() != null) { 5996 mInjector.getIBackupManager() 5997 .setBackupServiceActive(UserHandle.USER_SYSTEM, false); 5998 } 5999 } catch (RemoteException e) { 6000 throw new IllegalStateException("Failed deactivating backup service.", e); 6001 } finally { 6002 mInjector.binderRestoreCallingIdentity(ident); 6003 } 6004 6005 if (isAdb()) { 6006 // Log device owner provisioning was started using adb. 6007 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 6008 } 6009 6010 mOwners.setDeviceOwner(admin, ownerName, userId); 6011 mOwners.writeDeviceOwner(); 6012 updateDeviceOwnerLocked(); 6013 setDeviceOwnerSystemPropertyLocked(); 6014 6015 final Set<String> restrictions = 6016 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner(); 6017 if (!restrictions.isEmpty()) { 6018 for (String restriction : restrictions) { 6019 activeAdmin.ensureUserRestrictions().putBoolean(restriction, true); 6020 } 6021 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions); 6022 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions); 6023 6024 saveUserRestrictionsLocked(userId); 6025 } 6026 6027 ident = mInjector.binderClearCallingIdentity(); 6028 try { 6029 // TODO Send to system too? 6030 mContext.sendBroadcastAsUser( 6031 new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), 6032 UserHandle.of(userId)); 6033 } finally { 6034 mInjector.binderRestoreCallingIdentity(ident); 6035 } 6036 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 6037 return true; 6038 } 6039 } 6040 6041 @Override 6042 public boolean hasDeviceOwner() { 6043 enforceDeviceOwnerOrManageUsers(); 6044 return mOwners.hasDeviceOwner(); 6045 } 6046 6047 boolean isDeviceOwner(ActiveAdmin admin) { 6048 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 6049 } 6050 6051 public boolean isDeviceOwner(ComponentName who, int userId) { 6052 synchronized (this) { 6053 return mOwners.hasDeviceOwner() 6054 && mOwners.getDeviceOwnerUserId() == userId 6055 && mOwners.getDeviceOwnerComponent().equals(who); 6056 } 6057 } 6058 6059 private boolean isDeviceOwnerPackage(String packageName, int userId) { 6060 synchronized (this) { 6061 return mOwners.hasDeviceOwner() 6062 && mOwners.getDeviceOwnerUserId() == userId 6063 && mOwners.getDeviceOwnerPackageName().equals(packageName); 6064 } 6065 } 6066 6067 public boolean isProfileOwner(ComponentName who, int userId) { 6068 final ComponentName profileOwner = getProfileOwner(userId); 6069 return who != null && who.equals(profileOwner); 6070 } 6071 6072 @Override 6073 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 6074 if (!mHasFeature) { 6075 return null; 6076 } 6077 if (!callingUserOnly) { 6078 enforceManageUsers(); 6079 } 6080 synchronized (this) { 6081 if (!mOwners.hasDeviceOwner()) { 6082 return null; 6083 } 6084 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 6085 mOwners.getDeviceOwnerUserId()) { 6086 return null; 6087 } 6088 return mOwners.getDeviceOwnerComponent(); 6089 } 6090 } 6091 6092 @Override 6093 public int getDeviceOwnerUserId() { 6094 if (!mHasFeature) { 6095 return UserHandle.USER_NULL; 6096 } 6097 enforceManageUsers(); 6098 synchronized (this) { 6099 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 6100 } 6101 } 6102 6103 /** 6104 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 6105 * MANAGE_USERS. 6106 */ 6107 @Override 6108 public String getDeviceOwnerName() { 6109 if (!mHasFeature) { 6110 return null; 6111 } 6112 enforceManageUsers(); 6113 synchronized (this) { 6114 if (!mOwners.hasDeviceOwner()) { 6115 return null; 6116 } 6117 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 6118 // Should setDeviceOwner/ProfileOwner still take a name? 6119 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 6120 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 6121 } 6122 } 6123 6124 /** Returns the active device owner or {@code null} if there is no device owner. */ 6125 @VisibleForTesting 6126 ActiveAdmin getDeviceOwnerAdminLocked() { 6127 ComponentName component = mOwners.getDeviceOwnerComponent(); 6128 if (component == null) { 6129 return null; 6130 } 6131 6132 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 6133 final int n = policy.mAdminList.size(); 6134 for (int i = 0; i < n; i++) { 6135 ActiveAdmin admin = policy.mAdminList.get(i); 6136 if (component.equals(admin.info.getComponent())) { 6137 return admin; 6138 } 6139 } 6140 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 6141 return null; 6142 } 6143 6144 @Override 6145 public void clearDeviceOwner(String packageName) { 6146 Preconditions.checkNotNull(packageName, "packageName is null"); 6147 final int callingUid = mInjector.binderGetCallingUid(); 6148 try { 6149 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 6150 UserHandle.getUserId(callingUid)); 6151 if (uid != callingUid) { 6152 throw new SecurityException("Invalid packageName"); 6153 } 6154 } catch (NameNotFoundException e) { 6155 throw new SecurityException(e); 6156 } 6157 synchronized (this) { 6158 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 6159 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 6160 if (!mOwners.hasDeviceOwner() 6161 || !deviceOwnerComponent.getPackageName().equals(packageName) 6162 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) { 6163 throw new SecurityException( 6164 "clearDeviceOwner can only be called by the device owner"); 6165 } 6166 enforceUserUnlocked(deviceOwnerUserId); 6167 6168 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 6169 long ident = mInjector.binderClearCallingIdentity(); 6170 try { 6171 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 6172 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 6173 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED); 6174 mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId)); 6175 } finally { 6176 mInjector.binderRestoreCallingIdentity(ident); 6177 } 6178 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 6179 } 6180 } 6181 6182 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 6183 if (admin != null) { 6184 admin.disableCamera = false; 6185 admin.userRestrictions = null; 6186 admin.defaultEnabledRestrictionsAlreadySet.clear(); 6187 admin.forceEphemeralUsers = false; 6188 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 6189 final DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 6190 policyData.mLastSecurityLogRetrievalTime = -1; 6191 policyData.mLastBugReportRequestTime = -1; 6192 policyData.mLastNetworkLogsRetrievalTime = -1; 6193 saveSettingsLocked(UserHandle.USER_SYSTEM); 6194 } 6195 clearUserPoliciesLocked(userId); 6196 6197 mOwners.clearDeviceOwner(); 6198 mOwners.writeDeviceOwner(); 6199 updateDeviceOwnerLocked(); 6200 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded(); 6201 try { 6202 if (mInjector.getIBackupManager() != null) { 6203 // Reactivate backup service. 6204 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true); 6205 } 6206 } catch (RemoteException e) { 6207 throw new IllegalStateException("Failed reactivating backup service.", e); 6208 } 6209 } 6210 6211 @Override 6212 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 6213 if (!mHasFeature) { 6214 return false; 6215 } 6216 if (who == null 6217 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) { 6218 throw new IllegalArgumentException("Component " + who 6219 + " not installed for userId:" + userHandle); 6220 } 6221 final boolean hasIncompatibleAccounts = hasIncompatibleAccountsNoLock(userHandle, who); 6222 synchronized (this) { 6223 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccounts); 6224 6225 if (getActiveAdminUncheckedLocked(who, userHandle) == null 6226 || getUserData(userHandle).mRemovingAdmins.contains(who)) { 6227 throw new IllegalArgumentException("Not active admin: " + who); 6228 } 6229 6230 if (isAdb()) { 6231 // Log profile owner provisioning was started using adb. 6232 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 6233 } 6234 6235 mOwners.setProfileOwner(who, ownerName, userHandle); 6236 mOwners.writeProfileOwner(userHandle); 6237 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 6238 6239 return true; 6240 } 6241 } 6242 6243 @Override 6244 public void clearProfileOwner(ComponentName who) { 6245 if (!mHasFeature) { 6246 return; 6247 } 6248 final UserHandle callingUser = mInjector.binderGetCallingUserHandle(); 6249 final int userId = callingUser.getIdentifier(); 6250 enforceNotManagedProfile(userId, "clear profile owner"); 6251 enforceUserUnlocked(userId); 6252 // Check if this is the profile owner who is calling 6253 final ActiveAdmin admin = 6254 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6255 synchronized (this) { 6256 final long ident = mInjector.binderClearCallingIdentity(); 6257 try { 6258 clearProfileOwnerLocked(admin, userId); 6259 removeActiveAdminLocked(who, userId); 6260 } finally { 6261 mInjector.binderRestoreCallingIdentity(ident); 6262 } 6263 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 6264 } 6265 } 6266 6267 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 6268 if (admin != null) { 6269 admin.disableCamera = false; 6270 admin.userRestrictions = null; 6271 admin.defaultEnabledRestrictionsAlreadySet.clear(); 6272 } 6273 clearUserPoliciesLocked(userId); 6274 mOwners.removeProfileOwner(userId); 6275 mOwners.writeProfileOwner(userId); 6276 } 6277 6278 @Override 6279 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 6280 Preconditions.checkNotNull(who, "ComponentName is null"); 6281 if (!mHasFeature) { 6282 return; 6283 } 6284 6285 synchronized (this) { 6286 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6287 long token = mInjector.binderClearCallingIdentity(); 6288 try { 6289 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null); 6290 } finally { 6291 mInjector.binderRestoreCallingIdentity(token); 6292 } 6293 } 6294 } 6295 6296 @Override 6297 public CharSequence getDeviceOwnerLockScreenInfo() { 6298 return mLockPatternUtils.getDeviceOwnerInfo(); 6299 } 6300 6301 private void clearUserPoliciesLocked(int userId) { 6302 // Reset some of the user-specific policies 6303 DevicePolicyData policy = getUserData(userId); 6304 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 6305 policy.mDelegatedCertInstallerPackage = null; 6306 policy.mApplicationRestrictionsManagingPackage = null; 6307 policy.mStatusBarDisabled = false; 6308 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 6309 saveSettingsLocked(userId); 6310 6311 try { 6312 mIPackageManager.updatePermissionFlagsForAllApps( 6313 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 6314 0 /* flagValues */, userId); 6315 pushUserRestrictions(userId); 6316 } catch (RemoteException re) { 6317 // Shouldn't happen. 6318 } 6319 } 6320 6321 @Override 6322 public boolean hasUserSetupCompleted() { 6323 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 6324 } 6325 6326 // This checks only if the Setup Wizard has run. Since Wear devices pair before 6327 // completing Setup Wizard, and pairing involves transferring user data, calling 6328 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). 6329 private boolean hasUserSetupCompleted(int userHandle) { 6330 if (!mHasFeature) { 6331 return true; 6332 } 6333 return getUserData(userHandle).mUserSetupComplete; 6334 } 6335 6336 private boolean hasPaired(int userHandle) { 6337 if (!mHasFeature) { 6338 return true; 6339 } 6340 return getUserData(userHandle).mPaired; 6341 } 6342 6343 @Override 6344 public int getUserProvisioningState() { 6345 if (!mHasFeature) { 6346 return DevicePolicyManager.STATE_USER_UNMANAGED; 6347 } 6348 int userHandle = mInjector.userHandleGetCallingUserId(); 6349 return getUserProvisioningState(userHandle); 6350 } 6351 6352 private int getUserProvisioningState(int userHandle) { 6353 return getUserData(userHandle).mUserProvisioningState; 6354 } 6355 6356 @Override 6357 public void setUserProvisioningState(int newState, int userHandle) { 6358 if (!mHasFeature) { 6359 return; 6360 } 6361 6362 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle) 6363 && getManagedUserId(userHandle) == -1) { 6364 // No managed device, user or profile, so setting provisioning state makes no sense. 6365 throw new IllegalStateException("Not allowed to change provisioning state unless a " 6366 + "device or profile owner is set."); 6367 } 6368 6369 synchronized (this) { 6370 boolean transitionCheckNeeded = true; 6371 6372 // Calling identity/permission checks. 6373 if (isAdb()) { 6374 // ADB shell can only move directly from un-managed to finalized as part of directly 6375 // setting profile-owner or device-owner. 6376 if (getUserProvisioningState(userHandle) != 6377 DevicePolicyManager.STATE_USER_UNMANAGED 6378 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 6379 throw new IllegalStateException("Not allowed to change provisioning state " 6380 + "unless current provisioning state is unmanaged, and new state is " 6381 + "finalized."); 6382 } 6383 transitionCheckNeeded = false; 6384 } else { 6385 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS. 6386 enforceCanManageProfileAndDeviceOwners(); 6387 } 6388 6389 final DevicePolicyData policyData = getUserData(userHandle); 6390 if (transitionCheckNeeded) { 6391 // Optional state transition check for non-ADB case. 6392 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState); 6393 } 6394 policyData.mUserProvisioningState = newState; 6395 saveSettingsLocked(userHandle); 6396 } 6397 } 6398 6399 private void checkUserProvisioningStateTransition(int currentState, int newState) { 6400 // Valid transitions for normal use-cases. 6401 switch (currentState) { 6402 case DevicePolicyManager.STATE_USER_UNMANAGED: 6403 // Can move to any state from unmanaged (except itself as an edge case).. 6404 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 6405 return; 6406 } 6407 break; 6408 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 6409 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 6410 // Can only move to finalized from these states. 6411 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 6412 return; 6413 } 6414 break; 6415 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 6416 // Current user has a managed-profile, but current user is not managed, so 6417 // rather than moving to finalized state, go back to unmanaged once 6418 // profile provisioning is complete. 6419 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 6420 return; 6421 } 6422 break; 6423 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED: 6424 // Cannot transition out of finalized. 6425 break; 6426 } 6427 6428 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 6429 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 6430 + "from state [" + currentState + "]"); 6431 } 6432 6433 @Override 6434 public void setProfileEnabled(ComponentName who) { 6435 if (!mHasFeature) { 6436 return; 6437 } 6438 Preconditions.checkNotNull(who, "ComponentName is null"); 6439 synchronized (this) { 6440 // Check if this is the profile owner who is calling 6441 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6442 final int userId = UserHandle.getCallingUserId(); 6443 enforceManagedProfile(userId, "enable the profile"); 6444 // Check if the profile is already enabled. 6445 UserInfo managedProfile = getUserInfo(userId); 6446 if (managedProfile.isEnabled()) { 6447 Slog.e(LOG_TAG, 6448 "setProfileEnabled is called when the profile is already enabled"); 6449 return; 6450 } 6451 long id = mInjector.binderClearCallingIdentity(); 6452 try { 6453 mUserManager.setUserEnabled(userId); 6454 UserInfo parent = mUserManager.getProfileParent(userId); 6455 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 6456 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 6457 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 6458 Intent.FLAG_RECEIVER_FOREGROUND); 6459 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id)); 6460 } finally { 6461 mInjector.binderRestoreCallingIdentity(id); 6462 } 6463 } 6464 } 6465 6466 @Override 6467 public void setProfileName(ComponentName who, String profileName) { 6468 Preconditions.checkNotNull(who, "ComponentName is null"); 6469 int userId = UserHandle.getCallingUserId(); 6470 // Check if this is the profile owner (includes device owner). 6471 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6472 6473 long id = mInjector.binderClearCallingIdentity(); 6474 try { 6475 mUserManager.setUserName(userId, profileName); 6476 } finally { 6477 mInjector.binderRestoreCallingIdentity(id); 6478 } 6479 } 6480 6481 @Override 6482 public ComponentName getProfileOwner(int userHandle) { 6483 if (!mHasFeature) { 6484 return null; 6485 } 6486 6487 synchronized (this) { 6488 return mOwners.getProfileOwnerComponent(userHandle); 6489 } 6490 } 6491 6492 // Returns the active profile owner for this user or null if the current user has no 6493 // profile owner. 6494 @VisibleForTesting 6495 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 6496 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 6497 if (profileOwner == null) { 6498 return null; 6499 } 6500 DevicePolicyData policy = getUserData(userHandle); 6501 final int n = policy.mAdminList.size(); 6502 for (int i = 0; i < n; i++) { 6503 ActiveAdmin admin = policy.mAdminList.get(i); 6504 if (profileOwner.equals(admin.info.getComponent())) { 6505 return admin; 6506 } 6507 } 6508 return null; 6509 } 6510 6511 @Override 6512 public String getProfileOwnerName(int userHandle) { 6513 if (!mHasFeature) { 6514 return null; 6515 } 6516 enforceManageUsers(); 6517 ComponentName profileOwner = getProfileOwner(userHandle); 6518 if (profileOwner == null) { 6519 return null; 6520 } 6521 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 6522 } 6523 6524 /** 6525 * Canonical name for a given package. 6526 */ 6527 private String getApplicationLabel(String packageName, int userHandle) { 6528 long token = mInjector.binderClearCallingIdentity(); 6529 try { 6530 final Context userContext; 6531 try { 6532 UserHandle handle = new UserHandle(userHandle); 6533 userContext = mContext.createPackageContextAsUser(packageName, 0, handle); 6534 } catch (PackageManager.NameNotFoundException nnfe) { 6535 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe); 6536 return null; 6537 } 6538 ApplicationInfo appInfo = userContext.getApplicationInfo(); 6539 CharSequence result = null; 6540 if (appInfo != null) { 6541 PackageManager pm = userContext.getPackageManager(); 6542 result = pm.getApplicationLabel(appInfo); 6543 } 6544 return result != null ? result.toString() : null; 6545 } finally { 6546 mInjector.binderRestoreCallingIdentity(token); 6547 } 6548 } 6549 6550 /** 6551 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 6552 * permission. 6553 * The profile owner can only be set before the user setup phase has completed, 6554 * except for: 6555 * - SYSTEM_UID 6556 * - adb unless hasIncompatibleAccounts is true. 6557 */ 6558 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle, 6559 boolean hasIncompatibleAccounts) { 6560 UserInfo info = getUserInfo(userHandle); 6561 if (info == null) { 6562 // User doesn't exist. 6563 throw new IllegalArgumentException( 6564 "Attempted to set profile owner for invalid userId: " + userHandle); 6565 } 6566 if (info.isGuest()) { 6567 throw new IllegalStateException("Cannot set a profile owner on a guest"); 6568 } 6569 if (mOwners.hasProfileOwner(userHandle)) { 6570 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 6571 + "is already set."); 6572 } 6573 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 6574 throw new IllegalStateException("Trying to set the profile owner, but the user " 6575 + "already has a device owner."); 6576 } 6577 if (isAdb()) { 6578 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 6579 && hasIncompatibleAccounts) { 6580 throw new IllegalStateException("Not allowed to set the profile owner because " 6581 + "there are already some accounts on the profile"); 6582 } 6583 return; 6584 } 6585 enforceCanManageProfileAndDeviceOwners(); 6586 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) { 6587 throw new IllegalStateException("Cannot set the profile owner on a user which is " 6588 + "already set-up"); 6589 } 6590 } 6591 6592 /** 6593 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 6594 * permission. 6595 */ 6596 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId, 6597 boolean hasIncompatibleAccounts) { 6598 if (!isAdb()) { 6599 enforceCanManageProfileAndDeviceOwners(); 6600 } 6601 6602 final int code = checkDeviceOwnerProvisioningPreConditionLocked( 6603 owner, userId, isAdb(), hasIncompatibleAccounts); 6604 switch (code) { 6605 case CODE_OK: 6606 return; 6607 case CODE_HAS_DEVICE_OWNER: 6608 throw new IllegalStateException( 6609 "Trying to set the device owner, but device owner is already set."); 6610 case CODE_USER_HAS_PROFILE_OWNER: 6611 throw new IllegalStateException("Trying to set the device owner, but the user " 6612 + "already has a profile owner."); 6613 case CODE_USER_NOT_RUNNING: 6614 throw new IllegalStateException("User not running: " + userId); 6615 case CODE_NOT_SYSTEM_USER: 6616 throw new IllegalStateException("User is not system user"); 6617 case CODE_USER_SETUP_COMPLETED: 6618 throw new IllegalStateException( 6619 "Cannot set the device owner if the device is already set-up"); 6620 case CODE_NONSYSTEM_USER_EXISTS: 6621 throw new IllegalStateException("Not allowed to set the device owner because there " 6622 + "are already several users on the device"); 6623 case CODE_ACCOUNTS_NOT_EMPTY: 6624 throw new IllegalStateException("Not allowed to set the device owner because there " 6625 + "are already some accounts on the device"); 6626 case CODE_HAS_PAIRED: 6627 throw new IllegalStateException("Not allowed to set the device owner because this " 6628 + "device has already paired"); 6629 default: 6630 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code); 6631 } 6632 } 6633 6634 private void enforceUserUnlocked(int userId) { 6635 // Since we're doing this operation on behalf of an app, we only 6636 // want to use the actual "unlocked" state. 6637 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 6638 "User must be running and unlocked"); 6639 } 6640 6641 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 6642 if (parent) { 6643 enforceUserUnlocked(getProfileParentId(userId)); 6644 } else { 6645 enforceUserUnlocked(userId); 6646 } 6647 } 6648 6649 private void enforceManageUsers() { 6650 final int callingUid = mInjector.binderGetCallingUid(); 6651 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 6652 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 6653 } 6654 } 6655 6656 private void enforceFullCrossUsersPermission(int userHandle) { 6657 enforceSystemUserOrPermission(userHandle, 6658 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 6659 } 6660 6661 private void enforceCrossUsersPermission(int userHandle) { 6662 enforceSystemUserOrPermission(userHandle, 6663 android.Manifest.permission.INTERACT_ACROSS_USERS); 6664 } 6665 6666 private void enforceSystemUserOrPermission(int userHandle, String permission) { 6667 if (userHandle < 0) { 6668 throw new IllegalArgumentException("Invalid userId " + userHandle); 6669 } 6670 final int callingUid = mInjector.binderGetCallingUid(); 6671 if (userHandle == UserHandle.getUserId(callingUid)) { 6672 return; 6673 } 6674 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 6675 mContext.enforceCallingOrSelfPermission(permission, 6676 "Must be system or have " + permission + " permission"); 6677 } 6678 } 6679 6680 private void enforceManagedProfile(int userHandle, String message) { 6681 if(!isManagedProfile(userHandle)) { 6682 throw new SecurityException("You can not " + message + " outside a managed profile."); 6683 } 6684 } 6685 6686 private void enforceNotManagedProfile(int userHandle, String message) { 6687 if(isManagedProfile(userHandle)) { 6688 throw new SecurityException("You can not " + message + " for a managed profile."); 6689 } 6690 } 6691 6692 private void enforceDeviceOwnerOrManageUsers() { 6693 synchronized (this) { 6694 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 6695 mInjector.binderGetCallingUid()) != null) { 6696 return; 6697 } 6698 } 6699 enforceManageUsers(); 6700 } 6701 6702 private void ensureCallerPackage(@Nullable String packageName) { 6703 if (packageName == null) { 6704 Preconditions.checkState(isCallerWithSystemUid(), 6705 "Only caller can omit package name"); 6706 } else { 6707 final int callingUid = mInjector.binderGetCallingUid(); 6708 final int userId = mInjector.userHandleGetCallingUserId(); 6709 try { 6710 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 6711 packageName, 0, userId); 6712 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name"); 6713 } catch (RemoteException e) { 6714 // Shouldn't happen 6715 } 6716 } 6717 } 6718 6719 private boolean isCallerWithSystemUid() { 6720 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID); 6721 } 6722 6723 private int getProfileParentId(int userHandle) { 6724 final long ident = mInjector.binderClearCallingIdentity(); 6725 try { 6726 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 6727 return parentUser != null ? parentUser.id : userHandle; 6728 } finally { 6729 mInjector.binderRestoreCallingIdentity(ident); 6730 } 6731 } 6732 6733 private int getCredentialOwner(int userHandle, boolean parent) { 6734 final long ident = mInjector.binderClearCallingIdentity(); 6735 try { 6736 if (parent) { 6737 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 6738 if (parentProfile != null) { 6739 userHandle = parentProfile.id; 6740 } 6741 } 6742 return mUserManager.getCredentialOwnerProfile(userHandle); 6743 } finally { 6744 mInjector.binderRestoreCallingIdentity(ident); 6745 } 6746 } 6747 6748 private boolean isManagedProfile(int userHandle) { 6749 final UserInfo user = getUserInfo(userHandle); 6750 return user != null && user.isManagedProfile(); 6751 } 6752 6753 private void enableIfNecessary(String packageName, int userId) { 6754 try { 6755 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 6756 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 6757 userId); 6758 if (ai.enabledSetting 6759 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 6760 mIPackageManager.setApplicationEnabledSetting(packageName, 6761 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 6762 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 6763 } 6764 } catch (RemoteException e) { 6765 } 6766 } 6767 6768 @Override 6769 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 6770 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 6771 != PackageManager.PERMISSION_GRANTED) { 6772 6773 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid=" 6774 + mInjector.binderGetCallingPid() 6775 + ", uid=" + mInjector.binderGetCallingUid()); 6776 return; 6777 } 6778 6779 synchronized (this) { 6780 pw.println("Current Device Policy Manager state:"); 6781 mOwners.dump(" ", pw); 6782 int userCount = mUserData.size(); 6783 for (int u = 0; u < userCount; u++) { 6784 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 6785 pw.println(); 6786 pw.println(" Enabled Device Admins (User " + policy.mUserHandle 6787 + ", provisioningState: " + policy.mUserProvisioningState + "):"); 6788 final int N = policy.mAdminList.size(); 6789 for (int i=0; i<N; i++) { 6790 ActiveAdmin ap = policy.mAdminList.get(i); 6791 if (ap != null) { 6792 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 6793 pw.println(":"); 6794 ap.dump(" ", pw); 6795 } 6796 } 6797 if (!policy.mRemovingAdmins.isEmpty()) { 6798 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 6799 + policy.mRemovingAdmins); 6800 } 6801 6802 pw.println(" "); 6803 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 6804 } 6805 pw.println(); 6806 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 6807 } 6808 } 6809 6810 private String getEncryptionStatusName(int encryptionStatus) { 6811 switch (encryptionStatus) { 6812 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 6813 return "inactive"; 6814 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 6815 return "block default key"; 6816 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 6817 return "block"; 6818 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 6819 return "per-user"; 6820 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 6821 return "unsupported"; 6822 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 6823 return "activating"; 6824 default: 6825 return "unknown"; 6826 } 6827 } 6828 6829 @Override 6830 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 6831 ComponentName activity) { 6832 Preconditions.checkNotNull(who, "ComponentName is null"); 6833 final int userHandle = UserHandle.getCallingUserId(); 6834 synchronized (this) { 6835 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6836 6837 long id = mInjector.binderClearCallingIdentity(); 6838 try { 6839 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 6840 } catch (RemoteException re) { 6841 // Shouldn't happen 6842 } finally { 6843 mInjector.binderRestoreCallingIdentity(id); 6844 } 6845 } 6846 } 6847 6848 @Override 6849 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 6850 Preconditions.checkNotNull(who, "ComponentName is null"); 6851 final int userHandle = UserHandle.getCallingUserId(); 6852 synchronized (this) { 6853 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6854 6855 long id = mInjector.binderClearCallingIdentity(); 6856 try { 6857 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 6858 } catch (RemoteException re) { 6859 // Shouldn't happen 6860 } finally { 6861 mInjector.binderRestoreCallingIdentity(id); 6862 } 6863 } 6864 } 6865 6866 @Override 6867 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 6868 String packageName) { 6869 Preconditions.checkNotNull(admin, "ComponentName is null"); 6870 6871 final int userHandle = mInjector.userHandleGetCallingUserId(); 6872 synchronized (this) { 6873 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6874 if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) { 6875 return false; 6876 } 6877 DevicePolicyData policy = getUserData(userHandle); 6878 policy.mApplicationRestrictionsManagingPackage = packageName; 6879 saveSettingsLocked(userHandle); 6880 return true; 6881 } 6882 } 6883 6884 @Override 6885 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 6886 Preconditions.checkNotNull(admin, "ComponentName is null"); 6887 6888 final int userHandle = mInjector.userHandleGetCallingUserId(); 6889 synchronized (this) { 6890 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6891 DevicePolicyData policy = getUserData(userHandle); 6892 return policy.mApplicationRestrictionsManagingPackage; 6893 } 6894 } 6895 6896 @Override 6897 public boolean isCallerApplicationRestrictionsManagingPackage() { 6898 final int callingUid = mInjector.binderGetCallingUid(); 6899 final int userHandle = UserHandle.getUserId(callingUid); 6900 synchronized (this) { 6901 final DevicePolicyData policy = getUserData(userHandle); 6902 if (policy.mApplicationRestrictionsManagingPackage == null) { 6903 return false; 6904 } 6905 6906 try { 6907 int uid = mInjector.getPackageManager().getPackageUidAsUser( 6908 policy.mApplicationRestrictionsManagingPackage, userHandle); 6909 return uid == callingUid; 6910 } catch (NameNotFoundException e) { 6911 return false; 6912 } 6913 } 6914 } 6915 6916 private void enforceCanManageApplicationRestrictions(ComponentName who) { 6917 if (who != null) { 6918 synchronized (this) { 6919 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6920 } 6921 } else if (!isCallerApplicationRestrictionsManagingPackage()) { 6922 throw new SecurityException( 6923 "No admin component given, and caller cannot manage application restrictions " 6924 + "for other apps."); 6925 } 6926 } 6927 6928 @Override 6929 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) { 6930 enforceCanManageApplicationRestrictions(who); 6931 6932 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 6933 final long id = mInjector.binderClearCallingIdentity(); 6934 try { 6935 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 6936 } finally { 6937 mInjector.binderRestoreCallingIdentity(id); 6938 } 6939 } 6940 6941 @Override 6942 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 6943 PersistableBundle args, boolean parent) { 6944 if (!mHasFeature) { 6945 return; 6946 } 6947 Preconditions.checkNotNull(admin, "admin is null"); 6948 Preconditions.checkNotNull(agent, "agent is null"); 6949 final int userHandle = UserHandle.getCallingUserId(); 6950 synchronized (this) { 6951 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 6952 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 6953 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 6954 saveSettingsLocked(userHandle); 6955 } 6956 } 6957 6958 @Override 6959 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 6960 ComponentName agent, int userHandle, boolean parent) { 6961 if (!mHasFeature) { 6962 return null; 6963 } 6964 Preconditions.checkNotNull(agent, "agent null"); 6965 enforceFullCrossUsersPermission(userHandle); 6966 6967 synchronized (this) { 6968 final String componentName = agent.flattenToString(); 6969 if (admin != null) { 6970 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 6971 if (ap == null) return null; 6972 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 6973 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 6974 List<PersistableBundle> result = new ArrayList<>(); 6975 result.add(trustAgentInfo.options); 6976 return result; 6977 } 6978 6979 // Return strictest policy for this user and profiles that are visible from this user. 6980 List<PersistableBundle> result = null; 6981 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 6982 // of the options. If any admin doesn't have options, discard options for the rest 6983 // and return null. 6984 List<ActiveAdmin> admins = 6985 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 6986 boolean allAdminsHaveOptions = true; 6987 final int N = admins.size(); 6988 for (int i = 0; i < N; i++) { 6989 final ActiveAdmin active = admins.get(i); 6990 6991 final boolean disablesTrust = (active.disabledKeyguardFeatures 6992 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 6993 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 6994 if (info != null && info.options != null && !info.options.isEmpty()) { 6995 if (disablesTrust) { 6996 if (result == null) { 6997 result = new ArrayList<>(); 6998 } 6999 result.add(info.options); 7000 } else { 7001 Log.w(LOG_TAG, "Ignoring admin " + active.info 7002 + " because it has trust options but doesn't declare " 7003 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 7004 } 7005 } else if (disablesTrust) { 7006 allAdminsHaveOptions = false; 7007 break; 7008 } 7009 } 7010 return allAdminsHaveOptions ? result : null; 7011 } 7012 } 7013 7014 @Override 7015 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 7016 Preconditions.checkNotNull(who, "ComponentName is null"); 7017 synchronized (this) { 7018 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7019 7020 int userHandle = UserHandle.getCallingUserId(); 7021 DevicePolicyData userData = getUserData(userHandle); 7022 userData.mRestrictionsProvider = permissionProvider; 7023 saveSettingsLocked(userHandle); 7024 } 7025 } 7026 7027 @Override 7028 public ComponentName getRestrictionsProvider(int userHandle) { 7029 synchronized (this) { 7030 if (!isCallerWithSystemUid()) { 7031 throw new SecurityException("Only the system can query the permission provider"); 7032 } 7033 DevicePolicyData userData = getUserData(userHandle); 7034 return userData != null ? userData.mRestrictionsProvider : null; 7035 } 7036 } 7037 7038 @Override 7039 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 7040 Preconditions.checkNotNull(who, "ComponentName is null"); 7041 int callingUserId = UserHandle.getCallingUserId(); 7042 synchronized (this) { 7043 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7044 7045 long id = mInjector.binderClearCallingIdentity(); 7046 try { 7047 UserInfo parent = mUserManager.getProfileParent(callingUserId); 7048 if (parent == null) { 7049 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 7050 + "parent"); 7051 return; 7052 } 7053 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 7054 mIPackageManager.addCrossProfileIntentFilter( 7055 filter, who.getPackageName(), callingUserId, parent.id, 0); 7056 } 7057 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 7058 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 7059 parent.id, callingUserId, 0); 7060 } 7061 } catch (RemoteException re) { 7062 // Shouldn't happen 7063 } finally { 7064 mInjector.binderRestoreCallingIdentity(id); 7065 } 7066 } 7067 } 7068 7069 @Override 7070 public void clearCrossProfileIntentFilters(ComponentName who) { 7071 Preconditions.checkNotNull(who, "ComponentName is null"); 7072 int callingUserId = UserHandle.getCallingUserId(); 7073 synchronized (this) { 7074 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7075 long id = mInjector.binderClearCallingIdentity(); 7076 try { 7077 UserInfo parent = mUserManager.getProfileParent(callingUserId); 7078 if (parent == null) { 7079 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 7080 + "parent"); 7081 return; 7082 } 7083 // Removing those that go from the managed profile to the parent. 7084 mIPackageManager.clearCrossProfileIntentFilters( 7085 callingUserId, who.getPackageName()); 7086 // And those that go from the parent to the managed profile. 7087 // If we want to support multiple managed profiles, we will have to only remove 7088 // those that have callingUserId as their target. 7089 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 7090 } catch (RemoteException re) { 7091 // Shouldn't happen 7092 } finally { 7093 mInjector.binderRestoreCallingIdentity(id); 7094 } 7095 } 7096 } 7097 7098 /** 7099 * @return true if all packages in enabledPackages are either in the list 7100 * permittedList or are a system app. 7101 */ 7102 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 7103 List<String> permittedList, int userIdToCheck) { 7104 long id = mInjector.binderClearCallingIdentity(); 7105 try { 7106 // If we have an enabled packages list for a managed profile the packages 7107 // we should check are installed for the parent user. 7108 UserInfo user = getUserInfo(userIdToCheck); 7109 if (user.isManagedProfile()) { 7110 userIdToCheck = user.profileGroupId; 7111 } 7112 7113 for (String enabledPackage : enabledPackages) { 7114 boolean systemService = false; 7115 try { 7116 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 7117 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 7118 userIdToCheck); 7119 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7120 } catch (RemoteException e) { 7121 Log.i(LOG_TAG, "Can't talk to package managed", e); 7122 } 7123 if (!systemService && !permittedList.contains(enabledPackage)) { 7124 return false; 7125 } 7126 } 7127 } finally { 7128 mInjector.binderRestoreCallingIdentity(id); 7129 } 7130 return true; 7131 } 7132 7133 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 7134 // Not using AccessibilityManager.getInstance because that guesses 7135 // at the user you require based on callingUid and caches for a given 7136 // process. 7137 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 7138 IAccessibilityManager service = iBinder == null 7139 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 7140 return new AccessibilityManager(mContext, service, userId); 7141 } 7142 7143 @Override 7144 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 7145 if (!mHasFeature) { 7146 return false; 7147 } 7148 Preconditions.checkNotNull(who, "ComponentName is null"); 7149 7150 if (packageList != null) { 7151 int userId = UserHandle.getCallingUserId(); 7152 List<AccessibilityServiceInfo> enabledServices = null; 7153 long id = mInjector.binderClearCallingIdentity(); 7154 try { 7155 UserInfo user = getUserInfo(userId); 7156 if (user.isManagedProfile()) { 7157 userId = user.profileGroupId; 7158 } 7159 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 7160 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 7161 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 7162 } finally { 7163 mInjector.binderRestoreCallingIdentity(id); 7164 } 7165 7166 if (enabledServices != null) { 7167 List<String> enabledPackages = new ArrayList<String>(); 7168 for (AccessibilityServiceInfo service : enabledServices) { 7169 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 7170 } 7171 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 7172 userId)) { 7173 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 7174 + "because it contains already enabled accesibility services."); 7175 return false; 7176 } 7177 } 7178 } 7179 7180 synchronized (this) { 7181 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7182 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7183 admin.permittedAccessiblityServices = packageList; 7184 saveSettingsLocked(UserHandle.getCallingUserId()); 7185 } 7186 return true; 7187 } 7188 7189 @Override 7190 public List getPermittedAccessibilityServices(ComponentName who) { 7191 if (!mHasFeature) { 7192 return null; 7193 } 7194 Preconditions.checkNotNull(who, "ComponentName is null"); 7195 7196 synchronized (this) { 7197 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7198 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7199 return admin.permittedAccessiblityServices; 7200 } 7201 } 7202 7203 @Override 7204 public List getPermittedAccessibilityServicesForUser(int userId) { 7205 if (!mHasFeature) { 7206 return null; 7207 } 7208 synchronized (this) { 7209 List<String> result = null; 7210 // If we have multiple profiles we return the intersection of the 7211 // permitted lists. This can happen in cases where we have a device 7212 // and profile owner. 7213 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 7214 for (int profileId : profileIds) { 7215 // Just loop though all admins, only device or profiles 7216 // owners can have permitted lists set. 7217 DevicePolicyData policy = getUserDataUnchecked(profileId); 7218 final int N = policy.mAdminList.size(); 7219 for (int j = 0; j < N; j++) { 7220 ActiveAdmin admin = policy.mAdminList.get(j); 7221 List<String> fromAdmin = admin.permittedAccessiblityServices; 7222 if (fromAdmin != null) { 7223 if (result == null) { 7224 result = new ArrayList<>(fromAdmin); 7225 } else { 7226 result.retainAll(fromAdmin); 7227 } 7228 } 7229 } 7230 } 7231 7232 // If we have a permitted list add all system accessibility services. 7233 if (result != null) { 7234 long id = mInjector.binderClearCallingIdentity(); 7235 try { 7236 UserInfo user = getUserInfo(userId); 7237 if (user.isManagedProfile()) { 7238 userId = user.profileGroupId; 7239 } 7240 AccessibilityManager accessibilityManager = 7241 getAccessibilityManagerForUser(userId); 7242 List<AccessibilityServiceInfo> installedServices = 7243 accessibilityManager.getInstalledAccessibilityServiceList(); 7244 7245 if (installedServices != null) { 7246 for (AccessibilityServiceInfo service : installedServices) { 7247 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 7248 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 7249 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7250 result.add(serviceInfo.packageName); 7251 } 7252 } 7253 } 7254 } finally { 7255 mInjector.binderRestoreCallingIdentity(id); 7256 } 7257 } 7258 7259 return result; 7260 } 7261 } 7262 7263 @Override 7264 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 7265 int userHandle) { 7266 if (!mHasFeature) { 7267 return true; 7268 } 7269 Preconditions.checkNotNull(who, "ComponentName is null"); 7270 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 7271 if (!isCallerWithSystemUid()){ 7272 throw new SecurityException( 7273 "Only the system can query if an accessibility service is disabled by admin"); 7274 } 7275 synchronized (this) { 7276 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7277 if (admin == null) { 7278 return false; 7279 } 7280 if (admin.permittedAccessiblityServices == null) { 7281 return true; 7282 } 7283 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName), 7284 admin.permittedAccessiblityServices, userHandle); 7285 } 7286 } 7287 7288 private boolean checkCallerIsCurrentUserOrProfile() { 7289 int callingUserId = UserHandle.getCallingUserId(); 7290 long token = mInjector.binderClearCallingIdentity(); 7291 try { 7292 UserInfo currentUser; 7293 UserInfo callingUser = getUserInfo(callingUserId); 7294 try { 7295 currentUser = mInjector.getIActivityManager().getCurrentUser(); 7296 } catch (RemoteException e) { 7297 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 7298 return false; 7299 } 7300 7301 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 7302 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 7303 + "of a user that isn't the foreground user."); 7304 return false; 7305 } 7306 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 7307 Slog.e(LOG_TAG, "Cannot set permitted input methods " 7308 + "of a user that isn't the foreground user."); 7309 return false; 7310 } 7311 } finally { 7312 mInjector.binderRestoreCallingIdentity(token); 7313 } 7314 return true; 7315 } 7316 7317 @Override 7318 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 7319 if (!mHasFeature) { 7320 return false; 7321 } 7322 Preconditions.checkNotNull(who, "ComponentName is null"); 7323 7324 // TODO When InputMethodManager supports per user calls remove 7325 // this restriction. 7326 if (!checkCallerIsCurrentUserOrProfile()) { 7327 return false; 7328 } 7329 7330 if (packageList != null) { 7331 // InputMethodManager fetches input methods for current user. 7332 // So this can only be set when calling user is the current user 7333 // or parent is current user in case of managed profiles. 7334 InputMethodManager inputMethodManager = 7335 mContext.getSystemService(InputMethodManager.class); 7336 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList(); 7337 7338 if (enabledImes != null) { 7339 List<String> enabledPackages = new ArrayList<String>(); 7340 for (InputMethodInfo ime : enabledImes) { 7341 enabledPackages.add(ime.getPackageName()); 7342 } 7343 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 7344 mInjector.binderGetCallingUserHandle().getIdentifier())) { 7345 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 7346 + "because it contains already enabled input method."); 7347 return false; 7348 } 7349 } 7350 } 7351 7352 synchronized (this) { 7353 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7354 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7355 admin.permittedInputMethods = packageList; 7356 saveSettingsLocked(UserHandle.getCallingUserId()); 7357 } 7358 return true; 7359 } 7360 7361 @Override 7362 public List getPermittedInputMethods(ComponentName who) { 7363 if (!mHasFeature) { 7364 return null; 7365 } 7366 Preconditions.checkNotNull(who, "ComponentName is null"); 7367 7368 synchronized (this) { 7369 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7370 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7371 return admin.permittedInputMethods; 7372 } 7373 } 7374 7375 @Override 7376 public List getPermittedInputMethodsForCurrentUser() { 7377 UserInfo currentUser; 7378 try { 7379 currentUser = mInjector.getIActivityManager().getCurrentUser(); 7380 } catch (RemoteException e) { 7381 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e); 7382 // Activity managed is dead, just allow all IMEs 7383 return null; 7384 } 7385 7386 int userId = currentUser.id; 7387 synchronized (this) { 7388 List<String> result = null; 7389 // If we have multiple profiles we return the intersection of the 7390 // permitted lists. This can happen in cases where we have a device 7391 // and profile owner. 7392 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 7393 for (int profileId : profileIds) { 7394 // Just loop though all admins, only device or profiles 7395 // owners can have permitted lists set. 7396 DevicePolicyData policy = getUserDataUnchecked(profileId); 7397 final int N = policy.mAdminList.size(); 7398 for (int j = 0; j < N; j++) { 7399 ActiveAdmin admin = policy.mAdminList.get(j); 7400 List<String> fromAdmin = admin.permittedInputMethods; 7401 if (fromAdmin != null) { 7402 if (result == null) { 7403 result = new ArrayList<String>(fromAdmin); 7404 } else { 7405 result.retainAll(fromAdmin); 7406 } 7407 } 7408 } 7409 } 7410 7411 // If we have a permitted list add all system input methods. 7412 if (result != null) { 7413 InputMethodManager inputMethodManager = 7414 mContext.getSystemService(InputMethodManager.class); 7415 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList(); 7416 long id = mInjector.binderClearCallingIdentity(); 7417 try { 7418 if (imes != null) { 7419 for (InputMethodInfo ime : imes) { 7420 ServiceInfo serviceInfo = ime.getServiceInfo(); 7421 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 7422 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7423 result.add(serviceInfo.packageName); 7424 } 7425 } 7426 } 7427 } finally { 7428 mInjector.binderRestoreCallingIdentity(id); 7429 } 7430 } 7431 return result; 7432 } 7433 } 7434 7435 @Override 7436 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 7437 int userHandle) { 7438 if (!mHasFeature) { 7439 return true; 7440 } 7441 Preconditions.checkNotNull(who, "ComponentName is null"); 7442 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 7443 if (!isCallerWithSystemUid()) { 7444 throw new SecurityException( 7445 "Only the system can query if an input method is disabled by admin"); 7446 } 7447 synchronized (this) { 7448 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7449 if (admin == null) { 7450 return false; 7451 } 7452 if (admin.permittedInputMethods == null) { 7453 return true; 7454 } 7455 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName), 7456 admin.permittedInputMethods, userHandle); 7457 } 7458 } 7459 7460 private void sendAdminEnabledBroadcastLocked(int userHandle) { 7461 DevicePolicyData policyData = getUserData(userHandle); 7462 if (policyData.mAdminBroadcastPending) { 7463 // Send the initialization data to profile owner and delete the data 7464 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 7465 if (admin != null) { 7466 PersistableBundle initBundle = policyData.mInitBundle; 7467 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 7468 initBundle == null ? null : new Bundle(initBundle), null); 7469 } 7470 policyData.mInitBundle = null; 7471 policyData.mAdminBroadcastPending = false; 7472 saveSettingsLocked(userHandle); 7473 } 7474 } 7475 7476 @Override 7477 public UserHandle createAndManageUser(ComponentName admin, String name, 7478 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 7479 Preconditions.checkNotNull(admin, "admin is null"); 7480 Preconditions.checkNotNull(profileOwner, "profileOwner is null"); 7481 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 7482 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 7483 + admin + " are not in the same package"); 7484 } 7485 // Only allow the system user to use this method 7486 if (!mInjector.binderGetCallingUserHandle().isSystem()) { 7487 throw new SecurityException("createAndManageUser was called from non-system user"); 7488 } 7489 if (!mInjector.userManagerIsSplitSystemUser() 7490 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) { 7491 throw new IllegalArgumentException( 7492 "Ephemeral users are only supported on systems with a split system user."); 7493 } 7494 // Create user. 7495 UserHandle user = null; 7496 synchronized (this) { 7497 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7498 7499 final long id = mInjector.binderClearCallingIdentity(); 7500 try { 7501 int userInfoFlags = 0; 7502 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) { 7503 userInfoFlags |= UserInfo.FLAG_EPHEMERAL; 7504 } 7505 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 7506 userInfoFlags); 7507 if (userInfo != null) { 7508 user = userInfo.getUserHandle(); 7509 } 7510 } finally { 7511 mInjector.binderRestoreCallingIdentity(id); 7512 } 7513 } 7514 if (user == null) { 7515 return null; 7516 } 7517 // Set admin. 7518 final long id = mInjector.binderClearCallingIdentity(); 7519 try { 7520 final String adminPkg = admin.getPackageName(); 7521 7522 final int userHandle = user.getIdentifier(); 7523 try { 7524 // Install the profile owner if not present. 7525 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) { 7526 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle); 7527 } 7528 } catch (RemoteException e) { 7529 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, " 7530 + "removing created user", e); 7531 mUserManager.removeUser(user.getIdentifier()); 7532 return null; 7533 } 7534 7535 setActiveAdmin(profileOwner, true, userHandle); 7536 // User is not started yet, the broadcast by setActiveAdmin will not be received. 7537 // So we store adminExtras for broadcasting when the user starts for first time. 7538 synchronized(this) { 7539 DevicePolicyData policyData = getUserData(userHandle); 7540 policyData.mInitBundle = adminExtras; 7541 policyData.mAdminBroadcastPending = true; 7542 saveSettingsLocked(userHandle); 7543 } 7544 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier()); 7545 setProfileOwner(profileOwner, ownerName, userHandle); 7546 7547 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 7548 Settings.Secure.putIntForUser(mContext.getContentResolver(), 7549 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 7550 } 7551 7552 return user; 7553 } finally { 7554 mInjector.binderRestoreCallingIdentity(id); 7555 } 7556 } 7557 7558 @Override 7559 public boolean removeUser(ComponentName who, UserHandle userHandle) { 7560 Preconditions.checkNotNull(who, "ComponentName is null"); 7561 synchronized (this) { 7562 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7563 } 7564 7565 final int callingUserId = mInjector.userHandleGetCallingUserId(); 7566 final long id = mInjector.binderClearCallingIdentity(); 7567 try { 7568 String restriction = isManagedProfile(userHandle.getIdentifier()) 7569 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 7570 : UserManager.DISALLOW_REMOVE_USER; 7571 if (isAdminAffectedByRestriction(who, restriction, callingUserId)) { 7572 Log.w(LOG_TAG, "The device owner cannot remove a user because " 7573 + restriction + " is enabled, and was not set by the device owner"); 7574 return false; 7575 } 7576 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 7577 } finally { 7578 mInjector.binderRestoreCallingIdentity(id); 7579 } 7580 } 7581 7582 private boolean isAdminAffectedByRestriction( 7583 ComponentName admin, String userRestriction, int userId) { 7584 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 7585 case UserManager.RESTRICTION_NOT_SET: 7586 return false; 7587 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 7588 return !isDeviceOwner(admin, userId); 7589 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 7590 return !isProfileOwner(admin, userId); 7591 default: 7592 return true; 7593 } 7594 } 7595 7596 @Override 7597 public boolean switchUser(ComponentName who, UserHandle userHandle) { 7598 Preconditions.checkNotNull(who, "ComponentName is null"); 7599 synchronized (this) { 7600 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7601 7602 long id = mInjector.binderClearCallingIdentity(); 7603 try { 7604 int userId = UserHandle.USER_SYSTEM; 7605 if (userHandle != null) { 7606 userId = userHandle.getIdentifier(); 7607 } 7608 return mInjector.getIActivityManager().switchUser(userId); 7609 } catch (RemoteException e) { 7610 Log.e(LOG_TAG, "Couldn't switch user", e); 7611 return false; 7612 } finally { 7613 mInjector.binderRestoreCallingIdentity(id); 7614 } 7615 } 7616 } 7617 7618 @Override 7619 public Bundle getApplicationRestrictions(ComponentName who, String packageName) { 7620 enforceCanManageApplicationRestrictions(who); 7621 7622 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 7623 final long id = mInjector.binderClearCallingIdentity(); 7624 try { 7625 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 7626 // if no restrictions were saved, mUserManager.getApplicationRestrictions 7627 // returns null, but DPM method should return an empty Bundle as per JavaDoc 7628 return bundle != null ? bundle : Bundle.EMPTY; 7629 } finally { 7630 mInjector.binderRestoreCallingIdentity(id); 7631 } 7632 } 7633 7634 @Override 7635 public String[] setPackagesSuspended(ComponentName who, String[] packageNames, 7636 boolean suspended) { 7637 Preconditions.checkNotNull(who, "ComponentName is null"); 7638 int callingUserId = UserHandle.getCallingUserId(); 7639 synchronized (this) { 7640 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7641 7642 long id = mInjector.binderClearCallingIdentity(); 7643 try { 7644 return mIPackageManager.setPackagesSuspendedAsUser( 7645 packageNames, suspended, callingUserId); 7646 } catch (RemoteException re) { 7647 // Shouldn't happen. 7648 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 7649 } finally { 7650 mInjector.binderRestoreCallingIdentity(id); 7651 } 7652 return packageNames; 7653 } 7654 } 7655 7656 @Override 7657 public boolean isPackageSuspended(ComponentName who, String packageName) { 7658 Preconditions.checkNotNull(who, "ComponentName is null"); 7659 int callingUserId = UserHandle.getCallingUserId(); 7660 synchronized (this) { 7661 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7662 7663 long id = mInjector.binderClearCallingIdentity(); 7664 try { 7665 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId); 7666 } catch (RemoteException re) { 7667 // Shouldn't happen. 7668 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 7669 } finally { 7670 mInjector.binderRestoreCallingIdentity(id); 7671 } 7672 return false; 7673 } 7674 } 7675 7676 @Override 7677 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) { 7678 Preconditions.checkNotNull(who, "ComponentName is null"); 7679 if (!UserRestrictionsUtils.isValidRestriction(key)) { 7680 return; 7681 } 7682 7683 final int userHandle = mInjector.userHandleGetCallingUserId(); 7684 synchronized (this) { 7685 ActiveAdmin activeAdmin = 7686 getActiveAdminForCallerLocked(who, 7687 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7688 final boolean isDeviceOwner = isDeviceOwner(who, userHandle); 7689 if (isDeviceOwner) { 7690 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 7691 throw new SecurityException("Device owner cannot set user restriction " + key); 7692 } 7693 } else { // profile owner 7694 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) { 7695 throw new SecurityException("Profile owner cannot set user restriction " + key); 7696 } 7697 } 7698 7699 // Save the restriction to ActiveAdmin. 7700 activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner); 7701 saveUserRestrictionsLocked(userHandle); 7702 } 7703 } 7704 7705 private void saveUserRestrictionsLocked(int userId) { 7706 saveSettingsLocked(userId); 7707 pushUserRestrictions(userId); 7708 sendChangedNotification(userId); 7709 } 7710 7711 private void pushUserRestrictions(int userId) { 7712 synchronized (this) { 7713 final Bundle global; 7714 final Bundle local = new Bundle(); 7715 if (mOwners.isDeviceOwnerUserId(userId)) { 7716 global = new Bundle(); 7717 7718 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7719 if (deviceOwner == null) { 7720 return; // Shouldn't happen. 7721 } 7722 7723 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions, 7724 global, local); 7725 // DO can disable camera globally. 7726 if (deviceOwner.disableCamera) { 7727 global.putBoolean(UserManager.DISALLOW_CAMERA, true); 7728 } 7729 } else { 7730 global = null; 7731 7732 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 7733 if (profileOwner != null) { 7734 UserRestrictionsUtils.merge(local, profileOwner.userRestrictions); 7735 } 7736 } 7737 // Also merge in *local* camera restriction. 7738 if (getCameraDisabled(/* who= */ null, 7739 userId, /* mergeDeviceOwnerRestriction= */ false)) { 7740 local.putBoolean(UserManager.DISALLOW_CAMERA, true); 7741 } 7742 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global); 7743 } 7744 } 7745 7746 @Override 7747 public Bundle getUserRestrictions(ComponentName who) { 7748 if (!mHasFeature) { 7749 return null; 7750 } 7751 Preconditions.checkNotNull(who, "ComponentName is null"); 7752 synchronized (this) { 7753 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who, 7754 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7755 return activeAdmin.userRestrictions; 7756 } 7757 } 7758 7759 @Override 7760 public boolean setApplicationHidden(ComponentName who, String packageName, 7761 boolean hidden) { 7762 Preconditions.checkNotNull(who, "ComponentName is null"); 7763 int callingUserId = UserHandle.getCallingUserId(); 7764 synchronized (this) { 7765 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7766 7767 long id = mInjector.binderClearCallingIdentity(); 7768 try { 7769 return mIPackageManager.setApplicationHiddenSettingAsUser( 7770 packageName, hidden, callingUserId); 7771 } catch (RemoteException re) { 7772 // shouldn't happen 7773 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 7774 } finally { 7775 mInjector.binderRestoreCallingIdentity(id); 7776 } 7777 return false; 7778 } 7779 } 7780 7781 @Override 7782 public boolean isApplicationHidden(ComponentName who, String packageName) { 7783 Preconditions.checkNotNull(who, "ComponentName is null"); 7784 int callingUserId = UserHandle.getCallingUserId(); 7785 synchronized (this) { 7786 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7787 7788 long id = mInjector.binderClearCallingIdentity(); 7789 try { 7790 return mIPackageManager.getApplicationHiddenSettingAsUser( 7791 packageName, callingUserId); 7792 } catch (RemoteException re) { 7793 // shouldn't happen 7794 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 7795 } finally { 7796 mInjector.binderRestoreCallingIdentity(id); 7797 } 7798 return false; 7799 } 7800 } 7801 7802 @Override 7803 public void enableSystemApp(ComponentName who, String packageName) { 7804 Preconditions.checkNotNull(who, "ComponentName is null"); 7805 synchronized (this) { 7806 // This API can only be called by an active device admin, 7807 // so try to retrieve it to check that the caller is one. 7808 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7809 7810 int userId = UserHandle.getCallingUserId(); 7811 long id = mInjector.binderClearCallingIdentity(); 7812 7813 try { 7814 if (VERBOSE_LOG) { 7815 Slog.v(LOG_TAG, "installing " + packageName + " for " 7816 + userId); 7817 } 7818 7819 int parentUserId = getProfileParentId(userId); 7820 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) { 7821 throw new IllegalArgumentException("Only system apps can be enabled this way."); 7822 } 7823 7824 // Install the app. 7825 mIPackageManager.installExistingPackageAsUser(packageName, userId); 7826 7827 } catch (RemoteException re) { 7828 // shouldn't happen 7829 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 7830 } finally { 7831 mInjector.binderRestoreCallingIdentity(id); 7832 } 7833 } 7834 } 7835 7836 @Override 7837 public int enableSystemAppWithIntent(ComponentName who, Intent intent) { 7838 Preconditions.checkNotNull(who, "ComponentName is null"); 7839 synchronized (this) { 7840 // This API can only be called by an active device admin, 7841 // so try to retrieve it to check that the caller is one. 7842 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7843 7844 int userId = UserHandle.getCallingUserId(); 7845 long id = mInjector.binderClearCallingIdentity(); 7846 7847 try { 7848 int parentUserId = getProfileParentId(userId); 7849 List<ResolveInfo> activitiesToEnable = mIPackageManager 7850 .queryIntentActivities(intent, 7851 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 7852 PackageManager.MATCH_DIRECT_BOOT_AWARE 7853 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 7854 parentUserId) 7855 .getList(); 7856 7857 if (VERBOSE_LOG) { 7858 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 7859 } 7860 int numberOfAppsInstalled = 0; 7861 if (activitiesToEnable != null) { 7862 for (ResolveInfo info : activitiesToEnable) { 7863 if (info.activityInfo != null) { 7864 String packageName = info.activityInfo.packageName; 7865 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 7866 numberOfAppsInstalled++; 7867 mIPackageManager.installExistingPackageAsUser(packageName, userId); 7868 } else { 7869 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 7870 + " system app"); 7871 } 7872 } 7873 } 7874 } 7875 return numberOfAppsInstalled; 7876 } catch (RemoteException e) { 7877 // shouldn't happen 7878 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 7879 return 0; 7880 } finally { 7881 mInjector.binderRestoreCallingIdentity(id); 7882 } 7883 } 7884 } 7885 7886 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 7887 throws RemoteException { 7888 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 7889 userId); 7890 if (appInfo == null) { 7891 throw new IllegalArgumentException("The application " + packageName + 7892 " is not present on this device"); 7893 } 7894 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7895 } 7896 7897 @Override 7898 public void setAccountManagementDisabled(ComponentName who, String accountType, 7899 boolean disabled) { 7900 if (!mHasFeature) { 7901 return; 7902 } 7903 Preconditions.checkNotNull(who, "ComponentName is null"); 7904 synchronized (this) { 7905 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 7906 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7907 if (disabled) { 7908 ap.accountTypesWithManagementDisabled.add(accountType); 7909 } else { 7910 ap.accountTypesWithManagementDisabled.remove(accountType); 7911 } 7912 saveSettingsLocked(UserHandle.getCallingUserId()); 7913 } 7914 } 7915 7916 @Override 7917 public String[] getAccountTypesWithManagementDisabled() { 7918 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 7919 } 7920 7921 @Override 7922 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 7923 enforceFullCrossUsersPermission(userId); 7924 if (!mHasFeature) { 7925 return null; 7926 } 7927 synchronized (this) { 7928 DevicePolicyData policy = getUserData(userId); 7929 final int N = policy.mAdminList.size(); 7930 ArraySet<String> resultSet = new ArraySet<>(); 7931 for (int i = 0; i < N; i++) { 7932 ActiveAdmin admin = policy.mAdminList.get(i); 7933 resultSet.addAll(admin.accountTypesWithManagementDisabled); 7934 } 7935 return resultSet.toArray(new String[resultSet.size()]); 7936 } 7937 } 7938 7939 @Override 7940 public void setUninstallBlocked(ComponentName who, String packageName, 7941 boolean uninstallBlocked) { 7942 Preconditions.checkNotNull(who, "ComponentName is null"); 7943 final int userId = UserHandle.getCallingUserId(); 7944 synchronized (this) { 7945 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7946 7947 long id = mInjector.binderClearCallingIdentity(); 7948 try { 7949 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 7950 } catch (RemoteException re) { 7951 // Shouldn't happen. 7952 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 7953 } finally { 7954 mInjector.binderRestoreCallingIdentity(id); 7955 } 7956 } 7957 } 7958 7959 @Override 7960 public boolean isUninstallBlocked(ComponentName who, String packageName) { 7961 // This function should return true if and only if the package is blocked by 7962 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 7963 // when the package is a system app, or when it is an active device admin. 7964 final int userId = UserHandle.getCallingUserId(); 7965 7966 synchronized (this) { 7967 if (who != null) { 7968 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7969 } 7970 7971 long id = mInjector.binderClearCallingIdentity(); 7972 try { 7973 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 7974 } catch (RemoteException re) { 7975 // Shouldn't happen. 7976 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 7977 } finally { 7978 mInjector.binderRestoreCallingIdentity(id); 7979 } 7980 } 7981 return false; 7982 } 7983 7984 @Override 7985 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 7986 if (!mHasFeature) { 7987 return; 7988 } 7989 Preconditions.checkNotNull(who, "ComponentName is null"); 7990 synchronized (this) { 7991 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7992 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7993 if (admin.disableCallerId != disabled) { 7994 admin.disableCallerId = disabled; 7995 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 7996 } 7997 } 7998 } 7999 8000 @Override 8001 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 8002 if (!mHasFeature) { 8003 return false; 8004 } 8005 Preconditions.checkNotNull(who, "ComponentName is null"); 8006 synchronized (this) { 8007 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8008 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8009 return admin.disableCallerId; 8010 } 8011 } 8012 8013 @Override 8014 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 8015 enforceCrossUsersPermission(userId); 8016 synchronized (this) { 8017 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8018 return (admin != null) ? admin.disableCallerId : false; 8019 } 8020 } 8021 8022 @Override 8023 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 8024 if (!mHasFeature) { 8025 return; 8026 } 8027 Preconditions.checkNotNull(who, "ComponentName is null"); 8028 synchronized (this) { 8029 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8030 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8031 if (admin.disableContactsSearch != disabled) { 8032 admin.disableContactsSearch = disabled; 8033 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 8034 } 8035 } 8036 } 8037 8038 @Override 8039 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 8040 if (!mHasFeature) { 8041 return false; 8042 } 8043 Preconditions.checkNotNull(who, "ComponentName is null"); 8044 synchronized (this) { 8045 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8046 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8047 return admin.disableContactsSearch; 8048 } 8049 } 8050 8051 @Override 8052 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 8053 enforceCrossUsersPermission(userId); 8054 synchronized (this) { 8055 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8056 return (admin != null) ? admin.disableContactsSearch : false; 8057 } 8058 } 8059 8060 @Override 8061 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 8062 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 8063 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 8064 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 8065 final int callingUserId = UserHandle.getCallingUserId(); 8066 8067 final long ident = mInjector.binderClearCallingIdentity(); 8068 try { 8069 synchronized (this) { 8070 final int managedUserId = getManagedUserId(callingUserId); 8071 if (managedUserId < 0) { 8072 return; 8073 } 8074 if (isCrossProfileQuickContactDisabled(managedUserId)) { 8075 if (VERBOSE_LOG) { 8076 Log.v(LOG_TAG, 8077 "Cross-profile contacts access disabled for user " + managedUserId); 8078 } 8079 return; 8080 } 8081 ContactsInternal.startQuickContactWithErrorToastForUser( 8082 mContext, intent, new UserHandle(managedUserId)); 8083 } 8084 } finally { 8085 mInjector.binderRestoreCallingIdentity(ident); 8086 } 8087 } 8088 8089 /** 8090 * @return true if cross-profile QuickContact is disabled 8091 */ 8092 private boolean isCrossProfileQuickContactDisabled(int userId) { 8093 return getCrossProfileCallerIdDisabledForUser(userId) 8094 && getCrossProfileContactsSearchDisabledForUser(userId); 8095 } 8096 8097 /** 8098 * @return the user ID of the managed user that is linked to the current user, if any. 8099 * Otherwise -1. 8100 */ 8101 public int getManagedUserId(int callingUserId) { 8102 if (VERBOSE_LOG) { 8103 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 8104 } 8105 8106 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 8107 if (ui.id == callingUserId || !ui.isManagedProfile()) { 8108 continue; // Caller user self, or not a managed profile. Skip. 8109 } 8110 if (VERBOSE_LOG) { 8111 Log.v(LOG_TAG, "Managed user=" + ui.id); 8112 } 8113 return ui.id; 8114 } 8115 if (VERBOSE_LOG) { 8116 Log.v(LOG_TAG, "Managed user not found."); 8117 } 8118 return -1; 8119 } 8120 8121 @Override 8122 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 8123 if (!mHasFeature) { 8124 return; 8125 } 8126 Preconditions.checkNotNull(who, "ComponentName is null"); 8127 synchronized (this) { 8128 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8129 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8130 if (admin.disableBluetoothContactSharing != disabled) { 8131 admin.disableBluetoothContactSharing = disabled; 8132 saveSettingsLocked(UserHandle.getCallingUserId()); 8133 } 8134 } 8135 } 8136 8137 @Override 8138 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 8139 if (!mHasFeature) { 8140 return false; 8141 } 8142 Preconditions.checkNotNull(who, "ComponentName is null"); 8143 synchronized (this) { 8144 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8145 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8146 return admin.disableBluetoothContactSharing; 8147 } 8148 } 8149 8150 @Override 8151 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 8152 // TODO: Should there be a check to make sure this relationship is 8153 // within a profile group? 8154 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 8155 synchronized (this) { 8156 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8157 return (admin != null) ? admin.disableBluetoothContactSharing : false; 8158 } 8159 } 8160 8161 /** 8162 * Sets which packages may enter lock task mode. 8163 * 8164 * <p>This function can only be called by the device owner or alternatively by the profile owner 8165 * in case the user is affiliated. 8166 * 8167 * @param packages The list of packages allowed to enter lock task mode. 8168 */ 8169 @Override 8170 public void setLockTaskPackages(ComponentName who, String[] packages) 8171 throws SecurityException { 8172 Preconditions.checkNotNull(who, "ComponentName is null"); 8173 8174 synchronized (this) { 8175 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8176 final int userHandle = mInjector.userHandleGetCallingUserId(); 8177 if (isUserAffiliatedWithDevice(userHandle)) { 8178 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 8179 } else { 8180 throw new SecurityException("Admin " + who + 8181 " is neither the device owner or affiliated user's profile owner."); 8182 } 8183 } 8184 } 8185 8186 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 8187 DevicePolicyData policy = getUserData(userHandle); 8188 policy.mLockTaskPackages = packages; 8189 8190 // Store the settings persistently. 8191 saveSettingsLocked(userHandle); 8192 updateLockTaskPackagesLocked(packages, userHandle); 8193 } 8194 8195 /** 8196 * This function returns the list of components allowed to start the task lock mode. 8197 */ 8198 @Override 8199 public String[] getLockTaskPackages(ComponentName who) { 8200 Preconditions.checkNotNull(who, "ComponentName is null"); 8201 synchronized (this) { 8202 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8203 int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 8204 final List<String> packages = getLockTaskPackagesLocked(userHandle); 8205 return packages.toArray(new String[packages.size()]); 8206 } 8207 } 8208 8209 private List<String> getLockTaskPackagesLocked(int userHandle) { 8210 final DevicePolicyData policy = getUserData(userHandle); 8211 return policy.mLockTaskPackages; 8212 } 8213 8214 /** 8215 * This function lets the caller know whether the given package is allowed to start the 8216 * lock task mode. 8217 * @param pkg The package to check 8218 */ 8219 @Override 8220 public boolean isLockTaskPermitted(String pkg) { 8221 // Get current user's devicepolicy 8222 int uid = mInjector.binderGetCallingUid(); 8223 int userHandle = UserHandle.getUserId(uid); 8224 DevicePolicyData policy = getUserData(userHandle); 8225 synchronized (this) { 8226 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) { 8227 String lockTaskPackage = policy.mLockTaskPackages.get(i); 8228 8229 // If the given package equals one of the packages stored our list, 8230 // we allow this package to start lock task mode. 8231 if (lockTaskPackage.equals(pkg)) { 8232 return true; 8233 } 8234 } 8235 } 8236 return false; 8237 } 8238 8239 @Override 8240 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 8241 if (!isCallerWithSystemUid()) { 8242 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 8243 } 8244 synchronized (this) { 8245 final DevicePolicyData policy = getUserData(userHandle); 8246 Bundle adminExtras = new Bundle(); 8247 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 8248 for (ActiveAdmin admin : policy.mAdminList) { 8249 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 8250 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 8251 if (ownsDevice || ownsProfile) { 8252 if (isEnabled) { 8253 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 8254 adminExtras, null); 8255 } else { 8256 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 8257 } 8258 } 8259 } 8260 } 8261 } 8262 8263 @Override 8264 public void setGlobalSetting(ComponentName who, String setting, String value) { 8265 Preconditions.checkNotNull(who, "ComponentName is null"); 8266 8267 synchronized (this) { 8268 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8269 8270 // Some settings are no supported any more. However we do not want to throw a 8271 // SecurityException to avoid breaking apps. 8272 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 8273 Log.i(LOG_TAG, "Global setting no longer supported: " + setting); 8274 return; 8275 } 8276 8277 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) { 8278 throw new SecurityException(String.format( 8279 "Permission denial: device owners cannot update %1$s", setting)); 8280 } 8281 8282 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 8283 // ignore if it contradicts an existing policy 8284 long timeMs = getMaximumTimeToLock( 8285 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 8286 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) { 8287 return; 8288 } 8289 } 8290 8291 long id = mInjector.binderClearCallingIdentity(); 8292 try { 8293 mInjector.settingsGlobalPutString(setting, value); 8294 } finally { 8295 mInjector.binderRestoreCallingIdentity(id); 8296 } 8297 } 8298 } 8299 8300 @Override 8301 public void setSecureSetting(ComponentName who, String setting, String value) { 8302 Preconditions.checkNotNull(who, "ComponentName is null"); 8303 int callingUserId = mInjector.userHandleGetCallingUserId(); 8304 8305 synchronized (this) { 8306 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8307 8308 if (isDeviceOwner(who, callingUserId)) { 8309 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) { 8310 throw new SecurityException(String.format( 8311 "Permission denial: Device owners cannot update %1$s", setting)); 8312 } 8313 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) { 8314 throw new SecurityException(String.format( 8315 "Permission denial: Profile owners cannot update %1$s", setting)); 8316 } 8317 8318 long id = mInjector.binderClearCallingIdentity(); 8319 try { 8320 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 8321 } finally { 8322 mInjector.binderRestoreCallingIdentity(id); 8323 } 8324 } 8325 } 8326 8327 @Override 8328 public void setMasterVolumeMuted(ComponentName who, boolean on) { 8329 Preconditions.checkNotNull(who, "ComponentName is null"); 8330 synchronized (this) { 8331 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8332 setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on); 8333 } 8334 } 8335 8336 @Override 8337 public boolean isMasterVolumeMuted(ComponentName who) { 8338 Preconditions.checkNotNull(who, "ComponentName is null"); 8339 synchronized (this) { 8340 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8341 8342 AudioManager audioManager = 8343 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 8344 return audioManager.isMasterMute(); 8345 } 8346 } 8347 8348 @Override 8349 public void setUserIcon(ComponentName who, Bitmap icon) { 8350 synchronized (this) { 8351 Preconditions.checkNotNull(who, "ComponentName is null"); 8352 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8353 8354 int userId = UserHandle.getCallingUserId(); 8355 long id = mInjector.binderClearCallingIdentity(); 8356 try { 8357 mUserManagerInternal.setUserIcon(userId, icon); 8358 } finally { 8359 mInjector.binderRestoreCallingIdentity(id); 8360 } 8361 } 8362 } 8363 8364 @Override 8365 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 8366 Preconditions.checkNotNull(who, "ComponentName is null"); 8367 synchronized (this) { 8368 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8369 } 8370 final int userId = UserHandle.getCallingUserId(); 8371 8372 long ident = mInjector.binderClearCallingIdentity(); 8373 try { 8374 // disallow disabling the keyguard if a password is currently set 8375 if (disabled && mLockPatternUtils.isSecure(userId)) { 8376 return false; 8377 } 8378 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 8379 } finally { 8380 mInjector.binderRestoreCallingIdentity(ident); 8381 } 8382 return true; 8383 } 8384 8385 @Override 8386 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 8387 int userId = UserHandle.getCallingUserId(); 8388 synchronized (this) { 8389 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8390 DevicePolicyData policy = getUserData(userId); 8391 if (policy.mStatusBarDisabled != disabled) { 8392 if (!setStatusBarDisabledInternal(disabled, userId)) { 8393 return false; 8394 } 8395 policy.mStatusBarDisabled = disabled; 8396 saveSettingsLocked(userId); 8397 } 8398 } 8399 return true; 8400 } 8401 8402 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 8403 long ident = mInjector.binderClearCallingIdentity(); 8404 try { 8405 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 8406 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 8407 if (statusBarService != null) { 8408 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 8409 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 8410 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 8411 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 8412 return true; 8413 } 8414 } catch (RemoteException e) { 8415 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 8416 } finally { 8417 mInjector.binderRestoreCallingIdentity(ident); 8418 } 8419 return false; 8420 } 8421 8422 /** 8423 * We need to update the internal state of whether a user has completed setup or a 8424 * device has paired once. After that, we ignore any changes that reset the 8425 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 8426 * as we don't trust any apps that might try to reset them. 8427 * <p> 8428 * Unfortunately, we don't know which user's setup state was changed, so we write all of 8429 * them. 8430 */ 8431 void updateUserSetupCompleteAndPaired() { 8432 List<UserInfo> users = mUserManager.getUsers(true); 8433 final int N = users.size(); 8434 for (int i = 0; i < N; i++) { 8435 int userHandle = users.get(i).id; 8436 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 8437 userHandle) != 0) { 8438 DevicePolicyData policy = getUserData(userHandle); 8439 if (!policy.mUserSetupComplete) { 8440 policy.mUserSetupComplete = true; 8441 synchronized (this) { 8442 saveSettingsLocked(userHandle); 8443 } 8444 } 8445 } 8446 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 8447 userHandle) != 0) { 8448 DevicePolicyData policy = getUserData(userHandle); 8449 if (!policy.mPaired) { 8450 policy.mPaired = true; 8451 synchronized (this) { 8452 saveSettingsLocked(userHandle); 8453 } 8454 } 8455 } 8456 } 8457 } 8458 8459 private class SetupContentObserver extends ContentObserver { 8460 8461 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 8462 Settings.Secure.USER_SETUP_COMPLETE); 8463 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 8464 Settings.Global.DEVICE_PROVISIONED); 8465 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 8466 8467 public SetupContentObserver(Handler handler) { 8468 super(handler); 8469 } 8470 8471 void register() { 8472 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 8473 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 8474 if (mIsWatch) { 8475 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 8476 } 8477 } 8478 8479 @Override 8480 public void onChange(boolean selfChange, Uri uri) { 8481 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 8482 updateUserSetupCompleteAndPaired(); 8483 } else if (mDeviceProvisioned.equals(uri)) { 8484 synchronized (DevicePolicyManagerService.this) { 8485 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 8486 // is delayed until device is marked as provisioned. 8487 setDeviceOwnerSystemPropertyLocked(); 8488 } 8489 } 8490 } 8491 } 8492 8493 @VisibleForTesting 8494 final class LocalService extends DevicePolicyManagerInternal { 8495 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 8496 8497 @Override 8498 public List<String> getCrossProfileWidgetProviders(int profileId) { 8499 synchronized (DevicePolicyManagerService.this) { 8500 if (mOwners == null) { 8501 return Collections.emptyList(); 8502 } 8503 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 8504 if (ownerComponent == null) { 8505 return Collections.emptyList(); 8506 } 8507 8508 DevicePolicyData policy = getUserDataUnchecked(profileId); 8509 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 8510 8511 if (admin == null || admin.crossProfileWidgetProviders == null 8512 || admin.crossProfileWidgetProviders.isEmpty()) { 8513 return Collections.emptyList(); 8514 } 8515 8516 return admin.crossProfileWidgetProviders; 8517 } 8518 } 8519 8520 @Override 8521 public void addOnCrossProfileWidgetProvidersChangeListener( 8522 OnCrossProfileWidgetProvidersChangeListener listener) { 8523 synchronized (DevicePolicyManagerService.this) { 8524 if (mWidgetProviderListeners == null) { 8525 mWidgetProviderListeners = new ArrayList<>(); 8526 } 8527 if (!mWidgetProviderListeners.contains(listener)) { 8528 mWidgetProviderListeners.add(listener); 8529 } 8530 } 8531 } 8532 8533 @Override 8534 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 8535 synchronized(DevicePolicyManagerService.this) { 8536 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 8537 } 8538 } 8539 8540 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 8541 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 8542 synchronized (DevicePolicyManagerService.this) { 8543 listeners = new ArrayList<>(mWidgetProviderListeners); 8544 } 8545 final int listenerCount = listeners.size(); 8546 for (int i = 0; i < listenerCount; i++) { 8547 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 8548 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 8549 } 8550 } 8551 8552 @Override 8553 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 8554 // This method is called from AM with its lock held, so don't take the DPMS lock. 8555 // b/29242568 8556 8557 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 8558 if (profileOwner != null) { 8559 return createShowAdminSupportIntent(profileOwner, userId); 8560 } 8561 8562 final Pair<Integer, ComponentName> deviceOwner = 8563 mOwners.getDeviceOwnerUserIdAndComponent(); 8564 if (deviceOwner != null && deviceOwner.first == userId) { 8565 return createShowAdminSupportIntent(deviceOwner.second, userId); 8566 } 8567 8568 // We're not specifying the device admin because there isn't one. 8569 if (useDefaultIfNoAdmin) { 8570 return createShowAdminSupportIntent(null, userId); 8571 } 8572 return null; 8573 } 8574 8575 @Override 8576 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 8577 int source; 8578 long ident = mInjector.binderClearCallingIdentity(); 8579 try { 8580 source = mUserManager.getUserRestrictionSource(userRestriction, 8581 UserHandle.of(userId)); 8582 } finally { 8583 mInjector.binderRestoreCallingIdentity(ident); 8584 } 8585 if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) { 8586 /* 8587 * In this case, the user restriction is enforced by the system. 8588 * So we won't show an admin support intent, even if it is also 8589 * enforced by a profile/device owner. 8590 */ 8591 return null; 8592 } 8593 boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0; 8594 boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0; 8595 if (enforcedByDo && enforcedByPo) { 8596 // In this case, we'll show an admin support dialog that does not 8597 // specify the admin. 8598 return createShowAdminSupportIntent(null, userId); 8599 } else if (enforcedByPo) { 8600 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 8601 if (profileOwner != null) { 8602 return createShowAdminSupportIntent(profileOwner, userId); 8603 } 8604 // This could happen if another thread has changed the profile owner since we called 8605 // getUserRestrictionSource 8606 return null; 8607 } else if (enforcedByDo) { 8608 final Pair<Integer, ComponentName> deviceOwner 8609 = mOwners.getDeviceOwnerUserIdAndComponent(); 8610 if (deviceOwner != null) { 8611 return createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first); 8612 } 8613 // This could happen if another thread has changed the device owner since we called 8614 // getUserRestrictionSource 8615 return null; 8616 } 8617 return null; 8618 } 8619 8620 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) { 8621 // This method is called with AMS lock held, so don't take DPMS lock 8622 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 8623 intent.putExtra(Intent.EXTRA_USER_ID, userId); 8624 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin); 8625 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 8626 return intent; 8627 } 8628 } 8629 8630 /** 8631 * Returns true if specified admin is allowed to limit passwords and has a 8632 * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality} 8633 */ 8634 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 8635 if (admin.minimumPasswordMetrics.quality < minPasswordQuality) { 8636 return false; 8637 } 8638 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 8639 } 8640 8641 @Override 8642 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 8643 if (policy != null && !policy.isValid()) { 8644 throw new IllegalArgumentException("Invalid system update policy."); 8645 } 8646 synchronized (this) { 8647 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8648 if (policy == null) { 8649 mOwners.clearSystemUpdatePolicy(); 8650 } else { 8651 mOwners.setSystemUpdatePolicy(policy); 8652 } 8653 mOwners.writeDeviceOwner(); 8654 } 8655 mContext.sendBroadcastAsUser( 8656 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 8657 UserHandle.SYSTEM); 8658 } 8659 8660 @Override 8661 public SystemUpdatePolicy getSystemUpdatePolicy() { 8662 if (UserManager.isDeviceInDemoMode(mContext)) { 8663 // Pretending to have an automatic update policy when the device is in retail demo 8664 // mode. This will allow the device to download and install an ota without 8665 // any user interaction. 8666 return SystemUpdatePolicy.createAutomaticInstallPolicy(); 8667 } 8668 synchronized (this) { 8669 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 8670 if (policy != null && !policy.isValid()) { 8671 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 8672 return null; 8673 } 8674 return policy; 8675 } 8676 } 8677 8678 /** 8679 * Checks if the caller of the method is the device owner app. 8680 * 8681 * @param callerUid UID of the caller. 8682 * @return true if the caller is the device owner app 8683 */ 8684 @VisibleForTesting 8685 boolean isCallerDeviceOwner(int callerUid) { 8686 synchronized (this) { 8687 if (!mOwners.hasDeviceOwner()) { 8688 return false; 8689 } 8690 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 8691 return false; 8692 } 8693 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 8694 .getPackageName(); 8695 final String[] pkgs = mInjector.getPackageManager().getPackagesForUid(callerUid); 8696 8697 for (String pkg : pkgs) { 8698 if (deviceOwnerPackageName.equals(pkg)) { 8699 return true; 8700 } 8701 } 8702 } 8703 8704 return false; 8705 } 8706 8707 @Override 8708 public void notifyPendingSystemUpdate(long updateReceivedTime) { 8709 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 8710 "Only the system update service can broadcast update information"); 8711 8712 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 8713 Slog.w(LOG_TAG, "Only the system update service in the system user " + 8714 "can broadcast update information."); 8715 return; 8716 } 8717 Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE); 8718 intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 8719 updateReceivedTime); 8720 8721 synchronized (this) { 8722 final String deviceOwnerPackage = 8723 mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName() 8724 : null; 8725 if (deviceOwnerPackage == null) { 8726 return; 8727 } 8728 final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId()); 8729 8730 ActivityInfo[] receivers = null; 8731 try { 8732 receivers = mInjector.getPackageManager().getPackageInfo( 8733 deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers; 8734 } catch (NameNotFoundException e) { 8735 Log.e(LOG_TAG, "Cannot find device owner package", e); 8736 } 8737 if (receivers != null) { 8738 long ident = mInjector.binderClearCallingIdentity(); 8739 try { 8740 for (int i = 0; i < receivers.length; i++) { 8741 if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) { 8742 intent.setComponent(new ComponentName(deviceOwnerPackage, 8743 receivers[i].name)); 8744 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 8745 } 8746 } 8747 } finally { 8748 mInjector.binderRestoreCallingIdentity(ident); 8749 } 8750 } 8751 } 8752 } 8753 8754 @Override 8755 public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException { 8756 int userId = UserHandle.getCallingUserId(); 8757 synchronized (this) { 8758 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8759 DevicePolicyData userPolicy = getUserData(userId); 8760 if (userPolicy.mPermissionPolicy != policy) { 8761 userPolicy.mPermissionPolicy = policy; 8762 saveSettingsLocked(userId); 8763 } 8764 } 8765 } 8766 8767 @Override 8768 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 8769 int userId = UserHandle.getCallingUserId(); 8770 synchronized (this) { 8771 DevicePolicyData userPolicy = getUserData(userId); 8772 return userPolicy.mPermissionPolicy; 8773 } 8774 } 8775 8776 @Override 8777 public boolean setPermissionGrantState(ComponentName admin, String packageName, 8778 String permission, int grantState) throws RemoteException { 8779 UserHandle user = mInjector.binderGetCallingUserHandle(); 8780 synchronized (this) { 8781 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8782 long ident = mInjector.binderClearCallingIdentity(); 8783 try { 8784 if (getTargetSdk(packageName, user.getIdentifier()) 8785 < android.os.Build.VERSION_CODES.M) { 8786 return false; 8787 } 8788 final PackageManager packageManager = mInjector.getPackageManager(); 8789 switch (grantState) { 8790 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: { 8791 mInjector.getPackageManagerInternal().grantRuntimePermission(packageName, 8792 permission, user.getIdentifier(), true /* override policy */); 8793 packageManager.updatePermissionFlags(permission, packageName, 8794 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 8795 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 8796 } break; 8797 8798 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: { 8799 mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName, 8800 permission, user.getIdentifier(), true /* override policy */); 8801 packageManager.updatePermissionFlags(permission, packageName, 8802 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 8803 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 8804 } break; 8805 8806 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: { 8807 packageManager.updatePermissionFlags(permission, packageName, 8808 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user); 8809 } break; 8810 } 8811 return true; 8812 } catch (SecurityException se) { 8813 return false; 8814 } finally { 8815 mInjector.binderRestoreCallingIdentity(ident); 8816 } 8817 } 8818 } 8819 8820 @Override 8821 public int getPermissionGrantState(ComponentName admin, String packageName, 8822 String permission) throws RemoteException { 8823 PackageManager packageManager = mInjector.getPackageManager(); 8824 8825 UserHandle user = mInjector.binderGetCallingUserHandle(); 8826 synchronized (this) { 8827 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8828 long ident = mInjector.binderClearCallingIdentity(); 8829 try { 8830 int granted = mIPackageManager.checkPermission(permission, 8831 packageName, user.getIdentifier()); 8832 int permFlags = packageManager.getPermissionFlags(permission, packageName, user); 8833 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 8834 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 8835 // Not controlled by policy 8836 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 8837 } else { 8838 // Policy controlled so return result based on permission grant state 8839 return granted == PackageManager.PERMISSION_GRANTED 8840 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 8841 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 8842 } 8843 } finally { 8844 mInjector.binderRestoreCallingIdentity(ident); 8845 } 8846 } 8847 } 8848 8849 boolean isPackageInstalledForUser(String packageName, int userHandle) { 8850 try { 8851 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 8852 userHandle); 8853 return (pi != null) && (pi.applicationInfo.flags != 0); 8854 } catch (RemoteException re) { 8855 throw new RuntimeException("Package manager has died", re); 8856 } 8857 } 8858 8859 @Override 8860 public boolean isProvisioningAllowed(String action, String packageName) { 8861 Preconditions.checkNotNull(packageName); 8862 8863 final int callingUid = mInjector.binderGetCallingUid(); 8864 final long ident = mInjector.binderClearCallingIdentity(); 8865 try { 8866 final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser( 8867 packageName, UserHandle.getUserId(callingUid)); 8868 Preconditions.checkArgument(callingUid == uidForPackage, 8869 "Caller uid doesn't match the one for the provided package."); 8870 } catch (NameNotFoundException e) { 8871 throw new IllegalArgumentException("Invalid package provided " + packageName, e); 8872 } finally { 8873 mInjector.binderRestoreCallingIdentity(ident); 8874 } 8875 8876 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK; 8877 } 8878 8879 @Override 8880 public int checkProvisioningPreCondition(String action, String packageName) { 8881 Preconditions.checkNotNull(packageName); 8882 enforceCanManageProfileAndDeviceOwners(); 8883 return checkProvisioningPreConditionSkipPermission(action, packageName); 8884 } 8885 8886 private int checkProvisioningPreConditionSkipPermission(String action, String packageName) { 8887 if (!mHasFeature) { 8888 return CODE_DEVICE_ADMIN_NOT_SUPPORTED; 8889 } 8890 8891 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8892 if (action != null) { 8893 switch (action) { 8894 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 8895 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 8896 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 8897 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 8898 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER: 8899 return checkManagedUserProvisioningPreCondition(callingUserId); 8900 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE: 8901 return checkManagedShareableDeviceProvisioningPreCondition(callingUserId); 8902 } 8903 } 8904 throw new IllegalArgumentException("Unknown provisioning action " + action); 8905 } 8906 8907 /** 8908 * The device owner can only be set before the setup phase of the primary user has completed, 8909 * except for adb command if no accounts or additional users are present on the device. 8910 */ 8911 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 8912 int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccounts) { 8913 if (mOwners.hasDeviceOwner()) { 8914 return CODE_HAS_DEVICE_OWNER; 8915 } 8916 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 8917 return CODE_USER_HAS_PROFILE_OWNER; 8918 } 8919 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 8920 return CODE_USER_NOT_RUNNING; 8921 } 8922 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 8923 return CODE_HAS_PAIRED; 8924 } 8925 if (isAdb) { 8926 // if shell command runs after user setup completed check device status. Otherwise, OK. 8927 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 8928 if (!mInjector.userManagerIsSplitSystemUser()) { 8929 if (mUserManager.getUserCount() > 1) { 8930 return CODE_NONSYSTEM_USER_EXISTS; 8931 } 8932 if (hasIncompatibleAccounts) { 8933 return CODE_ACCOUNTS_NOT_EMPTY; 8934 } 8935 } else { 8936 // STOPSHIP Do proper check in split user mode 8937 } 8938 } 8939 return CODE_OK; 8940 } else { 8941 if (!mInjector.userManagerIsSplitSystemUser()) { 8942 // In non-split user mode, DO has to be user 0 8943 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 8944 return CODE_NOT_SYSTEM_USER; 8945 } 8946 // In non-split user mode, only provision DO before setup wizard completes 8947 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 8948 return CODE_USER_SETUP_COMPLETED; 8949 } 8950 } else { 8951 // STOPSHIP Do proper check in split user mode 8952 } 8953 return CODE_OK; 8954 } 8955 } 8956 8957 private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) { 8958 synchronized (this) { 8959 // hasIncompatibleAccounts doesn't matter since the caller is not adb. 8960 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 8961 deviceOwnerUserId, /* isAdb= */ false, /* hasIncompatibleAccounts=*/ true); 8962 } 8963 } 8964 8965 private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) { 8966 if (!hasFeatureManagedUsers()) { 8967 return CODE_MANAGED_USERS_NOT_SUPPORTED; 8968 } 8969 if (callingUserId == UserHandle.USER_SYSTEM 8970 && mInjector.userManagerIsSplitSystemUser()) { 8971 // Managed-profiles cannot be setup on the system user. 8972 return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 8973 } 8974 if (getProfileOwner(callingUserId) != null) { 8975 // Managed user cannot have a managed profile. 8976 return CODE_USER_HAS_PROFILE_OWNER; 8977 } 8978 8979 final long ident = mInjector.binderClearCallingIdentity(); 8980 try { 8981 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 8982 if (mUserManager.hasUserRestriction( 8983 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserHandle)) { 8984 // The DO can initiate provisioning if the restriction was set by the DO. 8985 if (!isDeviceOwnerPackage(packageName, callingUserId) 8986 || isAdminAffectedByRestriction(mOwners.getDeviceOwnerComponent(), 8987 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) { 8988 // Caller is not DO or the restriction was set by the system. 8989 return CODE_ADD_MANAGED_PROFILE_DISALLOWED; 8990 } 8991 } 8992 8993 // TODO: Allow it if the caller is the DO? DO could just call removeUser() before 8994 // provisioning, so not strictly required... 8995 boolean canRemoveProfile = !mUserManager.hasUserRestriction( 8996 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, callingUserHandle); 8997 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) { 8998 return CODE_CANNOT_ADD_MANAGED_PROFILE; 8999 } 9000 } finally { 9001 mInjector.binderRestoreCallingIdentity(ident); 9002 } 9003 return CODE_OK; 9004 } 9005 9006 private int checkManagedUserProvisioningPreCondition(int callingUserId) { 9007 if (!hasFeatureManagedUsers()) { 9008 return CODE_MANAGED_USERS_NOT_SUPPORTED; 9009 } 9010 if (!mInjector.userManagerIsSplitSystemUser()) { 9011 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems. 9012 return CODE_NOT_SYSTEM_USER_SPLIT; 9013 } 9014 if (callingUserId == UserHandle.USER_SYSTEM) { 9015 // System user cannot be a managed user. 9016 return CODE_SYSTEM_USER; 9017 } 9018 if (hasUserSetupCompleted(callingUserId)) { 9019 return CODE_USER_SETUP_COMPLETED; 9020 } 9021 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 9022 return CODE_HAS_PAIRED; 9023 } 9024 return CODE_OK; 9025 } 9026 9027 private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) { 9028 if (!mInjector.userManagerIsSplitSystemUser()) { 9029 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems. 9030 return CODE_NOT_SYSTEM_USER_SPLIT; 9031 } 9032 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 9033 } 9034 9035 private boolean hasFeatureManagedUsers() { 9036 try { 9037 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 9038 } catch (RemoteException e) { 9039 return false; 9040 } 9041 } 9042 9043 @Override 9044 public String getWifiMacAddress(ComponentName admin) { 9045 // Make sure caller has DO. 9046 synchronized (this) { 9047 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9048 } 9049 9050 final long ident = mInjector.binderClearCallingIdentity(); 9051 try { 9052 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo(); 9053 if (wifiInfo == null) { 9054 return null; 9055 } 9056 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null; 9057 } finally { 9058 mInjector.binderRestoreCallingIdentity(ident); 9059 } 9060 } 9061 9062 /** 9063 * Returns the target sdk version number that the given packageName was built for 9064 * in the given user. 9065 */ 9066 private int getTargetSdk(String packageName, int userId) { 9067 final ApplicationInfo ai; 9068 try { 9069 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 9070 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion; 9071 return targetSdkVersion; 9072 } catch (RemoteException e) { 9073 // Shouldn't happen 9074 return 0; 9075 } 9076 } 9077 9078 @Override 9079 public boolean isManagedProfile(ComponentName admin) { 9080 synchronized (this) { 9081 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9082 } 9083 return isManagedProfile(mInjector.userHandleGetCallingUserId()); 9084 } 9085 9086 @Override 9087 public boolean isSystemOnlyUser(ComponentName admin) { 9088 synchronized (this) { 9089 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9090 } 9091 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9092 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM; 9093 } 9094 9095 @Override 9096 public void reboot(ComponentName admin) { 9097 Preconditions.checkNotNull(admin); 9098 // Make sure caller has DO. 9099 synchronized (this) { 9100 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9101 } 9102 long ident = mInjector.binderClearCallingIdentity(); 9103 try { 9104 // Make sure there are no ongoing calls on the device. 9105 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 9106 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 9107 } 9108 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 9109 } finally { 9110 mInjector.binderRestoreCallingIdentity(ident); 9111 } 9112 } 9113 9114 @Override 9115 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 9116 if (!mHasFeature) { 9117 return; 9118 } 9119 Preconditions.checkNotNull(who, "ComponentName is null"); 9120 final int userHandle = mInjector.userHandleGetCallingUserId(); 9121 synchronized (this) { 9122 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9123 mInjector.binderGetCallingUid()); 9124 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 9125 admin.shortSupportMessage = message; 9126 saveSettingsLocked(userHandle); 9127 } 9128 } 9129 } 9130 9131 @Override 9132 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 9133 if (!mHasFeature) { 9134 return null; 9135 } 9136 Preconditions.checkNotNull(who, "ComponentName is null"); 9137 synchronized (this) { 9138 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9139 mInjector.binderGetCallingUid()); 9140 return admin.shortSupportMessage; 9141 } 9142 } 9143 9144 @Override 9145 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 9146 if (!mHasFeature) { 9147 return; 9148 } 9149 Preconditions.checkNotNull(who, "ComponentName is null"); 9150 final int userHandle = mInjector.userHandleGetCallingUserId(); 9151 synchronized (this) { 9152 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9153 mInjector.binderGetCallingUid()); 9154 if (!TextUtils.equals(admin.longSupportMessage, message)) { 9155 admin.longSupportMessage = message; 9156 saveSettingsLocked(userHandle); 9157 } 9158 } 9159 } 9160 9161 @Override 9162 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 9163 if (!mHasFeature) { 9164 return null; 9165 } 9166 Preconditions.checkNotNull(who, "ComponentName is null"); 9167 synchronized (this) { 9168 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9169 mInjector.binderGetCallingUid()); 9170 return admin.longSupportMessage; 9171 } 9172 } 9173 9174 @Override 9175 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 9176 if (!mHasFeature) { 9177 return null; 9178 } 9179 Preconditions.checkNotNull(who, "ComponentName is null"); 9180 if (!isCallerWithSystemUid()) { 9181 throw new SecurityException("Only the system can query support message for user"); 9182 } 9183 synchronized (this) { 9184 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 9185 if (admin != null) { 9186 return admin.shortSupportMessage; 9187 } 9188 } 9189 return null; 9190 } 9191 9192 @Override 9193 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 9194 if (!mHasFeature) { 9195 return null; 9196 } 9197 Preconditions.checkNotNull(who, "ComponentName is null"); 9198 if (!isCallerWithSystemUid()) { 9199 throw new SecurityException("Only the system can query support message for user"); 9200 } 9201 synchronized (this) { 9202 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 9203 if (admin != null) { 9204 return admin.longSupportMessage; 9205 } 9206 } 9207 return null; 9208 } 9209 9210 @Override 9211 public void setOrganizationColor(@NonNull ComponentName who, int color) { 9212 if (!mHasFeature) { 9213 return; 9214 } 9215 Preconditions.checkNotNull(who, "ComponentName is null"); 9216 final int userHandle = mInjector.userHandleGetCallingUserId(); 9217 enforceManagedProfile(userHandle, "set organization color"); 9218 synchronized (this) { 9219 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9220 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9221 admin.organizationColor = color; 9222 saveSettingsLocked(userHandle); 9223 } 9224 } 9225 9226 @Override 9227 public void setOrganizationColorForUser(int color, int userId) { 9228 if (!mHasFeature) { 9229 return; 9230 } 9231 enforceFullCrossUsersPermission(userId); 9232 enforceManageUsers(); 9233 enforceManagedProfile(userId, "set organization color"); 9234 synchronized (this) { 9235 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9236 admin.organizationColor = color; 9237 saveSettingsLocked(userId); 9238 } 9239 } 9240 9241 @Override 9242 public int getOrganizationColor(@NonNull ComponentName who) { 9243 if (!mHasFeature) { 9244 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 9245 } 9246 Preconditions.checkNotNull(who, "ComponentName is null"); 9247 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color"); 9248 synchronized (this) { 9249 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9250 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9251 return admin.organizationColor; 9252 } 9253 } 9254 9255 @Override 9256 public int getOrganizationColorForUser(int userHandle) { 9257 if (!mHasFeature) { 9258 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 9259 } 9260 enforceFullCrossUsersPermission(userHandle); 9261 enforceManagedProfile(userHandle, "get organization color"); 9262 synchronized (this) { 9263 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 9264 return (profileOwner != null) 9265 ? profileOwner.organizationColor 9266 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 9267 } 9268 } 9269 9270 @Override 9271 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 9272 if (!mHasFeature) { 9273 return; 9274 } 9275 Preconditions.checkNotNull(who, "ComponentName is null"); 9276 final int userHandle = mInjector.userHandleGetCallingUserId(); 9277 9278 synchronized (this) { 9279 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9280 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9281 if (!TextUtils.equals(admin.organizationName, text)) { 9282 admin.organizationName = (text == null || text.length() == 0) 9283 ? null : text.toString(); 9284 saveSettingsLocked(userHandle); 9285 } 9286 } 9287 } 9288 9289 @Override 9290 public CharSequence getOrganizationName(@NonNull ComponentName who) { 9291 if (!mHasFeature) { 9292 return null; 9293 } 9294 Preconditions.checkNotNull(who, "ComponentName is null"); 9295 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name"); 9296 synchronized(this) { 9297 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9298 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9299 return admin.organizationName; 9300 } 9301 } 9302 9303 @Override 9304 public CharSequence getDeviceOwnerOrganizationName() { 9305 if (!mHasFeature) { 9306 return null; 9307 } 9308 enforceDeviceOwnerOrManageUsers(); 9309 synchronized(this) { 9310 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 9311 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 9312 } 9313 } 9314 9315 @Override 9316 public CharSequence getOrganizationNameForUser(int userHandle) { 9317 if (!mHasFeature) { 9318 return null; 9319 } 9320 enforceFullCrossUsersPermission(userHandle); 9321 enforceManagedProfile(userHandle, "get organization name"); 9322 synchronized (this) { 9323 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 9324 return (profileOwner != null) 9325 ? profileOwner.organizationName 9326 : null; 9327 } 9328 } 9329 9330 @Override 9331 public void setAffiliationIds(ComponentName admin, List<String> ids) { 9332 if (!mHasFeature) { 9333 return; 9334 } 9335 9336 Preconditions.checkNotNull(admin); 9337 Preconditions.checkCollectionElementsNotNull(ids, "ids"); 9338 9339 final Set<String> affiliationIds = new ArraySet<String>(ids); 9340 Preconditions.checkArgument( 9341 !affiliationIds.contains(""), "ids must not contain empty strings"); 9342 9343 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9344 synchronized (this) { 9345 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9346 getUserData(callingUserId).mAffiliationIds = affiliationIds; 9347 saveSettingsLocked(callingUserId); 9348 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 9349 // Affiliation ids specified by the device owner are additionally stored in 9350 // UserHandle.USER_SYSTEM's DevicePolicyData. 9351 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 9352 saveSettingsLocked(UserHandle.USER_SYSTEM); 9353 } 9354 } 9355 } 9356 9357 @Override 9358 public List<String> getAffiliationIds(ComponentName admin) { 9359 if (!mHasFeature) { 9360 return Collections.emptyList(); 9361 } 9362 9363 Preconditions.checkNotNull(admin); 9364 synchronized (this) { 9365 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9366 return new ArrayList<String>( 9367 getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds); 9368 } 9369 } 9370 9371 @Override 9372 public boolean isAffiliatedUser() { 9373 return isUserAffiliatedWithDevice(mInjector.userHandleGetCallingUserId()); 9374 } 9375 9376 private boolean isUserAffiliatedWithDevice(int userId) { 9377 synchronized (this) { 9378 if (!mOwners.hasDeviceOwner()) { 9379 return false; 9380 } 9381 if (userId == mOwners.getDeviceOwnerUserId()) { 9382 // The user that the DO is installed on is always affiliated with the device. 9383 return true; 9384 } 9385 if (userId == UserHandle.USER_SYSTEM) { 9386 // The system user is always affiliated in a DO device, even if the DO is set on a 9387 // different user. This could be the case if the DO is set in the primary user 9388 // of a split user device. 9389 return true; 9390 } 9391 final ComponentName profileOwner = getProfileOwner(userId); 9392 if (profileOwner == null) { 9393 return false; 9394 } 9395 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 9396 final Set<String> deviceAffiliationIds = 9397 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 9398 for (String id : userAffiliationIds) { 9399 if (deviceAffiliationIds.contains(id)) { 9400 return true; 9401 } 9402 } 9403 } 9404 return false; 9405 } 9406 9407 private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() { 9408 final boolean isSingleUserManagedDevice = isDeviceOwnerManagedSingleUserDevice(); 9409 9410 // disable security logging if needed 9411 if (!isSingleUserManagedDevice) { 9412 mInjector.securityLogSetLoggingEnabledProperty(false); 9413 Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user managed" 9414 + " device."); 9415 } 9416 9417 // disable backup service if needed 9418 // note: when clearing DO, the backup service shouldn't be disabled if it was enabled by 9419 // the device owner 9420 if (mOwners.hasDeviceOwner() && !isSingleUserManagedDevice) { 9421 setBackupServiceEnabledInternal(false); 9422 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user."); 9423 } 9424 9425 // disable network logging if needed 9426 if (!isSingleUserManagedDevice) { 9427 setNetworkLoggingActiveInternal(false); 9428 Slog.w(LOG_TAG, "Network logging turned off as it's no longer a single user managed" 9429 + " device."); 9430 // if there still is a device owner, disable logging policy, otherwise the admin 9431 // has been nuked 9432 if (mOwners.hasDeviceOwner()) { 9433 getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = false; 9434 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 9435 } 9436 } 9437 } 9438 9439 @Override 9440 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) { 9441 Preconditions.checkNotNull(admin); 9442 ensureDeviceOwnerManagingSingleUser(admin); 9443 9444 synchronized (this) { 9445 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 9446 return; 9447 } 9448 mInjector.securityLogSetLoggingEnabledProperty(enabled); 9449 if (enabled) { 9450 mSecurityLogMonitor.start(); 9451 } else { 9452 mSecurityLogMonitor.stop(); 9453 } 9454 } 9455 } 9456 9457 @Override 9458 public boolean isSecurityLoggingEnabled(ComponentName admin) { 9459 Preconditions.checkNotNull(admin); 9460 synchronized (this) { 9461 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9462 return mInjector.securityLogGetLoggingEnabledProperty(); 9463 } 9464 } 9465 9466 private synchronized void recordSecurityLogRetrievalTime() { 9467 final long currentTime = System.currentTimeMillis(); 9468 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 9469 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 9470 policyData.mLastSecurityLogRetrievalTime = currentTime; 9471 saveSettingsLocked(UserHandle.USER_SYSTEM); 9472 } 9473 } 9474 9475 @Override 9476 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) { 9477 Preconditions.checkNotNull(admin); 9478 ensureDeviceOwnerManagingSingleUser(admin); 9479 9480 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) { 9481 return null; 9482 } 9483 9484 recordSecurityLogRetrievalTime(); 9485 9486 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 9487 try { 9488 SecurityLog.readPreviousEvents(output); 9489 return new ParceledListSlice<SecurityEvent>(output); 9490 } catch (IOException e) { 9491 Slog.w(LOG_TAG, "Fail to read previous events" , e); 9492 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 9493 } 9494 } 9495 9496 @Override 9497 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) { 9498 Preconditions.checkNotNull(admin); 9499 ensureDeviceOwnerManagingSingleUser(admin); 9500 9501 recordSecurityLogRetrievalTime(); 9502 9503 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 9504 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 9505 } 9506 9507 private void enforceCanManageDeviceAdmin() { 9508 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS, 9509 null); 9510 } 9511 9512 private void enforceCanManageProfileAndDeviceOwners() { 9513 mContext.enforceCallingOrSelfPermission( 9514 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 9515 } 9516 9517 private void enforceCallerSystemUserHandle() { 9518 final int callingUid = mInjector.binderGetCallingUid(); 9519 final int userId = UserHandle.getUserId(callingUid); 9520 if (userId != UserHandle.USER_SYSTEM) { 9521 throw new SecurityException("Caller has to be in user 0"); 9522 } 9523 } 9524 9525 @Override 9526 public boolean isUninstallInQueue(final String packageName) { 9527 enforceCanManageDeviceAdmin(); 9528 final int userId = mInjector.userHandleGetCallingUserId(); 9529 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 9530 synchronized (this) { 9531 return mPackagesToRemove.contains(packageUserPair); 9532 } 9533 } 9534 9535 @Override 9536 public void uninstallPackageWithActiveAdmins(final String packageName) { 9537 enforceCanManageDeviceAdmin(); 9538 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 9539 9540 final int userId = mInjector.userHandleGetCallingUserId(); 9541 9542 enforceUserUnlocked(userId); 9543 9544 final ComponentName profileOwner = getProfileOwner(userId); 9545 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 9546 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 9547 } 9548 9549 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 9550 if (getDeviceOwnerUserId() == userId && deviceOwner != null 9551 && packageName.equals(deviceOwner.getPackageName())) { 9552 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 9553 } 9554 9555 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 9556 synchronized (this) { 9557 mPackagesToRemove.add(packageUserPair); 9558 } 9559 9560 // All active admins on the user. 9561 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 9562 9563 // Active admins in the target package. 9564 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 9565 if (allActiveAdmins != null) { 9566 for (ComponentName activeAdmin : allActiveAdmins) { 9567 if (packageName.equals(activeAdmin.getPackageName())) { 9568 packageActiveAdmins.add(activeAdmin); 9569 removeActiveAdmin(activeAdmin, userId); 9570 } 9571 } 9572 } 9573 if (packageActiveAdmins.size() == 0) { 9574 startUninstallIntent(packageName, userId); 9575 } else { 9576 mHandler.postDelayed(new Runnable() { 9577 @Override 9578 public void run() { 9579 for (ComponentName activeAdmin : packageActiveAdmins) { 9580 removeAdminArtifacts(activeAdmin, userId); 9581 } 9582 startUninstallIntent(packageName, userId); 9583 } 9584 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 9585 } 9586 } 9587 9588 @Override 9589 public boolean isDeviceProvisioned() { 9590 return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT)); 9591 } 9592 9593 private void removePackageIfRequired(final String packageName, final int userId) { 9594 if (!packageHasActiveAdmins(packageName, userId)) { 9595 // Will not do anything if uninstall was not requested or was already started. 9596 startUninstallIntent(packageName, userId); 9597 } 9598 } 9599 9600 private void startUninstallIntent(final String packageName, final int userId) { 9601 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 9602 synchronized (this) { 9603 if (!mPackagesToRemove.contains(packageUserPair)) { 9604 // Do nothing if uninstall was not requested or was already started. 9605 return; 9606 } 9607 mPackagesToRemove.remove(packageUserPair); 9608 } 9609 try { 9610 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) { 9611 // Package does not exist. Nothing to do. 9612 return; 9613 } 9614 } catch (RemoteException re) { 9615 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info"); 9616 } 9617 9618 try { // force stop the package before uninstalling 9619 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 9620 } catch (RemoteException re) { 9621 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 9622 } 9623 final Uri packageURI = Uri.parse("package:" + packageName); 9624 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 9625 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 9626 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 9627 } 9628 9629 /** 9630 * Removes the admin from the policy. Ideally called after the admin's 9631 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 9632 * 9633 * @param adminReceiver The admin to remove 9634 * @param userHandle The user for which this admin has to be removed. 9635 */ 9636 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 9637 synchronized (this) { 9638 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 9639 if (admin == null) { 9640 return; 9641 } 9642 final DevicePolicyData policy = getUserData(userHandle); 9643 final boolean doProxyCleanup = admin.info.usesPolicy( 9644 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 9645 policy.mAdminList.remove(admin); 9646 policy.mAdminMap.remove(adminReceiver); 9647 validatePasswordOwnerLocked(policy); 9648 if (doProxyCleanup) { 9649 resetGlobalProxyLocked(policy); 9650 } 9651 saveSettingsLocked(userHandle); 9652 updateMaximumTimeToLockLocked(userHandle); 9653 policy.mRemovingAdmins.remove(adminReceiver); 9654 9655 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 9656 } 9657 // The removed admin might have disabled camera, so update user 9658 // restrictions. 9659 pushUserRestrictions(userHandle); 9660 } 9661 9662 @Override 9663 public void setDeviceProvisioningConfigApplied() { 9664 enforceManageUsers(); 9665 synchronized (this) { 9666 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 9667 policy.mDeviceProvisioningConfigApplied = true; 9668 saveSettingsLocked(UserHandle.USER_SYSTEM); 9669 } 9670 } 9671 9672 @Override 9673 public boolean isDeviceProvisioningConfigApplied() { 9674 enforceManageUsers(); 9675 synchronized (this) { 9676 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 9677 return policy.mDeviceProvisioningConfigApplied; 9678 } 9679 } 9680 9681 /** 9682 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 9683 * 9684 * It's added for testing only. Please use this API carefully if it's used by other system app 9685 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 9686 * apps. 9687 */ 9688 @Override 9689 public void forceUpdateUserSetupComplete() { 9690 enforceCanManageProfileAndDeviceOwners(); 9691 enforceCallerSystemUserHandle(); 9692 // no effect if it's called from user build 9693 if (!mInjector.isBuildDebuggable()) { 9694 return; 9695 } 9696 final int userId = UserHandle.USER_SYSTEM; 9697 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 9698 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 9699 DevicePolicyData policy = getUserData(userId); 9700 policy.mUserSetupComplete = isUserCompleted; 9701 synchronized (this) { 9702 saveSettingsLocked(userId); 9703 } 9704 } 9705 9706 @Override 9707 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 9708 Preconditions.checkNotNull(admin); 9709 if (!mHasFeature) { 9710 return; 9711 } 9712 ensureDeviceOwnerManagingSingleUser(admin); 9713 setBackupServiceEnabledInternal(enabled); 9714 } 9715 9716 private synchronized void setBackupServiceEnabledInternal(boolean enabled) { 9717 long ident = mInjector.binderClearCallingIdentity(); 9718 try { 9719 IBackupManager ibm = mInjector.getIBackupManager(); 9720 if (ibm != null) { 9721 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled); 9722 } 9723 } catch (RemoteException e) { 9724 throw new IllegalStateException( 9725 "Failed " + (enabled ? "" : "de") + "activating backup service.", e); 9726 } finally { 9727 mInjector.binderRestoreCallingIdentity(ident); 9728 } 9729 } 9730 9731 @Override 9732 public boolean isBackupServiceEnabled(ComponentName admin) { 9733 Preconditions.checkNotNull(admin); 9734 if (!mHasFeature) { 9735 return true; 9736 } 9737 synchronized (this) { 9738 try { 9739 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9740 IBackupManager ibm = mInjector.getIBackupManager(); 9741 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM); 9742 } catch (RemoteException e) { 9743 throw new IllegalStateException("Failed requesting backup service state.", e); 9744 } 9745 } 9746 } 9747 9748 @Override 9749 public boolean bindDeviceAdminServiceAsUser( 9750 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 9751 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 9752 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 9753 if (!mHasFeature) { 9754 return false; 9755 } 9756 Preconditions.checkNotNull(admin); 9757 Preconditions.checkNotNull(caller); 9758 Preconditions.checkNotNull(serviceIntent); 9759 Preconditions.checkArgument( 9760 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 9761 "Service intent must be explicit (with a package name or component): " 9762 + serviceIntent); 9763 Preconditions.checkNotNull(connection); 9764 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 9765 "target user id must be different from the calling user id"); 9766 9767 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 9768 throw new SecurityException("Not allowed to bind to target user id"); 9769 } 9770 9771 final String targetPackage; 9772 synchronized (this) { 9773 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 9774 } 9775 9776 final long callingIdentity = mInjector.binderClearCallingIdentity(); 9777 try { 9778 // Validate and sanitize the incoming service intent. 9779 final Intent sanitizedIntent = 9780 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 9781 if (sanitizedIntent == null) { 9782 // Fail, cannot lookup the target service. 9783 return false; 9784 } 9785 // Ask ActivityManager to bind it. Notice that we are binding the service with the 9786 // caller app instead of DevicePolicyManagerService. 9787 return mInjector.getIActivityManager().bindService( 9788 caller, activtiyToken, serviceIntent, 9789 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 9790 connection, flags, mContext.getOpPackageName(), 9791 targetUserId) != 0; 9792 } catch (RemoteException ex) { 9793 // Same process, should not happen. 9794 } finally { 9795 mInjector.binderRestoreCallingIdentity(callingIdentity); 9796 } 9797 9798 // Failed to bind. 9799 return false; 9800 } 9801 9802 @Override 9803 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 9804 if (!mHasFeature) { 9805 return Collections.emptyList(); 9806 } 9807 Preconditions.checkNotNull(admin); 9808 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 9809 9810 synchronized (this) { 9811 ActiveAdmin callingOwner = getActiveAdminForCallerLocked( 9812 admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9813 9814 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9815 final boolean isCallerDeviceOwner = isDeviceOwner(callingOwner); 9816 final boolean isCallerManagedProfile = isManagedProfile(callingUserId); 9817 if ((!isCallerDeviceOwner && !isCallerManagedProfile) 9818 || !isUserAffiliatedWithDevice(callingUserId)) { 9819 return targetUsers; 9820 } 9821 9822 final long callingIdentity = mInjector.binderClearCallingIdentity(); 9823 try { 9824 String callingOwnerPackage = callingOwner.info.getComponent().getPackageName(); 9825 for (int userId : mUserManager.getProfileIdsWithDisabled(callingUserId)) { 9826 if (userId == callingUserId) { 9827 continue; 9828 } 9829 9830 // We only allow the device owner and a managed profile owner to bind to each 9831 // other. 9832 if ((isCallerManagedProfile && userId == mOwners.getDeviceOwnerUserId()) 9833 || (isCallerDeviceOwner && isManagedProfile(userId))) { 9834 String targetOwnerPackage = getOwnerPackageNameForUserLocked(userId); 9835 9836 // Both must be the same package and be affiliated in order to bind. 9837 if (callingOwnerPackage.equals(targetOwnerPackage) 9838 && isUserAffiliatedWithDevice(userId)) { 9839 targetUsers.add(UserHandle.of(userId)); 9840 } 9841 } 9842 } 9843 } finally { 9844 mInjector.binderRestoreCallingIdentity(callingIdentity); 9845 } 9846 } 9847 9848 return targetUsers; 9849 } 9850 9851 /** 9852 * Return true if a given user has any accounts that'll prevent installing a device or profile 9853 * owner {@code owner}. 9854 * - If the user has no accounts, then return false. 9855 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 9856 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 9857 * ..._DISALLOWED, return true. 9858 * - Otherwise return false. 9859 * 9860 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 9861 */ 9862 private boolean hasIncompatibleAccountsNoLock(int userId, @Nullable ComponentName owner) { 9863 if (Thread.holdsLock(this)) { 9864 Slog.wtf(LOG_TAG, "hasIncompatibleAccountsNoLock() called with the DPMS lock held."); 9865 return true; 9866 } 9867 9868 final long token = mInjector.binderClearCallingIdentity(); 9869 try { 9870 final AccountManager am = AccountManager.get(mContext); 9871 final Account accounts[] = am.getAccountsAsUser(userId); 9872 if (accounts.length == 0) { 9873 return false; 9874 } 9875 synchronized (this) { 9876 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 9877 Log.w(LOG_TAG, 9878 "Non test-only owner can't be installed with existing accounts."); 9879 return true; 9880 } 9881 } 9882 9883 final String[] feature_allow = 9884 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 9885 final String[] feature_disallow = 9886 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 9887 9888 boolean compatible = true; 9889 for (Account account : accounts) { 9890 if (hasAccountFeatures(am, account, feature_disallow)) { 9891 Log.e(LOG_TAG, account + " has " + feature_disallow[0]); 9892 compatible = false; 9893 break; 9894 } 9895 if (!hasAccountFeatures(am, account, feature_allow)) { 9896 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]); 9897 compatible = false; 9898 break; 9899 } 9900 } 9901 if (compatible) { 9902 Log.w(LOG_TAG, "All accounts are compatible"); 9903 } else { 9904 Log.e(LOG_TAG, "Found incompatible accounts"); 9905 } 9906 return !compatible; 9907 } finally { 9908 mInjector.binderRestoreCallingIdentity(token); 9909 } 9910 } 9911 9912 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 9913 try { 9914 return am.hasFeatures(account, features, null, null).getResult(); 9915 } catch (Exception e) { 9916 Log.w(LOG_TAG, "Failed to get account feature", e); 9917 return false; 9918 } 9919 } 9920 9921 private boolean isAdb() { 9922 final int callingUid = mInjector.binderGetCallingUid(); 9923 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 9924 } 9925 9926 @Override 9927 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) { 9928 if (!mHasFeature) { 9929 return; 9930 } 9931 Preconditions.checkNotNull(admin); 9932 ensureDeviceOwnerManagingSingleUser(admin); 9933 9934 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 9935 // already in the requested state 9936 return; 9937 } 9938 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 9939 deviceOwner.isNetworkLoggingEnabled = enabled; 9940 if (!enabled) { 9941 deviceOwner.numNetworkLoggingNotifications = 0; 9942 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 9943 } 9944 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 9945 9946 setNetworkLoggingActiveInternal(enabled); 9947 } 9948 9949 private synchronized void setNetworkLoggingActiveInternal(boolean active) { 9950 final long callingIdentity = mInjector.binderClearCallingIdentity(); 9951 try { 9952 if (active) { 9953 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal()); 9954 if (!mNetworkLogger.startNetworkLogging()) { 9955 mNetworkLogger = null; 9956 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging" 9957 + " service not being available yet."); 9958 } 9959 sendNetworkLoggingNotificationLocked(); 9960 } else { 9961 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 9962 mNetworkLogger = null; 9963 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 9964 + " service not being available yet."); 9965 } 9966 mNetworkLogger = null; 9967 } 9968 } finally { 9969 mInjector.binderRestoreCallingIdentity(callingIdentity); 9970 } 9971 } 9972 9973 @Override 9974 public boolean isNetworkLoggingEnabled(ComponentName admin) { 9975 if (!mHasFeature) { 9976 return false; 9977 } 9978 synchronized (this) { 9979 enforceDeviceOwnerOrManageUsers(); 9980 return isNetworkLoggingEnabledInternalLocked(); 9981 } 9982 } 9983 9984 private boolean isNetworkLoggingEnabledInternalLocked() { 9985 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 9986 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled; 9987 } 9988 9989 /* 9990 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 9991 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 9992 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 9993 * 9994 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 9995 */ 9996 @Override 9997 public synchronized List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, 9998 long batchToken) { 9999 if (!mHasFeature) { 10000 return null; 10001 } 10002 Preconditions.checkNotNull(admin); 10003 ensureDeviceOwnerManagingSingleUser(admin); 10004 10005 if (mNetworkLogger == null) { 10006 return null; 10007 } 10008 10009 if (!isNetworkLoggingEnabledInternalLocked()) { 10010 return null; 10011 } 10012 10013 final long currentTime = System.currentTimeMillis(); 10014 synchronized (this) { 10015 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 10016 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 10017 policyData.mLastNetworkLogsRetrievalTime = currentTime; 10018 saveSettingsLocked(UserHandle.USER_SYSTEM); 10019 } 10020 } 10021 10022 return mNetworkLogger.retrieveLogs(batchToken); 10023 } 10024 10025 private void sendNetworkLoggingNotificationLocked() { 10026 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10027 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 10028 return; 10029 } 10030 if (deviceOwner.numNetworkLoggingNotifications >= 10031 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 10032 return; 10033 } 10034 final long now = System.currentTimeMillis(); 10035 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 10036 return; 10037 } 10038 deviceOwner.numNetworkLoggingNotifications++; 10039 if (deviceOwner.numNetworkLoggingNotifications 10040 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 10041 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 10042 } else { 10043 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 10044 } 10045 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 10046 intent.setPackage("com.android.systemui"); 10047 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0, 10048 UserHandle.CURRENT); 10049 Notification notification = new Notification.Builder(mContext) 10050 .setSmallIcon(R.drawable.ic_qs_network_logging) 10051 .setContentTitle(mContext.getString(R.string.network_logging_notification_title)) 10052 .setContentText(mContext.getString(R.string.network_logging_notification_text)) 10053 .setShowWhen(true) 10054 .setContentIntent(pendingIntent) 10055 .build(); 10056 mInjector.getNotificationManager().notify(NETWORK_LOGGING_NOTIFICATION_ID, notification); 10057 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 10058 } 10059 10060 /** 10061 * Return the package name of owner in a given user. 10062 */ 10063 private String getOwnerPackageNameForUserLocked(int userId) { 10064 return mOwners.getDeviceOwnerUserId() == userId 10065 ? mOwners.getDeviceOwnerPackageName() 10066 : mOwners.getProfileOwnerPackage(userId); 10067 } 10068 10069 /** 10070 * @param rawIntent Original service intent specified by caller. It must be explicit. 10071 * @param expectedPackageName The expected package name of the resolved service. 10072 * @return Intent that have component explicitly set. {@code null} if no service is resolved 10073 * with the given intent. 10074 * @throws SecurityException if the intent is resolved to an invalid service. 10075 */ 10076 private Intent createCrossUserServiceIntent( 10077 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 10078 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 10079 ResolveInfo info = mIPackageManager.resolveService( 10080 rawIntent, 10081 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 10082 0, // flags 10083 targetUserId); 10084 if (info == null || info.serviceInfo == null) { 10085 Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent 10086 + " or user " + targetUserId + " is not running"); 10087 return null; 10088 } 10089 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 10090 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 10091 } 10092 if (info.serviceInfo.exported) { 10093 throw new SecurityException("The service must be unexported"); 10094 } 10095 // It is the system server to bind the service, it would be extremely dangerous if it 10096 // can be exploited to bind any service. Set the component explicitly to make sure we 10097 // do not bind anything accidentally. 10098 rawIntent.setComponent(info.serviceInfo.getComponentName()); 10099 return rawIntent; 10100 } 10101 10102 @Override 10103 public long getLastSecurityLogRetrievalTime() { 10104 enforceDeviceOwnerOrManageUsers(); 10105 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 10106 } 10107 10108 @Override 10109 public long getLastBugReportRequestTime() { 10110 enforceDeviceOwnerOrManageUsers(); 10111 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 10112 } 10113 10114 @Override 10115 public long getLastNetworkLogRetrievalTime() { 10116 enforceDeviceOwnerOrManageUsers(); 10117 return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime; 10118 } 10119} 10120