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