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