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