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