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