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