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