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