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