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