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