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