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