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