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