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