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