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