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