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