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