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