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