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