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