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 17 package com.android.server.devicepolicy; 18 19 import static android.Manifest.permission.BIND_DEVICE_ADMIN; 20 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES; 21 import static android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY; 22 import static android.accessibilityservice.AccessibilityServiceInfo.FEEDBACK_ALL_MASK; 23 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE; 24 import static android.app.AppOpsManager.MODE_ALLOWED; 25 import static android.app.AppOpsManager.MODE_DEFAULT; 26 import static android.app.admin.DeviceAdminReceiver.ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED; 27 import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE; 28 import static android.app.admin.DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE; 29 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE; 30 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE; 31 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER; 32 import static android.app.admin.DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED; 33 import static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY; 34 import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE; 35 import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED; 36 import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER; 37 import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED; 38 import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED; 39 import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS; 40 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER; 41 import static android.app.admin.DevicePolicyManager.CODE_OK; 42 import static android.app.admin.DevicePolicyManager.CODE_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS; 43 import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER; 44 import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER; 45 import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING; 46 import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED; 47 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS; 48 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL; 49 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL; 50 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_SELECTION; 51 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP; 52 import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE; 53 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES; 54 import static android.app.admin.DevicePolicyManager.DELEGATION_NETWORK_LOGGING; 55 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS; 56 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT; 57 import static android.app.admin.DevicePolicyManager.DELEGATION_SECURITY_LOGGING; 58 import static android.app.admin.DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 59 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO; 60 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI; 61 import static android.app.admin.DevicePolicyManager.ID_TYPE_INDIVIDUAL_ATTESTATION; 62 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID; 63 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL; 64 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED; 65 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME; 66 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS; 67 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW; 68 import static android.app.admin.DevicePolicyManager.NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 69 import static android.app.admin.DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 70 import static android.app.admin.DevicePolicyManager.OPERATION_SAFETY_REASON_NONE; 71 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH; 72 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_LOW; 73 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM; 74 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE; 75 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC; 76 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC; 77 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK; 78 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 79 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED; 80 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC; 81 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX; 82 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; 83 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 84 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED; 85 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_EXPLICITLY; 86 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT; 87 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OFF; 88 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OPPORTUNISTIC; 89 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME; 90 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_UNKNOWN; 91 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_ERROR_FAILURE_SETTING; 92 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR; 93 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 94 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED; 95 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_PRE_CONDITION_FAILED; 96 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_PROFILE_CREATION_FAILED; 97 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_REMOVE_NON_REQUIRED_APPS_FAILED; 98 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_SETTING_PROFILE_OWNER_FAILED; 99 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_SET_DEVICE_OWNER_FAILED; 100 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_STARTING_PROFILE_FAILED; 101 import static android.app.admin.DevicePolicyManager.STATE_USER_UNMANAGED; 102 import static android.app.admin.DevicePolicyManager.WIPE_EUICC; 103 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE; 104 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA; 105 import static android.app.admin.DevicePolicyManager.WIPE_SILENTLY; 106 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; 107 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 108 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 109 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 110 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT; 111 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE; 112 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK; 113 import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER; 114 import static android.provider.Settings.Secure.USER_SETUP_COMPLETE; 115 import static android.provider.Telephony.Carriers.DPC_URI; 116 import static android.provider.Telephony.Carriers.ENFORCE_KEY; 117 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI; 118 import static android.security.keystore.AttestationUtils.USE_INDIVIDUAL_ATTESTATION; 119 120 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB; 121 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE; 122 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW; 123 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS; 124 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER; 125 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER; 126 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 127 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_DEVICE_OWNER; 128 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER; 129 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE; 130 131 import android.Manifest; 132 import android.Manifest.permission; 133 import android.accessibilityservice.AccessibilityServiceInfo; 134 import android.accounts.Account; 135 import android.accounts.AccountManager; 136 import android.accounts.AccountManagerFuture; 137 import android.accounts.AuthenticatorException; 138 import android.accounts.OperationCanceledException; 139 import android.annotation.IntDef; 140 import android.annotation.NonNull; 141 import android.annotation.Nullable; 142 import android.annotation.UserIdInt; 143 import android.app.Activity; 144 import android.app.ActivityManager; 145 import android.app.ActivityManagerInternal; 146 import android.app.ActivityTaskManager; 147 import android.app.ActivityThread; 148 import android.app.AlarmManager; 149 import android.app.AppGlobals; 150 import android.app.AppOpsManager; 151 import android.app.AppOpsManager.Mode; 152 import android.app.BroadcastOptions; 153 import android.app.IActivityManager; 154 import android.app.IActivityTaskManager; 155 import android.app.IApplicationThread; 156 import android.app.IServiceConnection; 157 import android.app.Notification; 158 import android.app.NotificationManager; 159 import android.app.PendingIntent; 160 import android.app.StatusBarManager; 161 import android.app.admin.DeviceAdminInfo; 162 import android.app.admin.DeviceAdminReceiver; 163 import android.app.admin.DevicePolicyCache; 164 import android.app.admin.DevicePolicyEventLogger; 165 import android.app.admin.DevicePolicyManager; 166 import android.app.admin.DevicePolicyManager.DeviceOwnerType; 167 import android.app.admin.DevicePolicyManager.DevicePolicyOperation; 168 import android.app.admin.DevicePolicyManager.OperationSafetyReason; 169 import android.app.admin.DevicePolicyManager.PasswordComplexity; 170 import android.app.admin.DevicePolicyManager.PersonalAppsSuspensionReason; 171 import android.app.admin.DevicePolicyManagerInternal; 172 import android.app.admin.DevicePolicyManagerLiteInternal; 173 import android.app.admin.DevicePolicySafetyChecker; 174 import android.app.admin.DeviceStateCache; 175 import android.app.admin.FactoryResetProtectionPolicy; 176 import android.app.admin.FullyManagedDeviceProvisioningParams; 177 import android.app.admin.ManagedProfileProvisioningParams; 178 import android.app.admin.NetworkEvent; 179 import android.app.admin.ParcelableGranteeMap; 180 import android.app.admin.PasswordMetrics; 181 import android.app.admin.PasswordPolicy; 182 import android.app.admin.SecurityLog; 183 import android.app.admin.SecurityLog.SecurityEvent; 184 import android.app.admin.StartInstallingUpdateCallback; 185 import android.app.admin.SystemUpdateInfo; 186 import android.app.admin.SystemUpdatePolicy; 187 import android.app.admin.UnsafeStateException; 188 import android.app.backup.IBackupManager; 189 import android.app.compat.CompatChanges; 190 import android.app.trust.TrustManager; 191 import android.app.usage.UsageStatsManagerInternal; 192 import android.compat.annotation.ChangeId; 193 import android.compat.annotation.EnabledAfter; 194 import android.compat.annotation.EnabledSince; 195 import android.content.ActivityNotFoundException; 196 import android.content.BroadcastReceiver; 197 import android.content.ComponentName; 198 import android.content.ContentValues; 199 import android.content.Context; 200 import android.content.IIntentReceiver; 201 import android.content.IIntentSender; 202 import android.content.Intent; 203 import android.content.IntentFilter; 204 import android.content.IntentSender; 205 import android.content.PermissionChecker; 206 import android.content.pm.ActivityInfo; 207 import android.content.pm.ApplicationInfo; 208 import android.content.pm.CrossProfileApps; 209 import android.content.pm.CrossProfileAppsInternal; 210 import android.content.pm.IPackageDataObserver; 211 import android.content.pm.IPackageManager; 212 import android.content.pm.PackageInfo; 213 import android.content.pm.PackageInstaller; 214 import android.content.pm.PackageManager; 215 import android.content.pm.PackageManager.NameNotFoundException; 216 import android.content.pm.PackageManagerInternal; 217 import android.content.pm.ParceledListSlice; 218 import android.content.pm.PermissionInfo; 219 import android.content.pm.ResolveInfo; 220 import android.content.pm.ServiceInfo; 221 import android.content.pm.StringParceledListSlice; 222 import android.content.pm.UserInfo; 223 import android.content.res.Resources; 224 import android.database.ContentObserver; 225 import android.database.Cursor; 226 import android.graphics.Bitmap; 227 import android.hardware.usb.UsbManager; 228 import android.location.LocationManager; 229 import android.media.AudioManager; 230 import android.media.IAudioService; 231 import android.net.ConnectivityManager; 232 import android.net.ConnectivitySettingsManager; 233 import android.net.IIpConnectivityMetrics; 234 import android.net.ProxyInfo; 235 import android.net.Uri; 236 import android.net.VpnManager; 237 import android.net.metrics.IpConnectivityLog; 238 import android.net.wifi.WifiManager; 239 import android.os.Binder; 240 import android.os.Build; 241 import android.os.Bundle; 242 import android.os.Environment; 243 import android.os.Handler; 244 import android.os.IBinder; 245 import android.os.Looper; 246 import android.os.ParcelFileDescriptor; 247 import android.os.PersistableBundle; 248 import android.os.PowerManager; 249 import android.os.PowerManagerInternal; 250 import android.os.Process; 251 import android.os.RemoteCallback; 252 import android.os.RemoteException; 253 import android.os.ResultReceiver; 254 import android.os.ServiceManager; 255 import android.os.ServiceSpecificException; 256 import android.os.ShellCallback; 257 import android.os.SystemClock; 258 import android.os.SystemProperties; 259 import android.os.UserHandle; 260 import android.os.UserManager; 261 import android.os.storage.StorageManager; 262 import android.permission.AdminPermissionControlParams; 263 import android.permission.IPermissionManager; 264 import android.permission.PermissionControllerManager; 265 import android.provider.CalendarContract; 266 import android.provider.ContactsContract.QuickContact; 267 import android.provider.ContactsInternal; 268 import android.provider.Settings; 269 import android.provider.Settings.Global; 270 import android.provider.Telephony; 271 import android.security.AppUriAuthenticationPolicy; 272 import android.security.IKeyChainAliasCallback; 273 import android.security.IKeyChainService; 274 import android.security.KeyChain; 275 import android.security.KeyChain.KeyChainConnection; 276 import android.security.KeyStore; 277 import android.security.keymaster.KeymasterCertificateChain; 278 import android.security.keystore.AttestationUtils; 279 import android.security.keystore.KeyGenParameterSpec; 280 import android.security.keystore.ParcelableKeyGenParameterSpec; 281 import android.stats.devicepolicy.DevicePolicyEnums; 282 import android.telephony.TelephonyManager; 283 import android.telephony.data.ApnSetting; 284 import android.text.TextUtils; 285 import android.text.format.DateUtils; 286 import android.util.ArrayMap; 287 import android.util.ArraySet; 288 import android.util.AtomicFile; 289 import android.util.IndentingPrintWriter; 290 import android.util.Log; 291 import android.util.Pair; 292 import android.util.SparseArray; 293 import android.util.TypedXmlPullParser; 294 import android.util.TypedXmlSerializer; 295 import android.util.Xml; 296 import android.view.IWindowManager; 297 import android.view.accessibility.AccessibilityManager; 298 import android.view.accessibility.IAccessibilityManager; 299 import android.view.inputmethod.InputMethodInfo; 300 301 import com.android.internal.R; 302 import com.android.internal.annotations.GuardedBy; 303 import com.android.internal.annotations.VisibleForTesting; 304 import com.android.internal.app.LocalePicker; 305 import com.android.internal.logging.MetricsLogger; 306 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 307 import com.android.internal.net.NetworkUtilsInternal; 308 import com.android.internal.notification.SystemNotificationChannels; 309 import com.android.internal.os.BackgroundThread; 310 import com.android.internal.statusbar.IStatusBarService; 311 import com.android.internal.telephony.SmsApplication; 312 import com.android.internal.util.ArrayUtils; 313 import com.android.internal.util.DumpUtils; 314 import com.android.internal.util.FunctionalUtils.ThrowingRunnable; 315 import com.android.internal.util.FunctionalUtils.ThrowingSupplier; 316 import com.android.internal.util.JournaledFile; 317 import com.android.internal.util.Preconditions; 318 import com.android.internal.util.StatLogger; 319 import com.android.internal.widget.LockPatternUtils; 320 import com.android.internal.widget.LockSettingsInternal; 321 import com.android.internal.widget.LockscreenCredential; 322 import com.android.internal.widget.PasswordValidationError; 323 import com.android.net.module.util.ProxyUtils; 324 import com.android.server.LocalServices; 325 import com.android.server.LockGuard; 326 import com.android.server.PersistentDataBlockManagerInternal; 327 import com.android.server.SystemServerInitThreadPool; 328 import com.android.server.SystemService; 329 import com.android.server.devicepolicy.ActiveAdmin.TrustAgentInfo; 330 import com.android.server.devicepolicy.Owners.OwnerDto; 331 import com.android.server.inputmethod.InputMethodManagerInternal; 332 import com.android.server.net.NetworkPolicyManagerInternal; 333 import com.android.server.pm.RestrictionsSet; 334 import com.android.server.pm.UserManagerInternal; 335 import com.android.server.pm.UserManagerInternal.UserRestrictionsListener; 336 import com.android.server.pm.UserRestrictionsUtils; 337 import com.android.server.pm.parsing.pkg.AndroidPackage; 338 import com.android.server.storage.DeviceStorageMonitorInternal; 339 import com.android.server.uri.NeededUriGrants; 340 import com.android.server.uri.UriGrantsManagerInternal; 341 import com.android.server.utils.Slogf; 342 import com.android.server.wm.ActivityTaskManagerInternal; 343 344 import com.google.android.collect.Sets; 345 346 import org.xmlpull.v1.XmlPullParserException; 347 348 import java.io.ByteArrayInputStream; 349 import java.io.File; 350 import java.io.FileDescriptor; 351 import java.io.FileInputStream; 352 import java.io.FileOutputStream; 353 import java.io.IOException; 354 import java.io.PrintWriter; 355 import java.lang.reflect.Constructor; 356 import java.security.cert.CertificateException; 357 import java.security.cert.CertificateFactory; 358 import java.security.cert.X509Certificate; 359 import java.text.DateFormat; 360 import java.time.LocalDate; 361 import java.util.ArrayList; 362 import java.util.Arrays; 363 import java.util.Collection; 364 import java.util.Collections; 365 import java.util.Date; 366 import java.util.HashMap; 367 import java.util.HashSet; 368 import java.util.List; 369 import java.util.Locale; 370 import java.util.Map; 371 import java.util.Objects; 372 import java.util.Set; 373 import java.util.concurrent.TimeUnit; 374 import java.util.function.Function; 375 import java.util.function.Predicate; 376 import java.util.stream.Collectors; 377 378 /** 379 * Implementation of the device policy APIs. 380 */ 381 public class DevicePolicyManagerService extends BaseIDevicePolicyManager { 382 383 protected static final String LOG_TAG = "DevicePolicyManager"; 384 385 static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE 386 387 static final String DEVICE_POLICIES_XML = "device_policies.xml"; 388 389 static final String POLICIES_VERSION_XML = "device_policies_version"; 390 391 private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML = 392 "transfer-ownership-parameters.xml"; 393 394 private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle"; 395 396 private static final int REQUEST_EXPIRE_PASSWORD = 5571; 397 398 private static final int REQUEST_PROFILE_OFF_DEADLINE = 5572; 399 400 private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1); 401 402 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms 403 private static final long MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD = 3 * MS_PER_DAY; 404 /** When to warn the user about the approaching work profile off deadline: 1 day before */ 405 private static final long MANAGED_PROFILE_OFF_WARNING_PERIOD = 1 * MS_PER_DAY; 406 407 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION = 408 "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION"; 409 410 /** Broadcast action invoked when the user taps a notification to turn the profile on. */ 411 @VisibleForTesting 412 static final String ACTION_TURN_PROFILE_ON_NOTIFICATION = 413 "com.android.server.ACTION_TURN_PROFILE_ON_NOTIFICATION"; 414 415 /** Broadcast action for tracking managed profile maximum time off. */ 416 @VisibleForTesting 417 static final String ACTION_PROFILE_OFF_DEADLINE = 418 "com.android.server.ACTION_PROFILE_OFF_DEADLINE"; 419 420 private static final String CALLED_FROM_PARENT = "calledFromParent"; 421 private static final String NOT_CALLED_FROM_PARENT = "notCalledFromParent"; 422 423 private static final String CREDENTIAL_MANAGEMENT_APP = "credentialManagementApp"; 424 private static final String NOT_CREDENTIAL_MANAGEMENT_APP = "notCredentialManagementApp"; 425 426 private static final String NULL_STRING_ARRAY = "nullStringArray"; 427 428 private static final String ALLOW_USER_PROVISIONING_KEY = "ro.config.allowuserprovisioning"; 429 430 // Comprehensive list of delegations. 431 private static final String DELEGATIONS[] = { 432 DELEGATION_CERT_INSTALL, 433 DELEGATION_APP_RESTRICTIONS, 434 DELEGATION_BLOCK_UNINSTALL, 435 DELEGATION_ENABLE_SYSTEM_APP, 436 DELEGATION_KEEP_UNINSTALLED_PACKAGES, 437 DELEGATION_PACKAGE_ACCESS, 438 DELEGATION_PERMISSION_GRANT, 439 DELEGATION_INSTALL_EXISTING_PACKAGE, 440 DELEGATION_KEEP_UNINSTALLED_PACKAGES, 441 DELEGATION_NETWORK_LOGGING, 442 DELEGATION_SECURITY_LOGGING, 443 DELEGATION_CERT_SELECTION, 444 }; 445 446 // Subset of delegations that can only be delegated by Device Owner or Profile Owner of a 447 // managed profile. 448 private static final List<String> DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS = 449 Arrays.asList(new String[]{ 450 DELEGATION_NETWORK_LOGGING, 451 }); 452 453 // Subset of delegations that can only be delegated by Device Owner or Profile Owner of an 454 // organization-owned and managed profile. 455 private static final List<String> 456 DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS = 457 Arrays.asList(new String[]{ 458 DELEGATION_SECURITY_LOGGING, 459 }); 460 461 // Subset of delegations that only one single package within a given user can hold 462 private static final List<String> EXCLUSIVE_DELEGATIONS = Arrays.asList(new String[] { 463 DELEGATION_NETWORK_LOGGING, 464 DELEGATION_SECURITY_LOGGING, 465 DELEGATION_CERT_SELECTION, 466 }); 467 468 /** 469 * System property whose value indicates whether the device is fully owned by an organization: 470 * it can be either a device owner device, or a device with an organization-owned managed 471 * profile. 472 * 473 * <p>The state is stored as a Boolean string. 474 */ 475 private static final String PROPERTY_ORGANIZATION_OWNED = "ro.organization_owned"; 476 477 private static final int STATUS_BAR_DISABLE_MASK = 478 StatusBarManager.DISABLE_EXPAND | 479 StatusBarManager.DISABLE_NOTIFICATION_ICONS | 480 StatusBarManager.DISABLE_NOTIFICATION_ALERTS | 481 StatusBarManager.DISABLE_SEARCH; 482 483 private static final int STATUS_BAR_DISABLE2_MASK = 484 StatusBarManager.DISABLE2_QUICK_SETTINGS; 485 486 private static final Set<String> SECURE_SETTINGS_ALLOWLIST; 487 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST; 488 private static final Set<String> GLOBAL_SETTINGS_ALLOWLIST; 489 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED; 490 private static final Set<String> SYSTEM_SETTINGS_ALLOWLIST; 491 private static final Set<Integer> DA_DISALLOWED_POLICIES; 492 private static final String AB_DEVICE_KEY = "ro.build.ab_update"; 493 // The version of the current DevicePolicyManagerService data. This version is used 494 // to decide whether an existing policy in the {@link #DEVICE_POLICIES_XML} needs to 495 // be upgraded. See {@link PolicyVersionUpgrader} on instructions how to add an upgrade 496 // step. 497 static final int DPMS_VERSION = 2; 498 499 static { 500 SECURE_SETTINGS_ALLOWLIST = new ArraySet<>(); 501 SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.DEFAULT_INPUT_METHOD); 502 SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS); 503 SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS); 504 505 SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST = new ArraySet<>(); 506 SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.addAll(SECURE_SETTINGS_ALLOWLIST); 507 SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.add(Settings.Secure.LOCATION_MODE); 508 509 GLOBAL_SETTINGS_ALLOWLIST = new ArraySet<>(); 510 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_ENABLED); 511 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_WIFI_ENABLED); 512 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME); 513 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME_ZONE); 514 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.DATA_ROAMING); 515 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED); 516 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_SLEEP_POLICY); 517 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN); 518 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN); 519 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_MODE); 520 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER); 521 522 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>(); 523 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON); 524 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); 525 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER); 526 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE); 527 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON); 528 529 SYSTEM_SETTINGS_ALLOWLIST = new ArraySet<>(); 530 SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS); 531 SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_FLOAT); 532 SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE); 533 SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_OFF_TIMEOUT); 534 535 DA_DISALLOWED_POLICIES = new ArraySet<>(); 536 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 537 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES); 538 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD); 539 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 540 } 541 542 /** 543 * Keyguard features that when set on a profile affect the profile content or challenge only. 544 * These cannot be set on the managed profile's parent DPM instance 545 */ 546 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY = 547 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS; 548 549 /** Keyguard features that are allowed to be set on a managed profile */ 550 private static final int PROFILE_KEYGUARD_FEATURES = 551 NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER 552 | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY; 553 554 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000; 555 556 /** 557 * Minimum timeout in milliseconds after which unlocking with weak auth times out, 558 * i.e. the user has to use a strong authentication method like password, PIN or pattern. 559 */ 560 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1); 561 562 /** 563 * The amount of ms that a managed kiosk must go without user interaction to be considered 564 * unattended. 565 */ 566 private static final int UNATTENDED_MANAGED_KIOSK_MS = 30000; 567 568 /** 569 * Strings logged with {@link 570 * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}, 571 * {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB}, 572 * {@link DevicePolicyEnums#SET_NETWORK_LOGGING_ENABLED} and 573 * {@link DevicePolicyEnums#RETRIEVE_NETWORK_LOGS}. 574 */ 575 private static final String LOG_TAG_PROFILE_OWNER = "profile-owner"; 576 private static final String LOG_TAG_DEVICE_OWNER = "device-owner"; 577 578 /** 579 * For admin apps targeting R+, throw when the app sets password requirement 580 * that is not taken into account at given quality. For example when quality is set 581 * to {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, it doesn't 582 * make sense to require certain password length. If the intent is to require a password of 583 * certain length having at least NUMERIC quality, the admin should first call 584 * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} and only then call 585 * {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLength}. 586 * 587 * <p>Conversely when an admin app targeting R+ lowers password quality, those 588 * requirements that stop making sense are reset to default values. 589 */ 590 @ChangeId 591 @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q) 592 private static final long ADMIN_APP_PASSWORD_COMPLEXITY = 123562444L; 593 594 /** 595 * Admin apps targeting Android R+ may not use 596 * {@link android.app.admin.DevicePolicyManager#setSecureSetting} to change the deprecated 597 * {@link android.provider.Settings.Secure#LOCATION_MODE} setting. Instead they should use 598 * {@link android.app.admin.DevicePolicyManager#setLocationEnabled}. 599 */ 600 @ChangeId 601 @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q) 602 private static final long USE_SET_LOCATION_ENABLED = 117835097L; 603 604 // Only add to the end of the list. Do not change or rearrange these values, that will break 605 // historical data. Do not use negative numbers or zero, logger only handles positive 606 // integers. 607 private static final int COPY_ACCOUNT_SUCCEEDED = 1; 608 private static final int COPY_ACCOUNT_FAILED = 2; 609 private static final int COPY_ACCOUNT_TIMED_OUT = 3; 610 private static final int COPY_ACCOUNT_EXCEPTION = 4; 611 612 @IntDef({ 613 COPY_ACCOUNT_SUCCEEDED, 614 COPY_ACCOUNT_FAILED, 615 COPY_ACCOUNT_TIMED_OUT, 616 COPY_ACCOUNT_EXCEPTION}) 617 private @interface CopyAccountStatus {} 618 619 /** 620 * Admin apps targeting Android S+ may not use 621 * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} to set password quality 622 * on the {@code DevicePolicyManager} instance obtained by calling 623 * {@link android.app.admin.DevicePolicyManager#getParentProfileInstance}. 624 * Instead, they should use 625 * {@link android.app.admin.DevicePolicyManager#setRequiredPasswordComplexity} to set 626 * coarse-grained password requirements device-wide. 627 */ 628 @ChangeId 629 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S) 630 private static final long PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT = 165573442L; 631 632 private static final String CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG = 633 "The alias provided must be contained in the aliases specified in the credential " 634 + "management app's authentication policy"; 635 private static final String NOT_SYSTEM_CALLER_MSG = "Only the system can %s"; 636 637 final Context mContext; 638 final Injector mInjector; 639 final IPackageManager mIPackageManager; 640 final IPermissionManager mIPermissionManager; 641 final UserManager mUserManager; 642 final UserManagerInternal mUserManagerInternal; 643 final UsageStatsManagerInternal mUsageStatsManagerInternal; 644 final TelephonyManager mTelephonyManager; 645 private final LockPatternUtils mLockPatternUtils; 646 private final LockSettingsInternal mLockSettingsInternal; 647 private final DeviceAdminServiceController mDeviceAdminServiceController; 648 private final OverlayPackagesProvider mOverlayPackagesProvider; 649 650 private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl(); 651 private final DeviceStateCacheImpl mStateCache = new DeviceStateCacheImpl(); 652 653 /** 654 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p 655 * is requested for user u. 656 */ 657 private final Set<Pair<String, Integer>> mPackagesToRemove = 658 new ArraySet<Pair<String, Integer>>(); 659 660 final LocalService mLocalService; 661 662 // Stores and loads state on device and profile owners. 663 @VisibleForTesting 664 final Owners mOwners; 665 666 private final Binder mToken = new Binder(); 667 668 /** 669 * Whether or not device admin feature is supported. If it isn't return defaults for all 670 * public methods, unless the caller has the appropriate permission for a particular method. 671 */ 672 final boolean mHasFeature; 673 674 /** 675 * Whether or not this device is a watch. 676 */ 677 final boolean mIsWatch; 678 679 /** 680 * Whether or not this device is an automotive. 681 */ 682 private final boolean mIsAutomotive; 683 684 /** 685 * Whether this device has the telephony feature. 686 */ 687 final boolean mHasTelephonyFeature; 688 689 private final CertificateMonitor mCertificateMonitor; 690 private final SecurityLogMonitor mSecurityLogMonitor; 691 private final RemoteBugreportManager mBugreportCollectionManager; 692 693 @GuardedBy("getLockObject()") 694 private NetworkLogger mNetworkLogger; 695 696 private final SetupContentObserver mSetupContentObserver; 697 private final DevicePolicyConstantsObserver mConstantsObserver; 698 699 private DevicePolicyConstants mConstants; 700 701 private static final boolean ENABLE_LOCK_GUARD = true; 702 703 /** 704 * Profile off deadline is not set or more than MANAGED_PROFILE_OFF_WARNING_PERIOD away, or the 705 * user is running unlocked, no need for notification. 706 */ 707 private static final int PROFILE_OFF_NOTIFICATION_NONE = 0; 708 /** 709 * Profile off deadline is closer than MANAGED_PROFILE_OFF_WARNING_PERIOD. 710 */ 711 private static final int PROFILE_OFF_NOTIFICATION_WARNING = 1; 712 /** 713 * Profile off deadline reached, notify the user that personal apps blocked. 714 */ 715 private static final int PROFILE_OFF_NOTIFICATION_SUSPENDED = 2; 716 717 interface Stats { 718 int LOCK_GUARD_GUARD = 0; 719 720 int COUNT = LOCK_GUARD_GUARD + 1; 721 } 722 723 private final StatLogger mStatLogger = new StatLogger(new String[] { 724 "LockGuard.guard()", 725 }); 726 727 private final Object mLockDoNoUseDirectly = LockGuard.installNewLock( 728 LockGuard.INDEX_DPMS, /* doWtf=*/ true); 729 getLockObject()730 final Object getLockObject() { 731 if (ENABLE_LOCK_GUARD) { 732 final long start = mStatLogger.getTime(); 733 LockGuard.guard(LockGuard.INDEX_DPMS); 734 mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start); 735 } 736 return mLockDoNoUseDirectly; 737 } 738 739 /** 740 * Check if the current thread holds the DPMS lock, and if not, do a WTF. 741 * 742 * (Doing this check too much may be costly, so don't call it in a hot path.) 743 */ ensureLocked()744 final void ensureLocked() { 745 if (Thread.holdsLock(mLockDoNoUseDirectly)) { 746 return; 747 } 748 Slogf.wtfStack(LOG_TAG, "Not holding DPMS lock."); 749 } 750 751 /** 752 * Calls wtfStack() if called with the DPMS lock held. 753 */ wtfIfInLock()754 private void wtfIfInLock() { 755 if (Thread.holdsLock(mLockDoNoUseDirectly)) { 756 Slogf.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held"); 757 } 758 } 759 760 @VisibleForTesting 761 final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager; 762 763 @Nullable 764 private DevicePolicySafetyChecker mSafetyChecker; 765 766 @GuardedBy("getLockObject()") 767 private final ArrayList<Object> mPendingUserCreatedCallbackTokens = new ArrayList<>(); 768 769 public static final class Lifecycle extends SystemService { 770 private BaseIDevicePolicyManager mService; 771 Lifecycle(Context context)772 public Lifecycle(Context context) { 773 super(context); 774 String dpmsClassName = context.getResources() 775 .getString(R.string.config_deviceSpecificDevicePolicyManagerService); 776 if (TextUtils.isEmpty(dpmsClassName)) { 777 dpmsClassName = DevicePolicyManagerService.class.getName(); 778 } 779 try { 780 Class<?> serviceClass = Class.forName(dpmsClassName); 781 Constructor<?> constructor = serviceClass.getConstructor(Context.class); 782 mService = (BaseIDevicePolicyManager) constructor.newInstance(context); 783 } catch (Exception e) { 784 throw new IllegalStateException( 785 "Failed to instantiate DevicePolicyManagerService with class name: " 786 + dpmsClassName, e); 787 } 788 } 789 790 /** Sets the {@link DevicePolicySafetyChecker}. */ setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)791 public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) { 792 mService.setDevicePolicySafetyChecker(safetyChecker); 793 } 794 795 @Override onStart()796 public void onStart() { 797 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService); 798 } 799 800 @Override onBootPhase(int phase)801 public void onBootPhase(int phase) { 802 mService.systemReady(phase); 803 } 804 805 @Override onUserStarting(@onNull TargetUser user)806 public void onUserStarting(@NonNull TargetUser user) { 807 if (user.isPreCreated()) return; 808 mService.handleStartUser(user.getUserIdentifier()); 809 } 810 811 @Override onUserUnlocking(@onNull TargetUser user)812 public void onUserUnlocking(@NonNull TargetUser user) { 813 if (user.isPreCreated()) return; 814 mService.handleUnlockUser(user.getUserIdentifier()); 815 } 816 817 @Override onUserStopping(@onNull TargetUser user)818 public void onUserStopping(@NonNull TargetUser user) { 819 if (user.isPreCreated()) return; 820 mService.handleStopUser(user.getUserIdentifier()); 821 } 822 823 @Override onUserUnlocked(@onNull TargetUser user)824 public void onUserUnlocked(@NonNull TargetUser user) { 825 if (user.isPreCreated()) return; 826 mService.handleOnUserUnlocked(user.getUserIdentifier()); 827 } 828 } 829 830 @GuardedBy("getLockObject()") 831 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>(); 832 833 @GuardedBy("getLockObject()") 834 835 final Handler mHandler; 836 final Handler mBackgroundHandler; 837 838 /** Listens only if mHasFeature == true. */ 839 final BroadcastReceiver mReceiver = new BroadcastReceiver() { 840 @Override 841 public void onReceive(Context context, Intent intent) { 842 final String action = intent.getAction(); 843 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 844 getSendingUserId()); 845 846 /* 847 * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(), 848 * however it's too early in the boot process to register with IIpConnectivityMetrics 849 * to listen for events. 850 */ 851 if (Intent.ACTION_USER_STARTED.equals(action) && userHandle == UserHandle.USER_SYSTEM) { 852 synchronized (getLockObject()) { 853 if (isNetworkLoggingEnabledInternalLocked()) { 854 setNetworkLoggingActiveInternal(true); 855 } 856 } 857 } 858 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 859 && userHandle == mOwners.getDeviceOwnerUserId()) { 860 mBugreportCollectionManager.checkForPendingBugreportAfterBoot(); 861 862 } 863 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 864 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) { 865 if (VERBOSE_LOG) { 866 Slogf.v(LOG_TAG, "Sending password expiration notifications for action " 867 + action + " for user " + userHandle); 868 } 869 mHandler.post(new Runnable() { 870 @Override 871 public void run() { 872 handlePasswordExpirationNotification(userHandle); 873 } 874 }); 875 } 876 877 if (Intent.ACTION_USER_ADDED.equals(action)) { 878 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle); 879 synchronized (getLockObject()) { 880 // It might take a while for the user to become affiliated. Make security 881 // and network logging unavailable in the meantime. 882 maybePauseDeviceWideLoggingLocked(); 883 } 884 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 885 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle); 886 synchronized (getLockObject()) { 887 // Check whether the user is affiliated, *before* removing its data. 888 boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle); 889 removeUserData(userHandle); 890 if (!isRemovedUserAffiliated) { 891 // We discard the logs when unaffiliated users are deleted (so that the 892 // device owner cannot retrieve data about that user after it's gone). 893 discardDeviceWideLogsLocked(); 894 // Resume logging if all remaining users are affiliated. 895 maybeResumeDeviceWideLoggingLocked(); 896 } 897 } 898 } else if (Intent.ACTION_USER_STARTED.equals(action)) { 899 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle); 900 synchronized (getLockObject()) { 901 maybeSendAdminEnabledBroadcastLocked(userHandle); 902 // Reset the policy data 903 mUserData.remove(userHandle); 904 } 905 handlePackagesChanged(null /* check all admins */, userHandle); 906 updatePersonalAppsSuspensionOnUserStart(userHandle); 907 } else if (Intent.ACTION_USER_STOPPED.equals(action)) { 908 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle); 909 if (isManagedProfile(userHandle)) { 910 Slogf.d(LOG_TAG, "Managed profile was stopped"); 911 updatePersonalAppsSuspension(userHandle, false /* unlocked */); 912 } 913 } else if (Intent.ACTION_USER_SWITCHED.equals(action)) { 914 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle); 915 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) { 916 synchronized (getLockObject()) { 917 maybeSendAdminEnabledBroadcastLocked(userHandle); 918 } 919 if (isManagedProfile(userHandle)) { 920 Slogf.d(LOG_TAG, "Managed profile became unlocked"); 921 final boolean suspended = 922 updatePersonalAppsSuspension(userHandle, true /* unlocked */); 923 triggerPolicyComplianceCheckIfNeeded(userHandle, suspended); 924 } 925 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { 926 handlePackagesChanged(null /* check all admins */, userHandle); 927 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { 928 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 929 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { 930 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 931 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 932 } else { 933 handleNewPackageInstalled(intent.getData().getSchemeSpecificPart(), userHandle); 934 } 935 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action) 936 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 937 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 938 removeCredentialManagementApp(intent.getData().getSchemeSpecificPart()); 939 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) { 940 clearWipeProfileNotification(); 941 } else if (Intent.ACTION_DATE_CHANGED.equals(action) 942 || Intent.ACTION_TIME_CHANGED.equals(action)) { 943 // Update freeze period record when clock naturally progresses to the next day 944 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made 945 // (ACTION_TIME_CHANGED) 946 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true); 947 final int userId = getManagedUserId(UserHandle.USER_SYSTEM); 948 if (userId >= 0) { 949 updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked(userId)); 950 } 951 } else if (ACTION_PROFILE_OFF_DEADLINE.equals(action)) { 952 Slogf.i(LOG_TAG, "Profile off deadline alarm was triggered"); 953 final int userId = getManagedUserId(UserHandle.USER_SYSTEM); 954 if (userId >= 0) { 955 updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked(userId)); 956 } else { 957 Slogf.wtf(LOG_TAG, "Got deadline alarm for nonexistent profile"); 958 } 959 } else if (ACTION_TURN_PROFILE_ON_NOTIFICATION.equals(action)) { 960 Slogf.i(LOG_TAG, "requesting to turn on the profile: " + userHandle); 961 mUserManager.requestQuietModeEnabled(false, UserHandle.of(userHandle)); 962 } 963 } 964 965 private void sendDeviceOwnerUserCommand(String action, int userHandle) { 966 synchronized (getLockObject()) { 967 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 968 if (deviceOwner != null) { 969 Bundle extras = new Bundle(); 970 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 971 sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null, 972 /* inForeground */ true); 973 } 974 } 975 } 976 }; 977 978 protected static class RestrictionsListener implements UserRestrictionsListener { 979 private final Context mContext; 980 private final UserManagerInternal mUserManagerInternal; 981 private final DevicePolicyManagerService mDpms; 982 RestrictionsListener( Context context, UserManagerInternal userManagerInternal, DevicePolicyManagerService dpms)983 public RestrictionsListener( 984 Context context, 985 UserManagerInternal userManagerInternal, 986 DevicePolicyManagerService dpms) { 987 mContext = context; 988 mUserManagerInternal = userManagerInternal; 989 mDpms = dpms; 990 } 991 992 @Override onUserRestrictionsChanged(int userId, Bundle newRestrictions, Bundle prevRestrictions)993 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions, 994 Bundle prevRestrictions) { 995 resetCrossProfileIntentFiltersIfNeeded(userId, newRestrictions, prevRestrictions); 996 resetUserVpnIfNeeded(userId, newRestrictions, prevRestrictions); 997 } 998 resetUserVpnIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)999 private void resetUserVpnIfNeeded( 1000 int userId, Bundle newRestrictions, Bundle prevRestrictions) { 1001 final boolean newlyEnforced = 1002 !prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN) 1003 && newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN); 1004 if (newlyEnforced) { 1005 mDpms.clearUserConfiguredVpns(userId); 1006 } 1007 } 1008 resetCrossProfileIntentFiltersIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1009 private void resetCrossProfileIntentFiltersIfNeeded( 1010 int userId, Bundle newRestrictions, Bundle prevRestrictions) { 1011 if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions, 1012 UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE)) { 1013 final int parentId = mUserManagerInternal.getProfileParentId(userId); 1014 if (parentId == userId) { 1015 return; 1016 } 1017 1018 // Always reset filters on the parent user, which handles cross profile intent 1019 // filters between the parent and its profiles. 1020 Slogf.i(LOG_TAG, "Resetting cross-profile intent filters on restriction " 1021 + "change"); 1022 mDpms.resetDefaultCrossProfileIntentFilters(parentId); 1023 mContext.sendBroadcastAsUser( 1024 new Intent(DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_APPLIED), 1025 UserHandle.of(userId)); 1026 } 1027 } 1028 } 1029 clearUserConfiguredVpns(int userId)1030 private void clearUserConfiguredVpns(int userId) { 1031 final String adminConfiguredVpnPkg; 1032 synchronized (getLockObject()) { 1033 final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 1034 if (owner == null) { 1035 Slogf.wtf(LOG_TAG, "Admin not found"); 1036 return; 1037 } 1038 adminConfiguredVpnPkg = owner.mAlwaysOnVpnPackage; 1039 } 1040 1041 // Clear always-on configuration if it wasn't set by the admin. 1042 if (adminConfiguredVpnPkg == null) { 1043 mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(userId, null, false, null); 1044 } 1045 1046 // Clear app authorizations to establish VPNs. When DISALLOW_CONFIG_VPN is enforced apps 1047 // won't be able to get those authorizations unless it is configured by an admin. 1048 final List<AppOpsManager.PackageOps> allVpnOps = mInjector.getAppOpsManager() 1049 .getPackagesForOps(new int[] {AppOpsManager.OP_ACTIVATE_VPN}); 1050 if (allVpnOps == null) { 1051 return; 1052 } 1053 for (AppOpsManager.PackageOps pkgOps : allVpnOps) { 1054 if (UserHandle.getUserId(pkgOps.getUid()) != userId 1055 || pkgOps.getPackageName().equals(adminConfiguredVpnPkg)) { 1056 continue; 1057 } 1058 if (pkgOps.getOps().size() != 1) { 1059 Slogf.wtf(LOG_TAG, "Unexpected number of ops returned"); 1060 continue; 1061 } 1062 final @Mode int mode = pkgOps.getOps().get(0).getMode(); 1063 if (mode == MODE_ALLOWED) { 1064 Slogf.i(LOG_TAG, String.format("Revoking VPN authorization for package %s uid %d", 1065 pkgOps.getPackageName(), pkgOps.getUid())); 1066 mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN, pkgOps.getUid(), 1067 pkgOps.getPackageName(), MODE_DEFAULT); 1068 } 1069 } 1070 } 1071 1072 private final class UserLifecycleListener implements UserManagerInternal.UserLifecycleListener { 1073 1074 @Override onUserCreated(UserInfo user, Object token)1075 public void onUserCreated(UserInfo user, Object token) { 1076 mHandler.post(() -> handleNewUserCreated(user, token)); 1077 } 1078 } 1079 handlePackagesChanged(@ullable String packageName, int userHandle)1080 private void handlePackagesChanged(@Nullable String packageName, int userHandle) { 1081 boolean removedAdmin = false; 1082 if (VERBOSE_LOG) { 1083 Slogf.d(LOG_TAG, "Handling package changes package " + packageName 1084 + " for user " + userHandle); 1085 } 1086 DevicePolicyData policy = getUserData(userHandle); 1087 synchronized (getLockObject()) { 1088 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 1089 ActiveAdmin aa = policy.mAdminList.get(i); 1090 try { 1091 // If we're checking all packages or if the specific one we're checking matches, 1092 // then check if the package and receiver still exist. 1093 final String adminPackage = aa.info.getPackageName(); 1094 if (packageName == null || packageName.equals(adminPackage)) { 1095 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null 1096 || mIPackageManager.getReceiverInfo(aa.info.getComponent(), 1097 PackageManager.MATCH_DIRECT_BOOT_AWARE 1098 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 1099 userHandle) == null) { 1100 removedAdmin = true; 1101 policy.mAdminList.remove(i); 1102 policy.mAdminMap.remove(aa.info.getComponent()); 1103 pushActiveAdminPackagesLocked(userHandle); 1104 pushMeteredDisabledPackagesLocked(userHandle); 1105 } 1106 } 1107 } catch (RemoteException re) { 1108 // Shouldn't happen. 1109 } 1110 } 1111 if (removedAdmin) { 1112 policy.validatePasswordOwner(); 1113 } 1114 1115 boolean removedDelegate = false; 1116 1117 // Check if a delegate was removed. 1118 for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) { 1119 final String delegatePackage = policy.mDelegationMap.keyAt(i); 1120 if (isRemovedPackage(packageName, delegatePackage, userHandle)) { 1121 policy.mDelegationMap.removeAt(i); 1122 removedDelegate = true; 1123 } 1124 } 1125 1126 // If it's an owner package, we may need to refresh the bound connection. 1127 final ComponentName owner = getOwnerComponent(userHandle); 1128 if ((packageName != null) && (owner != null) 1129 && (owner.getPackageName().equals(packageName))) { 1130 startOwnerService(userHandle, "package-broadcast"); 1131 } 1132 1133 // Persist updates if the removed package was an admin or delegate. 1134 if (removedAdmin || removedDelegate) { 1135 saveSettingsLocked(policy.mUserId); 1136 } 1137 } 1138 if (removedAdmin) { 1139 // The removed admin might have disabled camera, so update user restrictions. 1140 pushUserRestrictions(userHandle); 1141 } 1142 } 1143 removeCredentialManagementApp(String packageName)1144 private void removeCredentialManagementApp(String packageName) { 1145 mBackgroundHandler.post(() -> { 1146 try (KeyChainConnection connection = mInjector.keyChainBind()) { 1147 IKeyChainService service = connection.getService(); 1148 if (service.hasCredentialManagementApp() 1149 && packageName.equals(service.getCredentialManagementAppPackageName())) { 1150 service.removeCredentialManagementApp(); 1151 } 1152 } catch (RemoteException | InterruptedException | IllegalStateException e) { 1153 Slogf.e(LOG_TAG, "Unable to remove the credential management app"); 1154 } 1155 }); 1156 } 1157 isRemovedPackage(String changedPackage, String targetPackage, int userHandle)1158 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) { 1159 try { 1160 return targetPackage != null 1161 && (changedPackage == null || changedPackage.equals(targetPackage)) 1162 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null; 1163 } catch (RemoteException e) { 1164 // Shouldn't happen 1165 } 1166 1167 return false; 1168 } 1169 handleNewPackageInstalled(String packageName, int userHandle)1170 private void handleNewPackageInstalled(String packageName, int userHandle) { 1171 // If personal apps were suspended by the admin, suspend the newly installed one. 1172 if (!getUserData(userHandle).mAppsSuspended) { 1173 return; 1174 } 1175 final String[] packagesToSuspend = { packageName }; 1176 // Check if package is considered not suspendable? 1177 if (mInjector.getPackageManager(userHandle) 1178 .getUnsuspendablePackages(packagesToSuspend).length != 0) { 1179 Slogf.i(LOG_TAG, "Newly installed package is unsuspendable: " + packageName); 1180 return; 1181 } 1182 try { 1183 mIPackageManager.setPackagesSuspendedAsUser(packagesToSuspend, true /*suspend*/, 1184 null, null, null, PLATFORM_PACKAGE_NAME, userHandle); 1185 } catch (RemoteException ignored) { 1186 // shouldn't happen. 1187 } 1188 } 1189 1190 @Override setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1191 public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) { 1192 CallerIdentity callerIdentity = getCallerIdentity(); 1193 Preconditions.checkCallAuthorization(mIsAutomotive || isAdb(callerIdentity), "can only set " 1194 + "DevicePolicySafetyChecker on automotive builds or from ADB (but caller is %s)", 1195 callerIdentity); 1196 setDevicePolicySafetyCheckerUnchecked(safetyChecker); 1197 } 1198 1199 /** 1200 * Used by {@code setDevicePolicySafetyChecker()} above and {@link OneTimeSafetyChecker}. 1201 */ setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker)1202 void setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker) { 1203 Slogf.i(LOG_TAG, "Setting DevicePolicySafetyChecker as %s", safetyChecker); 1204 mSafetyChecker = safetyChecker; 1205 mInjector.setDevicePolicySafetyChecker(safetyChecker); 1206 } 1207 1208 /** 1209 * Used by {@link OneTimeSafetyChecker} only. 1210 */ getDevicePolicySafetyChecker()1211 DevicePolicySafetyChecker getDevicePolicySafetyChecker() { 1212 return mSafetyChecker; 1213 } 1214 1215 /** 1216 * Checks if it's safe to execute the given {@code operation}. 1217 * 1218 * @throws UnsafeStateException if it's not safe to execute the operation. 1219 */ checkCanExecuteOrThrowUnsafe(@evicePolicyOperation int operation)1220 private void checkCanExecuteOrThrowUnsafe(@DevicePolicyOperation int operation) { 1221 int reason = getUnsafeOperationReason(operation); 1222 if (reason == OPERATION_SAFETY_REASON_NONE) return; 1223 1224 if (mSafetyChecker == null) { 1225 // Happens on CTS after it's set just once (by OneTimeSafetyChecker) 1226 throw new UnsafeStateException(operation, reason); 1227 } 1228 // Let mSafetyChecker customize it (for example, by explaining how to retry) 1229 throw mSafetyChecker.newUnsafeStateException(operation, reason); 1230 } 1231 1232 /** 1233 * Returns whether it's safe to execute the given {@code operation}, and why. 1234 */ 1235 @OperationSafetyReason getUnsafeOperationReason(@evicePolicyOperation int operation)1236 int getUnsafeOperationReason(@DevicePolicyOperation int operation) { 1237 return mSafetyChecker == null ? OPERATION_SAFETY_REASON_NONE 1238 : mSafetyChecker.getUnsafeOperationReason(operation); 1239 } 1240 1241 @Override setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)1242 public void setNextOperationSafety(@DevicePolicyOperation int operation, 1243 @OperationSafetyReason int reason) { 1244 Preconditions.checkCallAuthorization( 1245 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 1246 Slogf.i(LOG_TAG, "setNextOperationSafety(%s, %s)", 1247 DevicePolicyManager.operationToString(operation), 1248 DevicePolicyManager.operationSafetyReasonToString(reason)); 1249 mSafetyChecker = new OneTimeSafetyChecker(this, operation, reason); 1250 } 1251 1252 @Override isSafeOperation(@perationSafetyReason int reason)1253 public boolean isSafeOperation(@OperationSafetyReason int reason) { 1254 if (VERBOSE_LOG) { 1255 Slogf.v(LOG_TAG, "checking isSafeOperation(%s) using mSafetyChecker %s", 1256 DevicePolicyManager.operationSafetyReasonToString(reason), mSafetyChecker); 1257 } 1258 return mSafetyChecker == null ? true : mSafetyChecker.isSafeOperation(reason); 1259 } 1260 1261 // Used by DevicePolicyManagerServiceShellCommand listAllOwners()1262 List<OwnerDto> listAllOwners() { 1263 Preconditions.checkCallAuthorization( 1264 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 1265 return mInjector.binderWithCleanCallingIdentity(() -> { 1266 List<OwnerDto> owners = mOwners.listAllOwners(); 1267 synchronized (getLockObject()) { 1268 for (int i = 0; i < owners.size(); i++) { 1269 OwnerDto owner = owners.get(i); 1270 owner.isAffiliated = isUserAffiliatedWithDeviceLocked(owner.userId); 1271 } 1272 } 1273 return owners; 1274 }); 1275 } 1276 1277 /** 1278 * Unit test will subclass it to inject mocks. 1279 */ 1280 @VisibleForTesting 1281 static class Injector { 1282 1283 public final Context mContext; 1284 1285 private @Nullable DevicePolicySafetyChecker mSafetyChecker; 1286 Injector(Context context)1287 Injector(Context context) { 1288 mContext = context; 1289 } 1290 hasFeature()1291 public boolean hasFeature() { 1292 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN); 1293 } 1294 createContextAsUser(UserHandle user)1295 Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException { 1296 final String packageName = mContext.getPackageName(); 1297 return mContext.createPackageContextAsUser(packageName, 0, user); 1298 } 1299 getResources()1300 Resources getResources() { 1301 return mContext.getResources(); 1302 } 1303 newOwners()1304 Owners newOwners() { 1305 return new Owners(getUserManager(), getUserManagerInternal(), 1306 getPackageManagerInternal(), getActivityTaskManagerInternal(), 1307 getActivityManagerInternal()); 1308 } 1309 getUserManager()1310 UserManager getUserManager() { 1311 return UserManager.get(mContext); 1312 } 1313 getUserManagerInternal()1314 UserManagerInternal getUserManagerInternal() { 1315 return LocalServices.getService(UserManagerInternal.class); 1316 } 1317 getPackageManagerInternal()1318 PackageManagerInternal getPackageManagerInternal() { 1319 return LocalServices.getService(PackageManagerInternal.class); 1320 } 1321 getActivityTaskManagerInternal()1322 ActivityTaskManagerInternal getActivityTaskManagerInternal() { 1323 return LocalServices.getService(ActivityTaskManagerInternal.class); 1324 } 1325 getPermissionControllerManager( @onNull UserHandle user)1326 @NonNull PermissionControllerManager getPermissionControllerManager( 1327 @NonNull UserHandle user) { 1328 if (user.equals(mContext.getUser())) { 1329 return mContext.getSystemService(PermissionControllerManager.class); 1330 } else { 1331 try { 1332 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, 1333 user).getSystemService(PermissionControllerManager.class); 1334 } catch (NameNotFoundException notPossible) { 1335 // not possible 1336 throw new IllegalStateException(notPossible); 1337 } 1338 } 1339 } 1340 getUsageStatsManagerInternal()1341 UsageStatsManagerInternal getUsageStatsManagerInternal() { 1342 return LocalServices.getService(UsageStatsManagerInternal.class); 1343 } 1344 getNetworkPolicyManagerInternal()1345 NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() { 1346 return LocalServices.getService(NetworkPolicyManagerInternal.class); 1347 } 1348 getNotificationManager()1349 NotificationManager getNotificationManager() { 1350 return mContext.getSystemService(NotificationManager.class); 1351 } 1352 getIIpConnectivityMetrics()1353 IIpConnectivityMetrics getIIpConnectivityMetrics() { 1354 return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface( 1355 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME)); 1356 } 1357 getPackageManager()1358 PackageManager getPackageManager() { 1359 return mContext.getPackageManager(); 1360 } 1361 getPackageManager(int userId)1362 PackageManager getPackageManager(int userId) { 1363 return mContext 1364 .createContextAsUser(UserHandle.of(userId), 0 /* flags */).getPackageManager(); 1365 } 1366 getPowerManagerInternal()1367 PowerManagerInternal getPowerManagerInternal() { 1368 return LocalServices.getService(PowerManagerInternal.class); 1369 } 1370 getTelephonyManager()1371 TelephonyManager getTelephonyManager() { 1372 return mContext.getSystemService(TelephonyManager.class); 1373 } 1374 getTrustManager()1375 TrustManager getTrustManager() { 1376 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE); 1377 } 1378 getAlarmManager()1379 AlarmManager getAlarmManager() { 1380 return mContext.getSystemService(AlarmManager.class); 1381 } 1382 getConnectivityManager()1383 ConnectivityManager getConnectivityManager() { 1384 return mContext.getSystemService(ConnectivityManager.class); 1385 } 1386 getVpnManager()1387 VpnManager getVpnManager() { 1388 return mContext.getSystemService(VpnManager.class); 1389 } 1390 getLocationManager()1391 LocationManager getLocationManager() { 1392 return mContext.getSystemService(LocationManager.class); 1393 } 1394 getIWindowManager()1395 IWindowManager getIWindowManager() { 1396 return IWindowManager.Stub 1397 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)); 1398 } 1399 getIActivityManager()1400 IActivityManager getIActivityManager() { 1401 return ActivityManager.getService(); 1402 } 1403 getIActivityTaskManager()1404 IActivityTaskManager getIActivityTaskManager() { 1405 return ActivityTaskManager.getService(); 1406 } 1407 getActivityManagerInternal()1408 ActivityManagerInternal getActivityManagerInternal() { 1409 return LocalServices.getService(ActivityManagerInternal.class); 1410 } 1411 getIPackageManager()1412 IPackageManager getIPackageManager() { 1413 return AppGlobals.getPackageManager(); 1414 } 1415 getIPermissionManager()1416 IPermissionManager getIPermissionManager() { 1417 return AppGlobals.getPermissionManager(); 1418 } 1419 getIBackupManager()1420 IBackupManager getIBackupManager() { 1421 return IBackupManager.Stub.asInterface( 1422 ServiceManager.getService(Context.BACKUP_SERVICE)); 1423 } 1424 getIAudioService()1425 IAudioService getIAudioService() { 1426 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE)); 1427 } 1428 getPersistentDataBlockManagerInternal()1429 PersistentDataBlockManagerInternal getPersistentDataBlockManagerInternal() { 1430 return LocalServices.getService(PersistentDataBlockManagerInternal.class); 1431 } 1432 getAppOpsManager()1433 AppOpsManager getAppOpsManager() { 1434 return mContext.getSystemService(AppOpsManager.class); 1435 } 1436 getLockSettingsInternal()1437 LockSettingsInternal getLockSettingsInternal() { 1438 return LocalServices.getService(LockSettingsInternal.class); 1439 } 1440 getCrossProfileApps()1441 CrossProfileApps getCrossProfileApps() { 1442 return mContext.getSystemService(CrossProfileApps.class); 1443 } 1444 hasUserSetupCompleted(DevicePolicyData userData)1445 boolean hasUserSetupCompleted(DevicePolicyData userData) { 1446 return userData.mUserSetupComplete; 1447 } 1448 isBuildDebuggable()1449 boolean isBuildDebuggable() { 1450 return Build.IS_DEBUGGABLE; 1451 } 1452 newLockPatternUtils()1453 LockPatternUtils newLockPatternUtils() { 1454 return new LockPatternUtils(mContext); 1455 } 1456 storageManagerIsFileBasedEncryptionEnabled()1457 boolean storageManagerIsFileBasedEncryptionEnabled() { 1458 return StorageManager.isFileEncryptedNativeOnly(); 1459 } 1460 storageManagerIsNonDefaultBlockEncrypted()1461 boolean storageManagerIsNonDefaultBlockEncrypted() { 1462 final long identity = Binder.clearCallingIdentity(); 1463 try { 1464 return StorageManager.isNonDefaultBlockEncrypted(); 1465 } finally { 1466 Binder.restoreCallingIdentity(identity); 1467 } 1468 } 1469 storageManagerIsEncrypted()1470 boolean storageManagerIsEncrypted() { 1471 return StorageManager.isEncrypted(); 1472 } 1473 storageManagerIsEncryptable()1474 boolean storageManagerIsEncryptable() { 1475 return StorageManager.isEncryptable(); 1476 } 1477 getMyLooper()1478 Looper getMyLooper() { 1479 return Looper.myLooper(); 1480 } 1481 getWifiManager()1482 WifiManager getWifiManager() { 1483 return mContext.getSystemService(WifiManager.class); 1484 } 1485 getUsbManager()1486 UsbManager getUsbManager() { 1487 return mContext.getSystemService(UsbManager.class); 1488 } 1489 1490 @SuppressWarnings("AndroidFrameworkBinderIdentity") binderClearCallingIdentity()1491 long binderClearCallingIdentity() { 1492 return Binder.clearCallingIdentity(); 1493 } 1494 1495 @SuppressWarnings("AndroidFrameworkBinderIdentity") binderRestoreCallingIdentity(long token)1496 void binderRestoreCallingIdentity(long token) { 1497 Binder.restoreCallingIdentity(token); 1498 } 1499 binderGetCallingUid()1500 int binderGetCallingUid() { 1501 return Binder.getCallingUid(); 1502 } 1503 binderGetCallingPid()1504 int binderGetCallingPid() { 1505 return Binder.getCallingPid(); 1506 } 1507 binderGetCallingUserHandle()1508 UserHandle binderGetCallingUserHandle() { 1509 return Binder.getCallingUserHandle(); 1510 } 1511 binderIsCallingUidMyUid()1512 boolean binderIsCallingUidMyUid() { 1513 return getCallingUid() == Process.myUid(); 1514 } 1515 binderWithCleanCallingIdentity(@onNull ThrowingRunnable action)1516 void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) { 1517 Binder.withCleanCallingIdentity(action); 1518 } 1519 binderWithCleanCallingIdentity(@onNull ThrowingSupplier<T> action)1520 final <T> T binderWithCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) { 1521 return Binder.withCleanCallingIdentity(action); 1522 } 1523 userHandleGetCallingUserId()1524 final int userHandleGetCallingUserId() { 1525 return UserHandle.getUserId(binderGetCallingUid()); 1526 } 1527 environmentGetUserSystemDirectory(int userId)1528 File environmentGetUserSystemDirectory(int userId) { 1529 return Environment.getUserSystemDirectory(userId); 1530 } 1531 powerManagerGoToSleep(long time, int reason, int flags)1532 void powerManagerGoToSleep(long time, int reason, int flags) { 1533 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags); 1534 } 1535 powerManagerReboot(String reason)1536 void powerManagerReboot(String reason) { 1537 mContext.getSystemService(PowerManager.class).reboot(reason); 1538 } 1539 recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)1540 boolean recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, 1541 boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData) 1542 throws IOException { 1543 return FactoryResetter.newBuilder(mContext).setSafetyChecker(mSafetyChecker) 1544 .setReason(reason).setShutdown(shutdown).setForce(force).setWipeEuicc(wipeEuicc) 1545 .setWipeAdoptableStorage(wipeExtRequested) 1546 .setWipeFactoryResetProtection(wipeResetProtectionData) 1547 .build().factoryReset(); 1548 } 1549 systemPropertiesGetBoolean(String key, boolean def)1550 boolean systemPropertiesGetBoolean(String key, boolean def) { 1551 return SystemProperties.getBoolean(key, def); 1552 } 1553 systemPropertiesGetLong(String key, long def)1554 long systemPropertiesGetLong(String key, long def) { 1555 return SystemProperties.getLong(key, def); 1556 } 1557 systemPropertiesGet(String key, String def)1558 String systemPropertiesGet(String key, String def) { 1559 return SystemProperties.get(key, def); 1560 } 1561 systemPropertiesGet(String key)1562 String systemPropertiesGet(String key) { 1563 return SystemProperties.get(key); 1564 } 1565 systemPropertiesSet(String key, String value)1566 void systemPropertiesSet(String key, String value) { 1567 SystemProperties.set(key, value); 1568 } 1569 userManagerIsHeadlessSystemUserMode()1570 boolean userManagerIsHeadlessSystemUserMode() { 1571 return UserManager.isHeadlessSystemUserMode(); 1572 } 1573 getDevicePolicyFilePathForSystemUser()1574 String getDevicePolicyFilePathForSystemUser() { 1575 return "/data/system/"; 1576 } 1577 1578 @SuppressWarnings("AndroidFrameworkPendingIntentMutability") pendingIntentGetActivityAsUser(Context context, int requestCode, @NonNull Intent intent, int flags, Bundle options, UserHandle user)1579 PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode, 1580 @NonNull Intent intent, int flags, Bundle options, UserHandle user) { 1581 return PendingIntent.getActivityAsUser( 1582 context, requestCode, intent, flags, options, user); 1583 } 1584 1585 @SuppressWarnings("AndroidFrameworkPendingIntentMutability") pendingIntentGetBroadcast( Context context, int requestCode, Intent intent, int flags)1586 PendingIntent pendingIntentGetBroadcast( 1587 Context context, int requestCode, Intent intent, int flags) { 1588 return PendingIntent.getBroadcast(context, requestCode, intent, flags); 1589 } 1590 registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer, int userHandle)1591 void registerContentObserver(Uri uri, boolean notifyForDescendents, 1592 ContentObserver observer, int userHandle) { 1593 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents, 1594 observer, userHandle); 1595 } 1596 settingsSecureGetIntForUser(String name, int def, int userHandle)1597 int settingsSecureGetIntForUser(String name, int def, int userHandle) { 1598 return Settings.Secure.getIntForUser(mContext.getContentResolver(), 1599 name, def, userHandle); 1600 } 1601 settingsSecureGetStringForUser(String name, int userHandle)1602 String settingsSecureGetStringForUser(String name, int userHandle) { 1603 return Settings.Secure.getStringForUser(mContext.getContentResolver(), name, 1604 userHandle); 1605 } 1606 settingsSecurePutIntForUser(String name, int value, int userHandle)1607 void settingsSecurePutIntForUser(String name, int value, int userHandle) { 1608 Settings.Secure.putIntForUser(mContext.getContentResolver(), 1609 name, value, userHandle); 1610 } 1611 settingsSecurePutStringForUser(String name, String value, int userHandle)1612 void settingsSecurePutStringForUser(String name, String value, int userHandle) { 1613 Settings.Secure.putStringForUser(mContext.getContentResolver(), 1614 name, value, userHandle); 1615 } 1616 settingsGlobalPutStringForUser(String name, String value, int userHandle)1617 void settingsGlobalPutStringForUser(String name, String value, int userHandle) { 1618 Settings.Global.putStringForUser(mContext.getContentResolver(), 1619 name, value, userHandle); 1620 } 1621 settingsSecurePutInt(String name, int value)1622 void settingsSecurePutInt(String name, int value) { 1623 Settings.Secure.putInt(mContext.getContentResolver(), name, value); 1624 } 1625 settingsGlobalGetInt(String name, int def)1626 int settingsGlobalGetInt(String name, int def) { 1627 return Settings.Global.getInt(mContext.getContentResolver(), name, def); 1628 } 1629 1630 @Nullable settingsGlobalGetString(String name)1631 String settingsGlobalGetString(String name) { 1632 return Settings.Global.getString(mContext.getContentResolver(), name); 1633 } 1634 settingsGlobalPutInt(String name, int value)1635 void settingsGlobalPutInt(String name, int value) { 1636 Settings.Global.putInt(mContext.getContentResolver(), name, value); 1637 } 1638 settingsSecurePutString(String name, String value)1639 void settingsSecurePutString(String name, String value) { 1640 Settings.Secure.putString(mContext.getContentResolver(), name, value); 1641 } 1642 settingsGlobalPutString(String name, String value)1643 void settingsGlobalPutString(String name, String value) { 1644 Settings.Global.putString(mContext.getContentResolver(), name, value); 1645 } 1646 settingsSystemPutStringForUser(String name, String value, int userId)1647 void settingsSystemPutStringForUser(String name, String value, int userId) { 1648 Settings.System.putStringForUser( 1649 mContext.getContentResolver(), name, value, userId); 1650 } 1651 securityLogSetLoggingEnabledProperty(boolean enabled)1652 void securityLogSetLoggingEnabledProperty(boolean enabled) { 1653 SecurityLog.setLoggingEnabledProperty(enabled); 1654 } 1655 securityLogGetLoggingEnabledProperty()1656 boolean securityLogGetLoggingEnabledProperty() { 1657 return SecurityLog.getLoggingEnabledProperty(); 1658 } 1659 securityLogIsLoggingEnabled()1660 boolean securityLogIsLoggingEnabled() { 1661 return SecurityLog.isLoggingEnabled(); 1662 } 1663 keyChainBind()1664 KeyChainConnection keyChainBind() throws InterruptedException { 1665 return KeyChain.bind(mContext); 1666 } 1667 keyChainBindAsUser(UserHandle user)1668 KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException { 1669 return KeyChain.bindAsUser(mContext, user); 1670 } 1671 postOnSystemServerInitThreadPool(Runnable runnable)1672 void postOnSystemServerInitThreadPool(Runnable runnable) { 1673 SystemServerInitThreadPool.submit(runnable, LOG_TAG); 1674 } 1675 newTransferOwnershipMetadataManager()1676 public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() { 1677 return new TransferOwnershipMetadataManager(); 1678 } 1679 runCryptoSelfTest()1680 public void runCryptoSelfTest() { 1681 CryptoTestHelper.runAndLogSelfTest(); 1682 } 1683 getPersonalAppsForSuspension(@serIdInt int userId)1684 public String[] getPersonalAppsForSuspension(@UserIdInt int userId) { 1685 return PersonalAppsSuspensionHelper.forUser(mContext, userId) 1686 .getPersonalAppsForSuspension(); 1687 } 1688 systemCurrentTimeMillis()1689 public long systemCurrentTimeMillis() { 1690 return System.currentTimeMillis(); 1691 } 1692 isChangeEnabled(long changeId, String packageName, int userId)1693 public boolean isChangeEnabled(long changeId, String packageName, int userId) { 1694 return CompatChanges.isChangeEnabled(changeId, packageName, UserHandle.of(userId)); 1695 } 1696 setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1697 void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) { 1698 mSafetyChecker = safetyChecker; 1699 } 1700 } 1701 1702 /** 1703 * Instantiates the service. 1704 */ DevicePolicyManagerService(Context context)1705 public DevicePolicyManagerService(Context context) { 1706 this(new Injector(context)); 1707 } 1708 1709 @VisibleForTesting DevicePolicyManagerService(Injector injector)1710 DevicePolicyManagerService(Injector injector) { 1711 mInjector = injector; 1712 mContext = Objects.requireNonNull(injector.mContext); 1713 mHandler = new Handler(Objects.requireNonNull(injector.getMyLooper())); 1714 1715 mConstantsObserver = new DevicePolicyConstantsObserver(mHandler); 1716 mConstantsObserver.register(); 1717 mConstants = loadConstants(); 1718 1719 mOwners = Objects.requireNonNull(injector.newOwners()); 1720 1721 mUserManager = Objects.requireNonNull(injector.getUserManager()); 1722 mUserManagerInternal = Objects.requireNonNull(injector.getUserManagerInternal()); 1723 mUsageStatsManagerInternal = Objects.requireNonNull( 1724 injector.getUsageStatsManagerInternal()); 1725 mIPackageManager = Objects.requireNonNull(injector.getIPackageManager()); 1726 mIPermissionManager = Objects.requireNonNull(injector.getIPermissionManager()); 1727 mTelephonyManager = Objects.requireNonNull(injector.getTelephonyManager()); 1728 1729 mLocalService = new LocalService(); 1730 mLockPatternUtils = injector.newLockPatternUtils(); 1731 mLockSettingsInternal = injector.getLockSettingsInternal(); 1732 // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false? 1733 mSecurityLogMonitor = new SecurityLogMonitor(this); 1734 1735 mHasFeature = mInjector.hasFeature(); 1736 mIsWatch = mInjector.getPackageManager() 1737 .hasSystemFeature(PackageManager.FEATURE_WATCH); 1738 mHasTelephonyFeature = mInjector.getPackageManager() 1739 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY); 1740 mIsAutomotive = mInjector.getPackageManager() 1741 .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE); 1742 mBackgroundHandler = BackgroundThread.getHandler(); 1743 1744 // Needed when mHasFeature == false, because it controls the certificate warning text. 1745 mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler); 1746 1747 mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants); 1748 mOverlayPackagesProvider = new OverlayPackagesProvider(mContext); 1749 mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager(); 1750 mBugreportCollectionManager = new RemoteBugreportManager(this, mInjector); 1751 1752 // "Lite" interface is available even when the device doesn't have the feature 1753 LocalServices.addService(DevicePolicyManagerLiteInternal.class, mLocalService); 1754 if (!mHasFeature) { 1755 // Skip the rest of the initialization 1756 mSetupContentObserver = null; 1757 return; 1758 } 1759 1760 IntentFilter filter = new IntentFilter(); 1761 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 1762 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION); 1763 filter.addAction(ACTION_TURN_PROFILE_ON_NOTIFICATION); 1764 filter.addAction(ACTION_PROFILE_OFF_DEADLINE); 1765 filter.addAction(Intent.ACTION_USER_ADDED); 1766 filter.addAction(Intent.ACTION_USER_REMOVED); 1767 filter.addAction(Intent.ACTION_USER_STARTED); 1768 filter.addAction(Intent.ACTION_USER_STOPPED); 1769 filter.addAction(Intent.ACTION_USER_SWITCHED); 1770 filter.addAction(Intent.ACTION_USER_UNLOCKED); 1771 filter.addAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE); 1772 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 1773 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1774 filter = new IntentFilter(); 1775 filter.addAction(Intent.ACTION_PACKAGE_CHANGED); 1776 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 1777 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 1778 filter.addAction(Intent.ACTION_PACKAGE_ADDED); 1779 filter.addDataScheme("package"); 1780 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1781 filter = new IntentFilter(); 1782 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED); 1783 filter.addAction(Intent.ACTION_TIME_CHANGED); 1784 filter.addAction(Intent.ACTION_DATE_CHANGED); 1785 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1786 1787 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService); 1788 1789 mSetupContentObserver = new SetupContentObserver(mHandler); 1790 1791 mUserManagerInternal.addUserRestrictionsListener( 1792 new RestrictionsListener(mContext, mUserManagerInternal, this)); 1793 mUserManagerInternal.addUserLifecycleListener(new UserLifecycleListener()); 1794 1795 loadOwners(); 1796 } 1797 1798 /** 1799 * Creates and loads the policy data from xml. 1800 * @param userHandle the user for whom to load the policy data 1801 * @return 1802 */ 1803 @NonNull getUserData(int userHandle)1804 DevicePolicyData getUserData(int userHandle) { 1805 synchronized (getLockObject()) { 1806 DevicePolicyData policy = mUserData.get(userHandle); 1807 if (policy == null) { 1808 policy = new DevicePolicyData(userHandle); 1809 mUserData.append(userHandle, policy); 1810 loadSettingsLocked(policy, userHandle); 1811 if (userHandle == UserHandle.USER_SYSTEM) { 1812 mStateCache.setDeviceProvisioned(policy.mUserSetupComplete); 1813 } 1814 1815 migrateDeviceOwnerProtectedPackagesToOwners(userHandle, policy); 1816 } 1817 return policy; 1818 } 1819 } 1820 1821 /** 1822 * Only used by {@link #getUserData(int)} to migrate <b>existing</b> device owner protected 1823 * packages that were stored in {@link DevicePolicyData#mUserControlDisabledPackages} to 1824 * {@link Owners} because the device owner protected packages are now stored on a per device 1825 * owner basis instead of on a per user basis. 1826 * 1827 * Any calls to {@link #setUserControlDisabledPackages(ComponentName, List)} would now store 1828 * the device owner protected packages in {@link Owners} instead of {@link DevicePolicyData}. 1829 * @param userHandle The device owner user 1830 * @param policy The policy data of the device owner user 1831 */ migrateDeviceOwnerProtectedPackagesToOwners( int userHandle, DevicePolicyData policy)1832 private void migrateDeviceOwnerProtectedPackagesToOwners( 1833 int userHandle, DevicePolicyData policy) { 1834 ComponentName deviceOwnerComponent = getOwnerComponent(userHandle); 1835 if (isDeviceOwner(deviceOwnerComponent, userHandle) 1836 && !policy.mUserControlDisabledPackages.isEmpty()) { 1837 mOwners.setDeviceOwnerProtectedPackages( 1838 deviceOwnerComponent.getPackageName(), 1839 policy.mUserControlDisabledPackages); 1840 1841 policy.mUserControlDisabledPackages = new ArrayList<>(); 1842 saveSettingsLocked(userHandle); 1843 } 1844 } 1845 1846 /** 1847 * Creates and loads the policy data from xml for data that is shared between 1848 * various profiles of a user. In contrast to {@link #getUserData(int)} 1849 * it allows access to data of users other than the calling user. 1850 * 1851 * This function should only be used for shared data, e.g. everything regarding 1852 * passwords and should be removed once multiple screen locks are present. 1853 * @param userHandle the user for whom to load the policy data 1854 * @return 1855 */ getUserDataUnchecked(int userHandle)1856 DevicePolicyData getUserDataUnchecked(int userHandle) { 1857 return mInjector.binderWithCleanCallingIdentity(() -> getUserData(userHandle)); 1858 } 1859 removeUserData(int userHandle)1860 void removeUserData(int userHandle) { 1861 final boolean isOrgOwned; 1862 synchronized (getLockObject()) { 1863 if (userHandle == UserHandle.USER_SYSTEM) { 1864 Slogf.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring."); 1865 return; 1866 } 1867 updatePasswordQualityCacheForUserGroup(userHandle); 1868 mPolicyCache.onUserRemoved(userHandle); 1869 1870 isOrgOwned = mOwners.isProfileOwnerOfOrganizationOwnedDevice(userHandle); 1871 1872 mOwners.removeProfileOwner(userHandle); 1873 mOwners.writeProfileOwner(userHandle); 1874 1875 DevicePolicyData policy = mUserData.get(userHandle); 1876 if (policy != null) { 1877 mUserData.remove(userHandle); 1878 } 1879 1880 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle), 1881 DEVICE_POLICIES_XML); 1882 policyFile.delete(); 1883 Slogf.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath()); 1884 } 1885 if (isOrgOwned) { 1886 final UserInfo primaryUser = mUserManager.getPrimaryUser(); 1887 if (primaryUser != null) { 1888 clearOrgOwnedProfileOwnerDeviceWidePolicies(primaryUser.id); 1889 } else { 1890 Slogf.wtf(LOG_TAG, "Was unable to get primary user."); 1891 } 1892 } 1893 } 1894 1895 /** 1896 * Load information about device and profile owners of the device, populating mOwners and 1897 * pushing owner info to other system services. This is called at a fairly early stage of 1898 * system server initialiation (via DevicePolicyManagerService's ctor), so care should to 1899 * be taken to not interact with system services that are initialiated after DPMS. 1900 * onLockSettingsReady() is a safer place to do initialization work not critical during 1901 * the first boot stage. 1902 * Note this only loads the list of owners, and not their actual policy (DevicePolicyData). 1903 * The policy is normally loaded lazily when it's first accessed. In several occasions 1904 * the list of owners is necessary for providing callers with aggregated policies across 1905 * multiple owners, hence the owner list is loaded as part of DPMS's construction here. 1906 */ loadOwners()1907 void loadOwners() { 1908 synchronized (getLockObject()) { 1909 mOwners.load(); 1910 setDeviceOwnershipSystemPropertyLocked(); 1911 findOwnerComponentIfNecessaryLocked(); 1912 1913 // TODO PO may not have a class name either due to b/17652534. Address that too. 1914 updateDeviceOwnerLocked(); 1915 } 1916 } 1917 1918 /** 1919 * Creates a new {@link CallerIdentity} object to represent the caller's identity. 1920 */ getCallerIdentity()1921 private CallerIdentity getCallerIdentity() { 1922 return getCallerIdentity(null, null); 1923 } 1924 1925 /** 1926 * Creates a new {@link CallerIdentity} object to represent the caller's identity. 1927 */ getCallerIdentity(@ullable String callerPackage)1928 private CallerIdentity getCallerIdentity(@Nullable String callerPackage) { 1929 1930 return getCallerIdentity(null, callerPackage); 1931 } 1932 1933 /** 1934 * Creates a new {@link CallerIdentity} object to represent the caller's identity. 1935 * The component name should be an active admin for the calling user. 1936 */ 1937 @VisibleForTesting getCallerIdentity(@ullable ComponentName adminComponent)1938 CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent) { 1939 return getCallerIdentity(adminComponent, null); 1940 } 1941 1942 /** 1943 * Creates a new {@link CallerIdentity} object to represent the caller's identity. 1944 * If {@code adminComponent} is provided, it's validated against the list of known 1945 * active admins and caller uid. If {@code callerPackage} is provided, it's validated 1946 * against the caller uid. If a valid {@code adminComponent} is provided but not 1947 * {@code callerPackage}, the package name of the {@code adminComponent} is used instead. 1948 */ 1949 @VisibleForTesting getCallerIdentity(@ullable ComponentName adminComponent, @Nullable String callerPackage)1950 CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent, 1951 @Nullable String callerPackage) { 1952 final int callerUid = mInjector.binderGetCallingUid(); 1953 1954 if (callerPackage != null) { 1955 if (!isCallingFromPackage(callerPackage, callerUid)) { 1956 throw new SecurityException( 1957 String.format("Caller with uid %d is not %s", callerUid, callerPackage)); 1958 } 1959 } 1960 1961 if (adminComponent != null) { 1962 final DevicePolicyData policy = getUserData(UserHandle.getUserId(callerUid)); 1963 ActiveAdmin admin = policy.mAdminMap.get(adminComponent); 1964 1965 if (admin == null) { 1966 throw new SecurityException(String.format( 1967 "No active admin for %s", adminComponent)); 1968 } 1969 if (admin.getUid() != callerUid) { 1970 throw new SecurityException(String.format( 1971 "Admin %s is not owned by uid %d", adminComponent, callerUid)); 1972 } 1973 if (callerPackage != null) { 1974 Preconditions.checkArgument(callerPackage.equals(adminComponent.getPackageName())); 1975 } else { 1976 callerPackage = adminComponent.getPackageName(); 1977 } 1978 } 1979 1980 return new CallerIdentity(callerUid, callerPackage, adminComponent); 1981 } 1982 1983 /** 1984 * Checks if the device is in COMP mode, and if so migrates it to managed profile on a 1985 * corporate owned device. 1986 */ 1987 @GuardedBy("getLockObject()") migrateToProfileOnOrganizationOwnedDeviceIfCompLocked()1988 private void migrateToProfileOnOrganizationOwnedDeviceIfCompLocked() { 1989 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Checking whether we need to migrate COMP "); 1990 final int doUserId = mOwners.getDeviceOwnerUserId(); 1991 if (doUserId == UserHandle.USER_NULL) { 1992 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping migration."); 1993 return; 1994 } 1995 1996 final List<UserInfo> profiles = mUserManager.getProfiles(doUserId); 1997 if (profiles.size() != 2) { 1998 if (profiles.size() == 1) { 1999 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Profile not found, skipping migration."); 2000 } else { 2001 Slogf.wtf(LOG_TAG, "Found " + profiles.size() + " profiles, skipping migration"); 2002 } 2003 return; 2004 } 2005 2006 final int poUserId = getManagedUserId(doUserId); 2007 if (poUserId < 0) { 2008 Slogf.wtf(LOG_TAG, "Found DO and a profile, but it is not managed, skipping migration"); 2009 return; 2010 } 2011 2012 final ActiveAdmin doAdmin = getDeviceOwnerAdminLocked(); 2013 final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(poUserId); 2014 if (doAdmin == null || poAdmin == null) { 2015 Slogf.wtf(LOG_TAG, "Failed to get either PO or DO admin, aborting migration."); 2016 return; 2017 } 2018 2019 final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent(); 2020 final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(poUserId); 2021 if (doAdminComponent == null || poAdminComponent == null) { 2022 Slogf.wtf(LOG_TAG, "Cannot find PO or DO component name, aborting migration."); 2023 return; 2024 } 2025 if (!doAdminComponent.getPackageName().equals(poAdminComponent.getPackageName())) { 2026 Slogf.e(LOG_TAG, "DO and PO are different packages, aborting migration."); 2027 return; 2028 } 2029 2030 Slogf.i(LOG_TAG, "Migrating COMP to PO on a corp owned device; primary user: %d; " 2031 + "profile: %d", doUserId, poUserId); 2032 2033 Slogf.i(LOG_TAG, "Giving the PO additional power..."); 2034 markProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(poAdminComponent, poUserId); 2035 Slogf.i(LOG_TAG, "Migrating DO policies to PO..."); 2036 moveDoPoliciesToProfileParentAdminLocked(doAdmin, poAdmin.getParentActiveAdmin()); 2037 migratePersonalAppSuspensionLocked(doUserId, poUserId, poAdmin); 2038 saveSettingsLocked(poUserId); 2039 Slogf.i(LOG_TAG, "Clearing the DO..."); 2040 final ComponentName doAdminReceiver = doAdmin.info.getComponent(); 2041 clearDeviceOwnerLocked(doAdmin, doUserId); 2042 Slogf.i(LOG_TAG, "Removing admin artifacts..."); 2043 removeAdminArtifacts(doAdminReceiver, doUserId); 2044 Slogf.i(LOG_TAG, "Uninstalling the DO..."); 2045 uninstallOrDisablePackage(doAdminComponent.getPackageName(), doUserId); 2046 Slogf.i(LOG_TAG, "Migration complete."); 2047 2048 // Note: KeyChain keys are not removed and will remain accessible for the apps that have 2049 // been given grants to use them. 2050 2051 DevicePolicyEventLogger 2052 .createEvent(DevicePolicyEnums.COMP_TO_ORG_OWNED_PO_MIGRATED) 2053 .setAdmin(poAdminComponent) 2054 .write(); 2055 } 2056 2057 @GuardedBy("getLockObject()") migratePersonalAppSuspensionLocked( int doUserId, int poUserId, ActiveAdmin poAdmin)2058 private void migratePersonalAppSuspensionLocked( 2059 int doUserId, int poUserId, ActiveAdmin poAdmin) { 2060 final PackageManagerInternal pmi = mInjector.getPackageManagerInternal(); 2061 if (!pmi.isSuspendingAnyPackages(PLATFORM_PACKAGE_NAME, doUserId)) { 2062 Slogf.i(LOG_TAG, "DO is not suspending any apps."); 2063 return; 2064 } 2065 2066 if (getTargetSdk(poAdmin.info.getPackageName(), poUserId) >= Build.VERSION_CODES.R) { 2067 Slogf.i(LOG_TAG, "PO is targeting R+, keeping personal apps suspended."); 2068 getUserData(doUserId).mAppsSuspended = true; 2069 poAdmin.mSuspendPersonalApps = true; 2070 } else { 2071 Slogf.i(LOG_TAG, "PO isn't targeting R+, unsuspending personal apps."); 2072 pmi.unsuspendForSuspendingPackage(PLATFORM_PACKAGE_NAME, doUserId); 2073 } 2074 } 2075 uninstallOrDisablePackage(String packageName, @UserIdInt int userId)2076 private void uninstallOrDisablePackage(String packageName, @UserIdInt int userId) { 2077 final ApplicationInfo appInfo; 2078 try { 2079 appInfo = mIPackageManager.getApplicationInfo( 2080 packageName, MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId); 2081 } catch (RemoteException e) { 2082 // Shouldn't happen. 2083 return; 2084 } 2085 if (appInfo == null) { 2086 Slogf.wtf(LOG_TAG, "Failed to get package info for " + packageName); 2087 return; 2088 } 2089 if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 2090 Slogf.i(LOG_TAG, "Package %s is pre-installed, marking disabled until used", 2091 packageName); 2092 mContext.getPackageManager().setApplicationEnabledSetting(packageName, 2093 PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, /* flags= */ 0); 2094 return; 2095 } 2096 2097 final IIntentSender.Stub mLocalSender = new IIntentSender.Stub() { 2098 @Override 2099 public void send(int code, Intent intent, String resolvedType, IBinder allowlistToken, 2100 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 2101 final int status = intent.getIntExtra( 2102 PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE); 2103 if (status == PackageInstaller.STATUS_SUCCESS) { 2104 Slogf.i(LOG_TAG, "Package %s uninstalled for user %d", packageName, userId); 2105 } else { 2106 Slogf.e(LOG_TAG, "Failed to uninstall %s; status: %d", packageName, status); 2107 } 2108 } 2109 }; 2110 2111 final PackageInstaller pi = mInjector.getPackageManager(userId).getPackageInstaller(); 2112 pi.uninstall(packageName, /* flags= */ 0, new IntentSender((IIntentSender) mLocalSender)); 2113 } 2114 2115 @GuardedBy("getLockObject()") moveDoPoliciesToProfileParentAdminLocked( ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2116 private void moveDoPoliciesToProfileParentAdminLocked( 2117 ActiveAdmin doAdmin, ActiveAdmin parentAdmin) { 2118 // The following policies can be already controlled via parent instance, skip if so. 2119 if (parentAdmin.mPasswordPolicy.quality == PASSWORD_QUALITY_UNSPECIFIED) { 2120 parentAdmin.mPasswordPolicy = doAdmin.mPasswordPolicy; 2121 } 2122 if (parentAdmin.passwordHistoryLength == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) { 2123 parentAdmin.passwordHistoryLength = doAdmin.passwordHistoryLength; 2124 } 2125 if (parentAdmin.passwordExpirationTimeout == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) { 2126 parentAdmin.passwordExpirationTimeout = doAdmin.passwordExpirationTimeout; 2127 } 2128 if (parentAdmin.maximumFailedPasswordsForWipe 2129 == ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 2130 parentAdmin.maximumFailedPasswordsForWipe = doAdmin.maximumFailedPasswordsForWipe; 2131 } 2132 if (parentAdmin.maximumTimeToUnlock == ActiveAdmin.DEF_MAXIMUM_TIME_TO_UNLOCK) { 2133 parentAdmin.maximumTimeToUnlock = doAdmin.maximumTimeToUnlock; 2134 } 2135 if (parentAdmin.strongAuthUnlockTimeout 2136 == DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 2137 parentAdmin.strongAuthUnlockTimeout = doAdmin.strongAuthUnlockTimeout; 2138 } 2139 parentAdmin.disabledKeyguardFeatures |= 2140 doAdmin.disabledKeyguardFeatures & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 2141 2142 parentAdmin.trustAgentInfos.putAll(doAdmin.trustAgentInfos); 2143 2144 // The following policies weren't available to PO, but will be available after migration. 2145 parentAdmin.disableCamera = doAdmin.disableCamera; 2146 parentAdmin.disableScreenCapture = doAdmin.disableScreenCapture; 2147 parentAdmin.accountTypesWithManagementDisabled.addAll( 2148 doAdmin.accountTypesWithManagementDisabled); 2149 2150 moveDoUserRestrictionsToCopeParent(doAdmin, parentAdmin); 2151 2152 // From Android 11, {@link setAutoTimeRequired} is no longer used. The user restriction 2153 // {@link UserManager#DISALLOW_CONFIG_DATE_TIME} should be used to enforce auto time 2154 // settings instead. 2155 if (doAdmin.requireAutoTime) { 2156 parentAdmin.ensureUserRestrictions().putBoolean( 2157 UserManager.DISALLOW_CONFIG_DATE_TIME, true); 2158 } 2159 } 2160 moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2161 private void moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin) { 2162 if (doAdmin.userRestrictions == null) { 2163 return; 2164 } 2165 for (final String restriction : doAdmin.userRestrictions.keySet()) { 2166 if (UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(restriction)) { 2167 parentAdmin.ensureUserRestrictions().putBoolean( 2168 restriction, doAdmin.userRestrictions.getBoolean(restriction)); 2169 } 2170 } 2171 } 2172 2173 /** 2174 * If the device is in Device Owner mode, apply the restriction on adding 2175 * a managed profile. 2176 */ 2177 @GuardedBy("getLockObject()") applyManagedProfileRestrictionIfDeviceOwnerLocked()2178 private void applyManagedProfileRestrictionIfDeviceOwnerLocked() { 2179 final int doUserId = mOwners.getDeviceOwnerUserId(); 2180 if (doUserId == UserHandle.USER_NULL) { 2181 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping application of restriction."); 2182 return; 2183 } 2184 2185 final UserHandle doUserHandle = UserHandle.of(doUserId); 2186 // Set the restriction if not set. 2187 if (!mUserManager.hasUserRestriction( 2188 UserManager.DISALLOW_ADD_MANAGED_PROFILE, doUserHandle)) { 2189 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true, 2190 doUserHandle); 2191 } 2192 } 2193 2194 /** Apply default restrictions that haven't been applied to profile owners yet. */ maybeSetDefaultProfileOwnerUserRestrictions()2195 private void maybeSetDefaultProfileOwnerUserRestrictions() { 2196 synchronized (getLockObject()) { 2197 for (final int userId : mOwners.getProfileOwnerKeys()) { 2198 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 2199 // The following restrictions used to be applied to managed profiles by different 2200 // means (via Settings or by disabling components). Now they are proper user 2201 // restrictions so we apply them to managed profile owners. Non-managed secondary 2202 // users didn't have those restrictions so we skip them to keep existing behavior. 2203 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) { 2204 continue; 2205 } 2206 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner, 2207 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 2208 ensureUnknownSourcesRestrictionForProfileOwnerLocked( 2209 userId, profileOwner, false /* newOwner */); 2210 } 2211 } 2212 } 2213 2214 /** 2215 * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the 2216 * set of restrictions for this profile owner. 2217 */ ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, ActiveAdmin profileOwner, boolean newOwner)2218 private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, 2219 ActiveAdmin profileOwner, boolean newOwner) { 2220 if (newOwner || mInjector.settingsSecureGetIntForUser( 2221 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) { 2222 profileOwner.ensureUserRestrictions().putBoolean( 2223 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true); 2224 saveUserRestrictionsLocked(userId); 2225 mInjector.settingsSecurePutIntForUser( 2226 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId); 2227 } 2228 } 2229 2230 /** 2231 * Apply default restrictions that haven't been applied to a given admin yet. 2232 */ maybeSetDefaultRestrictionsForAdminLocked( int userId, ActiveAdmin admin, Set<String> defaultRestrictions)2233 private void maybeSetDefaultRestrictionsForAdminLocked( 2234 int userId, ActiveAdmin admin, Set<String> defaultRestrictions) { 2235 if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) { 2236 return; // The same set of default restrictions has been already applied. 2237 } 2238 Slogf.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId); 2239 2240 if (VERBOSE_LOG) { 2241 Slogf.d(LOG_TAG, "Default enabled restrictions: " 2242 + defaultRestrictions 2243 + ". Restrictions already enabled: " 2244 + admin.defaultEnabledRestrictionsAlreadySet); 2245 } 2246 2247 final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions); 2248 restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet); 2249 if (!restrictionsToSet.isEmpty()) { 2250 for (final String restriction : restrictionsToSet) { 2251 admin.ensureUserRestrictions().putBoolean(restriction, true); 2252 } 2253 admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet); 2254 Slogf.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet); 2255 saveUserRestrictionsLocked(userId); 2256 } 2257 } 2258 setDeviceOwnershipSystemPropertyLocked()2259 private void setDeviceOwnershipSystemPropertyLocked() { 2260 // Still at the first stage of CryptKeeper double bounce, nothing can be learnt about 2261 // the real system at this point. 2262 if (StorageManager.inCryptKeeperBounce()) { 2263 return; 2264 } 2265 final boolean deviceProvisioned = 2266 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0; 2267 final boolean hasDeviceOwner = mOwners.hasDeviceOwner(); 2268 final boolean hasOrgOwnedProfile = isOrganizationOwnedDeviceWithManagedProfile(); 2269 // If the device is not provisioned and there is currently no management, do not set the 2270 // read-only system property yet, since device owner / org-owned profile may still be 2271 // provisioned. 2272 if (!hasDeviceOwner && !hasOrgOwnedProfile && !deviceProvisioned) { 2273 return; 2274 } 2275 final String value = Boolean.toString(hasDeviceOwner || hasOrgOwnedProfile); 2276 final String currentVal = mInjector.systemPropertiesGet(PROPERTY_ORGANIZATION_OWNED, null); 2277 if (TextUtils.isEmpty(currentVal)) { 2278 Slogf.i(LOG_TAG, "Set ro.organization_owned property to " + value); 2279 mInjector.systemPropertiesSet(PROPERTY_ORGANIZATION_OWNED, value); 2280 } else if (!value.equals(currentVal)) { 2281 Slogf.w(LOG_TAG, "Cannot change existing ro.organization_owned to " + value); 2282 } 2283 } 2284 maybeStartSecurityLogMonitorOnActivityManagerReady()2285 private void maybeStartSecurityLogMonitorOnActivityManagerReady() { 2286 synchronized (getLockObject()) { 2287 if (mInjector.securityLogIsLoggingEnabled()) { 2288 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser()); 2289 mInjector.runCryptoSelfTest(); 2290 maybePauseDeviceWideLoggingLocked(); 2291 } 2292 } 2293 } 2294 findOwnerComponentIfNecessaryLocked()2295 private void findOwnerComponentIfNecessaryLocked() { 2296 if (!mOwners.hasDeviceOwner()) { 2297 return; 2298 } 2299 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent(); 2300 2301 if (!TextUtils.isEmpty(doComponentName.getClassName())) { 2302 return; // Already a full component name. 2303 } 2304 2305 final ComponentName doComponent = findAdminComponentWithPackageLocked( 2306 doComponentName.getPackageName(), 2307 mOwners.getDeviceOwnerUserId()); 2308 if (doComponent == null) { 2309 Slogf.e(LOG_TAG, "Device-owner isn't registered as device-admin"); 2310 } else { 2311 mOwners.setDeviceOwnerWithRestrictionsMigrated( 2312 doComponent, 2313 mOwners.getDeviceOwnerName(), 2314 mOwners.getDeviceOwnerUserId(), 2315 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()); 2316 mOwners.writeDeviceOwner(); 2317 if (VERBOSE_LOG) { 2318 Slogf.v(LOG_TAG, "Device owner component filled in"); 2319 } 2320 } 2321 } 2322 2323 /** 2324 * We didn't use to persist user restrictions for each owners but only persisted in user 2325 * manager. 2326 */ migrateUserRestrictionsIfNecessaryLocked()2327 private void migrateUserRestrictionsIfNecessaryLocked() { 2328 boolean migrated = false; 2329 // Migrate for the DO. Basically all restrictions should be considered to be set by DO, 2330 // except for the "system controlled" ones. 2331 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) { 2332 if (VERBOSE_LOG) { 2333 Slogf.v(LOG_TAG, "Migrating DO user restrictions"); 2334 } 2335 migrated = true; 2336 2337 // Migrate user 0 restrictions to DO. 2338 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 2339 2340 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin, 2341 /* exceptionList =*/ null, /* isDeviceOwner =*/ true); 2342 2343 // Push DO user restrictions to user manager. 2344 pushUserRestrictions(UserHandle.USER_SYSTEM); 2345 2346 mOwners.setDeviceOwnerUserRestrictionsMigrated(); 2347 } 2348 2349 // Migrate for POs. 2350 2351 // The following restrictions can be set on secondary users by the device owner, so we 2352 // assume they're not from the PO. 2353 final Set<String> secondaryUserExceptionList = Sets.newArraySet( 2354 UserManager.DISALLOW_OUTGOING_CALLS, 2355 UserManager.DISALLOW_SMS); 2356 2357 for (UserInfo ui : mUserManager.getUsers()) { 2358 final int userId = ui.id; 2359 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) { 2360 if (VERBOSE_LOG) { 2361 Slogf.v(LOG_TAG, "Migrating PO user restrictions for user %d", userId); 2362 } 2363 migrated = true; 2364 2365 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId); 2366 2367 final Set<String> exceptionList = 2368 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList; 2369 2370 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin, 2371 exceptionList, /* isDeviceOwner =*/ false); 2372 2373 // Note if a secondary user has no PO but has a DA that disables camera, we 2374 // don't get here and won't push the camera user restriction to UserManager 2375 // here. That's okay because we'll push user restrictions anyway when a user 2376 // starts. But we still do it because we want to let user manager persist 2377 // upon migration. 2378 pushUserRestrictions(userId); 2379 2380 mOwners.setProfileOwnerUserRestrictionsMigrated(userId); 2381 } 2382 } 2383 if (VERBOSE_LOG && migrated) { 2384 Slogf.v(LOG_TAG, "User restrictions migrated."); 2385 } 2386 } 2387 migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, Set<String> exceptionList, boolean isDeviceOwner)2388 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, 2389 Set<String> exceptionList, boolean isDeviceOwner) { 2390 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions( 2391 user.getIdentifier()); 2392 2393 final Bundle newBaseRestrictions = new Bundle(); 2394 final Bundle newOwnerRestrictions = new Bundle(); 2395 2396 for (String key : origRestrictions.keySet()) { 2397 if (!origRestrictions.getBoolean(key)) { 2398 continue; 2399 } 2400 final boolean canOwnerChange = isDeviceOwner 2401 ? UserRestrictionsUtils.canDeviceOwnerChange(key) 2402 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier()); 2403 2404 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) { 2405 newBaseRestrictions.putBoolean(key, true); 2406 } else { 2407 newOwnerRestrictions.putBoolean(key, true); 2408 } 2409 } 2410 2411 if (VERBOSE_LOG) { 2412 Slogf.v(LOG_TAG, "origRestrictions=%s", origRestrictions); 2413 Slogf.v(LOG_TAG, "newBaseRestrictions=%s", newBaseRestrictions); 2414 Slogf.v(LOG_TAG, "newOwnerRestrictions=%s", newOwnerRestrictions); 2415 } 2416 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(), 2417 newBaseRestrictions); 2418 2419 if (admin != null) { 2420 admin.ensureUserRestrictions().clear(); 2421 admin.ensureUserRestrictions().putAll(newOwnerRestrictions); 2422 } else { 2423 Slogf.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier()); 2424 } 2425 saveSettingsLocked(user.getIdentifier()); 2426 } 2427 2428 /** 2429 * Fix left-over restrictions and auto-time policy during COMP -> COPE migration. 2430 * 2431 * When a COMP device with requireAutoTime policy set was migrated to an 2432 * organization-owned profile, a DISALLOW_CONFIG_DATE_TIME restriction is set 2433 * on user 0 from the DO user, which becomes unremovable by the organization-owned 2434 * profile owner. Fix this by force removing that restriction. Also revert the 2435 * parentAdmin.requireAutoTime bit (since the COPE PO cannot unset this bit) 2436 * and replace it with DISALLOW_CONFIG_DATE_TIME on the correct 2437 * admin, in line with the deprecation recommendation of setAutoTimeRequired(). 2438 */ fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration()2439 private void fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration() { 2440 for (UserInfo ui : mUserManager.getUsers()) { 2441 final int userId = ui.id; 2442 if (isProfileOwnerOfOrganizationOwnedDevice(userId)) { 2443 final ActiveAdmin parent = getProfileOwnerAdminLocked(userId).parentAdmin; 2444 if (parent != null && parent.requireAutoTime) { 2445 // Remove deprecated requireAutoTime 2446 parent.requireAutoTime = false; 2447 saveSettingsLocked(userId); 2448 2449 // Remove user restrictions set by the device owner before the upgrade to 2450 // Android 11. 2451 mUserManagerInternal.setDevicePolicyUserRestrictions(UserHandle.USER_SYSTEM, 2452 new Bundle(), new RestrictionsSet(), /* isDeviceOwner */ false); 2453 2454 // Apply user restriction to parent active admin instead 2455 parent.ensureUserRestrictions().putBoolean( 2456 UserManager.DISALLOW_CONFIG_DATE_TIME, true); 2457 pushUserRestrictions(userId); 2458 } 2459 } 2460 } 2461 } 2462 findAdminComponentWithPackageLocked(String packageName, int userId)2463 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) { 2464 final DevicePolicyData policy = getUserData(userId); 2465 final int n = policy.mAdminList.size(); 2466 ComponentName found = null; 2467 int nFound = 0; 2468 for (int i = 0; i < n; i++) { 2469 final ActiveAdmin admin = policy.mAdminList.get(i); 2470 if (packageName.equals(admin.info.getPackageName())) { 2471 // Found! 2472 if (nFound == 0) { 2473 found = admin.info.getComponent(); 2474 } 2475 nFound++; 2476 } 2477 } 2478 if (nFound > 1) { 2479 Slogf.w(LOG_TAG, "Multiple DA found; assume the first one is DO."); 2480 } 2481 return found; 2482 } 2483 2484 /** 2485 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration 2486 * reminders. Clears alarm if no expirations are configured. 2487 */ setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent)2488 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) { 2489 final long expiration = getPasswordExpirationLocked(null, userHandle, parent); 2490 final long now = System.currentTimeMillis(); 2491 final long timeToExpire = expiration - now; 2492 final long alarmTime; 2493 if (expiration == 0) { 2494 // No expirations are currently configured: Cancel alarm. 2495 alarmTime = 0; 2496 } else if (timeToExpire <= 0) { 2497 // The password has already expired: Repeat every 24 hours. 2498 alarmTime = now + MS_PER_DAY; 2499 } else { 2500 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before 2501 // the expiration time. 2502 long alarmInterval = timeToExpire % MS_PER_DAY; 2503 if (alarmInterval == 0) { 2504 alarmInterval = MS_PER_DAY; 2505 } 2506 alarmTime = now + alarmInterval; 2507 } 2508 2509 mInjector.binderWithCleanCallingIdentity(() -> { 2510 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle; 2511 AlarmManager am = mInjector.getAlarmManager(); 2512 // Broadcast alarms sent by system are immutable 2513 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD, 2514 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION), 2515 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT 2516 | PendingIntent.FLAG_IMMUTABLE, 2517 UserHandle.of(affectedUserHandle)); 2518 am.cancel(pi); 2519 if (alarmTime != 0) { 2520 am.set(AlarmManager.RTC, alarmTime, pi); 2521 } 2522 }); 2523 } 2524 getActiveAdminUncheckedLocked(ComponentName who, int userHandle)2525 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) { 2526 ensureLocked(); 2527 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who); 2528 if (admin != null 2529 && who.getPackageName().equals(admin.info.getActivityInfo().packageName) 2530 && who.getClassName().equals(admin.info.getActivityInfo().name)) { 2531 return admin; 2532 } 2533 return null; 2534 } 2535 getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent)2536 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) { 2537 ensureLocked(); 2538 if (parent) { 2539 Preconditions.checkCallAuthorization(isManagedProfile(userHandle), 2540 "You can not call APIs on the parent profile outside a managed profile, " 2541 + "userId = %d", userHandle); 2542 } 2543 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2544 if (admin != null && parent) { 2545 admin = admin.getParentActiveAdmin(); 2546 } 2547 return admin; 2548 } 2549 getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)2550 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy) 2551 throws SecurityException { 2552 return getActiveAdminOrCheckPermissionForCallerLocked(who, 2553 reqPolicy, /* permission= */ null); 2554 } 2555 getDeviceOwnerLocked(final CallerIdentity caller)2556 @NonNull ActiveAdmin getDeviceOwnerLocked(final CallerIdentity caller) { 2557 ensureLocked(); 2558 ComponentName doComponent = mOwners.getDeviceOwnerComponent(); 2559 Preconditions.checkState(doComponent != null, 2560 "No device owner for user %d", caller.getUid()); 2561 2562 // Use the user ID of the caller instead of mOwners.getDeviceOwnerUserId() because 2563 // secondary, affiliated users will have their own admin. 2564 ActiveAdmin doAdmin = getUserData(caller.getUserId()).mAdminMap.get(doComponent); 2565 Preconditions.checkState(doAdmin != null, 2566 "Device owner %s for user %d not found", doComponent, 2567 caller.getUid()); 2568 2569 Preconditions.checkCallAuthorization(doAdmin.getUid() == caller.getUid(), 2570 "Admin %s is not owned by uid %d, but uid %d", doComponent, 2571 caller.getUid(), doAdmin.getUid()); 2572 2573 Preconditions.checkCallAuthorization( 2574 !caller.hasAdminComponent() 2575 || doAdmin.info.getComponent().equals(caller.getComponentName()), 2576 "Caller component %s is not device owner", 2577 caller.getComponentName()); 2578 2579 return doAdmin; 2580 } 2581 getProfileOwnerLocked(final CallerIdentity caller)2582 @NonNull ActiveAdmin getProfileOwnerLocked(final CallerIdentity caller) { 2583 ensureLocked(); 2584 final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(caller.getUserId()); 2585 2586 Preconditions.checkState(poAdminComponent != null, 2587 "No profile owner for user %d", caller.getUid()); 2588 2589 ActiveAdmin poAdmin = getUserData(caller.getUserId()).mAdminMap.get(poAdminComponent); 2590 Preconditions.checkState(poAdmin != null, 2591 "No device profile owner for caller %d", caller.getUid()); 2592 2593 Preconditions.checkCallAuthorization(poAdmin.getUid() == caller.getUid(), 2594 "Admin %s is not owned by uid %d", poAdminComponent, 2595 caller.getUid()); 2596 2597 Preconditions.checkCallAuthorization( 2598 !caller.hasAdminComponent() 2599 || poAdmin.info.getComponent().equals(caller.getComponentName()), 2600 "Caller component %s is not profile owner", 2601 caller.getComponentName()); 2602 2603 return poAdmin; 2604 } 2605 getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller)2606 @NonNull ActiveAdmin getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller) { 2607 final ActiveAdmin profileOwner = getProfileOwnerLocked(caller); 2608 2609 Preconditions.checkCallAuthorization( 2610 mOwners.isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()), 2611 "Admin %s is not of an org-owned device", 2612 profileOwner.info.getComponent()); 2613 2614 return profileOwner; 2615 } 2616 getProfileOwnerOrDeviceOwnerLocked(final CallerIdentity caller)2617 @NonNull ActiveAdmin getProfileOwnerOrDeviceOwnerLocked(final CallerIdentity caller) { 2618 ensureLocked(); 2619 // Try to find an admin which can use reqPolicy 2620 final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(caller.getUserId()); 2621 final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent(); 2622 2623 if (poAdminComponent == null && doAdminComponent == null) { 2624 throw new IllegalStateException( 2625 String.format("No profile or device owner for user %d", caller.getUid())); 2626 } 2627 2628 if (poAdminComponent != null) { 2629 return getProfileOwnerLocked(caller); 2630 } 2631 2632 return getDeviceOwnerLocked(caller); 2633 } 2634 getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent)2635 @NonNull ActiveAdmin getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent) { 2636 Objects.requireNonNull(admin); 2637 return parent ? admin.getParentActiveAdmin() : admin; 2638 } 2639 2640 /** 2641 * Finds an active admin for the caller then checks {@code permission} if admin check failed. 2642 * 2643 * @return an active admin or {@code null} if there is no active admin but 2644 * {@code permission} is granted 2645 * @throws SecurityException if caller neither has an active admin nor {@code permission} 2646 */ 2647 @Nullable getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, @Nullable String permission)2648 ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked( 2649 ComponentName who, 2650 int reqPolicy, 2651 @Nullable String permission) throws SecurityException { 2652 ensureLocked(); 2653 final CallerIdentity caller = getCallerIdentity(); 2654 2655 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, caller.getUid()); 2656 if (result != null) { 2657 return result; 2658 } else if (permission != null && hasCallingPermission(permission)) { 2659 return null; 2660 } 2661 2662 // Code for handling failure from getActiveAdminWithPolicyForUidLocked to find an admin 2663 // that satisfies the required policy. 2664 // Throws a security exception with the right error message. 2665 if (who != null) { 2666 final DevicePolicyData policy = getUserData(caller.getUserId()); 2667 ActiveAdmin admin = policy.mAdminMap.get(who); 2668 final boolean isDeviceOwner = isDeviceOwner(admin.info.getComponent(), 2669 caller.getUserId()); 2670 final boolean isProfileOwner = isProfileOwner(admin.info.getComponent(), 2671 caller.getUserId()); 2672 2673 if (DA_DISALLOWED_POLICIES.contains(reqPolicy) && !isDeviceOwner && !isProfileOwner) { 2674 throw new SecurityException("Admin " + admin.info.getComponent() 2675 + " is not a device owner or profile owner, so may not use policy: " 2676 + admin.info.getTagForPolicy(reqPolicy)); 2677 } 2678 throw new SecurityException("Admin " + admin.info.getComponent() 2679 + " did not specify uses-policy for: " 2680 + admin.info.getTagForPolicy(reqPolicy)); 2681 } else { 2682 throw new SecurityException("No active admin owned by uid " 2683 + caller.getUid() + " for policy #" + reqPolicy + (permission == null ? "" 2684 : ", which doesn't have " + permission)); 2685 } 2686 } 2687 getActiveAdminForCallerLocked(@ullable ComponentName who, int reqPolicy, boolean parent)2688 ActiveAdmin getActiveAdminForCallerLocked(@Nullable ComponentName who, int reqPolicy, 2689 boolean parent) throws SecurityException { 2690 return getActiveAdminOrCheckPermissionForCallerLocked( 2691 who, reqPolicy, parent, /* permission= */ null); 2692 } 2693 2694 /** 2695 * Finds an active admin for the caller then checks {@code permission} if admin check failed. 2696 * 2697 * @return an active admin or {@code null} if there is no active admin but 2698 * {@code permission} is granted 2699 * @throws SecurityException if caller neither has an active admin nor {@code permission} 2700 */ 2701 @Nullable getActiveAdminOrCheckPermissionForCallerLocked( @ullable ComponentName who, int reqPolicy, boolean parent, @Nullable String permission)2702 ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked( 2703 @Nullable ComponentName who, 2704 int reqPolicy, 2705 boolean parent, 2706 @Nullable String permission) throws SecurityException { 2707 ensureLocked(); 2708 if (parent) { 2709 Preconditions.checkCallingUser(isManagedProfile(getCallerIdentity().getUserId())); 2710 } 2711 ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked( 2712 who, reqPolicy, permission); 2713 return parent ? admin.getParentActiveAdmin() : admin; 2714 } 2715 2716 /** 2717 * Find the admin for the component and userId bit of the uid, then check 2718 * the admin's uid matches the uid. 2719 */ getActiveAdminForUidLocked(ComponentName who, int uid)2720 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) { 2721 ensureLocked(); 2722 final int userId = UserHandle.getUserId(uid); 2723 final DevicePolicyData policy = getUserData(userId); 2724 ActiveAdmin admin = policy.mAdminMap.get(who); 2725 if (admin == null) { 2726 throw new SecurityException("No active admin " + who + " for UID " + uid); 2727 } 2728 if (admin.getUid() != uid) { 2729 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2730 } 2731 return admin; 2732 } 2733 2734 /** 2735 * Returns the active admin for the user of the caller as denoted by uid, which implements 2736 * the {@code reqPolicy}. 2737 * 2738 * The {@code who} parameter is used as a hint: 2739 * If provided, it must be the component name of the active admin for that user and the caller 2740 * uid must match the uid of the admin. 2741 * If not provided, iterate over all of the active admins in the DevicePolicyData for that user 2742 * and return the one with the uid specified as parameter, and has the policy specified. 2743 */ 2744 @Nullable getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, int uid)2745 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, 2746 int uid) { 2747 ensureLocked(); 2748 // Try to find an admin which can use reqPolicy 2749 final int userId = UserHandle.getUserId(uid); 2750 final DevicePolicyData policy = getUserData(userId); 2751 if (who != null) { 2752 ActiveAdmin admin = policy.mAdminMap.get(who); 2753 if (admin == null) { 2754 throw new SecurityException("No active admin " + who); 2755 } 2756 if (admin.getUid() != uid) { 2757 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2758 } 2759 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) { 2760 return admin; 2761 } 2762 } else { 2763 for (ActiveAdmin admin : policy.mAdminList) { 2764 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, 2765 userId)) { 2766 return admin; 2767 } 2768 } 2769 } 2770 2771 return null; 2772 } 2773 2774 @VisibleForTesting isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, int userId)2775 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, 2776 int userId) { 2777 ensureLocked(); 2778 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId); 2779 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId); 2780 2781 boolean allowedToUsePolicy = ownsDevice || ownsProfile 2782 || !DA_DISALLOWED_POLICIES.contains(reqPolicy) 2783 || getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.Q; 2784 return allowedToUsePolicy && admin.info.usesPolicy(reqPolicy); 2785 } 2786 2787 void sendAdminCommandLocked(ActiveAdmin admin, String action) { 2788 sendAdminCommandLocked(admin, action, null); 2789 } 2790 2791 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) { 2792 sendAdminCommandLocked(admin, action, null, result); 2793 } 2794 2795 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2796 BroadcastReceiver result) { 2797 sendAdminCommandLocked(admin, action, adminExtras, result, false); 2798 } 2799 2800 /** 2801 * Send an update to one specific admin, get notified when that admin returns a result. 2802 * 2803 * @return whether the broadcast was successfully sent 2804 */ 2805 boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2806 BroadcastReceiver result, boolean inForeground) { 2807 Intent intent = new Intent(action); 2808 intent.setComponent(admin.info.getComponent()); 2809 if (UserManager.isDeviceInDemoMode(mContext)) { 2810 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2811 } 2812 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) { 2813 intent.putExtra("expiration", admin.passwordExpirationDate); 2814 } 2815 if (inForeground) { 2816 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2817 } 2818 if (adminExtras != null) { 2819 intent.putExtras(adminExtras); 2820 } 2821 if (mInjector.getPackageManager().queryBroadcastReceiversAsUser( 2822 intent, 2823 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, 2824 admin.getUserHandle()).isEmpty()) { 2825 return false; 2826 } 2827 2828 final BroadcastOptions options = BroadcastOptions.makeBasic(); 2829 options.setBackgroundActivityStartsAllowed(true); 2830 2831 if (result != null) { 2832 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(), 2833 null, AppOpsManager.OP_NONE, options.toBundle(), 2834 result, mHandler, Activity.RESULT_OK, null, null); 2835 } else { 2836 mContext.sendBroadcastAsUser(intent, admin.getUserHandle(), null, options.toBundle()); 2837 } 2838 2839 return true; 2840 } 2841 2842 /** 2843 * Send an update to all admins of a user that enforce a specified policy. 2844 */ 2845 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) { 2846 final DevicePolicyData policy = getUserData(userHandle); 2847 final int count = policy.mAdminList.size(); 2848 for (int i = 0; i < count; i++) { 2849 final ActiveAdmin admin = policy.mAdminList.get(i); 2850 if (admin.info.usesPolicy(reqPolicy)) { 2851 sendAdminCommandLocked(admin, action, adminExtras, null); 2852 } 2853 } 2854 } 2855 2856 /** 2857 * Send an update intent to all admins of a user and its profiles. Only send to admins that 2858 * enforce a specified policy. 2859 */ 2860 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy, 2861 int userHandle, Bundle adminExtras) { 2862 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle); 2863 for (int profileId : profileIds) { 2864 sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras); 2865 } 2866 } 2867 2868 /** 2869 * Sends a broadcast to each profile that share the password unlock with the given user id. 2870 */ 2871 private void sendAdminCommandForLockscreenPoliciesLocked( 2872 String action, int reqPolicy, int userHandle) { 2873 final Bundle extras = new Bundle(); 2874 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 2875 if (isSeparateProfileChallengeEnabled(userHandle)) { 2876 sendAdminCommandLocked(action, reqPolicy, userHandle, extras); 2877 } else { 2878 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras); 2879 } 2880 } 2881 2882 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) { 2883 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 2884 DevicePolicyData policy = getUserData(userHandle); 2885 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) { 2886 policy.mRemovingAdmins.add(adminReceiver); 2887 sendAdminCommandLocked(admin, 2888 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED, 2889 new BroadcastReceiver() { 2890 @Override 2891 public void onReceive(Context context, Intent intent) { 2892 removeAdminArtifacts(adminReceiver, userHandle); 2893 removePackageIfRequired(adminReceiver.getPackageName(), userHandle); 2894 } 2895 }); 2896 } 2897 } 2898 2899 private DeviceAdminInfo findAdmin(final ComponentName adminName, final int userHandle, 2900 boolean throwForMissingPermission) { 2901 final ActivityInfo ai = mInjector.binderWithCleanCallingIdentity(() -> { 2902 try { 2903 return mIPackageManager.getReceiverInfo(adminName, 2904 PackageManager.GET_META_DATA 2905 | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS 2906 | PackageManager.MATCH_DIRECT_BOOT_AWARE 2907 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle); 2908 } catch (RemoteException e) { 2909 // shouldn't happen. 2910 return null; 2911 } 2912 }); 2913 if (ai == null) { 2914 throw new IllegalArgumentException("Unknown admin: " + adminName); 2915 } 2916 2917 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) { 2918 final String message = "DeviceAdminReceiver " + adminName + " must be protected with " 2919 + permission.BIND_DEVICE_ADMIN; 2920 Slogf.w(LOG_TAG, message); 2921 if (throwForMissingPermission && 2922 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) { 2923 throw new IllegalArgumentException(message); 2924 } 2925 } 2926 2927 try { 2928 return new DeviceAdminInfo(mContext, ai); 2929 } catch (XmlPullParserException | IOException e) { 2930 Slogf.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName, 2931 e); 2932 return null; 2933 } 2934 } 2935 2936 private File getPolicyFileDirectory(@UserIdInt int userId) { 2937 return userId == UserHandle.USER_SYSTEM 2938 ? new File(mInjector.getDevicePolicyFilePathForSystemUser()) 2939 : mInjector.environmentGetUserSystemDirectory(userId); 2940 } 2941 2942 private JournaledFile makeJournaledFile(@UserIdInt int userId, String fileName) { 2943 final String base = new File(getPolicyFileDirectory(userId), fileName) 2944 .getAbsolutePath(); 2945 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Opening %s", base); 2946 return new JournaledFile(new File(base), new File(base + ".tmp")); 2947 } 2948 2949 private JournaledFile makeJournaledFile(@UserIdInt int userId) { 2950 return makeJournaledFile(userId, DEVICE_POLICIES_XML); 2951 } 2952 2953 /** 2954 * Persist modified values to disk by calling {@link #saveSettingsLocked} for each 2955 * affected user ID. 2956 */ 2957 @GuardedBy("getLockObject()") 2958 private void saveSettingsForUsersLocked(Set<Integer> affectedUserIds) { 2959 for (int userId : affectedUserIds) { 2960 saveSettingsLocked(userId); 2961 } 2962 } 2963 2964 private void saveSettingsLocked(int userHandle) { 2965 if (DevicePolicyData.store( 2966 getUserData(userHandle), 2967 makeJournaledFile(userHandle), 2968 !mInjector.storageManagerIsFileBasedEncryptionEnabled())) { 2969 sendChangedNotification(userHandle); 2970 } 2971 } 2972 2973 private void sendChangedNotification(int userHandle) { 2974 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 2975 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 2976 mInjector.binderWithCleanCallingIdentity(() -> 2977 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle))); 2978 } 2979 2980 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) { 2981 DevicePolicyData.load(policy, 2982 !mInjector.storageManagerIsFileBasedEncryptionEnabled(), 2983 makeJournaledFile(userHandle), 2984 component -> findAdmin( 2985 component, userHandle, /* throwForMissingPermission= */ false), 2986 getOwnerComponent(userHandle)); 2987 2988 policy.validatePasswordOwner(); 2989 updateMaximumTimeToLockLocked(userHandle); 2990 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle); 2991 updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle); 2992 if (policy.mStatusBarDisabled) { 2993 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle); 2994 } 2995 } 2996 2997 private void updateLockTaskPackagesLocked(List<String> packages, int userId) { 2998 String[] packagesArray = null; 2999 3000 if (!packages.isEmpty()) { 3001 // When adding packages, we need to include the exempt apps so they can still be 3002 // launched (ideally we should use a different AM API as these apps don't need to use 3003 // lock-task mode). 3004 // They're not added when the packages is empty though, as in that case we're disabling 3005 // lock-task mode. 3006 List<String> exemptApps = listPolicyExemptAppsUnchecked(); 3007 if (!exemptApps.isEmpty()) { 3008 // TODO(b/175377361): add unit test to verify it (cannot be CTS because the policy- 3009 // -exempt apps are provided by OEM and the test would have no control over it) once 3010 // tests are migrated to the new infra-structure 3011 HashSet<String> updatedPackages = new HashSet<>(packages); 3012 updatedPackages.addAll(exemptApps); 3013 if (VERBOSE_LOG) { 3014 Slogf.v(LOG_TAG, "added %d policy-exempt apps to %d lock task packages. Final " 3015 + "list: %s", exemptApps.size(), packages.size(), updatedPackages); 3016 } 3017 packagesArray = updatedPackages.toArray(new String[updatedPackages.size()]); 3018 } 3019 } 3020 3021 if (packagesArray == null) { 3022 packagesArray = packages.toArray(new String[packages.size()]); 3023 } 3024 3025 long ident = mInjector.binderClearCallingIdentity(); 3026 try { 3027 mInjector.getIActivityManager().updateLockTaskPackages(userId, packagesArray); 3028 } catch (RemoteException e) { 3029 // Not gonna happen. 3030 } finally { 3031 mInjector.binderRestoreCallingIdentity(ident); 3032 } 3033 } 3034 3035 private void updateLockTaskFeaturesLocked(int flags, int userId) { 3036 long ident = mInjector.binderClearCallingIdentity(); 3037 try { 3038 mInjector.getIActivityTaskManager().updateLockTaskFeatures(userId, flags); 3039 } catch (RemoteException e) { 3040 // Not gonna happen. 3041 } finally { 3042 mInjector.binderRestoreCallingIdentity(ident); 3043 } 3044 } 3045 3046 private void updateDeviceOwnerLocked() { 3047 long ident = mInjector.binderClearCallingIdentity(); 3048 try { 3049 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the 3050 // user id and also protect all other DAs too. 3051 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 3052 if (deviceOwnerComponent != null) { 3053 mInjector.getIActivityManager() 3054 .updateDeviceOwner(deviceOwnerComponent.getPackageName()); 3055 } 3056 } catch (RemoteException e) { 3057 // Not gonna happen. 3058 } finally { 3059 mInjector.binderRestoreCallingIdentity(ident); 3060 } 3061 } 3062 3063 static void validateQualityConstant(int quality) { 3064 switch (quality) { 3065 case PASSWORD_QUALITY_UNSPECIFIED: 3066 case PASSWORD_QUALITY_BIOMETRIC_WEAK: 3067 case PASSWORD_QUALITY_SOMETHING: 3068 case PASSWORD_QUALITY_NUMERIC: 3069 case PASSWORD_QUALITY_NUMERIC_COMPLEX: 3070 case PASSWORD_QUALITY_ALPHABETIC: 3071 case PASSWORD_QUALITY_ALPHANUMERIC: 3072 case PASSWORD_QUALITY_COMPLEX: 3073 case PASSWORD_QUALITY_MANAGED: 3074 return; 3075 } 3076 throw new IllegalArgumentException("Invalid quality constant: 0x" 3077 + Integer.toHexString(quality)); 3078 } 3079 3080 @VisibleForTesting 3081 @Override 3082 void systemReady(int phase) { 3083 if (!mHasFeature) { 3084 return; 3085 } 3086 switch (phase) { 3087 case SystemService.PHASE_LOCK_SETTINGS_READY: 3088 onLockSettingsReady(); 3089 loadAdminDataAsync(); 3090 mOwners.systemReady(); 3091 break; 3092 case SystemService.PHASE_ACTIVITY_MANAGER_READY: 3093 synchronized (getLockObject()) { 3094 migrateToProfileOnOrganizationOwnedDeviceIfCompLocked(); 3095 applyManagedProfileRestrictionIfDeviceOwnerLocked(); 3096 } 3097 maybeStartSecurityLogMonitorOnActivityManagerReady(); 3098 break; 3099 case SystemService.PHASE_BOOT_COMPLETED: 3100 // Ideally it should be done earlier, but currently it relies on RecoverySystem, 3101 // which would hang on earlier phases 3102 factoryResetIfDelayedEarlier(); 3103 3104 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this. 3105 break; 3106 } 3107 } 3108 3109 private void updatePersonalAppsSuspensionOnUserStart(int userHandle) { 3110 final int profileUserHandle = getManagedUserId(userHandle); 3111 if (profileUserHandle >= 0) { 3112 // Given that the parent user has just started, profile should be locked. 3113 updatePersonalAppsSuspension(profileUserHandle, false /* unlocked */); 3114 } else { 3115 suspendPersonalAppsInternal(userHandle, false); 3116 } 3117 } 3118 3119 private void onLockSettingsReady() { 3120 synchronized (getLockObject()) { 3121 migrateUserRestrictionsIfNecessaryLocked(); 3122 fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration(); 3123 performPolicyVersionUpgrade(); 3124 } 3125 getUserData(UserHandle.USER_SYSTEM); 3126 cleanUpOldUsers(); 3127 maybeSetDefaultProfileOwnerUserRestrictions(); 3128 handleStartUser(UserHandle.USER_SYSTEM); 3129 maybeLogStart(); 3130 3131 // Register an observer for watching for user setup complete and settings changes. 3132 mSetupContentObserver.register(); 3133 // Initialize the user setup state, to handle the upgrade case. 3134 updateUserSetupCompleteAndPaired(); 3135 3136 List<String> packageList; 3137 synchronized (getLockObject()) { 3138 packageList = getKeepUninstalledPackagesLocked(); 3139 } 3140 if (packageList != null) { 3141 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 3142 } 3143 3144 synchronized (getLockObject()) { 3145 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 3146 if (deviceOwner != null) { 3147 // Push the force-ephemeral-users policy to the user manager. 3148 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers); 3149 3150 // Update user switcher message to activity manager. 3151 ActivityManagerInternal activityManagerInternal = 3152 mInjector.getActivityManagerInternal(); 3153 activityManagerInternal.setSwitchingFromSystemUserMessage( 3154 deviceOwner.startUserSessionMessage); 3155 activityManagerInternal.setSwitchingToSystemUserMessage( 3156 deviceOwner.endUserSessionMessage); 3157 } 3158 3159 revertTransferOwnershipIfNecessaryLocked(); 3160 } 3161 updateUsbDataSignal(); 3162 } 3163 3164 private class DpmsUpgradeDataProvider implements PolicyUpgraderDataProvider { 3165 @Override 3166 public boolean isDeviceOwner(int userId, ComponentName who) { 3167 return mOwners.isDeviceOwnerUserId(userId) 3168 && mOwners.getDeviceOwnerComponent().equals(who); 3169 } 3170 3171 @Override 3172 public boolean storageManagerIsFileBasedEncryptionEnabled() { 3173 return mInjector.storageManagerIsFileBasedEncryptionEnabled(); 3174 } 3175 3176 @Override 3177 public JournaledFile makeDevicePoliciesJournaledFile(int userId) { 3178 return DevicePolicyManagerService.this.makeJournaledFile(userId, DEVICE_POLICIES_XML); 3179 } 3180 3181 @Override 3182 public JournaledFile makePoliciesVersionJournaledFile(int userId) { 3183 return DevicePolicyManagerService.this.makeJournaledFile(userId, POLICIES_VERSION_XML); 3184 } 3185 3186 @Override 3187 public ComponentName getOwnerComponent(int userId) { 3188 return DevicePolicyManagerService.this.getOwnerComponent(userId); 3189 } 3190 3191 @Override 3192 public Function<ComponentName, DeviceAdminInfo> getAdminInfoSupplier(int userId) { 3193 return component -> findAdmin(component, userId, /* throwForMissingPermission= */ 3194 false); 3195 } 3196 3197 @Override 3198 public int[] getUsersForUpgrade() { 3199 List<UserInfo> allUsers = mUserManager.getUsers(); 3200 return allUsers.stream().mapToInt(u -> u.id).toArray(); 3201 } 3202 } 3203 3204 private void performPolicyVersionUpgrade() { 3205 PolicyVersionUpgrader upgrader = new PolicyVersionUpgrader( 3206 new DpmsUpgradeDataProvider()); 3207 3208 upgrader.upgradePolicy(DPMS_VERSION); 3209 } 3210 3211 private void revertTransferOwnershipIfNecessaryLocked() { 3212 if (!mTransferOwnershipMetadataManager.metadataFileExists()) { 3213 return; 3214 } 3215 Slogf.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer."); 3216 final TransferOwnershipMetadataManager.Metadata metadata = 3217 mTransferOwnershipMetadataManager.loadMetadataFile(); 3218 // Revert transfer 3219 if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) { 3220 transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent, 3221 metadata.userId); 3222 deleteTransferOwnershipMetadataFileLocked(); 3223 deleteTransferOwnershipBundleLocked(metadata.userId); 3224 } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) { 3225 transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent, 3226 metadata.userId); 3227 deleteTransferOwnershipMetadataFileLocked(); 3228 deleteTransferOwnershipBundleLocked(metadata.userId); 3229 } 3230 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true); 3231 } 3232 3233 private void maybeLogStart() { 3234 if (!SecurityLog.isLoggingEnabled()) { 3235 return; 3236 } 3237 final String verifiedBootState = 3238 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate"); 3239 final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode"); 3240 SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode); 3241 } 3242 3243 private void ensureDeviceOwnerUserStarted() { 3244 final int userId; 3245 synchronized (getLockObject()) { 3246 if (!mOwners.hasDeviceOwner()) { 3247 return; 3248 } 3249 userId = mOwners.getDeviceOwnerUserId(); 3250 } 3251 if (VERBOSE_LOG) { 3252 Log.v(LOG_TAG, "Starting non-system DO user: " + userId); 3253 } 3254 if (userId != UserHandle.USER_SYSTEM) { 3255 try { 3256 mInjector.getIActivityManager().startUserInBackground(userId); 3257 3258 // STOPSHIP Prevent the DO user from being killed. 3259 3260 } catch (RemoteException e) { 3261 Slogf.w(LOG_TAG, "Exception starting user", e); 3262 } 3263 } 3264 } 3265 3266 @Override 3267 void handleStartUser(int userId) { 3268 updateScreenCaptureDisabled(userId, 3269 getScreenCaptureDisabled(null, userId, false)); 3270 pushUserRestrictions(userId); 3271 // When system user is started (device boot), load cache for all users. 3272 // This is to mitigate the potential race between loading the cache and keyguard 3273 // reading the value during user switch, due to onStartUser() being asynchronous. 3274 updatePasswordQualityCacheForUserGroup( 3275 userId == UserHandle.USER_SYSTEM ? UserHandle.USER_ALL : userId); 3276 updatePermissionPolicyCache(userId); 3277 updateAdminCanGrantSensorsPermissionCache(userId); 3278 3279 final boolean preferentialNetworkServiceEnabled; 3280 synchronized (getLockObject()) { 3281 ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 3282 preferentialNetworkServiceEnabled = owner != null 3283 ? owner.mPreferentialNetworkServiceEnabled 3284 : DevicePolicyManager.PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT; 3285 } 3286 updateNetworkPreferenceForUser(userId, preferentialNetworkServiceEnabled); 3287 3288 startOwnerService(userId, "start-user"); 3289 } 3290 3291 @Override 3292 void handleUnlockUser(int userId) { 3293 startOwnerService(userId, "unlock-user"); 3294 } 3295 3296 @Override 3297 void handleOnUserUnlocked(int userId) { 3298 showNewUserDisclaimerIfNecessary(userId); 3299 } 3300 3301 @Override 3302 void handleStopUser(int userId) { 3303 updateNetworkPreferenceForUser(userId, false); 3304 stopOwnerService(userId, "stop-user"); 3305 } 3306 3307 private void startOwnerService(int userId, String actionForLog) { 3308 final ComponentName owner = getOwnerComponent(userId); 3309 if (owner != null) { 3310 mDeviceAdminServiceController.startServiceForOwner( 3311 owner.getPackageName(), userId, actionForLog); 3312 } 3313 } 3314 3315 private void stopOwnerService(int userId, String actionForLog) { 3316 mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog); 3317 } 3318 3319 private void cleanUpOldUsers() { 3320 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled 3321 // before reboot 3322 Set<Integer> usersWithProfileOwners; 3323 Set<Integer> usersWithData; 3324 synchronized (getLockObject()) { 3325 usersWithProfileOwners = mOwners.getProfileOwnerKeys(); 3326 usersWithData = new ArraySet<>(); 3327 for (int i = 0; i < mUserData.size(); i++) { 3328 usersWithData.add(mUserData.keyAt(i)); 3329 } 3330 } 3331 List<UserInfo> allUsers = mUserManager.getUsers(); 3332 3333 Set<Integer> deletedUsers = new ArraySet<>(); 3334 deletedUsers.addAll(usersWithProfileOwners); 3335 deletedUsers.addAll(usersWithData); 3336 for (UserInfo userInfo : allUsers) { 3337 deletedUsers.remove(userInfo.id); 3338 } 3339 for (Integer userId : deletedUsers) { 3340 removeUserData(userId); 3341 } 3342 } 3343 3344 private void handlePasswordExpirationNotification(int userHandle) { 3345 final Bundle adminExtras = new Bundle(); 3346 adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 3347 3348 synchronized (getLockObject()) { 3349 final long now = System.currentTimeMillis(); 3350 3351 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle); 3352 final int N = admins.size(); 3353 for (int i = 0; i < N; i++) { 3354 ActiveAdmin admin = admins.get(i); 3355 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD) 3356 && admin.passwordExpirationTimeout > 0L 3357 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS 3358 && admin.passwordExpirationDate > 0L) { 3359 sendAdminCommandLocked(admin, 3360 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null); 3361 } 3362 } 3363 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false); 3364 } 3365 } 3366 3367 /** 3368 * Clean up internal state when the set of installed trusted CA certificates changes. 3369 * 3370 * @param userHandle user to check for. This must be a real user and not, for example, 3371 * {@link UserHandle#ALL}. 3372 * @param installedCertificates the full set of certificate authorities currently installed for 3373 * {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will 3374 * correspond to some subset of this. 3375 */ 3376 protected void onInstalledCertificatesChanged(final UserHandle userHandle, 3377 final @NonNull Collection<String> installedCertificates) { 3378 if (!mHasFeature) { 3379 return; 3380 } 3381 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 3382 3383 synchronized (getLockObject()) { 3384 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3385 3386 boolean changed = false; 3387 changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates); 3388 changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates); 3389 if (changed) { 3390 saveSettingsLocked(userHandle.getIdentifier()); 3391 } 3392 } 3393 } 3394 3395 /** 3396 * Internal method used by {@link CertificateMonitor}. 3397 */ 3398 protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) { 3399 if (!mHasFeature) { 3400 return Collections.<String> emptySet(); 3401 } 3402 synchronized (getLockObject()) { 3403 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3404 return policy.mAcceptedCaCertificates; 3405 } 3406 } 3407 3408 /** 3409 * @param adminReceiver The admin to add 3410 * @param refreshing true = update an active admin, no error 3411 */ 3412 @Override 3413 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) { 3414 if (!mHasFeature) { 3415 return; 3416 } 3417 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3418 3419 final CallerIdentity caller = getCallerIdentity(); 3420 Preconditions.checkCallAuthorization( 3421 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 3422 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3423 3424 DevicePolicyData policy = getUserData(userHandle); 3425 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle, 3426 /* throwForMissingPermission= */ true); 3427 synchronized (getLockObject()) { 3428 checkActiveAdminPrecondition(adminReceiver, info, policy); 3429 mInjector.binderWithCleanCallingIdentity(() -> { 3430 final ActiveAdmin existingAdmin 3431 = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3432 if (!refreshing && existingAdmin != null) { 3433 throw new IllegalArgumentException("Admin is already added"); 3434 } 3435 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false); 3436 newAdmin.testOnlyAdmin = 3437 (existingAdmin != null) ? existingAdmin.testOnlyAdmin 3438 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle); 3439 policy.mAdminMap.put(adminReceiver, newAdmin); 3440 int replaceIndex = -1; 3441 final int N = policy.mAdminList.size(); 3442 for (int i=0; i < N; i++) { 3443 ActiveAdmin oldAdmin = policy.mAdminList.get(i); 3444 if (oldAdmin.info.getComponent().equals(adminReceiver)) { 3445 replaceIndex = i; 3446 break; 3447 } 3448 } 3449 if (replaceIndex == -1) { 3450 policy.mAdminList.add(newAdmin); 3451 enableIfNecessary(info.getPackageName(), userHandle); 3452 mUsageStatsManagerInternal.onActiveAdminAdded( 3453 adminReceiver.getPackageName(), userHandle); 3454 } else { 3455 policy.mAdminList.set(replaceIndex, newAdmin); 3456 } 3457 saveSettingsLocked(userHandle); 3458 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3459 /* adminExtras= */ null, /* result= */ null); 3460 }); 3461 } 3462 } 3463 3464 private void loadAdminDataAsync() { 3465 mInjector.postOnSystemServerInitThreadPool(() -> { 3466 pushActiveAdminPackages(); 3467 mUsageStatsManagerInternal.onAdminDataAvailable(); 3468 pushAllMeteredRestrictedPackages(); 3469 mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable(); 3470 }); 3471 } 3472 3473 private void pushActiveAdminPackages() { 3474 synchronized (getLockObject()) { 3475 final List<UserInfo> users = mUserManager.getUsers(); 3476 for (int i = users.size() - 1; i >= 0; --i) { 3477 final int userId = users.get(i).id; 3478 mUsageStatsManagerInternal.setActiveAdminApps( 3479 getActiveAdminPackagesLocked(userId), userId); 3480 } 3481 } 3482 } 3483 3484 private void pushAllMeteredRestrictedPackages() { 3485 synchronized (getLockObject()) { 3486 final List<UserInfo> users = mUserManager.getUsers(); 3487 for (int i = users.size() - 1; i >= 0; --i) { 3488 final int userId = users.get(i).id; 3489 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync( 3490 getMeteredDisabledPackagesLocked(userId), userId); 3491 } 3492 } 3493 } 3494 3495 private void pushActiveAdminPackagesLocked(int userId) { 3496 mUsageStatsManagerInternal.setActiveAdminApps( 3497 getActiveAdminPackagesLocked(userId), userId); 3498 } 3499 3500 private Set<String> getActiveAdminPackagesLocked(int userId) { 3501 final DevicePolicyData policy = getUserData(userId); 3502 Set<String> adminPkgs = null; 3503 for (int i = policy.mAdminList.size() - 1; i >= 0; --i) { 3504 final String pkgName = policy.mAdminList.get(i).info.getPackageName(); 3505 if (adminPkgs == null) { 3506 adminPkgs = new ArraySet<>(); 3507 } 3508 adminPkgs.add(pkgName); 3509 } 3510 return adminPkgs; 3511 } 3512 3513 private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver, 3514 ComponentName outgoingReceiver, int userHandle) { 3515 final DevicePolicyData policy = getUserData(userHandle); 3516 if (!policy.mAdminMap.containsKey(outgoingReceiver) 3517 && policy.mAdminMap.containsKey(incomingReceiver)) { 3518 // Nothing to transfer - the incoming receiver is already the active admin. 3519 return; 3520 } 3521 final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle, 3522 /* throwForMissingPermission= */ true); 3523 final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver); 3524 final int oldAdminUid = adminToTransfer.getUid(); 3525 3526 adminToTransfer.transfer(incomingDeviceInfo); 3527 policy.mAdminMap.remove(outgoingReceiver); 3528 policy.mAdminMap.put(incomingReceiver, adminToTransfer); 3529 if (policy.mPasswordOwner == oldAdminUid) { 3530 policy.mPasswordOwner = adminToTransfer.getUid(); 3531 } 3532 3533 saveSettingsLocked(userHandle); 3534 sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3535 null, null); 3536 } 3537 3538 private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info, 3539 DevicePolicyData policy) { 3540 if (info == null) { 3541 throw new IllegalArgumentException("Bad admin: " + adminReceiver); 3542 } 3543 if (!info.getActivityInfo().applicationInfo.isInternal()) { 3544 throw new IllegalArgumentException("Only apps in internal storage can be active admin: " 3545 + adminReceiver); 3546 } 3547 if (info.getActivityInfo().applicationInfo.isInstantApp()) { 3548 throw new IllegalArgumentException("Instant apps cannot be device admins: " 3549 + adminReceiver); 3550 } 3551 if (policy.mRemovingAdmins.contains(adminReceiver)) { 3552 throw new IllegalArgumentException( 3553 "Trying to set an admin which is being removed"); 3554 } 3555 } 3556 3557 private void checkAllUsersAreAffiliatedWithDevice() { 3558 Preconditions.checkCallAuthorization(areAllUsersAffiliatedWithDeviceLocked(), 3559 "operation not allowed when device has unaffiliated users"); 3560 } 3561 3562 @Override 3563 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) { 3564 if (!mHasFeature) { 3565 return false; 3566 } 3567 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3568 3569 final CallerIdentity caller = getCallerIdentity(); 3570 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3571 3572 synchronized (getLockObject()) { 3573 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null; 3574 } 3575 } 3576 3577 @Override 3578 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) { 3579 if (!mHasFeature) { 3580 return false; 3581 } 3582 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3583 3584 final CallerIdentity caller = getCallerIdentity(); 3585 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3586 3587 synchronized (getLockObject()) { 3588 DevicePolicyData policyData = getUserData(userHandle); 3589 return policyData.mRemovingAdmins.contains(adminReceiver); 3590 } 3591 } 3592 3593 @Override 3594 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) { 3595 if (!mHasFeature) { 3596 return false; 3597 } 3598 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3599 3600 final CallerIdentity caller = getCallerIdentity(); 3601 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3602 3603 synchronized (getLockObject()) { 3604 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3605 if (administrator == null) { 3606 throw new SecurityException("No active admin " + adminReceiver); 3607 } 3608 return administrator.info.usesPolicy(policyId); 3609 } 3610 } 3611 3612 @Override 3613 @SuppressWarnings("unchecked") 3614 public List<ComponentName> getActiveAdmins(int userHandle) { 3615 if (!mHasFeature) { 3616 return Collections.EMPTY_LIST; 3617 } 3618 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3619 3620 final CallerIdentity caller = getCallerIdentity(); 3621 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3622 3623 synchronized (getLockObject()) { 3624 DevicePolicyData policy = getUserData(userHandle); 3625 final int N = policy.mAdminList.size(); 3626 if (N <= 0) { 3627 return null; 3628 } 3629 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N); 3630 for (int i=0; i<N; i++) { 3631 res.add(policy.mAdminList.get(i).info.getComponent()); 3632 } 3633 return res; 3634 } 3635 } 3636 3637 @Override 3638 public boolean packageHasActiveAdmins(String packageName, int userHandle) { 3639 if (!mHasFeature) { 3640 return false; 3641 } 3642 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3643 3644 final CallerIdentity caller = getCallerIdentity(); 3645 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3646 3647 synchronized (getLockObject()) { 3648 DevicePolicyData policy = getUserData(userHandle); 3649 final int N = policy.mAdminList.size(); 3650 for (int i=0; i<N; i++) { 3651 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) { 3652 return true; 3653 } 3654 } 3655 return false; 3656 } 3657 } 3658 3659 @Override 3660 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) { 3661 if (!mHasFeature) { 3662 return; 3663 } 3664 Objects.requireNonNull(adminReceiver, "ComponentName is null"); 3665 Preconditions.checkCallAuthorization(isAdb(getCallerIdentity()) 3666 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS), 3667 "Caller must be shell or hold MANAGE_PROFILE_AND_DEVICE_OWNERS to call " 3668 + "forceRemoveActiveAdmin"); 3669 mInjector.binderWithCleanCallingIdentity(() -> { 3670 boolean isOrgOwnedProfile = false; 3671 synchronized (getLockObject()) { 3672 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) { 3673 throw new SecurityException("Attempt to remove non-test admin " 3674 + adminReceiver + " " + userHandle); 3675 } 3676 3677 // If admin is a device or profile owner tidy that up first. 3678 if (isDeviceOwner(adminReceiver, userHandle)) { 3679 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle); 3680 } 3681 if (isProfileOwner(adminReceiver, userHandle)) { 3682 isOrgOwnedProfile = isProfileOwnerOfOrganizationOwnedDevice(userHandle); 3683 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, 3684 userHandle, /* parent */ false); 3685 clearProfileOwnerLocked(admin, userHandle); 3686 } 3687 } 3688 // Remove the admin skipping sending the broadcast. 3689 removeAdminArtifacts(adminReceiver, userHandle); 3690 3691 // In case of PO on org owned device, clean device-wide policies and restrictions. 3692 if (isOrgOwnedProfile) { 3693 final UserHandle parentUser = UserHandle.of(getProfileParentId(userHandle)); 3694 clearOrgOwnedProfileOwnerUserRestrictions(parentUser); 3695 clearOrgOwnedProfileOwnerDeviceWidePolicies(parentUser.getIdentifier()); 3696 } 3697 3698 Slogf.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle); 3699 }); 3700 } 3701 3702 private void clearOrgOwnedProfileOwnerUserRestrictions(UserHandle parentUserHandle) { 3703 mUserManager.setUserRestriction( 3704 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, false, parentUserHandle); 3705 mUserManager.setUserRestriction( 3706 UserManager.DISALLOW_ADD_USER, false, parentUserHandle); 3707 } 3708 3709 private void clearDeviceOwnerUserRestriction(UserHandle userHandle) { 3710 // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state 3711 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) { 3712 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle); 3713 } 3714 // When a device owner is set, the system automatically restricts adding a managed profile. 3715 // Remove this restriction when the device owner is cleared. 3716 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, userHandle)) { 3717 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false, 3718 userHandle); 3719 } 3720 } 3721 3722 /** 3723 * Return if a given package has testOnly="true", in which case we'll relax certain rules 3724 * for CTS. 3725 * 3726 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked} 3727 * to check wehter an active admin is test-only or not. 3728 * 3729 * The system allows this flag to be changed when an app is updated, which is not good 3730 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed, 3731 * and used the persisted version in actual checks. (See b/31382361 and b/28928996) 3732 */ 3733 private boolean isPackageTestOnly(String packageName, int userHandle) { 3734 final ApplicationInfo ai; 3735 try { 3736 ai = mInjector.getIPackageManager().getApplicationInfo(packageName, 3737 (PackageManager.MATCH_DIRECT_BOOT_AWARE 3738 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle); 3739 } catch (RemoteException e) { 3740 throw new IllegalStateException(e); 3741 } 3742 if (ai == null) { 3743 throw new IllegalStateException("Couldn't find package: " 3744 + packageName + " on user " + userHandle); 3745 } 3746 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0; 3747 } 3748 3749 /** 3750 * See {@link #isPackageTestOnly}. 3751 */ 3752 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) { 3753 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3754 return (admin != null) && admin.testOnlyAdmin; 3755 } 3756 3757 @Override 3758 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) { 3759 if (!mHasFeature) { 3760 return; 3761 } 3762 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3763 3764 final CallerIdentity caller = getCallerIdentity(); 3765 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3766 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_ACTIVE_ADMIN); 3767 enforceUserUnlocked(userHandle); 3768 3769 synchronized (getLockObject()) { 3770 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3771 if (admin == null) { 3772 return; 3773 } 3774 // Active device/profile owners must remain active admins. 3775 if (isDeviceOwner(adminReceiver, userHandle) 3776 || isProfileOwner(adminReceiver, userHandle)) { 3777 Slogf.e(LOG_TAG, "Device/profile owner cannot be removed: component=" 3778 + adminReceiver); 3779 return; 3780 } 3781 Preconditions.checkCallAuthorization(admin.getUid() == caller.getUid() 3782 || hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 3783 mInjector.binderWithCleanCallingIdentity(() -> 3784 removeActiveAdminLocked(adminReceiver, userHandle)); 3785 } 3786 } 3787 3788 @Override 3789 public boolean isSeparateProfileChallengeAllowed(int userHandle) { 3790 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 3791 String.format(NOT_SYSTEM_CALLER_MSG, "query separate challenge support")); 3792 3793 ComponentName profileOwner = getProfileOwnerAsUser(userHandle); 3794 // Profile challenge is supported on N or newer release. 3795 return profileOwner != null && 3796 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M; 3797 } 3798 3799 private boolean canSetPasswordQualityOnParent(String packageName, final CallerIdentity caller) { 3800 return !mInjector.isChangeEnabled( 3801 PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT, packageName, caller.getUserId()) 3802 || isProfileOwnerOfOrganizationOwnedDevice(caller); 3803 } 3804 3805 private boolean isPasswordLimitingAdminTargetingP(CallerIdentity caller) { 3806 if (!caller.hasAdminComponent()) { 3807 return false; 3808 } 3809 3810 synchronized (getLockObject()) { 3811 return getActiveAdminWithPolicyForUidLocked( 3812 caller.getComponentName(), DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, 3813 caller.getUid()) != null; 3814 } 3815 } 3816 3817 @Override 3818 public void setPasswordQuality(ComponentName who, int quality, boolean parent) { 3819 if (!mHasFeature) { 3820 return; 3821 } 3822 Objects.requireNonNull(who, "ComponentName is null"); 3823 validateQualityConstant(quality); 3824 3825 final CallerIdentity caller = getCallerIdentity(who); 3826 Preconditions.checkCallAuthorization( 3827 isProfileOwner(caller) || isDeviceOwner(caller) || isSystemUid(caller) 3828 || isPasswordLimitingAdminTargetingP(caller)); 3829 3830 if (parent) { 3831 Preconditions.checkCallAuthorization( 3832 canSetPasswordQualityOnParent(who.getPackageName(), caller), 3833 "Profile Owner may not apply password quality requirements device-wide"); 3834 } 3835 3836 final int userId = caller.getUserId(); 3837 synchronized (getLockObject()) { 3838 ActiveAdmin ap = getActiveAdminForCallerLocked( 3839 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3840 3841 // If setPasswordQuality is called on the parent, ensure that 3842 // the primary admin does not have password complexity state (this is an 3843 // unsupported state). 3844 if (parent) { 3845 final ActiveAdmin primaryAdmin = getActiveAdminForCallerLocked( 3846 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, false); 3847 final boolean hasComplexitySet = 3848 primaryAdmin.mPasswordComplexity != PASSWORD_COMPLEXITY_NONE; 3849 Preconditions.checkState(!hasComplexitySet, 3850 "Cannot set password quality when complexity is set on the primary admin." 3851 + " Set the primary admin's complexity to NONE first."); 3852 } 3853 mInjector.binderWithCleanCallingIdentity(() -> { 3854 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 3855 if (passwordPolicy.quality != quality) { 3856 passwordPolicy.quality = quality; 3857 ap.mPasswordComplexity = PASSWORD_COMPLEXITY_NONE; 3858 resetInactivePasswordRequirementsIfRPlus(userId, ap); 3859 updatePasswordValidityCheckpointLocked(userId, parent); 3860 updatePasswordQualityCacheForUserGroup(userId); 3861 saveSettingsLocked(userId); 3862 } 3863 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 3864 }); 3865 } 3866 DevicePolicyEventLogger 3867 .createEvent(DevicePolicyEnums.SET_PASSWORD_QUALITY) 3868 .setAdmin(who) 3869 .setInt(quality) 3870 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 3871 .write(); 3872 } 3873 3874 private boolean passwordQualityInvocationOrderCheckEnabled(String packageName, int userId) { 3875 return mInjector.isChangeEnabled(ADMIN_APP_PASSWORD_COMPLEXITY, packageName, userId); 3876 } 3877 3878 /** 3879 * For admins targeting R+ reset various password constraints to default values when quality is 3880 * set to a value that makes those constraints that have no effect. 3881 */ 3882 private void resetInactivePasswordRequirementsIfRPlus(int userId, ActiveAdmin admin) { 3883 if (passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(), userId)) { 3884 final PasswordPolicy policy = admin.mPasswordPolicy; 3885 if (policy.quality < PASSWORD_QUALITY_NUMERIC) { 3886 policy.length = PasswordPolicy.DEF_MINIMUM_LENGTH; 3887 } 3888 if (policy.quality < PASSWORD_QUALITY_COMPLEX) { 3889 policy.letters = PasswordPolicy.DEF_MINIMUM_LETTERS; 3890 policy.upperCase = PasswordPolicy.DEF_MINIMUM_UPPER_CASE; 3891 policy.lowerCase = PasswordPolicy.DEF_MINIMUM_LOWER_CASE; 3892 policy.numeric = PasswordPolicy.DEF_MINIMUM_NUMERIC; 3893 policy.symbols = PasswordPolicy.DEF_MINIMUM_SYMBOLS; 3894 policy.nonLetter = PasswordPolicy.DEF_MINIMUM_NON_LETTER; 3895 } 3896 } 3897 } 3898 3899 /** 3900 * Updates a flag that tells us whether the user's password currently satisfies the 3901 * requirements set by all of the user's active admins. 3902 * This should be called whenever the password or the admin policies have changed. The caller 3903 * is responsible for calling {@link #saveSettingsLocked} to persist the change. 3904 * 3905 * @return the set of user IDs that have been affected 3906 */ 3907 @GuardedBy("getLockObject()") 3908 private Set<Integer> updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) { 3909 final ArraySet<Integer> affectedUserIds = new ArraySet<>(); 3910 final int credentialOwner = getCredentialOwner(userHandle, parent); 3911 DevicePolicyData policy = getUserData(credentialOwner); 3912 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner); 3913 // Update the checkpoint only if the user's password metrics is known 3914 if (metrics != null) { 3915 final int userToCheck = getProfileParentUserIfRequested(userHandle, parent); 3916 final boolean newCheckpoint = isPasswordSufficientForUserWithoutCheckpointLocked( 3917 metrics, userToCheck); 3918 if (newCheckpoint != policy.mPasswordValidAtLastCheckpoint) { 3919 policy.mPasswordValidAtLastCheckpoint = newCheckpoint; 3920 affectedUserIds.add(credentialOwner); 3921 } 3922 } 3923 return affectedUserIds; 3924 } 3925 3926 /** 3927 * Update password quality values in policy cache for all users in the same user group as 3928 * the given user. The cached password quality for user X is the aggregated quality among all 3929 * admins who have influence of user X's screenlock, i.e. it's equivalent to the return value of 3930 * getPasswordQuality(null, user X, false). 3931 * 3932 * Caches for all users in the same user group often need to be updated alltogether because a 3933 * user's admin policy can affect another's aggregated password quality in some situation. 3934 * For example a managed profile's policy will affect the parent user if the profile has unified 3935 * challenge. A profile can also explicitly set a parent password quality which will affect the 3936 * aggregated password quality of the parent user. 3937 */ 3938 private void updatePasswordQualityCacheForUserGroup(@UserIdInt int userId) { 3939 final List<UserInfo> users; 3940 if (userId == UserHandle.USER_ALL) { 3941 users = mUserManager.getUsers(); 3942 } else { 3943 users = mUserManager.getProfiles(userId); 3944 } 3945 for (UserInfo userInfo : users) { 3946 final int currentUserId = userInfo.id; 3947 mPolicyCache.setPasswordQuality(currentUserId, 3948 getPasswordQuality(null, currentUserId, false)); 3949 } 3950 } 3951 3952 @Override 3953 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) { 3954 if (!mHasFeature) { 3955 return PASSWORD_QUALITY_UNSPECIFIED; 3956 } 3957 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3958 3959 final CallerIdentity caller = getCallerIdentity(); 3960 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3961 3962 synchronized (getLockObject()) { 3963 int mode = PASSWORD_QUALITY_UNSPECIFIED; 3964 3965 if (who != null) { 3966 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3967 return admin != null ? admin.mPasswordPolicy.quality : mode; 3968 } 3969 3970 // Return the strictest policy across all participating admins. 3971 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 3972 getProfileParentUserIfRequested(userHandle, parent)); 3973 final int N = admins.size(); 3974 for (int i = 0; i < N; i++) { 3975 ActiveAdmin admin = admins.get(i); 3976 if (mode < admin.mPasswordPolicy.quality) { 3977 mode = admin.mPasswordPolicy.quality; 3978 } 3979 } 3980 return mode; 3981 } 3982 } 3983 3984 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(int userHandle) { 3985 if (isSeparateProfileChallengeEnabled(userHandle)) { 3986 // If this user has a separate challenge, only return its restrictions. 3987 return getUserDataUnchecked(userHandle).mAdminList; 3988 } 3989 // If isSeparateProfileChallengeEnabled is false and userHandle points to a managed profile 3990 // we need to query the parent user who owns the credential. 3991 return getActiveAdminsForUserAndItsManagedProfilesLocked(getProfileParentId(userHandle), 3992 (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id)); 3993 } 3994 3995 /** 3996 * Get the list of active admins for an affected user: 3997 * <ul> 3998 * <li>The active admins associated with the userHandle itself</li> 3999 * <li>The parent active admins for each managed profile associated with the userHandle</li> 4000 * </ul> 4001 * 4002 * @param userHandle the affected user for whom to get the active admins 4003 * @return the list of active admins for the affected user 4004 */ 4005 @GuardedBy("getLockObject()") 4006 private List<ActiveAdmin> getActiveAdminsForAffectedUserLocked(int userHandle) { 4007 if (isManagedProfile(userHandle)) { 4008 return getUserDataUnchecked(userHandle).mAdminList; 4009 } 4010 return getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle, 4011 /* shouldIncludeProfileAdmins */ (user) -> false); 4012 } 4013 4014 /** 4015 * Returns the list of admins on the given user, as well as parent admins for each managed 4016 * profile associated with the given user. Optionally also include the admin of each managed 4017 * profile. 4018 * <p> Should not be called on a profile user. 4019 */ 4020 @GuardedBy("getLockObject()") 4021 private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesLocked(int userHandle, 4022 Predicate<UserInfo> shouldIncludeProfileAdmins) { 4023 ArrayList<ActiveAdmin> admins = new ArrayList<>(); 4024 mInjector.binderWithCleanCallingIdentity(() -> { 4025 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4026 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 4027 if (userInfo.id == userHandle) { 4028 admins.addAll(policy.mAdminList); 4029 } else if (userInfo.isManagedProfile()) { 4030 for (int i = 0; i < policy.mAdminList.size(); i++) { 4031 ActiveAdmin admin = policy.mAdminList.get(i); 4032 if (admin.hasParentActiveAdmin()) { 4033 admins.add(admin.getParentActiveAdmin()); 4034 } 4035 if (shouldIncludeProfileAdmins.test(userInfo)) { 4036 admins.add(admin); 4037 } 4038 } 4039 } else { 4040 Slogf.w(LOG_TAG, "Unknown user type: " + userInfo); 4041 } 4042 } 4043 }); 4044 return admins; 4045 } 4046 4047 private boolean isSeparateProfileChallengeEnabled(int userHandle) { 4048 return mInjector.binderWithCleanCallingIdentity(() -> 4049 mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)); 4050 } 4051 4052 @Override 4053 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) { 4054 if (!mHasFeature) { 4055 return; 4056 } 4057 Objects.requireNonNull(who, "ComponentName is null"); 4058 final int userId = mInjector.userHandleGetCallingUserId(); 4059 synchronized (getLockObject()) { 4060 ActiveAdmin ap = getActiveAdminForCallerLocked( 4061 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4062 ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_NUMERIC, "setPasswordMinimumLength"); 4063 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4064 if (passwordPolicy.length != length) { 4065 passwordPolicy.length = length; 4066 updatePasswordValidityCheckpointLocked(userId, parent); 4067 saveSettingsLocked(userId); 4068 } 4069 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4070 } 4071 DevicePolicyEventLogger 4072 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LENGTH) 4073 .setAdmin(who) 4074 .setInt(length) 4075 .write(); 4076 } 4077 4078 private void ensureMinimumQuality( 4079 int userId, ActiveAdmin admin, int minimumQuality, String operation) { 4080 mInjector.binderWithCleanCallingIdentity(() -> { 4081 // This check will also take care of the case where the password requirements 4082 // are specified as complexity rather than quality: When a password complexity 4083 // is set, the quality is reset to "unspecified" which will be below any value 4084 // of minimumQuality. 4085 if (admin.mPasswordPolicy.quality < minimumQuality 4086 && passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(), 4087 userId)) { 4088 throw new IllegalStateException(String.format( 4089 "password quality should be at least %d for %s", 4090 minimumQuality, operation)); 4091 } 4092 }); 4093 } 4094 4095 @Override 4096 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) { 4097 return getStrictestPasswordRequirement(who, userHandle, parent, 4098 admin -> admin.mPasswordPolicy.length, PASSWORD_QUALITY_NUMERIC); 4099 } 4100 4101 @Override 4102 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) { 4103 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4104 return; 4105 } 4106 Objects.requireNonNull(who, "ComponentName is null"); 4107 final int userId = mInjector.userHandleGetCallingUserId(); 4108 synchronized (getLockObject()) { 4109 ActiveAdmin ap = getActiveAdminForCallerLocked( 4110 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4111 if (ap.passwordHistoryLength != length) { 4112 ap.passwordHistoryLength = length; 4113 updatePasswordValidityCheckpointLocked(userId, parent); 4114 saveSettingsLocked(userId); 4115 } 4116 } 4117 if (SecurityLog.isLoggingEnabled()) { 4118 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4119 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET, 4120 who.getPackageName(), userId, affectedUserId, length); 4121 } 4122 } 4123 4124 @Override 4125 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) { 4126 if (!mLockPatternUtils.hasSecureLockScreen()) { 4127 return 0; 4128 } 4129 return getStrictestPasswordRequirement(who, userHandle, parent, 4130 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED); 4131 } 4132 4133 @Override 4134 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) { 4135 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4136 return; 4137 } 4138 Objects.requireNonNull(who, "ComponentName is null"); 4139 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms"); 4140 final int userHandle = mInjector.userHandleGetCallingUserId(); 4141 synchronized (getLockObject()) { 4142 ActiveAdmin ap = getActiveAdminForCallerLocked( 4143 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent); 4144 // Calling this API automatically bumps the expiration date 4145 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 4146 ap.passwordExpirationDate = expiration; 4147 ap.passwordExpirationTimeout = timeout; 4148 if (timeout > 0L) { 4149 Slogf.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 4150 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 4151 .format(new Date(expiration))); 4152 } 4153 saveSettingsLocked(userHandle); 4154 4155 // in case this is the first one, set the alarm on the appropriate user. 4156 setExpirationAlarmCheckLocked(mContext, userHandle, parent); 4157 } 4158 if (SecurityLog.isLoggingEnabled()) { 4159 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 4160 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(), 4161 userHandle, affectedUserId, timeout); 4162 } 4163 } 4164 4165 /** 4166 * Return a single admin's expiration cycle time, or the min of all cycle times. 4167 * Returns 0 if not configured. 4168 */ 4169 @Override 4170 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) { 4171 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4172 return 0L; 4173 } 4174 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4175 4176 final CallerIdentity caller = getCallerIdentity(); 4177 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4178 4179 synchronized (getLockObject()) { 4180 long timeout = 0L; 4181 4182 if (who != null) { 4183 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4184 return admin != null ? admin.passwordExpirationTimeout : timeout; 4185 } 4186 4187 // Return the strictest policy across all participating admins. 4188 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4189 getProfileParentUserIfRequested(userHandle, parent)); 4190 final int N = admins.size(); 4191 for (int i = 0; i < N; i++) { 4192 ActiveAdmin admin = admins.get(i); 4193 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 4194 && timeout > admin.passwordExpirationTimeout)) { 4195 timeout = admin.passwordExpirationTimeout; 4196 } 4197 } 4198 return timeout; 4199 } 4200 } 4201 4202 @Override 4203 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4204 Objects.requireNonNull(admin, "ComponentName is null"); 4205 4206 final CallerIdentity caller = getCallerIdentity(admin); 4207 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 4208 List<String> changedProviders = null; 4209 4210 synchronized (getLockObject()) { 4211 ActiveAdmin activeAdmin = getProfileOwnerLocked(caller); 4212 if (activeAdmin.crossProfileWidgetProviders == null) { 4213 activeAdmin.crossProfileWidgetProviders = new ArrayList<>(); 4214 } 4215 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4216 if (!providers.contains(packageName)) { 4217 providers.add(packageName); 4218 changedProviders = new ArrayList<>(providers); 4219 saveSettingsLocked(caller.getUserId()); 4220 } 4221 } 4222 4223 DevicePolicyEventLogger 4224 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_WIDGET_PROVIDER) 4225 .setAdmin(admin) 4226 .write(); 4227 4228 if (changedProviders != null) { 4229 mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(), 4230 changedProviders); 4231 return true; 4232 } 4233 4234 return false; 4235 } 4236 4237 @Override 4238 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4239 Objects.requireNonNull(admin, "ComponentName is null"); 4240 4241 final CallerIdentity caller = getCallerIdentity(admin); 4242 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 4243 List<String> changedProviders = null; 4244 4245 synchronized (getLockObject()) { 4246 ActiveAdmin activeAdmin = getProfileOwnerLocked(caller); 4247 if (activeAdmin.crossProfileWidgetProviders == null 4248 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4249 return false; 4250 } 4251 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4252 if (providers.remove(packageName)) { 4253 changedProviders = new ArrayList<>(providers); 4254 saveSettingsLocked(caller.getUserId()); 4255 } 4256 } 4257 4258 DevicePolicyEventLogger 4259 .createEvent(DevicePolicyEnums.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER) 4260 .setAdmin(admin) 4261 .write(); 4262 4263 if (changedProviders != null) { 4264 mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(), 4265 changedProviders); 4266 return true; 4267 } 4268 4269 return false; 4270 } 4271 4272 @Override 4273 public List<String> getCrossProfileWidgetProviders(ComponentName admin) { 4274 Objects.requireNonNull(admin, "ComponentName is null"); 4275 4276 final CallerIdentity caller = getCallerIdentity(admin); 4277 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 4278 4279 synchronized (getLockObject()) { 4280 ActiveAdmin activeAdmin = getProfileOwnerLocked(caller); 4281 if (activeAdmin.crossProfileWidgetProviders == null 4282 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4283 return null; 4284 } 4285 if (mInjector.binderIsCallingUidMyUid()) { 4286 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders); 4287 } else { 4288 return activeAdmin.crossProfileWidgetProviders; 4289 } 4290 } 4291 } 4292 4293 /** 4294 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 4295 * Returns 0 if not configured. 4296 */ 4297 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) { 4298 long timeout = 0L; 4299 4300 if (who != null) { 4301 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4302 return admin != null ? admin.passwordExpirationDate : timeout; 4303 } 4304 4305 // Return the strictest policy across all participating admins. 4306 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4307 getProfileParentUserIfRequested(userHandle, parent)); 4308 final int N = admins.size(); 4309 for (int i = 0; i < N; i++) { 4310 ActiveAdmin admin = admins.get(i); 4311 if (timeout == 0L || (admin.passwordExpirationDate != 0 4312 && timeout > admin.passwordExpirationDate)) { 4313 timeout = admin.passwordExpirationDate; 4314 } 4315 } 4316 return timeout; 4317 } 4318 4319 @Override 4320 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) { 4321 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4322 return 0L; 4323 } 4324 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4325 4326 final CallerIdentity caller = getCallerIdentity(); 4327 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4328 4329 synchronized (getLockObject()) { 4330 return getPasswordExpirationLocked(who, userHandle, parent); 4331 } 4332 } 4333 4334 @Override 4335 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) { 4336 if (!mHasFeature) { 4337 return; 4338 } 4339 Objects.requireNonNull(who, "ComponentName is null"); 4340 final int userId = mInjector.userHandleGetCallingUserId(); 4341 synchronized (getLockObject()) { 4342 final ActiveAdmin ap = getActiveAdminForCallerLocked( 4343 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4344 ensureMinimumQuality( 4345 userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumUpperCase"); 4346 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4347 if (passwordPolicy.upperCase != length) { 4348 passwordPolicy.upperCase = length; 4349 updatePasswordValidityCheckpointLocked(userId, parent); 4350 saveSettingsLocked(userId); 4351 } 4352 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4353 } 4354 DevicePolicyEventLogger 4355 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_UPPER_CASE) 4356 .setAdmin(who) 4357 .setInt(length) 4358 .write(); 4359 } 4360 4361 @Override 4362 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) { 4363 return getStrictestPasswordRequirement(who, userHandle, parent, 4364 admin -> admin.mPasswordPolicy.upperCase, PASSWORD_QUALITY_COMPLEX); 4365 } 4366 4367 @Override 4368 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) { 4369 Objects.requireNonNull(who, "ComponentName is null"); 4370 final int userId = mInjector.userHandleGetCallingUserId(); 4371 synchronized (getLockObject()) { 4372 ActiveAdmin ap = getActiveAdminForCallerLocked( 4373 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4374 ensureMinimumQuality( 4375 userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLowerCase"); 4376 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4377 if (passwordPolicy.lowerCase != length) { 4378 passwordPolicy.lowerCase = length; 4379 updatePasswordValidityCheckpointLocked(userId, parent); 4380 saveSettingsLocked(userId); 4381 } 4382 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4383 } 4384 DevicePolicyEventLogger 4385 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LOWER_CASE) 4386 .setAdmin(who) 4387 .setInt(length) 4388 .write(); 4389 } 4390 4391 @Override 4392 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) { 4393 return getStrictestPasswordRequirement(who, userHandle, parent, 4394 admin -> admin.mPasswordPolicy.lowerCase, PASSWORD_QUALITY_COMPLEX); 4395 } 4396 4397 @Override 4398 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) { 4399 if (!mHasFeature) { 4400 return; 4401 } 4402 Objects.requireNonNull(who, "ComponentName is null"); 4403 final int userId = mInjector.userHandleGetCallingUserId(); 4404 synchronized (getLockObject()) { 4405 ActiveAdmin ap = getActiveAdminForCallerLocked( 4406 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4407 ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLetters"); 4408 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4409 if (passwordPolicy.letters != length) { 4410 passwordPolicy.letters = length; 4411 updatePasswordValidityCheckpointLocked(userId, parent); 4412 saveSettingsLocked(userId); 4413 } 4414 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4415 } 4416 DevicePolicyEventLogger 4417 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LETTERS) 4418 .setAdmin(who) 4419 .setInt(length) 4420 .write(); 4421 } 4422 4423 @Override 4424 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) { 4425 return getStrictestPasswordRequirement(who, userHandle, parent, 4426 admin -> admin.mPasswordPolicy.letters, PASSWORD_QUALITY_COMPLEX); 4427 } 4428 4429 @Override 4430 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) { 4431 if (!mHasFeature) { 4432 return; 4433 } 4434 Objects.requireNonNull(who, "ComponentName is null"); 4435 final int userId = mInjector.userHandleGetCallingUserId(); 4436 synchronized (getLockObject()) { 4437 ActiveAdmin ap = getActiveAdminForCallerLocked( 4438 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4439 ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNumeric"); 4440 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4441 if (passwordPolicy.numeric != length) { 4442 passwordPolicy.numeric = length; 4443 updatePasswordValidityCheckpointLocked(userId, parent); 4444 saveSettingsLocked(userId); 4445 } 4446 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4447 } 4448 DevicePolicyEventLogger 4449 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NUMERIC) 4450 .setAdmin(who) 4451 .setInt(length) 4452 .write(); 4453 } 4454 4455 @Override 4456 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) { 4457 return getStrictestPasswordRequirement(who, userHandle, parent, 4458 admin -> admin.mPasswordPolicy.numeric, PASSWORD_QUALITY_COMPLEX); 4459 } 4460 4461 @Override 4462 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) { 4463 if (!mHasFeature) { 4464 return; 4465 } 4466 Objects.requireNonNull(who, "ComponentName is null"); 4467 final int userId = mInjector.userHandleGetCallingUserId(); 4468 synchronized (getLockObject()) { 4469 ActiveAdmin ap = getActiveAdminForCallerLocked( 4470 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4471 ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumSymbols"); 4472 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4473 if (passwordPolicy.symbols != length) { 4474 ap.mPasswordPolicy.symbols = length; 4475 updatePasswordValidityCheckpointLocked(userId, parent); 4476 saveSettingsLocked(userId); 4477 } 4478 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4479 } 4480 DevicePolicyEventLogger 4481 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_SYMBOLS) 4482 .setAdmin(who) 4483 .setInt(length) 4484 .write(); 4485 } 4486 4487 @Override 4488 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) { 4489 return getStrictestPasswordRequirement(who, userHandle, parent, 4490 admin -> admin.mPasswordPolicy.symbols, PASSWORD_QUALITY_COMPLEX); 4491 } 4492 4493 @Override 4494 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) { 4495 if (!mHasFeature) { 4496 return; 4497 } 4498 Objects.requireNonNull(who, "ComponentName is null"); 4499 final int userId = mInjector.userHandleGetCallingUserId(); 4500 synchronized (getLockObject()) { 4501 ActiveAdmin ap = getActiveAdminForCallerLocked( 4502 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4503 ensureMinimumQuality( 4504 userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNonLetter"); 4505 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4506 if (passwordPolicy.nonLetter != length) { 4507 ap.mPasswordPolicy.nonLetter = length; 4508 updatePasswordValidityCheckpointLocked(userId, parent); 4509 saveSettingsLocked(userId); 4510 } 4511 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4512 } 4513 DevicePolicyEventLogger 4514 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NON_LETTER) 4515 .setAdmin(who) 4516 .setInt(length) 4517 .write(); 4518 } 4519 4520 @Override 4521 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) { 4522 return getStrictestPasswordRequirement(who, userHandle, parent, 4523 admin -> admin.mPasswordPolicy.nonLetter, PASSWORD_QUALITY_COMPLEX); 4524 } 4525 4526 /** 4527 * Calculates strictest (maximum) value for a given password property enforced by admin[s]. 4528 */ 4529 private int getStrictestPasswordRequirement(ComponentName who, int userHandle, 4530 boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) { 4531 if (!mHasFeature) { 4532 return 0; 4533 } 4534 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4535 4536 final CallerIdentity caller = getCallerIdentity(); 4537 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4538 4539 synchronized (getLockObject()) { 4540 if (who != null) { 4541 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4542 return admin != null ? getter.apply(admin) : 0; 4543 } 4544 4545 int maxValue = 0; 4546 final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4547 getProfileParentUserIfRequested(userHandle, parent)); 4548 final int N = admins.size(); 4549 for (int i = 0; i < N; i++) { 4550 final ActiveAdmin admin = admins.get(i); 4551 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) { 4552 continue; 4553 } 4554 final Integer adminValue = getter.apply(admin); 4555 if (adminValue > maxValue) { 4556 maxValue = adminValue; 4557 } 4558 } 4559 return maxValue; 4560 } 4561 } 4562 4563 /** 4564 * Calculates strictest (maximum) value for a given password property enforced by admin[s]. 4565 */ 4566 @Override 4567 public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle, 4568 boolean deviceWideOnly) { 4569 final CallerIdentity caller = getCallerIdentity(); 4570 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4571 return getPasswordMinimumMetricsUnchecked(userHandle, deviceWideOnly); 4572 } 4573 4574 private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId) { 4575 return getPasswordMinimumMetricsUnchecked(userId, false); 4576 } 4577 4578 private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId, 4579 boolean deviceWideOnly) { 4580 if (!mHasFeature) { 4581 new PasswordMetrics(CREDENTIAL_TYPE_NONE); 4582 } 4583 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 4584 if (deviceWideOnly) { 4585 Preconditions.checkArgument(!isManagedProfile(userId)); 4586 } 4587 4588 ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>(); 4589 final List<ActiveAdmin> admins; 4590 synchronized (getLockObject()) { 4591 if (deviceWideOnly) { 4592 admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userId, 4593 /* shouldIncludeProfileAdmins */ (user) -> false); 4594 } else { 4595 admins = getActiveAdminsForLockscreenPoliciesLocked(userId); 4596 } 4597 for (ActiveAdmin admin : admins) { 4598 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics()); 4599 } 4600 } 4601 return PasswordMetrics.merge(adminMetrics); 4602 } 4603 4604 @Override 4605 public boolean isActivePasswordSufficient(int userHandle, boolean parent) { 4606 if (!mHasFeature) { 4607 return true; 4608 } 4609 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4610 4611 final CallerIdentity caller = getCallerIdentity(); 4612 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4613 enforceUserUnlocked(userHandle, parent); 4614 4615 synchronized (getLockObject()) { 4616 // This API can only be called by an active device admin, 4617 // so try to retrieve it to check that the caller is one. 4618 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4619 int credentialOwner = getCredentialOwner(userHandle, parent); 4620 DevicePolicyData policy = getUserDataUnchecked(credentialOwner); 4621 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner); 4622 final int userToCheck = getProfileParentUserIfRequested(userHandle, parent); 4623 boolean activePasswordSufficientForUserLocked = isActivePasswordSufficientForUserLocked( 4624 policy.mPasswordValidAtLastCheckpoint, metrics, userToCheck); 4625 return activePasswordSufficientForUserLocked; 4626 } 4627 } 4628 4629 @Override 4630 public boolean isActivePasswordSufficientForDeviceRequirement() { 4631 if (!mHasFeature) { 4632 return true; 4633 } 4634 final CallerIdentity caller = getCallerIdentity(); 4635 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 4636 4637 final int profileUserId = caller.getUserId(); 4638 Preconditions.checkCallingUser(isManagedProfile(profileUserId)); 4639 4640 // This method is always called on the parent DPM instance to check if its password (i.e. 4641 // the device password) is sufficient for all explicit password requirement set on it 4642 // So retrieve the parent user Id to which the device password belongs. 4643 final int parentUser = getProfileParentId(profileUserId); 4644 enforceUserUnlocked(parentUser); 4645 4646 final boolean isSufficient; 4647 synchronized (getLockObject()) { 4648 4649 int complexity = getAggregatedPasswordComplexityLocked(parentUser, true); 4650 PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(parentUser, true); 4651 4652 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(parentUser); 4653 final List<PasswordValidationError> passwordValidationErrors = 4654 PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics); 4655 isSufficient = passwordValidationErrors.isEmpty(); 4656 } 4657 DevicePolicyEventLogger 4658 .createEvent(DevicePolicyEnums.IS_ACTIVE_PASSWORD_SUFFICIENT_FOR_DEVICE) 4659 .setStrings(mOwners.getProfileOwnerComponent(caller.getUserId()).getPackageName()) 4660 .write(); 4661 return isSufficient; 4662 } 4663 4664 @Override 4665 public boolean isUsingUnifiedPassword(ComponentName admin) { 4666 if (!mHasFeature) { 4667 return true; 4668 } 4669 Objects.requireNonNull(admin, "ComponentName is null"); 4670 4671 final CallerIdentity caller = getCallerIdentity(admin); 4672 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 4673 Preconditions.checkCallingUser(isManagedProfile(caller.getUserId())); 4674 4675 return !isSeparateProfileChallengeEnabled(caller.getUserId()); 4676 } 4677 4678 @Override 4679 public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) { 4680 if (!mHasFeature) { 4681 return true; 4682 } 4683 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4684 4685 final CallerIdentity caller = getCallerIdentity(); 4686 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4687 Preconditions.checkCallAuthorization(!isManagedProfile(userHandle), 4688 "You can not check password sufficiency for a managed profile, userId = %d", 4689 userHandle); 4690 enforceUserUnlocked(userHandle); 4691 4692 synchronized (getLockObject()) { 4693 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(userHandle); 4694 4695 // Combine password policies across the user and its profiles. Profile admins are 4696 // included if the profile is to be unified or currently has unified challenge 4697 List<ActiveAdmin> admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle, 4698 /* shouldIncludeProfileAdmins */ (user) -> user.id == profileUser 4699 || !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id)); 4700 ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>(admins.size()); 4701 int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE; 4702 for (ActiveAdmin admin : admins) { 4703 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics()); 4704 maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity); 4705 } 4706 return PasswordMetrics.validatePasswordMetrics(PasswordMetrics.merge(adminMetrics), 4707 maxRequiredComplexity, metrics).isEmpty(); 4708 } 4709 } 4710 4711 private boolean isActivePasswordSufficientForUserLocked( 4712 boolean passwordValidAtLastCheckpoint, @Nullable PasswordMetrics metrics, 4713 int userHandle) { 4714 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) { 4715 // Before user enters their password for the first time after a reboot, return the 4716 // value of this flag, which tells us whether the password was valid the last time 4717 // settings were saved. If DPC changes password requirements on boot so that the 4718 // current password no longer meets the requirements, this value will be stale until 4719 // the next time the password is entered. 4720 return passwordValidAtLastCheckpoint; 4721 } 4722 4723 if (metrics == null) { 4724 // Called on a FBE device when the user password exists but its metrics is unknown. 4725 // This shouldn't happen since we enforce the user to be unlocked (which would result 4726 // in the metrics known to the framework on a FBE device) at all call sites. 4727 throw new IllegalStateException("isActivePasswordSufficient called on FBE-locked user"); 4728 } 4729 4730 return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle); 4731 } 4732 4733 /** 4734 * Returns {@code true} if the password represented by the {@code metrics} argument 4735 * sufficiently fulfills the password requirements for the user corresponding to 4736 * {@code userId}. 4737 */ 4738 private boolean isPasswordSufficientForUserWithoutCheckpointLocked( 4739 @NonNull PasswordMetrics metrics, @UserIdInt int userId) { 4740 final int complexity = getAggregatedPasswordComplexityLocked(userId); 4741 PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userId); 4742 final List<PasswordValidationError> passwordValidationErrors = 4743 PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics); 4744 return passwordValidationErrors.isEmpty(); 4745 } 4746 4747 @Override 4748 @PasswordComplexity 4749 public int getPasswordComplexity(boolean parent) { 4750 final CallerIdentity caller = getCallerIdentity(); 4751 DevicePolicyEventLogger 4752 .createEvent(DevicePolicyEnums.GET_USER_PASSWORD_COMPLEXITY_LEVEL) 4753 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT, 4754 mInjector.getPackageManager().getPackagesForUid(caller.getUid())) 4755 .write(); 4756 4757 enforceUserUnlocked(caller.getUserId()); 4758 if (parent) { 4759 Preconditions.checkCallAuthorization( 4760 isDeviceOwner(caller) || isProfileOwner(caller) || isSystemUid(caller), 4761 "Only profile owner, device owner and system may call this method on parent."); 4762 } else { 4763 Preconditions.checkCallAuthorization( 4764 hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY) 4765 || isDeviceOwner(caller) || isProfileOwner(caller), 4766 "Must have " + REQUEST_PASSWORD_COMPLEXITY 4767 + " permission, or be a profile owner or device owner."); 4768 } 4769 4770 synchronized (getLockObject()) { 4771 final int credentialOwner = getCredentialOwner(caller.getUserId(), parent); 4772 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner); 4773 return metrics == null ? PASSWORD_COMPLEXITY_NONE : metrics.determineComplexity(); 4774 } 4775 } 4776 4777 @Override 4778 public void setRequiredPasswordComplexity(int passwordComplexity, boolean calledOnParent) { 4779 if (!mHasFeature) { 4780 return; 4781 } 4782 final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW, 4783 PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH); 4784 Preconditions.checkArgument(allowedModes.contains(passwordComplexity), 4785 "Provided complexity is not one of the allowed values."); 4786 4787 final CallerIdentity caller = getCallerIdentity(); 4788 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 4789 Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller)); 4790 4791 synchronized (getLockObject()) { 4792 final ActiveAdmin admin = getParentOfAdminIfRequired( 4793 getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParent); 4794 if (admin.mPasswordComplexity != passwordComplexity) { 4795 // We require the caller to explicitly clear any password quality requirements set 4796 // on the parent DPM instance, to avoid the case where password requirements are 4797 // specified in the form of quality on the parent but complexity on the profile 4798 // itself. 4799 if (!calledOnParent) { 4800 final boolean hasQualityRequirementsOnParent = admin.hasParentActiveAdmin() 4801 && admin.getParentActiveAdmin().mPasswordPolicy.quality 4802 != PASSWORD_QUALITY_UNSPECIFIED; 4803 Preconditions.checkState(!hasQualityRequirementsOnParent, 4804 "Password quality is set on the parent when attempting to set password" 4805 + "complexity. Clear the quality by setting the password quality " 4806 + "on the parent to PASSWORD_QUALITY_UNSPECIFIED first"); 4807 } 4808 4809 mInjector.binderWithCleanCallingIdentity(() -> { 4810 admin.mPasswordComplexity = passwordComplexity; 4811 // Reset the password policy. 4812 admin.mPasswordPolicy = new PasswordPolicy(); 4813 updatePasswordValidityCheckpointLocked(caller.getUserId(), calledOnParent); 4814 updatePasswordQualityCacheForUserGroup(caller.getUserId()); 4815 saveSettingsLocked(caller.getUserId()); 4816 }); 4817 4818 DevicePolicyEventLogger 4819 .createEvent(DevicePolicyEnums.SET_PASSWORD_COMPLEXITY) 4820 .setAdmin(admin.info.getPackageName()) 4821 .setInt(passwordComplexity) 4822 .setBoolean(calledOnParent) 4823 .write(); 4824 } 4825 logPasswordComplexityRequiredIfSecurityLogEnabled(admin.info.getComponent(), 4826 caller.getUserId(), calledOnParent, passwordComplexity); 4827 } 4828 } 4829 4830 private void logPasswordComplexityRequiredIfSecurityLogEnabled(ComponentName who, int userId, 4831 boolean parent, int complexity) { 4832 if (SecurityLog.isLoggingEnabled()) { 4833 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4834 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_REQUIRED, 4835 who.getPackageName(), userId, affectedUserId, complexity); 4836 } 4837 } 4838 4839 private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle) { 4840 return getAggregatedPasswordComplexityLocked(userHandle, false); 4841 } 4842 4843 private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle, 4844 boolean deviceWideOnly) { 4845 ensureLocked(); 4846 final List<ActiveAdmin> admins; 4847 if (deviceWideOnly) { 4848 admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle, 4849 /* shouldIncludeProfileAdmins */ (user) -> false); 4850 } else { 4851 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle); 4852 } 4853 int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE; 4854 for (ActiveAdmin admin : admins) { 4855 maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity); 4856 } 4857 return maxRequiredComplexity; 4858 } 4859 4860 @Override 4861 public int getRequiredPasswordComplexity(boolean calledOnParent) { 4862 if (!mHasFeature) { 4863 return PASSWORD_COMPLEXITY_NONE; 4864 } 4865 4866 final CallerIdentity caller = getCallerIdentity(); 4867 Preconditions.checkCallAuthorization( 4868 isDeviceOwner(caller) || isProfileOwner(caller)); 4869 4870 Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller)); 4871 4872 synchronized (getLockObject()) { 4873 final ActiveAdmin requiredAdmin = getParentOfAdminIfRequired( 4874 getDeviceOrProfileOwnerAdminLocked(caller.getUserId()), calledOnParent); 4875 return requiredAdmin.mPasswordComplexity; 4876 } 4877 } 4878 4879 @Override 4880 public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) { 4881 if (!mHasFeature) { 4882 return PASSWORD_COMPLEXITY_NONE; 4883 } 4884 4885 final CallerIdentity caller = getCallerIdentity(); 4886 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 4887 4888 synchronized (getLockObject()) { 4889 return getAggregatedPasswordComplexityLocked(userId, deviceWideOnly); 4890 } 4891 } 4892 4893 4894 @Override 4895 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) { 4896 if (!mLockPatternUtils.hasSecureLockScreen()) { 4897 return 0; 4898 } 4899 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4900 4901 final CallerIdentity caller = getCallerIdentity(); 4902 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4903 4904 synchronized (getLockObject()) { 4905 if (!isSystemUid(caller)) { 4906 // This API can be called by an active device admin or by keyguard code. 4907 if (!hasCallingPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)) { 4908 getActiveAdminForCallerLocked( 4909 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4910 } 4911 } 4912 4913 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4914 4915 return policy.mFailedPasswordAttempts; 4916 } 4917 } 4918 4919 @Override 4920 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) { 4921 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4922 return; 4923 } 4924 Objects.requireNonNull(who, "ComponentName is null"); 4925 final int userId = mInjector.userHandleGetCallingUserId(); 4926 synchronized (getLockObject()) { 4927 // This API can only be called by an active device admin, 4928 // so try to retrieve it to check that the caller is one. 4929 getActiveAdminForCallerLocked( 4930 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent); 4931 ActiveAdmin ap = getActiveAdminForCallerLocked( 4932 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4933 if (ap.maximumFailedPasswordsForWipe != num) { 4934 ap.maximumFailedPasswordsForWipe = num; 4935 saveSettingsLocked(userId); 4936 } 4937 } 4938 if (SecurityLog.isLoggingEnabled()) { 4939 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4940 SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(), 4941 userId, affectedUserId, num); 4942 } 4943 } 4944 4945 @Override 4946 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) { 4947 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4948 return 0; 4949 } 4950 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4951 4952 final CallerIdentity caller = getCallerIdentity(); 4953 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4954 4955 synchronized (getLockObject()) { 4956 ActiveAdmin admin = (who != null) 4957 ? getActiveAdminUncheckedLocked(who, userHandle, parent) 4958 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent); 4959 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 4960 } 4961 } 4962 4963 @Override 4964 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) { 4965 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4966 return UserHandle.USER_NULL; 4967 } 4968 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4969 4970 final CallerIdentity caller = getCallerIdentity(); 4971 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4972 4973 synchronized (getLockObject()) { 4974 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked( 4975 userHandle, parent); 4976 return admin != null ? getUserIdToWipeForFailedPasswords(admin) : UserHandle.USER_NULL; 4977 } 4978 } 4979 4980 /** 4981 * Returns the admin with the strictest policy on maximum failed passwords for: 4982 * <ul> 4983 * <li>this user if it has a separate profile challenge, or 4984 * <li>this user and all profiles that don't have their own challenge otherwise. 4985 * </ul> 4986 * <p>If the policy for the primary and any other profile are equal, it returns the admin for 4987 * the primary profile. Policy of a PO on an organization-owned device applies to the primary 4988 * profile. 4989 * Returns {@code null} if no participating admin has that policy set. 4990 */ 4991 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked( 4992 int userHandle, boolean parent) { 4993 int count = 0; 4994 ActiveAdmin strictestAdmin = null; 4995 4996 // Return the strictest policy across all participating admins. 4997 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4998 getProfileParentUserIfRequested(userHandle, parent)); 4999 final int N = admins.size(); 5000 for (int i = 0; i < N; i++) { 5001 ActiveAdmin admin = admins.get(i); 5002 if (admin.maximumFailedPasswordsForWipe == 5003 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 5004 continue; // No max number of failed passwords policy set for this profile. 5005 } 5006 5007 // We always favor the primary profile if several profiles have the same value set. 5008 final int userId = getUserIdToWipeForFailedPasswords(admin); 5009 if (count == 0 || 5010 count > admin.maximumFailedPasswordsForWipe || 5011 (count == admin.maximumFailedPasswordsForWipe && 5012 getUserInfo(userId).isPrimary())) { 5013 count = admin.maximumFailedPasswordsForWipe; 5014 strictestAdmin = admin; 5015 } 5016 } 5017 return strictestAdmin; 5018 } 5019 5020 private UserInfo getUserInfo(@UserIdInt int userId) { 5021 return mInjector.binderWithCleanCallingIdentity(() -> mUserManager.getUserInfo(userId)); 5022 } 5023 5024 private boolean setPasswordPrivileged(@NonNull String password, int flags, 5025 CallerIdentity caller) { 5026 // Only allow setting password on an unsecured user 5027 if (isLockScreenSecureUnchecked(caller.getUserId())) { 5028 throw new SecurityException("Cannot change current password"); 5029 } 5030 return resetPasswordInternal(password, 0, null, flags, caller); 5031 } 5032 5033 @Override 5034 public boolean resetPassword(@Nullable String password, int flags) throws RemoteException { 5035 if (!mLockPatternUtils.hasSecureLockScreen()) { 5036 Slogf.w(LOG_TAG, "Cannot reset password when the device has no lock screen"); 5037 return false; 5038 } 5039 if (password == null) password = ""; 5040 final CallerIdentity caller = getCallerIdentity(); 5041 final int userHandle = caller.getUserId(); 5042 5043 // As of R, only privileged caller holding RESET_PASSWORD can call resetPassword() to 5044 // set password to an unsecured user. 5045 if (hasCallingPermission(permission.RESET_PASSWORD)) { 5046 final boolean result = setPasswordPrivileged(password, flags, caller); 5047 if (result) { 5048 DevicePolicyEventLogger 5049 .createEvent(DevicePolicyEnums.RESET_PASSWORD) 5050 .write(); 5051 } 5052 return result; 5053 } 5054 5055 // If caller has PO (or DO) throw or fail silently depending on its target SDK level. 5056 if (isDeviceOwner(caller) || isProfileOwner(caller)) { 5057 synchronized (getLockObject()) { 5058 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 5059 if (getTargetSdk(admin.info.getPackageName(), userHandle) < Build.VERSION_CODES.O) { 5060 Slogf.e(LOG_TAG, "DPC can no longer call resetPassword()"); 5061 return false; 5062 } 5063 throw new SecurityException("Device admin can no longer call resetPassword()"); 5064 } 5065 } 5066 5067 // Caller is not DO or PO, could either be unauthorized or Device Admin. 5068 synchronized (getLockObject()) { 5069 // Legacy device admin cannot call resetPassword either 5070 ActiveAdmin admin = getActiveAdminForCallerLocked( 5071 null, DeviceAdminInfo.USES_POLICY_RESET_PASSWORD, false); 5072 Preconditions.checkCallAuthorization(admin != null, 5073 "Unauthorized caller cannot call resetPassword."); 5074 if (getTargetSdk(admin.info.getPackageName(), 5075 userHandle) <= android.os.Build.VERSION_CODES.M) { 5076 Slogf.e(LOG_TAG, "Device admin can no longer call resetPassword()"); 5077 return false; 5078 } 5079 throw new SecurityException("Device admin can no longer call resetPassword()"); 5080 } 5081 } 5082 5083 private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token, 5084 int flags, CallerIdentity caller) { 5085 final int callingUid = caller.getUid(); 5086 final int userHandle = UserHandle.getUserId(callingUid); 5087 final boolean isPin = PasswordMetrics.isNumericOnly(password); 5088 synchronized (getLockObject()) { 5089 final PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userHandle); 5090 final List<PasswordValidationError> validationErrors; 5091 final int complexity = getAggregatedPasswordComplexityLocked(userHandle); 5092 // TODO: Consider changing validation API to take LockscreenCredential. 5093 if (password.isEmpty()) { 5094 validationErrors = PasswordMetrics.validatePasswordMetrics( 5095 minMetrics, complexity, new PasswordMetrics(CREDENTIAL_TYPE_NONE)); 5096 } else { 5097 // TODO(b/120484642): remove getBytes() below 5098 validationErrors = PasswordMetrics.validatePassword( 5099 minMetrics, complexity, isPin, password.getBytes()); 5100 } 5101 5102 if (!validationErrors.isEmpty()) { 5103 Slogf.w(LOG_TAG, "Failed to reset password due to constraint violation: %s", 5104 validationErrors.get(0)); 5105 return false; 5106 } 5107 } 5108 5109 DevicePolicyData policy = getUserData(userHandle); 5110 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 5111 Slogf.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 5112 return false; 5113 } 5114 5115 boolean callerIsDeviceOwnerAdmin = isDeviceOwner(caller); 5116 boolean doNotAskCredentialsOnBoot = 5117 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 5118 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 5119 setDoNotAskCredentialsOnBoot(); 5120 } 5121 5122 // Don't do this with the lock held, because it is going to call 5123 // back in to the service. 5124 final long ident = mInjector.binderClearCallingIdentity(); 5125 final LockscreenCredential newCredential; 5126 if (isPin) { 5127 newCredential = LockscreenCredential.createPin(password); 5128 } else { 5129 newCredential = LockscreenCredential.createPasswordOrNone(password); 5130 } 5131 try { 5132 if (tokenHandle == 0 || token == null) { 5133 if (!mLockPatternUtils.setLockCredential(newCredential, 5134 LockscreenCredential.createNone(), userHandle)) { 5135 return false; 5136 } 5137 } else { 5138 if (!mLockPatternUtils.setLockCredentialWithToken(newCredential, tokenHandle, 5139 token, userHandle)) { 5140 return false; 5141 } 5142 } 5143 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 5144 if (requireEntry) { 5145 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, 5146 UserHandle.USER_ALL); 5147 } 5148 synchronized (getLockObject()) { 5149 int newOwner = requireEntry ? callingUid : -1; 5150 if (policy.mPasswordOwner != newOwner) { 5151 policy.mPasswordOwner = newOwner; 5152 saveSettingsLocked(userHandle); 5153 } 5154 } 5155 } finally { 5156 mInjector.binderRestoreCallingIdentity(ident); 5157 } 5158 return true; 5159 } 5160 5161 private boolean isLockScreenSecureUnchecked(int userId) { 5162 return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.isSecure(userId)); 5163 } 5164 5165 private void setDoNotAskCredentialsOnBoot() { 5166 synchronized (getLockObject()) { 5167 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 5168 if (!policyData.mDoNotAskCredentialsOnBoot) { 5169 policyData.mDoNotAskCredentialsOnBoot = true; 5170 saveSettingsLocked(UserHandle.USER_SYSTEM); 5171 } 5172 } 5173 } 5174 5175 @Override 5176 public boolean getDoNotAskCredentialsOnBoot() { 5177 Preconditions.checkCallAuthorization( 5178 hasCallingOrSelfPermission(permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT)); 5179 synchronized (getLockObject()) { 5180 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 5181 return policyData.mDoNotAskCredentialsOnBoot; 5182 } 5183 } 5184 5185 @Override 5186 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) { 5187 if (!mHasFeature) { 5188 return; 5189 } 5190 Objects.requireNonNull(who, "ComponentName is null"); 5191 final int userHandle = mInjector.userHandleGetCallingUserId(); 5192 synchronized (getLockObject()) { 5193 final ActiveAdmin ap = getActiveAdminForCallerLocked( 5194 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 5195 if (ap.maximumTimeToUnlock != timeMs) { 5196 ap.maximumTimeToUnlock = timeMs; 5197 saveSettingsLocked(userHandle); 5198 updateMaximumTimeToLockLocked(userHandle); 5199 } 5200 } 5201 if (SecurityLog.isLoggingEnabled()) { 5202 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 5203 SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET, 5204 who.getPackageName(), userHandle, affectedUserId, timeMs); 5205 } 5206 } 5207 5208 private void updateMaximumTimeToLockLocked(@UserIdInt int userId) { 5209 // Update the profile's timeout 5210 if (isManagedProfile(userId)) { 5211 updateProfileLockTimeoutLocked(userId); 5212 } 5213 5214 mInjector.binderWithCleanCallingIdentity(() -> { 5215 // Update the device timeout 5216 final int parentId = getProfileParentId(userId); 5217 final long timeMs = getMaximumTimeToLockPolicyFromAdmins( 5218 getActiveAdminsForLockscreenPoliciesLocked(parentId)); 5219 5220 final DevicePolicyData policy = getUserDataUnchecked(parentId); 5221 if (policy.mLastMaximumTimeToLock == timeMs) { 5222 return; 5223 } 5224 policy.mLastMaximumTimeToLock = timeMs; 5225 5226 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) { 5227 // Make sure KEEP_SCREEN_ON is disabled, since that 5228 // would allow bypassing of the maximum time to lock. 5229 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 5230 } 5231 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5232 UserHandle.USER_SYSTEM, timeMs); 5233 }); 5234 } 5235 5236 private void updateProfileLockTimeoutLocked(@UserIdInt int userId) { 5237 final long timeMs; 5238 if (isSeparateProfileChallengeEnabled(userId)) { 5239 timeMs = getMaximumTimeToLockPolicyFromAdmins( 5240 getActiveAdminsForLockscreenPoliciesLocked(userId)); 5241 } else { 5242 timeMs = Long.MAX_VALUE; 5243 } 5244 5245 final DevicePolicyData policy = getUserDataUnchecked(userId); 5246 if (policy.mLastMaximumTimeToLock == timeMs) { 5247 return; 5248 } 5249 policy.mLastMaximumTimeToLock = timeMs; 5250 5251 mInjector.binderWithCleanCallingIdentity(() -> 5252 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5253 userId, policy.mLastMaximumTimeToLock)); 5254 } 5255 5256 @Override 5257 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) { 5258 if (!mHasFeature) { 5259 return 0; 5260 } 5261 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 5262 5263 final CallerIdentity caller = getCallerIdentity(); 5264 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 5265 5266 synchronized (getLockObject()) { 5267 if (who != null) { 5268 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 5269 return admin != null ? admin.maximumTimeToUnlock : 0; 5270 } 5271 // Return the strictest policy across all participating admins. 5272 final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5273 getProfileParentUserIfRequested(userHandle, parent)); 5274 final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins); 5275 return timeMs == Long.MAX_VALUE ? 0 : timeMs; 5276 } 5277 } 5278 5279 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) { 5280 long time = Long.MAX_VALUE; 5281 for (final ActiveAdmin admin : admins) { 5282 if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) { 5283 time = admin.maximumTimeToUnlock; 5284 } 5285 } 5286 return time; 5287 } 5288 5289 @Override 5290 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, 5291 boolean parent) { 5292 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 5293 return; 5294 } 5295 Objects.requireNonNull(who, "ComponentName is null"); 5296 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number."); 5297 final CallerIdentity caller = getCallerIdentity(who); 5298 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 5299 // timeoutMs with value 0 means that the admin doesn't participate 5300 // timeoutMs is clamped to the interval in case the internal constants change in the future 5301 final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs(); 5302 if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) { 5303 timeoutMs = minimumStrongAuthTimeout; 5304 } 5305 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 5306 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5307 } 5308 5309 final int userHandle = caller.getUserId(); 5310 boolean changed = false; 5311 synchronized (getLockObject()) { 5312 ActiveAdmin ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller), 5313 parent); 5314 if (ap.strongAuthUnlockTimeout != timeoutMs) { 5315 ap.strongAuthUnlockTimeout = timeoutMs; 5316 saveSettingsLocked(userHandle); 5317 changed = true; 5318 } 5319 } 5320 if (changed) { 5321 mLockSettingsInternal.refreshStrongAuthTimeout(userHandle); 5322 // Refreshes the parent if profile has unified challenge, since the timeout would 5323 // also affect the parent user in this case. 5324 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 5325 mLockSettingsInternal.refreshStrongAuthTimeout(getProfileParentId(userHandle)); 5326 } 5327 } 5328 } 5329 5330 /** 5331 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all 5332 * admins if who is null. 5333 * Returns 0 if not configured for the provided admin. 5334 */ 5335 @Override 5336 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) { 5337 if (!mHasFeature) { 5338 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5339 } 5340 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 5341 5342 final CallerIdentity caller = getCallerIdentity(); 5343 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 5344 5345 if (!mLockPatternUtils.hasSecureLockScreen()) { 5346 // No strong auth timeout on devices not supporting the 5347 // {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature 5348 return 0; 5349 } 5350 synchronized (getLockObject()) { 5351 if (who != null) { 5352 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent); 5353 return admin != null ? admin.strongAuthUnlockTimeout : 0; 5354 } 5355 5356 // Return the strictest policy across all participating admins. 5357 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5358 getProfileParentUserIfRequested(userId, parent)); 5359 5360 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5361 for (int i = 0; i < admins.size(); i++) { 5362 final long timeout = admins.get(i).strongAuthUnlockTimeout; 5363 if (timeout != 0) { // take only participating admins into account 5364 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout); 5365 } 5366 } 5367 return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs()); 5368 } 5369 } 5370 5371 private long getMinimumStrongAuthTimeoutMs() { 5372 if (!mInjector.isBuildDebuggable()) { 5373 return MINIMUM_STRONG_AUTH_TIMEOUT_MS; 5374 } 5375 // ideally the property was named persist.sys.min_strong_auth_timeout, but system property 5376 // name cannot be longer than 31 characters 5377 return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo", 5378 MINIMUM_STRONG_AUTH_TIMEOUT_MS), 5379 MINIMUM_STRONG_AUTH_TIMEOUT_MS); 5380 } 5381 5382 @Override 5383 public void lockNow(int flags, boolean parent) { 5384 final CallerIdentity caller = getCallerIdentity(); 5385 5386 final int callingUserId = caller.getUserId(); 5387 ComponentName adminComponent = null; 5388 synchronized (getLockObject()) { 5389 // Make sure the caller has any active admin with the right policy or 5390 // the required permission. 5391 final ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked( 5392 null, 5393 DeviceAdminInfo.USES_POLICY_FORCE_LOCK, 5394 parent, 5395 android.Manifest.permission.LOCK_DEVICE); 5396 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOCK_NOW); 5397 final long ident = mInjector.binderClearCallingIdentity(); 5398 try { 5399 adminComponent = admin == null ? null : admin.info.getComponent(); 5400 if (adminComponent != null) { 5401 // For Profile Owners only, callers with only permission not allowed. 5402 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) { 5403 // Evict key 5404 Preconditions.checkCallingUser(isManagedProfile(callingUserId)); 5405 Preconditions.checkArgument(!parent, 5406 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent"); 5407 if (!isProfileOwner(adminComponent, callingUserId)) { 5408 throw new SecurityException("Only profile owner admins can set " 5409 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 5410 } 5411 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5412 throw new UnsupportedOperationException( 5413 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices"); 5414 } 5415 mUserManager.evictCredentialEncryptionKey(callingUserId); 5416 } 5417 } 5418 5419 // Lock all users unless this is a managed profile with a separate challenge 5420 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId) 5421 ? UserHandle.USER_ALL : callingUserId); 5422 mLockPatternUtils.requireStrongAuth( 5423 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock); 5424 5425 // Require authentication for the device or profile 5426 if (userToLock == UserHandle.USER_ALL) { 5427 if (mIsAutomotive) { 5428 if (VERBOSE_LOG) { 5429 Slogf.v(LOG_TAG, "lockNow(): not powering off display on automotive" 5430 + " build"); 5431 } 5432 } else { 5433 // Power off the display 5434 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(), 5435 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 5436 } 5437 mInjector.getIWindowManager().lockNow(null); 5438 } else { 5439 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true); 5440 } 5441 5442 if (SecurityLog.isLoggingEnabled() && adminComponent != null) { 5443 final int affectedUserId = 5444 parent ? getProfileParentId(callingUserId) : callingUserId; 5445 SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK, 5446 adminComponent.getPackageName(), callingUserId, affectedUserId); 5447 } 5448 } catch (RemoteException e) { 5449 } finally { 5450 mInjector.binderRestoreCallingIdentity(ident); 5451 } 5452 } 5453 DevicePolicyEventLogger 5454 .createEvent(DevicePolicyEnums.LOCK_NOW) 5455 .setAdmin(adminComponent) 5456 .setInt(flags) 5457 .write(); 5458 } 5459 5460 @Override 5461 public void enforceCanManageCaCerts(ComponentName who, String callerPackage) { 5462 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5463 Preconditions.checkCallAuthorization(canManageCaCerts(caller)); 5464 } 5465 5466 private boolean canManageCaCerts(CallerIdentity caller) { 5467 return (caller.hasAdminComponent() && (isDeviceOwner(caller) || isProfileOwner(caller))) 5468 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_INSTALL)) 5469 || hasCallingOrSelfPermission(MANAGE_CA_CERTIFICATES); 5470 } 5471 5472 @Override 5473 public boolean approveCaCert(String alias, int userId, boolean approval) { 5474 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 5475 5476 synchronized (getLockObject()) { 5477 Set<String> certs = getUserData(userId).mAcceptedCaCertificates; 5478 boolean changed = (approval ? certs.add(alias) : certs.remove(alias)); 5479 if (!changed) { 5480 return false; 5481 } 5482 saveSettingsLocked(userId); 5483 } 5484 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5485 return true; 5486 } 5487 5488 @Override 5489 public boolean isCaCertApproved(String alias, int userId) { 5490 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 5491 5492 synchronized (getLockObject()) { 5493 return getUserData(userId).mAcceptedCaCertificates.contains(alias); 5494 } 5495 } 5496 5497 private Set<Integer> removeCaApprovalsIfNeeded(int userId) { 5498 final ArraySet<Integer> affectedUserIds = new ArraySet<>(); 5499 for (UserInfo userInfo : mUserManager.getProfiles(userId)) { 5500 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id); 5501 if (userInfo.isManagedProfile()){ 5502 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id)); 5503 } 5504 if (!isSecure) { 5505 synchronized (getLockObject()) { 5506 getUserData(userInfo.id).mAcceptedCaCertificates.clear(); 5507 affectedUserIds.add(userInfo.id); 5508 } 5509 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5510 } 5511 } 5512 return affectedUserIds; 5513 } 5514 5515 @Override 5516 public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) { 5517 if (!mHasFeature) { 5518 return false; 5519 } 5520 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 5521 Preconditions.checkCallAuthorization(canManageCaCerts(caller)); 5522 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_CA_CERT); 5523 5524 final String alias = mInjector.binderWithCleanCallingIdentity(() -> { 5525 String installedAlias = mCertificateMonitor.installCaCert( 5526 caller.getUserHandle(), certBuffer); 5527 DevicePolicyEventLogger 5528 .createEvent(DevicePolicyEnums.INSTALL_CA_CERT) 5529 .setAdmin(caller.getPackageName()) 5530 .setBoolean(/* isDelegate */ admin == null) 5531 .write(); 5532 return installedAlias; 5533 }); 5534 5535 if (alias == null) { 5536 Slogf.w(LOG_TAG, "Problem installing cert"); 5537 return false; 5538 } 5539 5540 synchronized (getLockObject()) { 5541 getUserData(caller.getUserId()).mOwnerInstalledCaCerts.add(alias); 5542 saveSettingsLocked(caller.getUserId()); 5543 } 5544 return true; 5545 } 5546 5547 @Override 5548 public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) { 5549 if (!mHasFeature) { 5550 return; 5551 } 5552 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 5553 Preconditions.checkCallAuthorization(canManageCaCerts(caller)); 5554 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_UNINSTALL_CA_CERT); 5555 5556 mInjector.binderWithCleanCallingIdentity(() -> { 5557 mCertificateMonitor.uninstallCaCerts(caller.getUserHandle(), aliases); 5558 DevicePolicyEventLogger 5559 .createEvent(DevicePolicyEnums.UNINSTALL_CA_CERTS) 5560 .setAdmin(caller.getPackageName()) 5561 .setBoolean(/* isDelegate */ admin == null) 5562 .write(); 5563 }); 5564 5565 synchronized (getLockObject()) { 5566 if (getUserData(caller.getUserId()).mOwnerInstalledCaCerts.removeAll( 5567 Arrays.asList(aliases))) { 5568 saveSettingsLocked(caller.getUserId()); 5569 } 5570 } 5571 } 5572 5573 @Override 5574 public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey, 5575 byte[] cert, byte[] chain, String alias, boolean requestAccess, 5576 boolean isUserSelectable) { 5577 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5578 final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 5579 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 5580 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 5581 && (isProfileOwner(caller) || isDeviceOwner(caller))) 5582 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp))); 5583 if (isCredentialManagementApp) { 5584 Preconditions.checkCallAuthorization(!isUserSelectable, "The credential " 5585 + "management app is not allowed to install a user selectable key pair"); 5586 Preconditions.checkCallAuthorization( 5587 isAliasInCredentialManagementAppPolicy(caller, alias), 5588 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 5589 } 5590 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_KEY_PAIR); 5591 5592 final long id = mInjector.binderClearCallingIdentity(); 5593 try { 5594 final KeyChainConnection keyChainConnection = 5595 KeyChain.bindAsUser(mContext, caller.getUserHandle()); 5596 try { 5597 IKeyChainService keyChain = keyChainConnection.getService(); 5598 if (!keyChain.installKeyPair(privKey, cert, chain, alias, KeyStore.UID_SELF)) { 5599 logInstallKeyPairFailure(caller, isCredentialManagementApp); 5600 return false; 5601 } 5602 if (requestAccess) { 5603 keyChain.setGrant(caller.getUid(), alias, true); 5604 } 5605 keyChain.setUserSelectable(alias, isUserSelectable); 5606 DevicePolicyEventLogger 5607 .createEvent(DevicePolicyEnums.INSTALL_KEY_PAIR) 5608 .setAdmin(caller.getPackageName()) 5609 .setBoolean(/* isDelegate */ isCallerDelegate) 5610 .setStrings(isCredentialManagementApp 5611 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP) 5612 .write(); 5613 return true; 5614 } catch (RemoteException e) { 5615 Slogf.e(LOG_TAG, "Installing certificate", e); 5616 } finally { 5617 keyChainConnection.close(); 5618 } 5619 } catch (InterruptedException e) { 5620 Slogf.w(LOG_TAG, "Interrupted while installing certificate", e); 5621 Thread.currentThread().interrupt(); 5622 } finally { 5623 mInjector.binderRestoreCallingIdentity(id); 5624 } 5625 logInstallKeyPairFailure(caller, isCredentialManagementApp); 5626 return false; 5627 } 5628 5629 private void logInstallKeyPairFailure(CallerIdentity caller, 5630 boolean isCredentialManagementApp) { 5631 if (!isCredentialManagementApp) { 5632 return; 5633 } 5634 DevicePolicyEventLogger 5635 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_INSTALL_KEY_PAIR_FAILED) 5636 .setStrings(caller.getPackageName()) 5637 .write(); 5638 } 5639 5640 @Override 5641 public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) { 5642 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5643 final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 5644 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 5645 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 5646 && (isProfileOwner(caller) || isDeviceOwner(caller))) 5647 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp))); 5648 if (isCredentialManagementApp) { 5649 Preconditions.checkCallAuthorization( 5650 isAliasInCredentialManagementAppPolicy(caller, alias), 5651 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 5652 } 5653 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_KEY_PAIR); 5654 5655 final long id = Binder.clearCallingIdentity(); 5656 try { 5657 final KeyChainConnection keyChainConnection = 5658 KeyChain.bindAsUser(mContext, caller.getUserHandle()); 5659 try { 5660 IKeyChainService keyChain = keyChainConnection.getService(); 5661 DevicePolicyEventLogger 5662 .createEvent(DevicePolicyEnums.REMOVE_KEY_PAIR) 5663 .setAdmin(caller.getPackageName()) 5664 .setBoolean(/* isDelegate */ isCallerDelegate) 5665 .setStrings(isCredentialManagementApp 5666 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP) 5667 .write(); 5668 return keyChain.removeKeyPair(alias); 5669 } catch (RemoteException e) { 5670 Slogf.e(LOG_TAG, "Removing keypair", e); 5671 } finally { 5672 keyChainConnection.close(); 5673 } 5674 } catch (InterruptedException e) { 5675 Slogf.w(LOG_TAG, "Interrupted while removing keypair", e); 5676 Thread.currentThread().interrupt(); 5677 } finally { 5678 Binder.restoreCallingIdentity(id); 5679 } 5680 return false; 5681 } 5682 5683 @Override 5684 public boolean hasKeyPair(String callerPackage, String alias) { 5685 final CallerIdentity caller = getCallerIdentity(callerPackage); 5686 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 5687 Preconditions.checkCallAuthorization(canInstallCertificates(caller) 5688 || isCredentialManagementApp); 5689 if (isCredentialManagementApp) { 5690 Preconditions.checkCallAuthorization( 5691 isAliasInCredentialManagementAppPolicy(caller, alias), 5692 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 5693 } 5694 5695 return mInjector.binderWithCleanCallingIdentity(() -> { 5696 try (KeyChainConnection keyChainConnection = 5697 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 5698 return keyChainConnection.getService().containsKeyPair(alias); 5699 } catch (RemoteException e) { 5700 Slogf.e(LOG_TAG, "Querying keypair", e); 5701 } catch (InterruptedException e) { 5702 Slogf.w(LOG_TAG, "Interrupted while querying keypair", e); 5703 Thread.currentThread().interrupt(); 5704 } 5705 return false; 5706 }); 5707 } 5708 5709 private boolean canInstallCertificates(CallerIdentity caller) { 5710 return isProfileOwner(caller) || isDeviceOwner(caller) 5711 || isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 5712 } 5713 5714 private boolean canChooseCertificates(CallerIdentity caller) { 5715 return isProfileOwner(caller) || isDeviceOwner(caller) 5716 || isCallerDelegate(caller, DELEGATION_CERT_SELECTION); 5717 } 5718 5719 @Override 5720 public boolean setKeyGrantToWifiAuth(String callerPackage, String alias, boolean hasGrant) { 5721 Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty"); 5722 5723 final CallerIdentity caller = getCallerIdentity(callerPackage); 5724 Preconditions.checkCallAuthorization(canChooseCertificates(caller)); 5725 5726 return setKeyChainGrantInternal(alias, hasGrant, Process.WIFI_UID, caller.getUserHandle()); 5727 } 5728 5729 @Override 5730 public boolean isKeyPairGrantedToWifiAuth(String callerPackage, String alias) { 5731 Preconditions.checkStringNotEmpty(alias, "Alias to check cannot be empty"); 5732 5733 final CallerIdentity caller = getCallerIdentity(callerPackage); 5734 Preconditions.checkCallAuthorization(canChooseCertificates(caller)); 5735 5736 return mInjector.binderWithCleanCallingIdentity(() -> { 5737 try (KeyChainConnection keyChainConnection = 5738 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 5739 final List<String> result = new ArrayList<>(); 5740 final int[] granteeUids = keyChainConnection.getService().getGrants(alias); 5741 5742 for (final int uid : granteeUids) { 5743 if (uid == Process.WIFI_UID) { 5744 return true; 5745 } 5746 } 5747 return false; 5748 } catch (RemoteException e) { 5749 Slogf.e(LOG_TAG, "Querying grant to wifi auth.", e); 5750 return false; 5751 } 5752 }); 5753 } 5754 5755 @Override 5756 public boolean setKeyGrantForApp(ComponentName who, String callerPackage, String alias, 5757 String packageName, boolean hasGrant) { 5758 Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty"); 5759 Preconditions.checkStringNotEmpty(packageName, "Package to grant to cannot be empty"); 5760 5761 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5762 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 5763 && (isProfileOwner(caller) || isDeviceOwner(caller))) 5764 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_SELECTION))); 5765 5766 final int granteeUid; 5767 try { 5768 ApplicationInfo ai = mInjector.getIPackageManager().getApplicationInfo( 5769 packageName, 0, caller.getUserId()); 5770 Preconditions.checkArgument(ai != null, 5771 "Provided package %s is not installed", packageName); 5772 granteeUid = ai.uid; 5773 } catch (RemoteException e) { 5774 throw new IllegalStateException("Failure getting grantee uid", e); 5775 } 5776 5777 return setKeyChainGrantInternal(alias, hasGrant, granteeUid, caller.getUserHandle()); 5778 } 5779 5780 private boolean setKeyChainGrantInternal(String alias, boolean hasGrant, int granteeUid, 5781 UserHandle userHandle) { 5782 final long id = mInjector.binderClearCallingIdentity(); 5783 try { 5784 try (KeyChainConnection keyChainConnection = 5785 KeyChain.bindAsUser(mContext, userHandle)) { 5786 IKeyChainService keyChain = keyChainConnection.getService(); 5787 return keyChain.setGrant(granteeUid, alias, hasGrant); 5788 } catch (RemoteException e) { 5789 Slogf.e(LOG_TAG, "Setting grant for package.", e); 5790 return false; 5791 } 5792 } catch (InterruptedException e) { 5793 Slogf.w(LOG_TAG, "Interrupted while setting key grant", e); 5794 Thread.currentThread().interrupt(); 5795 } finally { 5796 mInjector.binderRestoreCallingIdentity(id); 5797 } 5798 return false; 5799 } 5800 5801 @Override 5802 public ParcelableGranteeMap getKeyPairGrants(String callerPackage, String alias) { 5803 final CallerIdentity caller = getCallerIdentity(callerPackage); 5804 Preconditions.checkCallAuthorization(canChooseCertificates(caller)); 5805 5806 final ArrayMap<Integer, Set<String>> result = new ArrayMap<>(); 5807 mInjector.binderWithCleanCallingIdentity(() -> { 5808 try (KeyChainConnection keyChainConnection = 5809 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 5810 final int[] granteeUids = keyChainConnection.getService().getGrants(alias); 5811 final PackageManager pm = mInjector.getPackageManager(caller.getUserId()); 5812 5813 for (final int uid : granteeUids) { 5814 final String[] packages = pm.getPackagesForUid(uid); 5815 if (packages == null) { 5816 Slogf.wtf(LOG_TAG, "No packages found for uid " + uid); 5817 continue; 5818 } 5819 result.put(uid, new ArraySet<String>(packages)); 5820 } 5821 } catch (RemoteException e) { 5822 Slogf.e(LOG_TAG, "Querying keypair grants", e); 5823 } catch (InterruptedException e) { 5824 Slogf.w(LOG_TAG, "Interrupted while querying keypair grants", e); 5825 Thread.currentThread().interrupt(); 5826 } 5827 }); 5828 return new ParcelableGranteeMap(result); 5829 } 5830 5831 /** 5832 * Enforce one the following conditions are met: 5833 * (1) The device has a Device Owner, and one of the following holds: 5834 * (1.1) The caller is the Device Owner 5835 * (1.2) The caller is another app in the same user as the device owner, AND 5836 * The caller is the delegated certificate installer. 5837 * (2) The user has a profile owner, AND: 5838 * (2.1) The profile owner has been granted access to Device IDs and one of the following 5839 * holds: 5840 * (2.1.1) The caller is the profile owner. 5841 * (2.1.2) The caller is from another app in the same user as the profile owner, AND 5842 * (2.1.2.1) The caller is the delegated cert installer. 5843 * 5844 * For the device owner case, simply check that the caller is the device owner or the 5845 * delegated certificate installer. 5846 * 5847 * For the profile owner case, first check that the caller is the profile owner or can 5848 * manage the DELEGATION_CERT_INSTALL scope. 5849 * If that check succeeds, ensure the profile owner was granted access to device 5850 * identifiers. The grant is transitive: The delegated cert installer is implicitly allowed 5851 * access to device identifiers in this case as part of the delegation. 5852 */ 5853 @VisibleForTesting 5854 public void enforceCallerCanRequestDeviceIdAttestation(CallerIdentity caller) 5855 throws SecurityException { 5856 /** 5857 * First check if there's a profile owner because the device could be in COMP mode (where 5858 * there's a device owner and profile owner on the same device). 5859 * If the caller is from the work profile, then it must be the PO or the delegate, and 5860 * it must have the right permission to access device identifiers. 5861 */ 5862 if (hasProfileOwner(caller.getUserId())) { 5863 // Make sure that the caller is the profile owner or delegate. 5864 Preconditions.checkCallAuthorization(canInstallCertificates(caller)); 5865 // Verify that the managed profile is on an organization-owned device and as such 5866 // the profile owner can access Device IDs. 5867 if (isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId())) { 5868 return; 5869 } 5870 throw new SecurityException( 5871 "Profile Owner is not allowed to access Device IDs."); 5872 } 5873 5874 // If not, fall back to the device owner check. 5875 Preconditions.checkCallAuthorization( 5876 isDeviceOwner(caller) || isCallerDelegate(caller, DELEGATION_CERT_INSTALL)); 5877 } 5878 5879 @VisibleForTesting 5880 public static int[] translateIdAttestationFlags( 5881 int idAttestationFlags) { 5882 Map<Integer, Integer> idTypeToAttestationFlag = new HashMap(); 5883 idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL); 5884 idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI); 5885 idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID); 5886 idTypeToAttestationFlag.put( 5887 ID_TYPE_INDIVIDUAL_ATTESTATION, USE_INDIVIDUAL_ATTESTATION); 5888 5889 int numFlagsSet = Integer.bitCount(idAttestationFlags); 5890 // No flags are set - return null to indicate no device ID attestation information should 5891 // be included in the attestation record. 5892 if (numFlagsSet == 0) { 5893 return null; 5894 } 5895 5896 // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if 5897 // no other flag is set. That will lead to inclusion of general device make data in the 5898 // attestation record, but no specific device identifiers. 5899 if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) { 5900 numFlagsSet -= 1; 5901 idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO); 5902 } 5903 5904 int[] attestationUtilsFlags = new int[numFlagsSet]; 5905 int i = 0; 5906 for (Integer idType: idTypeToAttestationFlag.keySet()) { 5907 if ((idType & idAttestationFlags) != 0) { 5908 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType); 5909 } 5910 } 5911 5912 return attestationUtilsFlags; 5913 } 5914 5915 @Override 5916 public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm, 5917 ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags, 5918 KeymasterCertificateChain attestationChain) { 5919 // Get attestation flags, if any. 5920 final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags); 5921 final boolean deviceIdAttestationRequired = attestationUtilsFlags != null; 5922 KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec(); 5923 final String alias = keySpec.getKeystoreAlias(); 5924 5925 Preconditions.checkStringNotEmpty(alias, "Empty alias provided"); 5926 Preconditions.checkArgument( 5927 !deviceIdAttestationRequired || keySpec.getAttestationChallenge() != null, 5928 "Requested Device ID attestation but challenge is empty"); 5929 5930 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5931 final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 5932 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 5933 if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) { 5934 // TODO: replace enforce methods 5935 enforceCallerCanRequestDeviceIdAttestation(caller); 5936 enforceIndividualAttestationSupportedIfRequested(attestationUtilsFlags); 5937 } else { 5938 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 5939 && (isProfileOwner(caller) || isDeviceOwner(caller))) 5940 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp))); 5941 if (isCredentialManagementApp) { 5942 Preconditions.checkCallAuthorization( 5943 isAliasInCredentialManagementAppPolicy(caller, alias), 5944 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 5945 } 5946 } 5947 5948 if (TextUtils.isEmpty(alias)) { 5949 throw new IllegalArgumentException("Empty alias provided."); 5950 } 5951 // As the caller will be granted access to the key, ensure no UID was specified, as 5952 // it will not have the desired effect. 5953 if (keySpec.getUid() != KeyStore.UID_SELF) { 5954 Slogf.e(LOG_TAG, "Only the caller can be granted access to the generated keypair."); 5955 logGenerateKeyPairFailure(caller, isCredentialManagementApp); 5956 return false; 5957 } 5958 5959 if (deviceIdAttestationRequired) { 5960 if (keySpec.getAttestationChallenge() == null) { 5961 throw new IllegalArgumentException( 5962 "Requested Device ID attestation but challenge is empty."); 5963 } 5964 KeyGenParameterSpec.Builder specBuilder = new KeyGenParameterSpec.Builder(keySpec); 5965 specBuilder.setAttestationIds(attestationUtilsFlags); 5966 specBuilder.setDevicePropertiesAttestationIncluded(true); 5967 keySpec = specBuilder.build(); 5968 } 5969 5970 final long id = mInjector.binderClearCallingIdentity(); 5971 try { 5972 try (KeyChainConnection keyChainConnection = 5973 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 5974 IKeyChainService keyChain = keyChainConnection.getService(); 5975 5976 final int generationResult = keyChain.generateKeyPair(algorithm, 5977 new ParcelableKeyGenParameterSpec(keySpec)); 5978 if (generationResult != KeyChain.KEY_GEN_SUCCESS) { 5979 Slogf.e(LOG_TAG, "KeyChain failed to generate a keypair, error %d.", 5980 generationResult); 5981 logGenerateKeyPairFailure(caller, isCredentialManagementApp); 5982 switch (generationResult) { 5983 case KeyChain.KEY_GEN_STRONGBOX_UNAVAILABLE: 5984 throw new ServiceSpecificException( 5985 DevicePolicyManager.KEY_GEN_STRONGBOX_UNAVAILABLE, 5986 String.format("KeyChain error: %d", generationResult)); 5987 case KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS: 5988 throw new UnsupportedOperationException( 5989 "Device does not support Device ID attestation."); 5990 default: 5991 return false; 5992 } 5993 } 5994 5995 // Set a grant for the caller here so that when the client calls 5996 // requestPrivateKey, it will be able to get the key from Keystore. 5997 // Note the use of the calling UID, since the request for the private 5998 // key will come from the client's process, so the grant has to be for 5999 // that UID. 6000 keyChain.setGrant(caller.getUid(), alias, true); 6001 6002 try { 6003 final List<byte[]> encodedCerts = new ArrayList(); 6004 final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 6005 final byte[] certChainBytes = keyChain.getCaCertificates(alias); 6006 encodedCerts.add(keyChain.getCertificate(alias)); 6007 if (certChainBytes != null) { 6008 final Collection<X509Certificate> certs = 6009 (Collection<X509Certificate>) certFactory.generateCertificates( 6010 new ByteArrayInputStream(certChainBytes)); 6011 for (X509Certificate cert : certs) { 6012 encodedCerts.add(cert.getEncoded()); 6013 } 6014 } 6015 6016 attestationChain.shallowCopyFrom(new KeymasterCertificateChain(encodedCerts)); 6017 } catch (CertificateException e) { 6018 logGenerateKeyPairFailure(caller, isCredentialManagementApp); 6019 Slogf.e(LOG_TAG, "While retrieving certificate chain.", e); 6020 return false; 6021 } 6022 6023 DevicePolicyEventLogger 6024 .createEvent(DevicePolicyEnums.GENERATE_KEY_PAIR) 6025 .setAdmin(caller.getPackageName()) 6026 .setBoolean(/* isDelegate */ isCallerDelegate) 6027 .setInt(idAttestationFlags) 6028 .setStrings(algorithm, isCredentialManagementApp 6029 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP) 6030 .write(); 6031 return true; 6032 } 6033 } catch (RemoteException e) { 6034 Slogf.e(LOG_TAG, "KeyChain error while generating a keypair", e); 6035 } catch (InterruptedException e) { 6036 Slogf.w(LOG_TAG, "Interrupted while generating keypair", e); 6037 Thread.currentThread().interrupt(); 6038 } finally { 6039 mInjector.binderRestoreCallingIdentity(id); 6040 } 6041 logGenerateKeyPairFailure(caller, isCredentialManagementApp); 6042 return false; 6043 } 6044 6045 private void logGenerateKeyPairFailure(CallerIdentity caller, 6046 boolean isCredentialManagementApp) { 6047 if (!isCredentialManagementApp) { 6048 return; 6049 } 6050 DevicePolicyEventLogger 6051 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_GENERATE_KEY_PAIR_FAILED) 6052 .setStrings(caller.getPackageName()) 6053 .write(); 6054 } 6055 6056 private void enforceIndividualAttestationSupportedIfRequested(int[] attestationUtilsFlags) { 6057 for (int attestationFlag : attestationUtilsFlags) { 6058 if (attestationFlag == USE_INDIVIDUAL_ATTESTATION 6059 && !mInjector.getPackageManager().hasSystemFeature( 6060 PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION)) { 6061 throw new UnsupportedOperationException("Device Individual attestation is not " 6062 + "supported on this device."); 6063 } 6064 } 6065 } 6066 6067 @Override 6068 public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias, 6069 byte[] cert, byte[] chain, boolean isUserSelectable) { 6070 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 6071 final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 6072 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 6073 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 6074 && (isProfileOwner(caller) || isDeviceOwner(caller))) 6075 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp))); 6076 if (isCredentialManagementApp) { 6077 Preconditions.checkCallAuthorization( 6078 isAliasInCredentialManagementAppPolicy(caller, alias), 6079 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 6080 } 6081 6082 final long id = mInjector.binderClearCallingIdentity(); 6083 try (final KeyChainConnection keyChainConnection = 6084 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 6085 IKeyChainService keyChain = keyChainConnection.getService(); 6086 if (!keyChain.setKeyPairCertificate(alias, cert, chain)) { 6087 return false; 6088 } 6089 keyChain.setUserSelectable(alias, isUserSelectable); 6090 DevicePolicyEventLogger 6091 .createEvent(DevicePolicyEnums.SET_KEY_PAIR_CERTIFICATE) 6092 .setAdmin(caller.getPackageName()) 6093 .setBoolean(/* isDelegate */ isCallerDelegate) 6094 .setStrings(isCredentialManagementApp 6095 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP) 6096 .write(); 6097 return true; 6098 } catch (InterruptedException e) { 6099 Slogf.w(LOG_TAG, "Interrupted while setting keypair certificate", e); 6100 Thread.currentThread().interrupt(); 6101 } catch (RemoteException e) { 6102 Slogf.e(LOG_TAG, "Failed setting keypair certificate", e); 6103 } finally { 6104 mInjector.binderRestoreCallingIdentity(id); 6105 } 6106 return false; 6107 } 6108 6109 @Override 6110 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, 6111 final IBinder response) { 6112 final CallerIdentity caller = getCallerIdentity(); 6113 Preconditions.checkCallAuthorization(isSystemUid(caller), 6114 String.format(NOT_SYSTEM_CALLER_MSG, "choose private key alias")); 6115 6116 // If there is a profile owner, redirect to that; otherwise query the device owner. 6117 ComponentName aliasChooser = getProfileOwnerAsUser(caller.getUserId()); 6118 if (aliasChooser == null && caller.getUserHandle().isSystem()) { 6119 synchronized (getLockObject()) { 6120 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 6121 if (deviceOwnerAdmin != null) { 6122 aliasChooser = deviceOwnerAdmin.info.getComponent(); 6123 } 6124 } 6125 } 6126 if (aliasChooser == null) { 6127 sendPrivateKeyAliasResponse(null, response); 6128 return; 6129 } 6130 6131 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 6132 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 6133 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri); 6134 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 6135 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 6136 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 6137 6138 final ComponentName delegateReceiver; 6139 delegateReceiver = resolveDelegateReceiver(DELEGATION_CERT_SELECTION, 6140 DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS, caller.getUserId()); 6141 6142 final boolean isDelegate; 6143 if (delegateReceiver != null) { 6144 intent.setComponent(delegateReceiver); 6145 isDelegate = true; 6146 } else { 6147 intent.setComponent(aliasChooser); 6148 isDelegate = false; 6149 } 6150 6151 mInjector.binderWithCleanCallingIdentity(() -> { 6152 mContext.sendOrderedBroadcastAsUser(intent, caller.getUserHandle(), null, 6153 new BroadcastReceiver() { 6154 @Override 6155 public void onReceive(Context context, Intent intent) { 6156 final String chosenAlias = getResultData(); 6157 sendPrivateKeyAliasResponse(chosenAlias, response); 6158 } 6159 }, null, Activity.RESULT_OK, null, null); 6160 DevicePolicyEventLogger 6161 .createEvent(DevicePolicyEnums.CHOOSE_PRIVATE_KEY_ALIAS) 6162 .setAdmin(intent.getComponent()) 6163 .setBoolean(isDelegate) 6164 .write(); 6165 }); 6166 } 6167 6168 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 6169 final IKeyChainAliasCallback keyChainAliasResponse = 6170 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 6171 // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback 6172 // is oneway, which means it won't block if the recipient lives in another process. 6173 try { 6174 keyChainAliasResponse.alias(alias); 6175 } catch (Exception e) { 6176 // Caller could throw RuntimeException or RemoteException back across processes. Catch 6177 // everything just to be sure. 6178 Slogf.e(LOG_TAG, "error while responding to callback", e); 6179 } 6180 } 6181 6182 /** 6183 * Determine whether DPMS should check if a delegate package is already installed before 6184 * granting it new delegations via {@link #setDelegatedScopes}. 6185 */ 6186 private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, 6187 int targetSdk, List<String> scopes) { 6188 // 1) Never skip is installed check from N. 6189 if (targetSdk >= Build.VERSION_CODES.N) { 6190 return true; 6191 } 6192 // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given. 6193 if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) { 6194 return false; 6195 } 6196 // 3) Skip if all previously granted scopes are being cleared. 6197 if (scopes.isEmpty()) { 6198 return false; 6199 } 6200 // Otherwise it should check that delegatePackage is installed. 6201 return true; 6202 } 6203 6204 /** 6205 * Set the scopes of a device owner or profile owner delegate. 6206 * 6207 * @param who the device owner or profile owner. 6208 * @param delegatePackage the name of the delegate package. 6209 * @param scopeList the list of delegation scopes to be given to the delegate package. 6210 */ 6211 @Override 6212 public void setDelegatedScopes(ComponentName who, String delegatePackage, 6213 List<String> scopeList) throws SecurityException { 6214 Objects.requireNonNull(who, "ComponentName is null"); 6215 Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty"); 6216 Preconditions.checkCollectionElementsNotNull(scopeList, "Scopes"); 6217 final CallerIdentity caller = getCallerIdentity(who); 6218 6219 // Remove possible duplicates. 6220 final ArrayList<String> scopes = new ArrayList(new ArraySet(scopeList)); 6221 // Ensure given scopes are valid. 6222 if (scopes.retainAll(Arrays.asList(DELEGATIONS))) { 6223 throw new IllegalArgumentException("Unexpected delegation scopes"); 6224 } 6225 // Retrieve the user ID of the calling process. 6226 final int userId = caller.getUserId(); 6227 // Ensure calling process is device/profile owner. 6228 if (!Collections.disjoint(scopes, DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS)) { 6229 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 6230 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))); 6231 } else if (!Collections.disjoint( 6232 scopes, DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS)) { 6233 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 6234 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 6235 } else { 6236 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 6237 } 6238 6239 synchronized (getLockObject()) { 6240 // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N). 6241 if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage, 6242 getTargetSdk(who.getPackageName(), userId), scopes)) { 6243 // Throw when the delegate package is not installed. 6244 if (!isPackageInstalledForUser(delegatePackage, userId)) { 6245 throw new IllegalArgumentException("Package " + delegatePackage 6246 + " is not installed on the current user"); 6247 } 6248 } 6249 6250 // Set the new delegate in user policies. 6251 final DevicePolicyData policy = getUserData(userId); 6252 List<String> exclusiveScopes = null; 6253 if (!scopes.isEmpty()) { 6254 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes)); 6255 exclusiveScopes = new ArrayList<>(scopes); 6256 exclusiveScopes.retainAll(EXCLUSIVE_DELEGATIONS); 6257 } else { 6258 // Remove any delegation info if the given scopes list is empty. 6259 policy.mDelegationMap.remove(delegatePackage); 6260 } 6261 sendDelegationChangedBroadcast(delegatePackage, scopes, userId); 6262 6263 // If set, remove exclusive scopes from all other delegates 6264 if (exclusiveScopes != null && !exclusiveScopes.isEmpty()) { 6265 for (int i = policy.mDelegationMap.size() - 1; i >= 0; --i) { 6266 final String currentPackage = policy.mDelegationMap.keyAt(i); 6267 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 6268 6269 if (!currentPackage.equals(delegatePackage)) { 6270 // Iterate through all other delegates 6271 if (currentScopes.removeAll(exclusiveScopes)) { 6272 // And if this delegate had some exclusive scopes which are now moved 6273 // to the new delegate, notify about its delegation changes. 6274 if (currentScopes.isEmpty()) { 6275 policy.mDelegationMap.removeAt(i); 6276 } 6277 sendDelegationChangedBroadcast(currentPackage, 6278 new ArrayList<>(currentScopes), userId); 6279 } 6280 } 6281 } 6282 } 6283 // Persist updates. 6284 saveSettingsLocked(userId); 6285 } 6286 } 6287 6288 private void sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes, 6289 int userId) { 6290 // Notify delegate package of updates. 6291 final Intent intent = new Intent( 6292 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED); 6293 // Only call receivers registered with Context#registerReceiver (don’t wake delegate). 6294 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 6295 // Limit components this intent resolves to to the delegate package. 6296 intent.setPackage(delegatePackage); 6297 // Include the list of delegated scopes as an extra. 6298 intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes); 6299 // Send the broadcast. 6300 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 6301 } 6302 6303 /** 6304 * Get the delegation scopes given to a delegate package by a device owner or profile owner. 6305 * 6306 * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by 6307 * passing in {@code null} as the {@code who} parameter and its own name as the 6308 * {@code delegatepackage}. 6309 * 6310 * @param who the device owner or profile owner, or {@code null} if the caller is 6311 * {@code delegatePackage}. 6312 * @param delegatePackage the name of the delegate package whose scopes are to be retrieved. 6313 * @return a list of the delegation scopes currently given to {@code delegatePackage}. 6314 */ 6315 @Override 6316 @NonNull 6317 public List<String> getDelegatedScopes(ComponentName who, 6318 String delegatePackage) throws SecurityException { 6319 Objects.requireNonNull(delegatePackage, "Delegate package is null"); 6320 final CallerIdentity caller = getCallerIdentity(who); 6321 6322 // Ensure the caller may call this method: 6323 // * Either it's a profile owner / device owner, if componentName is provided 6324 // * Or it's an app querying its own delegation scopes 6325 if (caller.hasAdminComponent()) { 6326 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 6327 } else { 6328 Preconditions.checkCallAuthorization(isPackage(caller, delegatePackage), 6329 String.format("Caller with uid %d is not %s", caller.getUid(), 6330 delegatePackage)); 6331 } 6332 synchronized (getLockObject()) { 6333 final DevicePolicyData policy = getUserData(caller.getUserId()); 6334 // Retrieve the scopes assigned to delegatePackage, or null if no scope was given. 6335 final List<String> scopes = policy.mDelegationMap.get(delegatePackage); 6336 return scopes == null ? Collections.EMPTY_LIST : scopes; 6337 } 6338 } 6339 6340 /** 6341 * Get a list of packages that were given a specific delegation scopes by a device owner or 6342 * profile owner. 6343 * 6344 * @param who the device owner or profile owner. 6345 * @param scope the scope whose delegates are to be retrieved. 6346 * @return a list of the delegate packages currently given the {@code scope} delegation. 6347 */ 6348 @NonNull 6349 public List<String> getDelegatePackages(ComponentName who, String scope) 6350 throws SecurityException { 6351 Objects.requireNonNull(who, "ComponentName is null"); 6352 Objects.requireNonNull(scope, "Scope is null"); 6353 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 6354 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 6355 } 6356 6357 // Retrieve the user ID of the calling process. 6358 final CallerIdentity caller = getCallerIdentity(who); 6359 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 6360 synchronized (getLockObject()) { 6361 return getDelegatePackagesInternalLocked(scope, caller.getUserId()); 6362 } 6363 } 6364 6365 private List<String> getDelegatePackagesInternalLocked(String scope, int userId) { 6366 final DevicePolicyData policy = getUserData(userId); 6367 6368 // Create a list to hold the resulting delegate packages. 6369 final List<String> delegatePackagesWithScope = new ArrayList<>(); 6370 // Add all delegations containing scope to the result list. 6371 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 6372 if (policy.mDelegationMap.valueAt(i).contains(scope)) { 6373 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i)); 6374 } 6375 } 6376 return delegatePackagesWithScope; 6377 } 6378 6379 /** 6380 * Return the ComponentName of the receiver that handles the given broadcast action, from 6381 * the app that holds the given delegation capability. If the app defines multiple receivers 6382 * with the same intent action filter, will return any one of them nondeterministically. 6383 * 6384 * @return ComponentName of the receiver or {@null} if none exists. 6385 */ 6386 private ComponentName resolveDelegateReceiver(String scope, String action, int userId) { 6387 6388 final List<String> delegates; 6389 synchronized (getLockObject()) { 6390 delegates = getDelegatePackagesInternalLocked(scope, userId); 6391 } 6392 if (delegates.size() == 0) { 6393 return null; 6394 } else if (delegates.size() > 1) { 6395 Slogf.wtf(LOG_TAG, "More than one delegate holds " + scope); 6396 return null; 6397 } 6398 final String pkg = delegates.get(0); 6399 Intent intent = new Intent(action); 6400 intent.setPackage(pkg); 6401 final List<ResolveInfo> receivers; 6402 try { 6403 receivers = mIPackageManager.queryIntentReceivers( 6404 intent, null, 0, userId).getList(); 6405 } catch (RemoteException e) { 6406 return null; 6407 } 6408 final int count = receivers.size(); 6409 if (count >= 1) { 6410 if (count > 1) { 6411 Slogf.w(LOG_TAG, pkg + " defines more than one delegate receiver for " + action); 6412 } 6413 return receivers.get(0).activityInfo.getComponentName(); 6414 } else { 6415 return null; 6416 } 6417 } 6418 6419 /** 6420 * Check whether a caller application has been delegated a given scope via 6421 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 6422 * device owner. 6423 * <p> 6424 * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and 6425 * then comparing the calling UID with the UID of {@code callerPackage} as reported by 6426 * {@link PackageManager#getPackageUidAsUser}. 6427 * 6428 * @param callerPackage the name of the package that is trying to invoke a function in the DPMS. 6429 * @param scope the delegation scope to be checked. 6430 * @return {@code true} if the calling process is a delegate of {@code scope}. 6431 */ 6432 private boolean isCallerDelegate(String callerPackage, int callerUid, String scope) { 6433 Objects.requireNonNull(callerPackage, "callerPackage is null"); 6434 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 6435 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 6436 } 6437 6438 // Retrieve the UID and user ID of the calling process. 6439 final int userId = UserHandle.getUserId(callerUid); 6440 synchronized (getLockObject()) { 6441 // Retrieve user policy data. 6442 final DevicePolicyData policy = getUserData(userId); 6443 // Retrieve the list of delegation scopes granted to callerPackage. 6444 final List<String> scopes = policy.mDelegationMap.get(callerPackage); 6445 // Check callingUid only if callerPackage has the required scope delegation. 6446 if (scopes != null && scopes.contains(scope)) { 6447 // Return true if the caller is actually callerPackage. 6448 return isCallingFromPackage(callerPackage, callerUid); 6449 } 6450 return false; 6451 } 6452 } 6453 6454 /** 6455 * Check whether a caller application has been delegated a given scope via 6456 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 6457 * device owner. 6458 * <p> 6459 * This is done by checking that the calling package was granted {@code scope} delegation and 6460 * then comparing the calling UID with the UID of the calling package as reported by 6461 * {@link PackageManager#getPackageUidAsUser}. 6462 * 6463 * @param caller the calling identity 6464 * @param scope the delegation scope to be checked. 6465 * @return {@code true} if the calling process is a delegate of {@code scope}. 6466 */ 6467 private boolean isCallerDelegate(CallerIdentity caller, String scope) { 6468 Objects.requireNonNull(caller.getPackageName(), "callerPackage is null"); 6469 Preconditions.checkArgument(Arrays.asList(DELEGATIONS).contains(scope), 6470 "Unexpected delegation scope: %s", scope); 6471 6472 synchronized (getLockObject()) { 6473 // Retrieve user policy data. 6474 final DevicePolicyData policy = getUserData(caller.getUserId()); 6475 // Retrieve the list of delegation scopes granted to callerPackage. 6476 final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName()); 6477 // Check callingUid only if callerPackage has the required scope delegation. 6478 return scopes != null && scopes.contains(scope); 6479 } 6480 } 6481 6482 /** 6483 * Helper function to preserve delegation behavior pre-O when using the deprecated functions 6484 * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}. 6485 */ 6486 private void setDelegatedScopePreO(ComponentName who, 6487 String delegatePackage, String scope) { 6488 Objects.requireNonNull(who, "ComponentName is null"); 6489 6490 final CallerIdentity caller = getCallerIdentity(who); 6491 // Ensure calling process is device/profile owner. 6492 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 6493 6494 synchronized (getLockObject()) { 6495 final DevicePolicyData policy = getUserData(caller.getUserId()); 6496 6497 if (delegatePackage != null) { 6498 // Set package as a delegate for scope if it is not already one. 6499 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 6500 if (scopes == null) { 6501 scopes = new ArrayList<>(); 6502 } 6503 if (!scopes.contains(scope)) { 6504 scopes.add(scope); 6505 setDelegatedScopes(who, delegatePackage, scopes); 6506 } 6507 } 6508 6509 // Clear any existing scope delegates. 6510 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 6511 final String currentPackage = policy.mDelegationMap.keyAt(i); 6512 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 6513 6514 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) { 6515 final List<String> newScopes = new ArrayList(currentScopes); 6516 newScopes.remove(scope); 6517 setDelegatedScopes(who, currentPackage, newScopes); 6518 } 6519 } 6520 } 6521 } 6522 6523 /** 6524 * Check whether a caller application is the credential management app, which can access 6525 * privileged APIs. 6526 * <p> 6527 * This is done by checking that the calling package is authorized to perform the app operation 6528 * {@link android.app.AppOpsManager#OP_MANAGE_CREDENTIALS}. 6529 * 6530 * @param caller the calling identity 6531 * @return {@code true} if the calling process is the credential management app. 6532 */ 6533 private boolean isCredentialManagementApp(CallerIdentity caller) { 6534 return mInjector.binderWithCleanCallingIdentity(() -> { 6535 AppOpsManager appOpsManager = mInjector.getAppOpsManager(); 6536 if (appOpsManager == null) return false; 6537 return appOpsManager.noteOpNoThrow(AppOpsManager.OP_MANAGE_CREDENTIALS, caller.getUid(), 6538 caller.getPackageName(), null, null) == AppOpsManager.MODE_ALLOWED; 6539 }); 6540 } 6541 6542 /** 6543 * If the caller is the credential management app, the alias provided must be contained 6544 * in the aliases specified in the credential management app's authentication policy. 6545 */ 6546 private boolean isAliasInCredentialManagementAppPolicy(CallerIdentity caller, String alias) { 6547 return mInjector.binderWithCleanCallingIdentity(() -> { 6548 try (KeyChainConnection connection = KeyChain.bindAsUser(mContext, 6549 caller.getUserHandle())) { 6550 // The policy will be null if there is no credential management app 6551 AppUriAuthenticationPolicy policy = 6552 connection.getService().getCredentialManagementAppPolicy(); 6553 return policy != null && !policy.getAppAndUriMappings().isEmpty() 6554 && containsAlias(policy, alias); 6555 } catch (RemoteException | InterruptedException e) { 6556 return false; 6557 } 6558 }); 6559 } 6560 6561 private static boolean containsAlias(AppUriAuthenticationPolicy policy, String alias) { 6562 for (Map.Entry<String, Map<Uri, String>> appsToUris : 6563 policy.getAppAndUriMappings().entrySet()) { 6564 for (Map.Entry<Uri, String> urisToAliases : appsToUris.getValue().entrySet()) { 6565 if (urisToAliases.getValue().equals(alias)) { 6566 return true; 6567 } 6568 } 6569 } 6570 return false; 6571 } 6572 6573 @Override 6574 public void setCertInstallerPackage(ComponentName who, String installerPackage) 6575 throws SecurityException { 6576 setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL); 6577 DevicePolicyEventLogger 6578 .createEvent(DevicePolicyEnums.SET_CERT_INSTALLER_PACKAGE) 6579 .setAdmin(who) 6580 .setStrings(installerPackage) 6581 .write(); 6582 } 6583 6584 @Override 6585 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 6586 final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL); 6587 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 6588 } 6589 6590 /** 6591 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is 6592 * not installed and therefore not available. 6593 * 6594 * @throws SecurityException if the caller is not a profile or device owner. 6595 * @throws UnsupportedOperationException if the package does not support being set as always-on. 6596 */ 6597 @Override 6598 public boolean setAlwaysOnVpnPackage(ComponentName who, String vpnPackage, boolean lockdown, 6599 List<String> lockdownAllowlist) 6600 throws SecurityException { 6601 Objects.requireNonNull(who, "ComponentName is null"); 6602 6603 final CallerIdentity caller = getCallerIdentity(who); 6604 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 6605 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_ALWAYS_ON_VPN_PACKAGE); 6606 6607 if (vpnPackage == null) { 6608 final String prevVpnPackage; 6609 synchronized (getLockObject()) { 6610 prevVpnPackage = getProfileOwnerOrDeviceOwnerLocked(caller).mAlwaysOnVpnPackage; 6611 // If the admin is clearing VPN package but hasn't configure any VPN previously, 6612 // ignore it so that it doesn't interfere with user-configured VPNs. 6613 if (TextUtils.isEmpty(prevVpnPackage)) { 6614 return true; 6615 } 6616 } 6617 revokeVpnAuthorizationForPackage(prevVpnPackage, caller.getUserId()); 6618 } 6619 6620 final int userId = caller.getUserId(); 6621 mInjector.binderWithCleanCallingIdentity(() -> { 6622 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) { 6623 Slogf.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage); 6624 throw new ServiceSpecificException( 6625 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage); 6626 } 6627 6628 if (vpnPackage != null && lockdown && lockdownAllowlist != null) { 6629 for (String packageName : lockdownAllowlist) { 6630 if (!isPackageInstalledForUser(packageName, userId)) { 6631 Slogf.w(LOG_TAG, "Non-existent package in VPN allowlist: " + packageName); 6632 throw new ServiceSpecificException( 6633 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName); 6634 } 6635 } 6636 } 6637 // If some package is uninstalled after the check above, it will be ignored by CM. 6638 if (!mInjector.getVpnManager().setAlwaysOnVpnPackageForUser( 6639 userId, vpnPackage, lockdown, lockdownAllowlist)) { 6640 throw new UnsupportedOperationException(); 6641 } 6642 }); 6643 DevicePolicyEventLogger 6644 .createEvent(DevicePolicyEnums.SET_ALWAYS_ON_VPN_PACKAGE) 6645 .setAdmin(caller.getComponentName()) 6646 .setStrings(vpnPackage) 6647 .setBoolean(lockdown) 6648 .setInt(lockdownAllowlist != null ? lockdownAllowlist.size() : 0) 6649 .write(); 6650 synchronized (getLockObject()) { 6651 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 6652 if (!TextUtils.equals(vpnPackage, admin.mAlwaysOnVpnPackage) 6653 || lockdown != admin.mAlwaysOnVpnLockdown) { 6654 admin.mAlwaysOnVpnPackage = vpnPackage; 6655 admin.mAlwaysOnVpnLockdown = lockdown; 6656 saveSettingsLocked(userId); 6657 } 6658 } 6659 return true; 6660 } 6661 6662 private void revokeVpnAuthorizationForPackage(String vpnPackage, int userId) { 6663 mInjector.binderWithCleanCallingIdentity(() -> { 6664 try { 6665 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 6666 vpnPackage, /* flags= */ 0, userId); 6667 if (ai == null) { 6668 Slogf.w(LOG_TAG, "Non-existent VPN package: " + vpnPackage); 6669 } else { 6670 mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN, 6671 ai.uid, vpnPackage, MODE_DEFAULT); 6672 } 6673 } catch (RemoteException e) { 6674 Slogf.e(LOG_TAG, "Can't talk to package managed", e); 6675 } 6676 }); 6677 } 6678 6679 @Override 6680 public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException { 6681 Objects.requireNonNull(admin, "ComponentName is null"); 6682 6683 final CallerIdentity caller = getCallerIdentity(admin); 6684 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 6685 6686 return mInjector.binderWithCleanCallingIdentity( 6687 () -> mInjector.getVpnManager().getAlwaysOnVpnPackageForUser(caller.getUserId())); 6688 } 6689 6690 @Override 6691 public String getAlwaysOnVpnPackageForUser(int userHandle) { 6692 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 6693 String.format(NOT_SYSTEM_CALLER_MSG, "call getAlwaysOnVpnPackageForUser")); 6694 synchronized (getLockObject()) { 6695 ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle); 6696 return admin != null ? admin.mAlwaysOnVpnPackage : null; 6697 } 6698 } 6699 6700 @Override 6701 public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException { 6702 final CallerIdentity caller; 6703 if (hasCallingPermission(PERMISSION_MAINLINE_NETWORK_STACK)) { 6704 // TODO: CaptivePortalLoginActivity erroneously calls this method with a non-admin 6705 // ComponentName, so we have to use a separate code path for it: 6706 // getCallerIdentity(admin) will throw if the admin is not in the known admin list. 6707 caller = getCallerIdentity(); 6708 } else { 6709 caller = getCallerIdentity(admin); 6710 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 6711 } 6712 6713 return mInjector.binderWithCleanCallingIdentity( 6714 () -> mInjector.getVpnManager().isVpnLockdownEnabled(caller.getUserId())); 6715 } 6716 6717 @Override 6718 public boolean isAlwaysOnVpnLockdownEnabledForUser(int userHandle) { 6719 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 6720 String.format(NOT_SYSTEM_CALLER_MSG, "call isAlwaysOnVpnLockdownEnabledForUser")); 6721 synchronized (getLockObject()) { 6722 ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle); 6723 return admin != null ? admin.mAlwaysOnVpnLockdown : null; 6724 } 6725 } 6726 6727 @Override 6728 public List<String> getAlwaysOnVpnLockdownAllowlist(ComponentName admin) 6729 throws SecurityException { 6730 Objects.requireNonNull(admin, "ComponentName is null"); 6731 6732 final CallerIdentity caller = getCallerIdentity(admin); 6733 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 6734 6735 return mInjector.binderWithCleanCallingIdentity( 6736 () -> mInjector.getVpnManager().getVpnLockdownAllowlist(caller.getUserId())); 6737 } 6738 6739 private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc, 6740 boolean wipeResetProtectionData) { 6741 wtfIfInLock(); 6742 boolean success = false; 6743 6744 try { 6745 boolean delayed = !mInjector.recoverySystemRebootWipeUserData( 6746 /* shutdown= */ false, reason, /* force= */ true, /* wipeEuicc= */ wipeEuicc, 6747 wipeExtRequested, wipeResetProtectionData); 6748 if (delayed) { 6749 // Persist the request so the device is automatically factory-reset on next start if 6750 // the system crashes or reboots before the {@code DevicePolicySafetyChecker} calls 6751 // its callback. 6752 Slogf.i(LOG_TAG, "Persisting factory reset request as it could be delayed by %s", 6753 mSafetyChecker); 6754 synchronized (getLockObject()) { 6755 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6756 policy.setDelayedFactoryReset(reason, wipeExtRequested, wipeEuicc, 6757 wipeResetProtectionData); 6758 saveSettingsLocked(UserHandle.USER_SYSTEM); 6759 } 6760 } 6761 success = true; 6762 } catch (IOException | SecurityException e) { 6763 Slogf.w(LOG_TAG, "Failed requesting data wipe", e); 6764 } finally { 6765 if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE); 6766 } 6767 } 6768 6769 private void factoryResetIfDelayedEarlier() { 6770 synchronized (getLockObject()) { 6771 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6772 6773 if (policy.mFactoryResetFlags == 0) return; 6774 6775 if (policy.mFactoryResetReason == null) { 6776 // Shouldn't happen. 6777 Slogf.e(LOG_TAG, "no persisted reason for factory resetting"); 6778 policy.mFactoryResetReason = "requested before boot"; 6779 } 6780 FactoryResetter factoryResetter = FactoryResetter.newBuilder(mContext) 6781 .setReason(policy.mFactoryResetReason).setForce(true) 6782 .setWipeEuicc((policy.mFactoryResetFlags & DevicePolicyData 6783 .FACTORY_RESET_FLAG_WIPE_EUICC) != 0) 6784 .setWipeAdoptableStorage((policy.mFactoryResetFlags & DevicePolicyData 6785 .FACTORY_RESET_FLAG_WIPE_EXTERNAL_STORAGE) != 0) 6786 .setWipeFactoryResetProtection((policy.mFactoryResetFlags & DevicePolicyData 6787 .FACTORY_RESET_FLAG_WIPE_FACTORY_RESET_PROTECTION) != 0) 6788 .build(); 6789 Slogf.i(LOG_TAG, "Factory resetting on boot using " + factoryResetter); 6790 try { 6791 if (!factoryResetter.factoryReset()) { 6792 // Shouldn't happen because FactoryResetter was created without a 6793 // DevicePolicySafetyChecker. 6794 Slogf.wtf(LOG_TAG, "Factory reset using " + factoryResetter + " failed."); 6795 } 6796 } catch (IOException e) { 6797 // Shouldn't happen. 6798 Slogf.wtf(LOG_TAG, "Could not factory reset using " + factoryResetter, e); 6799 } 6800 } 6801 } 6802 6803 private void forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently) { 6804 boolean success = false; 6805 try { 6806 if (getCurrentForegroundUserId() == userId) { 6807 mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM); 6808 } 6809 6810 success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId); 6811 if (!success) { 6812 Slogf.w(LOG_TAG, "Couldn't remove user " + userId); 6813 } else if (isManagedProfile(userId) && !wipeSilently) { 6814 sendWipeProfileNotification(wipeReasonForUser); 6815 } 6816 } catch (RemoteException re) { 6817 // Shouldn't happen 6818 } finally { 6819 if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE); 6820 } 6821 } 6822 6823 @Override 6824 public void wipeDataWithReason(int flags, String wipeReasonForUser, 6825 boolean calledOnParentInstance) { 6826 if (!mHasFeature && !hasCallingOrSelfPermission(permission.MASTER_CLEAR)) { 6827 return; 6828 } 6829 final CallerIdentity caller = getCallerIdentity(); 6830 boolean calledByProfileOwnerOnOrgOwnedDevice = 6831 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()); 6832 if (calledOnParentInstance) { 6833 Preconditions.checkCallAuthorization(calledByProfileOwnerOnOrgOwnedDevice, 6834 "Wiping the entire device can only be done by a profile owner on " 6835 + "organization-owned device."); 6836 } 6837 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 6838 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 6839 || calledByProfileOwnerOnOrgOwnedDevice, 6840 "Only device owners or profile owners of organization-owned device can set " 6841 + "WIPE_RESET_PROTECTION_DATA"); 6842 } 6843 6844 final ActiveAdmin admin; 6845 synchronized (getLockObject()) { 6846 admin = getActiveAdminWithPolicyForUidLocked(/* who= */ null, 6847 DeviceAdminInfo.USES_POLICY_WIPE_DATA, caller.getUid()); 6848 } 6849 6850 Preconditions.checkCallAuthorization( 6851 (admin != null) || hasCallingOrSelfPermission(permission.MASTER_CLEAR), 6852 "No active admin for user %d and caller %d does not hold MASTER_CLEAR permission", 6853 caller.getUserId(), caller.getUid()); 6854 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_WIPE_DATA); 6855 6856 if (TextUtils.isEmpty(wipeReasonForUser)) { 6857 if (calledByProfileOwnerOnOrgOwnedDevice && !calledOnParentInstance) { 6858 wipeReasonForUser = mContext.getString(R.string.device_ownership_relinquished); 6859 } else { 6860 wipeReasonForUser = mContext.getString( 6861 R.string.work_profile_deleted_description_dpm_wipe); 6862 } 6863 } 6864 6865 int userId = admin != null ? admin.getUserHandle().getIdentifier() 6866 : caller.getUserId(); 6867 Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser, admin, 6868 userId); 6869 if (calledByProfileOwnerOnOrgOwnedDevice) { 6870 // When wipeData is called on the parent instance, it implies wiping the entire device. 6871 if (calledOnParentInstance) { 6872 userId = UserHandle.USER_SYSTEM; 6873 } else { 6874 // when wipeData is _not_ called on the parent instance, it implies relinquishing 6875 // control over the device, wiping only the work profile. So the user restriction 6876 // on profile removal needs to be removed first. 6877 final UserHandle parentUser = UserHandle.of(getProfileParentId(userId)); 6878 mInjector.binderWithCleanCallingIdentity( 6879 () -> clearOrgOwnedProfileOwnerUserRestrictions(parentUser)); 6880 } 6881 } 6882 DevicePolicyEventLogger event = DevicePolicyEventLogger 6883 .createEvent(DevicePolicyEnums.WIPE_DATA_WITH_REASON) 6884 .setInt(flags) 6885 .setStrings(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT); 6886 6887 final String adminName; 6888 final ComponentName adminComp; 6889 if (admin != null) { 6890 adminComp = admin.info.getComponent(); 6891 adminName = adminComp.flattenToShortString(); 6892 event.setAdmin(adminComp); 6893 } else { 6894 adminComp = null; 6895 adminName = mInjector.getPackageManager().getPackagesForUid(caller.getUid())[0]; 6896 Slogf.i(LOG_TAG, "Logging wipeData() event admin as " + adminName); 6897 event.setAdmin(adminName); 6898 if (mInjector.userManagerIsHeadlessSystemUserMode()) { 6899 // On headless system user mode, the call is meant to factory reset the whole 6900 // device, otherwise the caller could simply remove the current user. 6901 userId = UserHandle.USER_SYSTEM; 6902 } 6903 } 6904 event.write(); 6905 6906 String internalReason = String.format( 6907 "DevicePolicyManager.wipeDataWithReason() from %s, organization-owned? %s", 6908 adminName, calledByProfileOwnerOnOrgOwnedDevice); 6909 6910 wipeDataNoLock(adminComp, flags, internalReason, wipeReasonForUser, userId); 6911 } 6912 6913 /** 6914 * Clears device wide policies enforced by COPE PO when relinquishing the device. This method 6915 * should be invoked once the admin is gone, so that all methods that rely on calculating 6916 * aggregate policy (e.g. strong auth timeout) from all admins aren't affected by its policies. 6917 * This method assumes that there is no other device or profile owners left on the device. 6918 * Shouldn't be called from binder thread without clearing identity. 6919 */ 6920 private void clearOrgOwnedProfileOwnerDeviceWidePolicies(@UserIdInt int parentId) { 6921 Slogf.i(LOG_TAG, "Cleaning up device-wide policies left over from org-owned profile..."); 6922 // Lockscreen message 6923 mLockPatternUtils.setDeviceOwnerInfo(null); 6924 // Wifi config lockdown 6925 mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0); 6926 // Security logging 6927 if (mInjector.securityLogGetLoggingEnabledProperty()) { 6928 mSecurityLogMonitor.stop(); 6929 mInjector.securityLogSetLoggingEnabledProperty(false); 6930 } 6931 // Network logging 6932 setNetworkLoggingActiveInternal(false); 6933 6934 // System update policy. 6935 final boolean hasSystemUpdatePolicy; 6936 synchronized (getLockObject()) { 6937 hasSystemUpdatePolicy = mOwners.getSystemUpdatePolicy() != null; 6938 if (hasSystemUpdatePolicy) { 6939 mOwners.clearSystemUpdatePolicy(); 6940 mOwners.writeDeviceOwner(); 6941 } 6942 } 6943 if (hasSystemUpdatePolicy) { 6944 mContext.sendBroadcastAsUser( 6945 new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM); 6946 } 6947 6948 // Unsuspend personal apps if needed. 6949 suspendPersonalAppsInternal(parentId, false); 6950 6951 // Notify FRP agent, LSS and WindowManager to ensure they don't hold on to stale policies. 6952 final int frpAgentUid = getFrpManagementAgentUid(); 6953 if (frpAgentUid > 0) { 6954 notifyResetProtectionPolicyChanged(frpAgentUid); 6955 } 6956 mLockSettingsInternal.refreshStrongAuthTimeout(parentId); 6957 updateScreenCaptureDisabled(parentId, getScreenCaptureDisabled(null, parentId, false)); 6958 6959 Slogf.i(LOG_TAG, "Cleaning up device-wide policies done."); 6960 } 6961 6962 private void wipeDataNoLock(ComponentName admin, int flags, String internalReason, 6963 String wipeReasonForUser, int userId) { 6964 wtfIfInLock(); 6965 6966 mInjector.binderWithCleanCallingIdentity(() -> { 6967 // First check whether the admin is allowed to wipe the device/user/profile. 6968 final String restriction; 6969 if (userId == UserHandle.USER_SYSTEM) { 6970 restriction = UserManager.DISALLOW_FACTORY_RESET; 6971 } else if (isManagedProfile(userId)) { 6972 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 6973 } else { 6974 restriction = UserManager.DISALLOW_REMOVE_USER; 6975 } 6976 if (isAdminAffectedByRestriction(admin, restriction, userId)) { 6977 throw new SecurityException("Cannot wipe data. " + restriction 6978 + " restriction is set for user " + userId); 6979 } 6980 6981 if (userId == UserHandle.USER_SYSTEM) { 6982 forceWipeDeviceNoLock( 6983 (flags & WIPE_EXTERNAL_STORAGE) != 0, 6984 internalReason, 6985 (flags & WIPE_EUICC) != 0, 6986 (flags & WIPE_RESET_PROTECTION_DATA) != 0); 6987 } else { 6988 forceWipeUser(userId, wipeReasonForUser, (flags & WIPE_SILENTLY) != 0); 6989 } 6990 }); 6991 } 6992 6993 private void sendWipeProfileNotification(String wipeReasonForUser) { 6994 Notification notification = 6995 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 6996 .setSmallIcon(android.R.drawable.stat_sys_warning) 6997 .setContentTitle(mContext.getString(R.string.work_profile_deleted)) 6998 .setContentText(wipeReasonForUser) 6999 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 7000 .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser)) 7001 .build(); 7002 mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification); 7003 } 7004 7005 private void clearWipeProfileNotification() { 7006 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED); 7007 } 7008 7009 @Override 7010 public void setFactoryResetProtectionPolicy(ComponentName who, 7011 @Nullable FactoryResetProtectionPolicy policy) { 7012 if (!mHasFeature) { 7013 return; 7014 } 7015 Preconditions.checkNotNull(who, "ComponentName is null"); 7016 CallerIdentity caller = getCallerIdentity(who); 7017 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 7018 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 7019 checkCanExecuteOrThrowUnsafe(DevicePolicyManager 7020 .OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY); 7021 7022 final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow(); 7023 synchronized (getLockObject()) { 7024 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7025 admin.mFactoryResetProtectionPolicy = policy; 7026 saveSettingsLocked(caller.getUserId()); 7027 } 7028 7029 mInjector.binderWithCleanCallingIdentity( 7030 () -> notifyResetProtectionPolicyChanged(frpManagementAgentUid)); 7031 7032 DevicePolicyEventLogger 7033 .createEvent(DevicePolicyEnums.SET_FACTORY_RESET_PROTECTION) 7034 .setAdmin(who) 7035 .write(); 7036 } 7037 7038 // Shouldn't be called from binder thread without clearing identity. 7039 private void notifyResetProtectionPolicyChanged(int frpManagementAgentUid) { 7040 final Intent intent = new Intent( 7041 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED).addFlags( 7042 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND | Intent.FLAG_RECEIVER_FOREGROUND); 7043 mContext.sendBroadcastAsUser(intent, 7044 UserHandle.getUserHandleForUid(frpManagementAgentUid), 7045 permission.MANAGE_FACTORY_RESET_PROTECTION); 7046 } 7047 7048 @Override 7049 public FactoryResetProtectionPolicy getFactoryResetProtectionPolicy( 7050 @Nullable ComponentName who) { 7051 if (!mHasFeature) { 7052 return null; 7053 } 7054 7055 final CallerIdentity caller = getCallerIdentity(who); 7056 final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow(); 7057 final ActiveAdmin admin; 7058 synchronized (getLockObject()) { 7059 if (who == null) { 7060 Preconditions.checkCallAuthorization(frpManagementAgentUid == caller.getUid() 7061 || hasCallingPermission(permission.MASTER_CLEAR), 7062 "Must be called by the FRP management agent on device"); 7063 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 7064 UserHandle.getUserId(frpManagementAgentUid)); 7065 } else { 7066 Preconditions.checkCallAuthorization( 7067 isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 7068 admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7069 } 7070 } 7071 7072 return admin != null ? admin.mFactoryResetProtectionPolicy : null; 7073 } 7074 7075 private int getFrpManagementAgentUid() { 7076 PersistentDataBlockManagerInternal pdb = mInjector.getPersistentDataBlockManagerInternal(); 7077 return pdb != null ? pdb.getAllowedUid() : -1; 7078 } 7079 7080 private int getFrpManagementAgentUidOrThrow() { 7081 int uid = getFrpManagementAgentUid(); 7082 if (uid == -1) { 7083 throw new UnsupportedOperationException( 7084 "The persistent data block service is not supported on this device"); 7085 } 7086 return uid; 7087 } 7088 7089 @Override 7090 public boolean isFactoryResetProtectionPolicySupported() { 7091 return getFrpManagementAgentUid() != -1; 7092 } 7093 7094 /** 7095 * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve 7096 * the remove warning for the given device admin. 7097 */ 7098 @Override 7099 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 7100 if (!mHasFeature) { 7101 return; 7102 } 7103 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7104 7105 final CallerIdentity caller = getCallerIdentity(); 7106 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7107 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7108 7109 synchronized (getLockObject()) { 7110 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 7111 if (admin == null) { 7112 result.sendResult(null); 7113 return; 7114 } 7115 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 7116 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 7117 intent.setComponent(admin.info.getComponent()); 7118 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 7119 null, new BroadcastReceiver() { 7120 @Override 7121 public void onReceive(Context context, Intent intent) { 7122 result.sendResult(getResultExtras(false)); 7123 } 7124 }, null, Activity.RESULT_OK, null, null); 7125 } 7126 } 7127 7128 @Override 7129 public void reportPasswordChanged(@UserIdInt int userId) { 7130 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 7131 return; 7132 } 7133 7134 final CallerIdentity caller = getCallerIdentity(); 7135 Preconditions.checkCallAuthorization(isSystemUid(caller)); 7136 // Managed Profile password can only be changed when it has a separate challenge. 7137 if (!isSeparateProfileChallengeEnabled(userId)) { 7138 Preconditions.checkCallAuthorization(!isManagedProfile(userId), "You can " 7139 + "not set the active password for a managed profile, userId = %d", userId); 7140 } 7141 7142 DevicePolicyData policy = getUserData(userId); 7143 final ArraySet<Integer> affectedUserIds = new ArraySet<>(); 7144 7145 synchronized (getLockObject()) { 7146 policy.mFailedPasswordAttempts = 0; 7147 affectedUserIds.add(userId); 7148 affectedUserIds.addAll(updatePasswordValidityCheckpointLocked( 7149 userId, /* parent */ false)); 7150 affectedUserIds.addAll(updatePasswordExpirationsLocked(userId)); 7151 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 7152 7153 // Send a broadcast to each profile using this password as its primary unlock. 7154 sendAdminCommandForLockscreenPoliciesLocked( 7155 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 7156 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 7157 7158 affectedUserIds.addAll(removeCaApprovalsIfNeeded(userId)); 7159 saveSettingsForUsersLocked(affectedUserIds); 7160 } 7161 } 7162 7163 /** 7164 * Called any time the device password is updated. Resets all password expiration clocks. 7165 * 7166 * @return the set of user IDs that have been affected 7167 */ 7168 private Set<Integer> updatePasswordExpirationsLocked(int userHandle) { 7169 final ArraySet<Integer> affectedUserIds = new ArraySet<>(); 7170 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle); 7171 for (int i = 0; i < admins.size(); i++) { 7172 ActiveAdmin admin = admins.get(i); 7173 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 7174 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 7175 long timeout = admin.passwordExpirationTimeout; 7176 admin.passwordExpirationDate = 7177 timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 7178 } 7179 } 7180 return affectedUserIds; 7181 } 7182 7183 @Override 7184 public void reportFailedPasswordAttempt(int userHandle) { 7185 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7186 7187 final CallerIdentity caller = getCallerIdentity(); 7188 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7189 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7190 if (!isSeparateProfileChallengeEnabled(userHandle)) { 7191 Preconditions.checkCallAuthorization(!isManagedProfile(userHandle), 7192 "You can not report failed password attempt if separate profile challenge is " 7193 + "not in place for a managed profile, userId = %d", userHandle); 7194 } 7195 7196 boolean wipeData = false; 7197 ActiveAdmin strictestAdmin = null; 7198 final long ident = mInjector.binderClearCallingIdentity(); 7199 try { 7200 synchronized (getLockObject()) { 7201 DevicePolicyData policy = getUserData(userHandle); 7202 policy.mFailedPasswordAttempts++; 7203 saveSettingsLocked(userHandle); 7204 if (mHasFeature) { 7205 strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 7206 userHandle, /* parent */ false); 7207 int max = strictestAdmin != null 7208 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 7209 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 7210 wipeData = true; 7211 } 7212 7213 sendAdminCommandForLockscreenPoliciesLocked( 7214 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 7215 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 7216 } 7217 } 7218 } finally { 7219 mInjector.binderRestoreCallingIdentity(ident); 7220 } 7221 7222 if (wipeData && strictestAdmin != null) { 7223 final int userId = getUserIdToWipeForFailedPasswords(strictestAdmin); 7224 Slogf.i(LOG_TAG, "Max failed password attempts policy reached for admin: " 7225 + strictestAdmin.info.getComponent().flattenToShortString() 7226 + ". Calling wipeData for user " + userId); 7227 7228 // Attempt to wipe the device/user/profile associated with the admin, as if the 7229 // admin had called wipeData(). That way we can check whether the admin is actually 7230 // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the 7231 // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be 7232 // able to do so). 7233 // IMPORTANT: Call without holding the lock to prevent deadlock. 7234 try { 7235 String wipeReasonForUser = mContext.getString( 7236 R.string.work_profile_deleted_reason_maximum_password_failure); 7237 wipeDataNoLock(strictestAdmin.info.getComponent(), 7238 /*flags=*/ 0, 7239 /*reason=*/ "reportFailedPasswordAttempt()", 7240 wipeReasonForUser, 7241 userId); 7242 } catch (SecurityException e) { 7243 Slogf.w(LOG_TAG, "Failed to wipe user " + userId 7244 + " after max failed password attempts reached.", e); 7245 } 7246 } 7247 7248 if (mInjector.securityLogIsLoggingEnabled()) { 7249 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, 7250 /*result*/ 0, /*method strength*/ 1); 7251 } 7252 } 7253 7254 /** 7255 * Returns which user should be wiped if this admin's maximum filed password attempts policy is 7256 * violated. 7257 */ 7258 private int getUserIdToWipeForFailedPasswords(ActiveAdmin admin) { 7259 final int userId = admin.getUserHandle().getIdentifier(); 7260 final ComponentName component = admin.info.getComponent(); 7261 return isProfileOwnerOfOrganizationOwnedDevice(component, userId) 7262 ? getProfileParentId(userId) : userId; 7263 } 7264 7265 @Override 7266 public void reportSuccessfulPasswordAttempt(int userHandle) { 7267 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7268 7269 final CallerIdentity caller = getCallerIdentity(); 7270 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7271 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7272 7273 synchronized (getLockObject()) { 7274 DevicePolicyData policy = getUserData(userHandle); 7275 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 7276 mInjector.binderWithCleanCallingIdentity(() -> { 7277 policy.mFailedPasswordAttempts = 0; 7278 policy.mPasswordOwner = -1; 7279 saveSettingsLocked(userHandle); 7280 if (mHasFeature) { 7281 sendAdminCommandForLockscreenPoliciesLocked( 7282 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 7283 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 7284 } 7285 }); 7286 } 7287 } 7288 7289 if (mInjector.securityLogIsLoggingEnabled()) { 7290 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 7291 /*method strength*/ 1); 7292 } 7293 } 7294 7295 @Override 7296 public void reportFailedBiometricAttempt(int userHandle) { 7297 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7298 7299 final CallerIdentity caller = getCallerIdentity(); 7300 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7301 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7302 7303 if (mInjector.securityLogIsLoggingEnabled()) { 7304 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 7305 /*method strength*/ 0); 7306 } 7307 } 7308 7309 @Override 7310 public void reportSuccessfulBiometricAttempt(int userHandle) { 7311 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7312 7313 final CallerIdentity caller = getCallerIdentity(); 7314 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7315 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7316 7317 if (mInjector.securityLogIsLoggingEnabled()) { 7318 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 7319 /*method strength*/ 0); 7320 } 7321 } 7322 7323 @Override 7324 public void reportKeyguardDismissed(int userHandle) { 7325 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7326 7327 final CallerIdentity caller = getCallerIdentity(); 7328 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7329 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7330 7331 if (mInjector.securityLogIsLoggingEnabled()) { 7332 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 7333 } 7334 } 7335 7336 @Override 7337 public void reportKeyguardSecured(int userHandle) { 7338 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7339 7340 final CallerIdentity caller = getCallerIdentity(); 7341 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7342 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7343 7344 if (mInjector.securityLogIsLoggingEnabled()) { 7345 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 7346 } 7347 } 7348 7349 @Override 7350 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 7351 String exclusionList) { 7352 if (!mHasFeature) { 7353 return null; 7354 } 7355 synchronized (getLockObject()) { 7356 Objects.requireNonNull(who, "ComponentName is null"); 7357 7358 // Only check if system user has set global proxy. We don't allow other users to set it. 7359 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 7360 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7361 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 7362 7363 // Scan through active admins and find if anyone has already 7364 // set the global proxy. 7365 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 7366 for (ComponentName component : compSet) { 7367 ActiveAdmin ap = policy.mAdminMap.get(component); 7368 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 7369 // Another admin already sets the global proxy 7370 // Return it to the caller. 7371 return component; 7372 } 7373 } 7374 7375 // If the user is not system, don't set the global proxy. Fail silently. 7376 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 7377 Slogf.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 7378 + UserHandle.getCallingUserId() + " is not permitted."); 7379 return null; 7380 } 7381 if (proxySpec == null) { 7382 admin.specifiesGlobalProxy = false; 7383 admin.globalProxySpec = null; 7384 admin.globalProxyExclusionList = null; 7385 } else { 7386 7387 admin.specifiesGlobalProxy = true; 7388 admin.globalProxySpec = proxySpec; 7389 admin.globalProxyExclusionList = exclusionList; 7390 } 7391 7392 // Reset the global proxy accordingly 7393 // Do this using system permissions, as apps cannot write to secure settings 7394 mInjector.binderWithCleanCallingIdentity(() -> resetGlobalProxyLocked(policy)); 7395 return null; 7396 } 7397 } 7398 7399 @Override 7400 public ComponentName getGlobalProxyAdmin(int userHandle) { 7401 if (!mHasFeature) { 7402 return null; 7403 } 7404 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7405 7406 final CallerIdentity caller = getCallerIdentity(); 7407 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7408 7409 synchronized (getLockObject()) { 7410 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 7411 // Scan through active admins and find if anyone has already 7412 // set the global proxy. 7413 final int N = policy.mAdminList.size(); 7414 for (int i = 0; i < N; i++) { 7415 ActiveAdmin ap = policy.mAdminList.get(i); 7416 if (ap.specifiesGlobalProxy) { 7417 // Device admin sets the global proxy 7418 // Return it to the caller. 7419 return ap.info.getComponent(); 7420 } 7421 } 7422 } 7423 // No device admin sets the global proxy. 7424 return null; 7425 } 7426 7427 @Override 7428 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 7429 Objects.requireNonNull(who, "ComponentName is null"); 7430 final CallerIdentity caller = getCallerIdentity(who); 7431 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 7432 checkAllUsersAreAffiliatedWithDevice(); 7433 mInjector.binderWithCleanCallingIdentity( 7434 () -> mInjector.getConnectivityManager().setGlobalProxy(proxyInfo)); 7435 } 7436 7437 private void resetGlobalProxyLocked(DevicePolicyData policy) { 7438 final int N = policy.mAdminList.size(); 7439 for (int i = 0; i < N; i++) { 7440 ActiveAdmin ap = policy.mAdminList.get(i); 7441 if (ap.specifiesGlobalProxy) { 7442 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 7443 return; 7444 } 7445 } 7446 // No device admins defining global proxies - reset global proxy settings to none 7447 saveGlobalProxyLocked(null, null); 7448 } 7449 7450 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 7451 if (exclusionList == null) { 7452 exclusionList = ""; 7453 } 7454 if (proxySpec == null) { 7455 proxySpec = ""; 7456 } 7457 // Remove white spaces 7458 proxySpec = proxySpec.trim(); 7459 String data[] = proxySpec.split(":"); 7460 int proxyPort = 8080; 7461 if (data.length > 1) { 7462 try { 7463 proxyPort = Integer.parseInt(data[1]); 7464 } catch (NumberFormatException e) {} 7465 } 7466 exclusionList = exclusionList.trim(); 7467 7468 ProxyInfo proxyProperties = ProxyInfo.buildDirectProxy(data[0], proxyPort, 7469 ProxyUtils.exclusionStringAsList(exclusionList)); 7470 if (!proxyProperties.isValid()) { 7471 Slogf.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 7472 return; 7473 } 7474 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 7475 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 7476 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 7477 exclusionList); 7478 } 7479 7480 /** 7481 * Called by an application that is administering the device to request that the storage system 7482 * be encrypted. Does nothing if the caller is on a secondary user or a managed profile. 7483 * 7484 * @return the new total request status (for all admins), or {@link 7485 * DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user 7486 */ 7487 @Override 7488 public int setStorageEncryption(ComponentName who, boolean encrypt) { 7489 if (!mHasFeature) { 7490 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7491 } 7492 Objects.requireNonNull(who, "ComponentName is null"); 7493 final int userHandle = UserHandle.getCallingUserId(); 7494 synchronized (getLockObject()) { 7495 // Check for permissions 7496 // Only system user can set storage encryption 7497 if (userHandle != UserHandle.USER_SYSTEM) { 7498 Slogf.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. " 7499 + "User " + UserHandle.getCallingUserId() + " is not permitted."); 7500 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7501 } 7502 7503 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 7504 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 7505 7506 // Quick exit: If the filesystem does not support encryption, we can exit early. 7507 if (!isEncryptionSupported()) { 7508 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7509 } 7510 7511 // (1) Record the value for the admin so it's sticky 7512 if (ap.encryptionRequested != encrypt) { 7513 ap.encryptionRequested = encrypt; 7514 saveSettingsLocked(userHandle); 7515 } 7516 7517 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 7518 // (2) Compute "max" for all admins 7519 boolean newRequested = false; 7520 final int N = policy.mAdminList.size(); 7521 for (int i = 0; i < N; i++) { 7522 newRequested |= policy.mAdminList.get(i).encryptionRequested; 7523 } 7524 7525 // Notify OS of new request 7526 setEncryptionRequested(newRequested); 7527 7528 // Return the new global request status 7529 return newRequested 7530 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 7531 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 7532 } 7533 } 7534 7535 /** 7536 * Get the current storage encryption request status for a given admin, or aggregate of all 7537 * active admins. 7538 */ 7539 @Override 7540 public boolean getStorageEncryption(@Nullable ComponentName who, int userHandle) { 7541 if (!mHasFeature) { 7542 return false; 7543 } 7544 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7545 7546 final CallerIdentity caller = getCallerIdentity(who); 7547 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7548 7549 synchronized (getLockObject()) { 7550 // Check for permissions if a particular caller is specified 7551 if (caller.hasAdminComponent()) { 7552 // When checking for a single caller, status is based on caller's request 7553 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 7554 return ap != null ? ap.encryptionRequested : false; 7555 } 7556 7557 // If no particular caller is specified, return the aggregate set of requests. 7558 // This is short circuited by returning true on the first hit. 7559 DevicePolicyData policy = getUserData(userHandle); 7560 final int N = policy.mAdminList.size(); 7561 for (int i = 0; i < N; i++) { 7562 if (policy.mAdminList.get(i).encryptionRequested) { 7563 return true; 7564 } 7565 } 7566 return false; 7567 } 7568 } 7569 7570 /** 7571 * Get the current encryption status of the device. 7572 */ 7573 @Override 7574 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 7575 if (!mHasFeature) { 7576 // Ok to return current status. 7577 } 7578 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7579 7580 final CallerIdentity caller = getCallerIdentity(callerPackage); 7581 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7582 7583 7584 final ApplicationInfo ai; 7585 try { 7586 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 7587 } catch (RemoteException e) { 7588 throw new SecurityException(e); 7589 } 7590 7591 boolean legacyApp = false; 7592 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 7593 legacyApp = true; 7594 } 7595 7596 final int rawStatus = getEncryptionStatus(); 7597 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 7598 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 7599 } 7600 return rawStatus; 7601 } 7602 7603 /** 7604 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 7605 */ 7606 private boolean isEncryptionSupported() { 7607 // Note, this can be implemented as 7608 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7609 // But is provided as a separate internal method if there's a faster way to do a 7610 // simple check for supported-or-not. 7611 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7612 } 7613 7614 /** 7615 * Hook to low-levels: Reporting the current status of encryption. 7616 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 7617 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 7618 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 7619 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or 7620 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 7621 */ 7622 private int getEncryptionStatus() { 7623 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 7624 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 7625 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) { 7626 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 7627 } else if (mInjector.storageManagerIsEncrypted()) { 7628 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 7629 } else if (mInjector.storageManagerIsEncryptable()) { 7630 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 7631 } else { 7632 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7633 } 7634 } 7635 7636 /** 7637 * Hook to low-levels: If needed, record the new admin setting for encryption. 7638 */ 7639 private void setEncryptionRequested(boolean encrypt) { 7640 } 7641 7642 /** 7643 * Set whether the screen capture is disabled for the user managed by the specified admin. 7644 */ 7645 @Override 7646 public void setScreenCaptureDisabled(ComponentName who, boolean disabled, boolean parent) { 7647 if (!mHasFeature) { 7648 return; 7649 } 7650 Objects.requireNonNull(who, "ComponentName is null"); 7651 7652 final CallerIdentity caller = getCallerIdentity(who); 7653 if (parent) { 7654 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 7655 } 7656 7657 synchronized (getLockObject()) { 7658 ActiveAdmin ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller), 7659 parent); 7660 if (ap.disableScreenCapture != disabled) { 7661 ap.disableScreenCapture = disabled; 7662 saveSettingsLocked(caller.getUserId()); 7663 final int affectedUserId = parent 7664 ? getProfileParentId(caller.getUserId()) 7665 : caller.getUserId(); 7666 updateScreenCaptureDisabled(affectedUserId, disabled); 7667 } 7668 } 7669 DevicePolicyEventLogger 7670 .createEvent(DevicePolicyEnums.SET_SCREEN_CAPTURE_DISABLED) 7671 .setAdmin(caller.getComponentName()) 7672 .setBoolean(disabled) 7673 .write(); 7674 } 7675 7676 /** 7677 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 7678 * active admin (if given admin is null). 7679 */ 7680 @Override 7681 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle, boolean parent) { 7682 if (!mHasFeature) { 7683 return false; 7684 } 7685 if (parent) { 7686 Preconditions.checkCallAuthorization( 7687 isProfileOwnerOfOrganizationOwnedDevice(getCallerIdentity().getUserId())); 7688 } 7689 7690 synchronized (getLockObject()) { 7691 if (who != null) { 7692 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 7693 return (admin != null) && admin.disableScreenCapture; 7694 } 7695 7696 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 7697 List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(affectedUserId); 7698 for (ActiveAdmin admin: admins) { 7699 if (admin.disableScreenCapture) { 7700 return true; 7701 } 7702 } 7703 return false; 7704 } 7705 } 7706 7707 private void updateScreenCaptureDisabled(int userHandle, boolean disabled) { 7708 mPolicyCache.setScreenCaptureAllowed(userHandle, !disabled); 7709 mHandler.post(() -> { 7710 try { 7711 mInjector.getIWindowManager().refreshScreenCaptureDisabled(userHandle); 7712 } catch (RemoteException e) { 7713 Slogf.w(LOG_TAG, "Unable to notify WindowManager.", e); 7714 } 7715 }); 7716 } 7717 7718 @Override 7719 public void setNearbyNotificationStreamingPolicy(int policy) { 7720 if (!mHasFeature) { 7721 return; 7722 } 7723 7724 final CallerIdentity caller = getCallerIdentity(); 7725 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 7726 7727 synchronized (getLockObject()) { 7728 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7729 if (admin.mNearbyNotificationStreamingPolicy != policy) { 7730 admin.mNearbyNotificationStreamingPolicy = policy; 7731 saveSettingsLocked(caller.getUserId()); 7732 } 7733 } 7734 } 7735 7736 @Override 7737 public int getNearbyNotificationStreamingPolicy(final int userId) { 7738 if (!mHasFeature) { 7739 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 7740 } 7741 7742 final CallerIdentity caller = getCallerIdentity(); 7743 Preconditions.checkCallAuthorization( 7744 isProfileOwner(caller) 7745 || isDeviceOwner(caller) 7746 || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY)); 7747 7748 synchronized (getLockObject()) { 7749 if (mOwners.hasProfileOwner(userId) || mOwners.hasDeviceOwner()) { 7750 final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId); 7751 return admin.mNearbyNotificationStreamingPolicy; 7752 } 7753 } 7754 7755 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 7756 } 7757 7758 @Override 7759 public void setNearbyAppStreamingPolicy(int policy) { 7760 if (!mHasFeature) { 7761 return; 7762 } 7763 7764 final CallerIdentity caller = getCallerIdentity(); 7765 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 7766 7767 synchronized (getLockObject()) { 7768 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7769 if (admin.mNearbyAppStreamingPolicy != policy) { 7770 admin.mNearbyAppStreamingPolicy = policy; 7771 saveSettingsLocked(caller.getUserId()); 7772 } 7773 } 7774 } 7775 7776 @Override 7777 public int getNearbyAppStreamingPolicy(final int userId) { 7778 if (!mHasFeature) { 7779 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 7780 } 7781 7782 final CallerIdentity caller = getCallerIdentity(); 7783 Preconditions.checkCallAuthorization( 7784 isProfileOwner(caller) 7785 || isDeviceOwner(caller) 7786 || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY)); 7787 7788 synchronized (getLockObject()) { 7789 if (mOwners.hasProfileOwner(userId) || mOwners.hasDeviceOwner()) { 7790 final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId); 7791 return admin.mNearbyAppStreamingPolicy; 7792 } 7793 } 7794 7795 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 7796 } 7797 7798 /** 7799 * Set whether auto time is required by the specified admin (must be device or profile owner). 7800 */ 7801 @Override 7802 public void setAutoTimeRequired(ComponentName who, boolean required) { 7803 if (!mHasFeature) { 7804 return; 7805 } 7806 Objects.requireNonNull(who, "ComponentName is null"); 7807 final CallerIdentity caller = getCallerIdentity(who); 7808 7809 boolean requireAutoTimeChanged = false; 7810 synchronized (getLockObject()) { 7811 Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()), 7812 "Managed profile cannot set auto time required"); 7813 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7814 if (admin.requireAutoTime != required) { 7815 admin.requireAutoTime = required; 7816 saveSettingsLocked(caller.getUserId()); 7817 requireAutoTimeChanged = true; 7818 } 7819 } 7820 // requireAutoTime is now backed by DISALLOW_CONFIG_DATE_TIME restriction, so propagate 7821 // updated restrictions to the framework. 7822 if (requireAutoTimeChanged) { 7823 pushUserRestrictions(caller.getUserId()); 7824 } 7825 // Turn AUTO_TIME on in settings if it is required 7826 if (required) { 7827 mInjector.binderWithCleanCallingIdentity( 7828 () -> mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 7829 1 /* AUTO_TIME on */)); 7830 } 7831 DevicePolicyEventLogger 7832 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_REQUIRED) 7833 .setAdmin(who) 7834 .setBoolean(required) 7835 .write(); 7836 } 7837 7838 /** 7839 * Returns whether or not auto time is required by the device owner or any profile owner. 7840 */ 7841 @Override 7842 public boolean getAutoTimeRequired() { 7843 if (!mHasFeature) { 7844 return false; 7845 } 7846 synchronized (getLockObject()) { 7847 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7848 if (deviceOwner != null && deviceOwner.requireAutoTime) { 7849 // If the device owner enforces auto time, we don't need to check the PO's 7850 return true; 7851 } 7852 7853 // Now check to see if any profile owner on any user enforces auto time 7854 for (Integer userId : mOwners.getProfileOwnerKeys()) { 7855 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 7856 if (profileOwner != null && profileOwner.requireAutoTime) { 7857 return true; 7858 } 7859 } 7860 7861 return false; 7862 } 7863 } 7864 7865 /** 7866 * Set whether auto time is enabled on the device. 7867 */ 7868 @Override 7869 public void setAutoTimeEnabled(ComponentName who, boolean enabled) { 7870 if (!mHasFeature) { 7871 return; 7872 } 7873 Objects.requireNonNull(who, "ComponentName is null"); 7874 7875 final CallerIdentity caller = getCallerIdentity(who); 7876 Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller) 7877 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDeviceOwner(caller)); 7878 7879 mInjector.binderWithCleanCallingIdentity(() -> 7880 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, enabled ? 1 : 0)); 7881 7882 DevicePolicyEventLogger 7883 .createEvent(DevicePolicyEnums.SET_AUTO_TIME) 7884 .setAdmin(caller.getComponentName()) 7885 .setBoolean(enabled) 7886 .write(); 7887 } 7888 7889 /** 7890 * Returns whether auto time is used on the device or not. 7891 */ 7892 @Override 7893 public boolean getAutoTimeEnabled(ComponentName who) { 7894 if (!mHasFeature) { 7895 return false; 7896 } 7897 Objects.requireNonNull(who, "ComponentName is null"); 7898 7899 final CallerIdentity caller = getCallerIdentity(who); 7900 Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller) 7901 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDeviceOwner(caller)); 7902 7903 return mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) > 0; 7904 } 7905 7906 /** 7907 * Set whether auto time zone is enabled on the device. 7908 */ 7909 @Override 7910 public void setAutoTimeZoneEnabled(ComponentName who, boolean enabled) { 7911 if (!mHasFeature) { 7912 return; 7913 } 7914 Objects.requireNonNull(who, "ComponentName is null"); 7915 7916 final CallerIdentity caller = getCallerIdentity(who); 7917 Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller) 7918 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDeviceOwner(caller)); 7919 7920 mInjector.binderWithCleanCallingIdentity(() -> 7921 mInjector.settingsGlobalPutInt(Global.AUTO_TIME_ZONE, enabled ? 1 : 0)); 7922 7923 DevicePolicyEventLogger 7924 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_ZONE) 7925 .setAdmin(caller.getComponentName()) 7926 .setBoolean(enabled) 7927 .write(); 7928 } 7929 7930 /** 7931 * Returns whether auto time zone is used on the device or not. 7932 */ 7933 @Override 7934 public boolean getAutoTimeZoneEnabled(ComponentName who) { 7935 if (!mHasFeature) { 7936 return false; 7937 } 7938 Objects.requireNonNull(who, "ComponentName is null"); 7939 7940 final CallerIdentity caller = getCallerIdentity(who); 7941 Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller) 7942 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDeviceOwner(caller)); 7943 7944 return mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) > 0; 7945 } 7946 7947 // TODO (b/137101239): remove this method in follow-up CL 7948 // since it's only used for split system user. 7949 @Override 7950 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 7951 throw new UnsupportedOperationException("This method was used by split system user only."); 7952 } 7953 7954 // TODO (b/137101239): remove this method in follow-up CL 7955 // since it's only used for split system user. 7956 @Override 7957 public boolean getForceEphemeralUsers(ComponentName who) { 7958 throw new UnsupportedOperationException("This method was used by split system user only."); 7959 } 7960 7961 @Override 7962 public boolean requestBugreport(ComponentName who) { 7963 if (!mHasFeature) { 7964 return false; 7965 } 7966 Objects.requireNonNull(who, "ComponentName is null"); 7967 // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport 7968 // which could still contain data related to that user. Should we disallow that, e.g. until 7969 // next boot? Might not be needed given that this still requires user consent. 7970 final CallerIdentity caller = getCallerIdentity(who); 7971 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 7972 checkAllUsersAreAffiliatedWithDevice(); 7973 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REQUEST_BUGREPORT); 7974 7975 if (mBugreportCollectionManager.requestBugreport()) { 7976 DevicePolicyEventLogger 7977 .createEvent(DevicePolicyEnums.REQUEST_BUGREPORT) 7978 .setAdmin(who) 7979 .write(); 7980 7981 final long currentTime = System.currentTimeMillis(); 7982 synchronized (getLockObject()) { 7983 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 7984 if (currentTime > policyData.mLastBugReportRequestTime) { 7985 policyData.mLastBugReportRequestTime = currentTime; 7986 saveSettingsLocked(UserHandle.USER_SYSTEM); 7987 } 7988 } 7989 7990 return true; 7991 } else { 7992 return false; 7993 } 7994 } 7995 7996 void sendDeviceOwnerCommand(String action, Bundle extras) { 7997 final int deviceOwnerUserId; 7998 final ComponentName receiverComponent; 7999 synchronized (getLockObject()) { 8000 deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 8001 receiverComponent = mOwners.getDeviceOwnerComponent(); 8002 } 8003 sendActiveAdminCommand(action, extras, deviceOwnerUserId, receiverComponent, 8004 /* inForeground */ false); 8005 } 8006 8007 void sendDeviceOwnerOrProfileOwnerCommand(String action, Bundle extras, int userId) { 8008 if (userId == UserHandle.USER_ALL) { 8009 userId = UserHandle.USER_SYSTEM; 8010 } 8011 boolean inForeground = false; 8012 ComponentName receiverComponent = null; 8013 if (action.equals(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE)) { 8014 inForeground = true; 8015 receiverComponent = resolveDelegateReceiver(DELEGATION_NETWORK_LOGGING, action, userId); 8016 } 8017 if (action.equals(DeviceAdminReceiver.ACTION_SECURITY_LOGS_AVAILABLE)) { 8018 inForeground = true; 8019 receiverComponent = resolveDelegateReceiver( 8020 DELEGATION_SECURITY_LOGGING, action, userId); 8021 } 8022 if (receiverComponent == null) { 8023 receiverComponent = getOwnerComponent(userId); 8024 } 8025 sendActiveAdminCommand(action, extras, userId, receiverComponent, inForeground); 8026 } 8027 8028 private void sendProfileOwnerCommand(String action, Bundle extras, @UserIdInt int userId) { 8029 sendActiveAdminCommand(action, extras, userId, mOwners.getProfileOwnerComponent(userId), 8030 /* inForeground */ false); 8031 } 8032 8033 private void sendActiveAdminCommand(String action, Bundle extras, 8034 @UserIdInt int userId, ComponentName receiverComponent, boolean inForeground) { 8035 final Intent intent = new Intent(action); 8036 intent.setComponent(receiverComponent); 8037 if (extras != null) { 8038 intent.putExtras(extras); 8039 } 8040 if (inForeground) { 8041 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8042 } 8043 8044 if (VERBOSE_LOG) { 8045 Slogf.v(LOG_TAG, "sendActiveAdminCommand(): broadcasting " + action + " to " 8046 + receiverComponent.flattenToShortString() + " on user " + userId); 8047 } 8048 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 8049 } 8050 8051 private void sendOwnerChangedBroadcast(String broadcast, int userId) { 8052 final Intent intent = new Intent(broadcast) 8053 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 8054 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 8055 } 8056 8057 void sendBugreportToDeviceOwner(Uri bugreportUri, String bugreportHash) { 8058 synchronized (getLockObject()) { 8059 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 8060 intent.setComponent(mOwners.getDeviceOwnerComponent()); 8061 intent.setDataAndType(bugreportUri, RemoteBugreportManager.BUGREPORT_MIMETYPE); 8062 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 8063 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8064 8065 final UriGrantsManagerInternal ugm = LocalServices 8066 .getService(UriGrantsManagerInternal.class); 8067 final NeededUriGrants needed = ugm.checkGrantUriPermissionFromIntent(intent, 8068 Process.SHELL_UID, mOwners.getDeviceOwnerComponent().getPackageName(), 8069 mOwners.getDeviceOwnerUserId()); 8070 ugm.grantUriPermissionUncheckedFromIntent(needed, null); 8071 8072 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 8073 } 8074 } 8075 8076 void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash) { 8077 synchronized (getLockObject()) { 8078 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 8079 } 8080 } 8081 8082 Pair<String, String> getDeviceOwnerRemoteBugreportUriAndHash() { 8083 synchronized (getLockObject()) { 8084 final String uri = mOwners.getDeviceOwnerRemoteBugreportUri(); 8085 return uri == null ? null 8086 : new Pair<>(uri, mOwners.getDeviceOwnerRemoteBugreportHash()); 8087 } 8088 } 8089 8090 /** 8091 * Disables all device cameras according to the specified admin. 8092 */ 8093 @Override 8094 public void setCameraDisabled(ComponentName who, boolean disabled, boolean parent) { 8095 if (!mHasFeature) { 8096 return; 8097 } 8098 Objects.requireNonNull(who, "ComponentName is null"); 8099 8100 final CallerIdentity caller = getCallerIdentity(who); 8101 if (parent) { 8102 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 8103 } 8104 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_CAMERA_DISABLED); 8105 8106 final int userHandle = caller.getUserId(); 8107 synchronized (getLockObject()) { 8108 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 8109 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA, parent); 8110 if (ap.disableCamera != disabled) { 8111 ap.disableCamera = disabled; 8112 saveSettingsLocked(userHandle); 8113 } 8114 } 8115 // Tell the user manager that the restrictions have changed. 8116 pushUserRestrictions(userHandle); 8117 8118 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 8119 if (SecurityLog.isLoggingEnabled()) { 8120 SecurityLog.writeEvent(SecurityLog.TAG_CAMERA_POLICY_SET, 8121 who.getPackageName(), userHandle, affectedUserId, disabled ? 1 : 0); 8122 } 8123 DevicePolicyEventLogger 8124 .createEvent(DevicePolicyEnums.SET_CAMERA_DISABLED) 8125 .setAdmin(caller.getComponentName()) 8126 .setBoolean(disabled) 8127 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 8128 .write(); 8129 } 8130 8131 /** 8132 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 8133 * active admins. 8134 */ 8135 @Override 8136 public boolean getCameraDisabled(ComponentName who, int userHandle, boolean parent) { 8137 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true, parent); 8138 } 8139 8140 private boolean getCameraDisabled(ComponentName who, int userHandle, 8141 boolean mergeDeviceOwnerRestriction, boolean parent) { 8142 if (!mHasFeature) { 8143 return false; 8144 } 8145 if (parent) { 8146 Preconditions.checkCallAuthorization( 8147 isProfileOwnerOfOrganizationOwnedDevice(getCallerIdentity().getUserId())); 8148 } 8149 8150 synchronized (getLockObject()) { 8151 if (who != null) { 8152 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 8153 return (admin != null) && admin.disableCamera; 8154 } 8155 // First, see if DO has set it. If so, it's device-wide. 8156 if (mergeDeviceOwnerRestriction) { 8157 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 8158 if (deviceOwner != null && deviceOwner.disableCamera) { 8159 return true; 8160 } 8161 } 8162 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 8163 // Return the strictest policy across all participating admins. 8164 List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(affectedUserId); 8165 // Determine whether or not the device camera is disabled for any active admins. 8166 for (ActiveAdmin admin: admins) { 8167 if (admin.disableCamera) { 8168 return true; 8169 } 8170 } 8171 return false; 8172 } 8173 } 8174 8175 @Override 8176 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 8177 if (!mHasFeature) { 8178 return; 8179 } 8180 Objects.requireNonNull(who, "ComponentName is null"); 8181 8182 final CallerIdentity caller = getCallerIdentity(who); 8183 8184 final int userHandle = caller.getUserId(); 8185 synchronized (getLockObject()) { 8186 ActiveAdmin ap = getActiveAdminForCallerLocked( 8187 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 8188 if (isManagedProfile(userHandle)) { 8189 if (parent) { 8190 if (isProfileOwnerOfOrganizationOwnedDevice(caller)) { 8191 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 8192 } else { 8193 which = which & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 8194 } 8195 } else { 8196 which = which & PROFILE_KEYGUARD_FEATURES; 8197 } 8198 } 8199 if (ap.disabledKeyguardFeatures != which) { 8200 ap.disabledKeyguardFeatures = which; 8201 saveSettingsLocked(userHandle); 8202 } 8203 } 8204 if (SecurityLog.isLoggingEnabled()) { 8205 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 8206 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET, 8207 who.getPackageName(), userHandle, affectedUserId, which); 8208 } 8209 DevicePolicyEventLogger 8210 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED_FEATURES) 8211 .setAdmin(caller.getComponentName()) 8212 .setInt(which) 8213 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 8214 .write(); 8215 } 8216 8217 /** 8218 * Gets the disabled state for features in keyguard for the given admin, 8219 * or the aggregate of all active admins if who is null. 8220 */ 8221 @Override 8222 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 8223 if (!mHasFeature) { 8224 return 0; 8225 } 8226 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 8227 8228 final CallerIdentity caller = getCallerIdentity(); 8229 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 8230 8231 final long ident = mInjector.binderClearCallingIdentity(); 8232 try { 8233 synchronized (getLockObject()) { 8234 if (who != null) { 8235 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 8236 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 8237 } 8238 8239 final List<ActiveAdmin> admins; 8240 if (!parent && isManagedProfile(userHandle)) { 8241 // If we are being asked about a managed profile, just return keyguard features 8242 // disabled by admins in the profile. 8243 admins = getUserDataUnchecked(userHandle).mAdminList; 8244 } else { 8245 // Otherwise return those set by admins in the user and its profiles. 8246 admins = getActiveAdminsForLockscreenPoliciesLocked( 8247 getProfileParentUserIfRequested(userHandle, parent)); 8248 } 8249 8250 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 8251 final int N = admins.size(); 8252 for (int i = 0; i < N; i++) { 8253 ActiveAdmin admin = admins.get(i); 8254 int userId = admin.getUserHandle().getIdentifier(); 8255 boolean isRequestedUser = !parent && (userId == userHandle); 8256 if (isRequestedUser || !isManagedProfile(userId)) { 8257 // If we are being asked explicitly about this user 8258 // return all disabled features even if its a managed profile. 8259 which |= admin.disabledKeyguardFeatures; 8260 } else { 8261 // Otherwise a managed profile is only allowed to disable 8262 // some features on the parent user. 8263 which |= (admin.disabledKeyguardFeatures 8264 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 8265 } 8266 } 8267 return which; 8268 } 8269 } finally { 8270 mInjector.binderRestoreCallingIdentity(ident); 8271 } 8272 } 8273 8274 @Override 8275 public void setKeepUninstalledPackages(ComponentName who, String callerPackage, 8276 List<String> packageList) { 8277 if (!mHasFeature) { 8278 return; 8279 } 8280 Objects.requireNonNull(packageList, "packageList is null"); 8281 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 8282 Preconditions.checkCallAuthorization((caller.hasAdminComponent() && isDeviceOwner(caller)) 8283 || (caller.hasPackage() 8284 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES))); 8285 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEEP_UNINSTALLED_PACKAGES); 8286 8287 synchronized (getLockObject()) { 8288 // Get the device owner 8289 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 8290 // Set list of packages to be kept even if uninstalled. 8291 deviceOwner.keepUninstalledPackages = packageList; 8292 // Save settings. 8293 saveSettingsLocked(caller.getUserId()); 8294 // Notify package manager. 8295 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 8296 } 8297 DevicePolicyEventLogger 8298 .createEvent(DevicePolicyEnums.SET_KEEP_UNINSTALLED_PACKAGES) 8299 .setAdmin(caller.getPackageName()) 8300 .setBoolean(/* isDelegate */ who == null) 8301 .setStrings(packageList.toArray(new String[0])) 8302 .write(); 8303 } 8304 8305 @Override 8306 public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) { 8307 if (!mHasFeature) { 8308 return null; 8309 } 8310 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 8311 Preconditions.checkCallAuthorization((caller.hasAdminComponent() && isDeviceOwner(caller)) 8312 || (caller.hasPackage() 8313 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES))); 8314 8315 synchronized (getLockObject()) { 8316 return getKeepUninstalledPackagesLocked(); 8317 } 8318 } 8319 8320 private List<String> getKeepUninstalledPackagesLocked() { 8321 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 8322 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 8323 } 8324 8325 /** 8326 * Logs a warning when the device doesn't have {@code PackageManager.FEATURE_DEVICE_ADMIN}. 8327 * 8328 * @param message action that was not executed; should not end with a period because the missing 8329 * feature will be appended to it. 8330 */ 8331 private void logMissingFeatureAction(String message) { 8332 Slogf.w(LOG_TAG, message + " because device does not have the " 8333 + PackageManager.FEATURE_DEVICE_ADMIN + " feature."); 8334 } 8335 8336 @Override 8337 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) { 8338 if (!mHasFeature) { 8339 logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(admin) 8340 + " as device owner for user " + userId); 8341 return false; 8342 } 8343 Preconditions.checkArgument(admin != null); 8344 8345 final CallerIdentity caller = getCallerIdentity(); 8346 // Cannot be called while holding the lock: 8347 final boolean hasIncompatibleAccountsOrNonAdb = 8348 hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, admin); 8349 synchronized (getLockObject()) { 8350 enforceCanSetDeviceOwnerLocked(caller, admin, userId, hasIncompatibleAccountsOrNonAdb); 8351 Preconditions.checkArgument(isPackageInstalledForUser(admin.getPackageName(), userId), 8352 "Invalid component " + admin + " for device owner"); 8353 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 8354 Preconditions.checkArgument(activeAdmin != null && !getUserData( 8355 userId).mRemovingAdmins.contains(admin), "Not active admin: " + admin); 8356 8357 // Shutting down backup manager service permanently. 8358 toggleBackupServiceActive(UserHandle.USER_SYSTEM, /* makeActive= */ false); 8359 if (isAdb(caller)) { 8360 // Log device owner provisioning was started using adb. 8361 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 8362 DevicePolicyEventLogger 8363 .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB) 8364 .setAdmin(admin) 8365 .setStrings(LOG_TAG_DEVICE_OWNER) 8366 .write(); 8367 } 8368 8369 mOwners.setDeviceOwner(admin, ownerName, userId); 8370 mOwners.writeDeviceOwner(); 8371 updateDeviceOwnerLocked(); 8372 setDeviceOwnershipSystemPropertyLocked(); 8373 8374 //TODO(b/180371154): when provisionFullyManagedDevice is used in tests, remove this 8375 // hard-coded default value setting. 8376 if (isAdb(caller)) { 8377 activeAdmin.mAdminCanGrantSensorsPermissions = true; 8378 mPolicyCache.setAdminCanGrantSensorsPermissions(userId, true); 8379 saveSettingsLocked(userId); 8380 } 8381 8382 mInjector.binderWithCleanCallingIdentity(() -> { 8383 // Restrict adding a managed profile when a device owner is set on the device. 8384 // That is to prevent the co-existence of a managed profile and a device owner 8385 // on the same device. 8386 // Instead, the device may be provisioned with an organization-owned managed 8387 // profile, such that the admin on that managed profile has extended management 8388 // capabilities that can affect the entire device (but not access private data 8389 // on the primary profile). 8390 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true, 8391 UserHandle.of(userId)); 8392 // TODO Send to system too? 8393 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId); 8394 }); 8395 mDeviceAdminServiceController.startServiceForOwner( 8396 admin.getPackageName(), userId, "set-device-owner"); 8397 8398 Slogf.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 8399 8400 if (mInjector.userManagerIsHeadlessSystemUserMode()) { 8401 int currentForegroundUser = getCurrentForegroundUserId(); 8402 Slogf.i(LOG_TAG, "setDeviceOwner(): setting " + admin 8403 + " as profile owner on user " + currentForegroundUser); 8404 // Sets profile owner on current foreground user since 8405 // the human user will complete the DO setup workflow from there. 8406 manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin, 8407 /* managedUser= */ currentForegroundUser, /* adminExtras= */ null, 8408 /* showDisclaimer= */ false); 8409 } 8410 return true; 8411 } 8412 } 8413 8414 @Override 8415 public boolean hasDeviceOwner() { 8416 final CallerIdentity caller = getCallerIdentity(); 8417 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || canManageUsers(caller)); 8418 return mOwners.hasDeviceOwner(); 8419 } 8420 8421 boolean isDeviceOwner(ActiveAdmin admin) { 8422 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 8423 } 8424 8425 public boolean isDeviceOwner(ComponentName who, int userId) { 8426 synchronized (getLockObject()) { 8427 return mOwners.hasDeviceOwner() 8428 && mOwners.getDeviceOwnerUserId() == userId 8429 && mOwners.getDeviceOwnerComponent().equals(who); 8430 } 8431 } 8432 8433 private boolean isDeviceOwner(CallerIdentity caller) { 8434 synchronized (getLockObject()) { 8435 if (!mOwners.hasDeviceOwner() || mOwners.getDeviceOwnerUserId() != caller.getUserId()) { 8436 return false; 8437 } 8438 8439 if (caller.hasAdminComponent()) { 8440 return mOwners.getDeviceOwnerComponent().equals(caller.getComponentName()); 8441 } else { 8442 return isUidDeviceOwnerLocked(caller.getUid()); 8443 } 8444 } 8445 } 8446 8447 private boolean isDeviceOwnerPackage(String packageName, int userId) { 8448 synchronized (getLockObject()) { 8449 return mOwners.hasDeviceOwner() 8450 && mOwners.getDeviceOwnerUserId() == userId 8451 && mOwners.getDeviceOwnerPackageName().equals(packageName); 8452 } 8453 } 8454 8455 private boolean isProfileOwnerPackage(String packageName, int userId) { 8456 synchronized (getLockObject()) { 8457 return mOwners.hasProfileOwner(userId) 8458 && mOwners.getProfileOwnerPackage(userId).equals(packageName); 8459 } 8460 } 8461 8462 public boolean isProfileOwner(ComponentName who, int userId) { 8463 final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() -> 8464 getProfileOwnerAsUser(userId)); 8465 return who != null && who.equals(profileOwner); 8466 } 8467 8468 /** 8469 * Returns {@code true} if the provided caller identity is of a profile owner. 8470 * @param caller identity of caller. 8471 * @return true if {@code identity} is a profile owner, false otherwise. 8472 */ 8473 public boolean isProfileOwner(CallerIdentity caller) { 8474 synchronized (getLockObject()) { 8475 final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() -> 8476 getProfileOwnerAsUser(caller.getUserId())); 8477 // No profile owner. 8478 if (profileOwner == null) { 8479 return false; 8480 } 8481 // The admin ComponentName was specified, check it directly. 8482 if (caller.hasAdminComponent()) { 8483 return profileOwner.equals(caller.getComponentName()); 8484 } else { 8485 return isUidProfileOwnerLocked(caller.getUid()); 8486 } 8487 } 8488 } 8489 8490 /** 8491 * Checks if the app uid provided is the profile owner. This method should only be called 8492 * if no componentName is available. 8493 * 8494 * @param appUid UID of the caller. 8495 * @return true if the caller is the profile owner 8496 */ 8497 private boolean isUidProfileOwnerLocked(int appUid) { 8498 ensureLocked(); 8499 8500 final int userId = UserHandle.getUserId(appUid); 8501 final ComponentName profileOwnerComponent = mOwners.getProfileOwnerComponent(userId); 8502 if (profileOwnerComponent == null) { 8503 return false; 8504 } 8505 for (ActiveAdmin admin : getUserData(userId).mAdminList) { 8506 final ComponentName currentAdminComponent = admin.info.getComponent(); 8507 if (admin.getUid() == appUid && profileOwnerComponent.equals(currentAdminComponent)) { 8508 return true; 8509 } 8510 } 8511 return false; 8512 } 8513 8514 private boolean hasProfileOwner(int userId) { 8515 synchronized (getLockObject()) { 8516 return mOwners.hasProfileOwner(userId); 8517 } 8518 } 8519 8520 /** 8521 * Returns {@code true} if the provided caller identity is of a profile owner of an organization 8522 * owned device. 8523 * 8524 * @param caller identity of caller 8525 * @return true if {@code identity} is a profile owner of an organization owned device, false 8526 * otherwise. 8527 */ 8528 private boolean isProfileOwnerOfOrganizationOwnedDevice(CallerIdentity caller) { 8529 return isProfileOwner(caller) && isProfileOwnerOfOrganizationOwnedDevice( 8530 caller.getUserId()); 8531 } 8532 8533 private boolean isProfileOwnerOfOrganizationOwnedDevice(int userId) { 8534 synchronized (getLockObject()) { 8535 return mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId); 8536 } 8537 } 8538 8539 private boolean isProfileOwnerOfOrganizationOwnedDevice(ComponentName who, int userId) { 8540 return isProfileOwner(who, userId) && isProfileOwnerOfOrganizationOwnedDevice(userId); 8541 } 8542 8543 private boolean isProfileOwnerOnUser0(CallerIdentity caller) { 8544 return isProfileOwner(caller) && caller.getUserHandle().isSystem(); 8545 } 8546 8547 private boolean isPackage(CallerIdentity caller, String packageName) { 8548 return isCallingFromPackage(packageName, caller.getUid()); 8549 } 8550 8551 @Override 8552 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 8553 if (!mHasFeature) { 8554 return null; 8555 } 8556 if (!callingUserOnly) { 8557 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()) 8558 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 8559 } 8560 synchronized (getLockObject()) { 8561 if (!mOwners.hasDeviceOwner()) { 8562 return null; 8563 } 8564 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 8565 mOwners.getDeviceOwnerUserId()) { 8566 return null; 8567 } 8568 return mOwners.getDeviceOwnerComponent(); 8569 } 8570 } 8571 8572 private int getDeviceOwnerUserIdUncheckedLocked() { 8573 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 8574 } 8575 8576 @Override 8577 public int getDeviceOwnerUserId() { 8578 if (!mHasFeature) { 8579 return UserHandle.USER_NULL; 8580 } 8581 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 8582 8583 synchronized (getLockObject()) { 8584 return getDeviceOwnerUserIdUncheckedLocked(); 8585 } 8586 } 8587 8588 /** 8589 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 8590 * MANAGE_USERS. 8591 */ 8592 @Override 8593 public String getDeviceOwnerName() { 8594 if (!mHasFeature) { 8595 return null; 8596 } 8597 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 8598 8599 synchronized (getLockObject()) { 8600 if (!mOwners.hasDeviceOwner()) { 8601 return null; 8602 } 8603 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 8604 // Should setDeviceOwner/ProfileOwner still take a name? 8605 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 8606 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 8607 } 8608 } 8609 8610 /** Returns the active device owner or {@code null} if there is no device owner. */ 8611 @VisibleForTesting 8612 ActiveAdmin getDeviceOwnerAdminLocked() { 8613 ensureLocked(); 8614 ComponentName component = mOwners.getDeviceOwnerComponent(); 8615 if (component == null) { 8616 return null; 8617 } 8618 8619 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 8620 final int n = policy.mAdminList.size(); 8621 for (int i = 0; i < n; i++) { 8622 ActiveAdmin admin = policy.mAdminList.get(i); 8623 if (component.equals(admin.info.getComponent())) { 8624 return admin; 8625 } 8626 } 8627 Slogf.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 8628 return null; 8629 } 8630 8631 ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(int userId) { 8632 ActiveAdmin admin = getDeviceOwnerAdminLocked(); 8633 if (admin == null) { 8634 admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId); 8635 } 8636 return admin; 8637 } 8638 8639 @Override 8640 public void clearDeviceOwner(String packageName) { 8641 Objects.requireNonNull(packageName, "packageName is null"); 8642 8643 final CallerIdentity caller = getCallerIdentity(packageName); 8644 synchronized (getLockObject()) { 8645 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 8646 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 8647 if (!mOwners.hasDeviceOwner() 8648 || !deviceOwnerComponent.getPackageName().equals(packageName) 8649 || (deviceOwnerUserId != caller.getUserId())) { 8650 throw new SecurityException( 8651 "clearDeviceOwner can only be called by the device owner"); 8652 } 8653 enforceUserUnlocked(deviceOwnerUserId); 8654 DevicePolicyData policy = getUserData(deviceOwnerUserId); 8655 if (policy.mPasswordTokenHandle != 0) { 8656 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, deviceOwnerUserId); 8657 } 8658 8659 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 8660 mInjector.binderWithCleanCallingIdentity(() -> { 8661 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 8662 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 8663 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, 8664 deviceOwnerUserId); 8665 }); 8666 Slogf.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 8667 } 8668 } 8669 8670 private void clearOverrideApnUnchecked() { 8671 if (!mHasTelephonyFeature) { 8672 return; 8673 } 8674 // Disable Override APNs and remove them from database. 8675 setOverrideApnsEnabledUnchecked(false); 8676 final List<ApnSetting> apns = getOverrideApnsUnchecked(); 8677 for (int i = 0; i < apns.size(); i ++) { 8678 removeOverrideApnUnchecked(apns.get(i).getId()); 8679 } 8680 } 8681 8682 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 8683 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner"); 8684 8685 if (admin != null) { 8686 admin.disableCamera = false; 8687 admin.userRestrictions = null; 8688 admin.defaultEnabledRestrictionsAlreadySet.clear(); 8689 admin.forceEphemeralUsers = false; 8690 admin.isNetworkLoggingEnabled = false; 8691 admin.requireAutoTime = false; 8692 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 8693 } 8694 final DevicePolicyData policyData = getUserData(userId); 8695 policyData.mCurrentInputMethodSet = false; 8696 saveSettingsLocked(userId); 8697 mPolicyCache.onUserRemoved(userId); 8698 final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM); 8699 systemPolicyData.mLastSecurityLogRetrievalTime = -1; 8700 systemPolicyData.mLastBugReportRequestTime = -1; 8701 systemPolicyData.mLastNetworkLogsRetrievalTime = -1; 8702 saveSettingsLocked(UserHandle.USER_SYSTEM); 8703 clearUserPoliciesLocked(userId); 8704 clearOverrideApnUnchecked(); 8705 clearApplicationRestrictions(userId); 8706 mInjector.getPackageManagerInternal().clearBlockUninstallForUser(userId); 8707 8708 mOwners.clearDeviceOwner(); 8709 mOwners.writeDeviceOwner(); 8710 updateDeviceOwnerLocked(); 8711 8712 clearDeviceOwnerUserRestriction(UserHandle.of(userId)); 8713 mInjector.securityLogSetLoggingEnabledProperty(false); 8714 mSecurityLogMonitor.stop(); 8715 setNetworkLoggingActiveInternal(false); 8716 deleteTransferOwnershipBundleLocked(userId); 8717 toggleBackupServiceActive(UserHandle.USER_SYSTEM, true); 8718 } 8719 8720 private void clearApplicationRestrictions(int userId) { 8721 // Changing app restrictions involves disk IO, offload it to the background thread. 8722 mBackgroundHandler.post(() -> { 8723 final List<PackageInfo> installedPackageInfos = mInjector.getPackageManager(userId) 8724 .getInstalledPackages(MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 8725 final UserHandle userHandle = UserHandle.of(userId); 8726 for (final PackageInfo packageInfo : installedPackageInfos) { 8727 mInjector.getUserManager().setApplicationRestrictions( 8728 packageInfo.packageName, null /* restrictions */, userHandle); 8729 } 8730 }); 8731 } 8732 8733 @Override 8734 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 8735 if (!mHasFeature) { 8736 logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(who) 8737 + " as profile owner for user " + userHandle); 8738 return false; 8739 } 8740 Preconditions.checkArgument(who != null); 8741 8742 final CallerIdentity caller = getCallerIdentity(); 8743 // Cannot be called while holding the lock: 8744 final boolean hasIncompatibleAccountsOrNonAdb = 8745 hasIncompatibleAccountsOrNonAdbNoLock(caller, userHandle, who); 8746 synchronized (getLockObject()) { 8747 enforceCanSetProfileOwnerLocked( 8748 caller, who, userHandle, hasIncompatibleAccountsOrNonAdb); 8749 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 8750 Preconditions.checkArgument( 8751 isPackageInstalledForUser(who.getPackageName(), userHandle) 8752 && admin != null 8753 && !getUserData(userHandle).mRemovingAdmins.contains(who), 8754 "Not active admin: " + who); 8755 8756 final int parentUserId = getProfileParentId(userHandle); 8757 // When trying to set a profile owner on a new user, it may be that this user is 8758 // a profile - but it may not be a managed profile if there's a restriction on the 8759 // parent to add managed profiles (e.g. if the device has a device owner). 8760 if (parentUserId != userHandle && mUserManager.hasUserRestriction( 8761 UserManager.DISALLOW_ADD_MANAGED_PROFILE, 8762 UserHandle.of(parentUserId))) { 8763 Slogf.i(LOG_TAG, "Cannot set profile owner because of restriction."); 8764 return false; 8765 } 8766 8767 if (isAdb(caller)) { 8768 // Log profile owner provisioning was started using adb. 8769 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 8770 DevicePolicyEventLogger 8771 .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB) 8772 .setAdmin(who) 8773 .setStrings(LOG_TAG_PROFILE_OWNER) 8774 .write(); 8775 } 8776 8777 // Shutting down backup manager service permanently. 8778 toggleBackupServiceActive(userHandle, /* makeActive= */ false); 8779 8780 mOwners.setProfileOwner(who, ownerName, userHandle); 8781 mOwners.writeProfileOwner(userHandle); 8782 Slogf.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 8783 8784 mInjector.binderWithCleanCallingIdentity(() -> { 8785 if (mUserManager.isManagedProfile(userHandle)) { 8786 maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin, 8787 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 8788 ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin, 8789 true /* newOwner */); 8790 } 8791 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 8792 userHandle); 8793 }); 8794 mDeviceAdminServiceController.startServiceForOwner( 8795 who.getPackageName(), userHandle, "set-profile-owner"); 8796 return true; 8797 } 8798 } 8799 8800 private void toggleBackupServiceActive(int userId, boolean makeActive) { 8801 long ident = mInjector.binderClearCallingIdentity(); 8802 try { 8803 if (mInjector.getIBackupManager() != null) { 8804 mInjector.getIBackupManager() 8805 .setBackupServiceActive(userId, makeActive); 8806 } 8807 } catch (RemoteException e) { 8808 throw new IllegalStateException(String.format("Failed %s backup service.", 8809 makeActive ? "activating" : "deactivating"), e); 8810 } finally { 8811 mInjector.binderRestoreCallingIdentity(ident); 8812 } 8813 8814 } 8815 8816 @Override 8817 public void clearProfileOwner(ComponentName who) { 8818 if (!mHasFeature) { 8819 return; 8820 } 8821 Objects.requireNonNull(who, "ComponentName is null"); 8822 8823 final CallerIdentity caller = getCallerIdentity(who); 8824 final int userId = caller.getUserId(); 8825 Preconditions.checkCallingUser(!isManagedProfile(userId)); 8826 8827 enforceUserUnlocked(userId); 8828 synchronized (getLockObject()) { 8829 // Check if this is the profile owner who is calling 8830 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 8831 8832 mInjector.binderWithCleanCallingIdentity(() -> { 8833 clearProfileOwnerLocked(admin, userId); 8834 removeActiveAdminLocked(who, userId); 8835 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 8836 userId); 8837 }); 8838 Slogf.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 8839 } 8840 } 8841 8842 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 8843 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner"); 8844 8845 if (admin != null) { 8846 admin.disableCamera = false; 8847 admin.userRestrictions = null; 8848 admin.defaultEnabledRestrictionsAlreadySet.clear(); 8849 } 8850 final DevicePolicyData policyData = getUserData(userId); 8851 policyData.mCurrentInputMethodSet = false; 8852 policyData.mOwnerInstalledCaCerts.clear(); 8853 saveSettingsLocked(userId); 8854 clearUserPoliciesLocked(userId); 8855 clearApplicationRestrictions(userId); 8856 mOwners.removeProfileOwner(userId); 8857 mOwners.writeProfileOwner(userId); 8858 deleteTransferOwnershipBundleLocked(userId); 8859 toggleBackupServiceActive(userId, true); 8860 applyManagedProfileRestrictionIfDeviceOwnerLocked(); 8861 setNetworkLoggingActiveInternal(false); 8862 } 8863 8864 @Override 8865 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 8866 if (!mHasFeature) { 8867 return; 8868 } 8869 Objects.requireNonNull(who, "ComponentName is null"); 8870 8871 final CallerIdentity caller = getCallerIdentity(who); 8872 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 8873 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 8874 8875 mInjector.binderWithCleanCallingIdentity(() -> 8876 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null)); 8877 8878 DevicePolicyEventLogger 8879 .createEvent(DevicePolicyEnums.SET_DEVICE_OWNER_LOCK_SCREEN_INFO) 8880 .setAdmin(caller.getComponentName()) 8881 .write(); 8882 } 8883 8884 @Override 8885 public CharSequence getDeviceOwnerLockScreenInfo() { 8886 return mLockPatternUtils.getDeviceOwnerInfo(); 8887 } 8888 8889 private void clearUserPoliciesLocked(int userId) { 8890 // Reset some of the user-specific policies. 8891 final DevicePolicyData policy = getUserData(userId); 8892 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 8893 // Clear delegations. 8894 policy.mDelegationMap.clear(); 8895 policy.mStatusBarDisabled = false; 8896 policy.mSecondaryLockscreenEnabled = false; 8897 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 8898 policy.mAffiliationIds.clear(); 8899 policy.mLockTaskPackages.clear(); 8900 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId); 8901 policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE; 8902 policy.mUserControlDisabledPackages.clear(); 8903 saveSettingsLocked(userId); 8904 8905 try { 8906 mIPermissionManager.updatePermissionFlagsForAllApps( 8907 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 8908 0 /* flagValues */, userId); 8909 pushUserRestrictions(userId); 8910 } catch (RemoteException re) { 8911 // Shouldn't happen. 8912 } 8913 } 8914 8915 @Override 8916 public boolean hasUserSetupCompleted() { 8917 return hasUserSetupCompleted(mInjector.userHandleGetCallingUserId()); 8918 } 8919 8920 // This checks only if the Setup Wizard has run. Since Wear devices pair before 8921 // completing Setup Wizard, and pairing involves transferring user data, calling 8922 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). 8923 private boolean hasUserSetupCompleted(int userHandle) { 8924 if (!mHasFeature) { 8925 return true; 8926 } 8927 return mInjector.hasUserSetupCompleted(getUserData(userHandle)); 8928 } 8929 8930 private boolean hasPaired(int userHandle) { 8931 if (!mHasFeature) { 8932 return true; 8933 } 8934 return getUserData(userHandle).mPaired; 8935 } 8936 8937 @Override 8938 public int getUserProvisioningState() { 8939 if (!mHasFeature) { 8940 return DevicePolicyManager.STATE_USER_UNMANAGED; 8941 } 8942 final CallerIdentity caller = getCallerIdentity(); 8943 Preconditions.checkCallAuthorization(canManageUsers(caller)); 8944 8945 return getUserProvisioningState(caller.getUserId()); 8946 } 8947 8948 private int getUserProvisioningState(int userHandle) { 8949 return getUserData(userHandle).mUserProvisioningState; 8950 } 8951 8952 @Override 8953 public void setUserProvisioningState(int newState, int userHandle) { 8954 if (!mHasFeature) { 8955 logMissingFeatureAction("Cannot set provisioning state " + newState + " for user " 8956 + userHandle); 8957 return; 8958 } 8959 8960 final CallerIdentity caller = getCallerIdentity(); 8961 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle) 8962 && getManagedUserId(userHandle) == -1 8963 && newState != STATE_USER_UNMANAGED) { 8964 // No managed device, user or profile, so setting provisioning state makes no sense. 8965 throw new IllegalStateException("Not allowed to change provisioning state unless a " 8966 + "device or profile owner is set."); 8967 } 8968 8969 synchronized (getLockObject()) { 8970 boolean transitionCheckNeeded = true; 8971 8972 // Calling identity/permission checks. 8973 if (isAdb(caller)) { 8974 // ADB shell can only move directly from un-managed to finalized as part of directly 8975 // setting profile-owner or device-owner. 8976 if (getUserProvisioningState(userHandle) != 8977 DevicePolicyManager.STATE_USER_UNMANAGED 8978 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 8979 throw new IllegalStateException("Not allowed to change provisioning state " 8980 + "unless current provisioning state is unmanaged, and new state is " 8981 + "finalized."); 8982 } 8983 transitionCheckNeeded = false; 8984 } else { 8985 Preconditions.checkCallAuthorization( 8986 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 8987 } 8988 8989 final DevicePolicyData policyData = getUserData(userHandle); 8990 if (transitionCheckNeeded) { 8991 // Optional state transition check for non-ADB case. 8992 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState); 8993 } 8994 policyData.mUserProvisioningState = newState; 8995 saveSettingsLocked(userHandle); 8996 } 8997 } 8998 8999 private void checkUserProvisioningStateTransition(int currentState, int newState) { 9000 // Valid transitions for normal use-cases. 9001 switch (currentState) { 9002 case DevicePolicyManager.STATE_USER_UNMANAGED: 9003 // Can move to any state from unmanaged (except itself as an edge case).. 9004 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 9005 return; 9006 } 9007 break; 9008 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 9009 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 9010 // Can only move to finalized from these states. 9011 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 9012 return; 9013 } 9014 break; 9015 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 9016 // Current user has a managed-profile, but current user is not managed, so 9017 // rather than moving to finalized state, go back to unmanaged once 9018 // profile provisioning is complete. 9019 if (newState == DevicePolicyManager.STATE_USER_PROFILE_FINALIZED) { 9020 return; 9021 } 9022 break; 9023 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED: 9024 // Cannot transition out of finalized. 9025 break; 9026 case DevicePolicyManager.STATE_USER_PROFILE_FINALIZED: 9027 // Should only move to an unmanaged state after removing the work profile. 9028 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 9029 return; 9030 } 9031 break; 9032 } 9033 9034 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 9035 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 9036 + "from state [" + currentState + "]"); 9037 } 9038 9039 @Override 9040 public void setProfileEnabled(ComponentName who) { 9041 if (!mHasFeature) { 9042 logMissingFeatureAction("Cannot enable profile for " 9043 + ComponentName.flattenToShortString(who)); 9044 return; 9045 } 9046 Objects.requireNonNull(who, "ComponentName is null"); 9047 9048 final CallerIdentity caller = getCallerIdentity(who); 9049 final int userId = caller.getUserId(); 9050 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 9051 Preconditions.checkCallingUser(isManagedProfile(userId)); 9052 9053 synchronized (getLockObject()) { 9054 // Check if the profile is already enabled. 9055 UserInfo managedProfile = getUserInfo(userId); 9056 if (managedProfile.isEnabled()) { 9057 Slogf.e(LOG_TAG, 9058 "setProfileEnabled is called when the profile is already enabled"); 9059 return; 9060 } 9061 mInjector.binderWithCleanCallingIdentity(() -> { 9062 mUserManager.setUserEnabled(userId); 9063 UserInfo parent = mUserManager.getProfileParent(userId); 9064 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 9065 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 9066 UserHandle parentHandle = new UserHandle(parent.id); 9067 mLocalService.broadcastIntentToCrossProfileManifestReceiversAsUser(intent, 9068 parentHandle, /* requiresPermission= */ true); 9069 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 9070 Intent.FLAG_RECEIVER_FOREGROUND); 9071 mContext.sendBroadcastAsUser(intent, parentHandle); 9072 }); 9073 } 9074 } 9075 9076 @Override 9077 public void setProfileName(ComponentName who, String profileName) { 9078 Objects.requireNonNull(who, "ComponentName is null"); 9079 9080 final CallerIdentity caller = getCallerIdentity(who); 9081 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 9082 9083 mInjector.binderWithCleanCallingIdentity(() -> { 9084 mUserManager.setUserName(caller.getUserId(), profileName); 9085 DevicePolicyEventLogger 9086 .createEvent(DevicePolicyEnums.SET_PROFILE_NAME) 9087 .setAdmin(caller.getComponentName()) 9088 .write(); 9089 }); 9090 } 9091 9092 @Override 9093 public ComponentName getProfileOwnerAsUser(int userId) { 9094 if (!mHasFeature) { 9095 return null; 9096 } 9097 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 9098 9099 CallerIdentity caller = getCallerIdentity(); 9100 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId) 9101 || hasFullCrossUsersPermission(caller, userId)); 9102 9103 synchronized (getLockObject()) { 9104 return mOwners.getProfileOwnerComponent(userId); 9105 } 9106 } 9107 9108 // Returns the active profile owner for this user or null if the current user has no 9109 // profile owner. 9110 @VisibleForTesting 9111 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 9112 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 9113 if (profileOwner == null) { 9114 return null; 9115 } 9116 DevicePolicyData policy = getUserData(userHandle); 9117 final int n = policy.mAdminList.size(); 9118 for (int i = 0; i < n; i++) { 9119 ActiveAdmin admin = policy.mAdminList.get(i); 9120 if (profileOwner.equals(admin.info.getComponent())) { 9121 return admin; 9122 } 9123 } 9124 return null; 9125 } 9126 9127 /** 9128 * Returns the ActiveAdmin associated wit the PO or DO on the given user. 9129 * @param userHandle 9130 * @return 9131 */ 9132 private @Nullable ActiveAdmin getDeviceOrProfileOwnerAdminLocked(int userHandle) { 9133 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 9134 if (admin == null && getDeviceOwnerUserIdUncheckedLocked() == userHandle) { 9135 admin = getDeviceOwnerAdminLocked(); 9136 } 9137 return admin; 9138 } 9139 9140 @GuardedBy("getLockObject()") 9141 ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked(int userHandle) { 9142 return mInjector.binderWithCleanCallingIdentity(() -> { 9143 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 9144 if (userInfo.isManagedProfile()) { 9145 if (getProfileOwnerAsUser(userInfo.id) != null 9146 && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) { 9147 ComponentName who = getProfileOwnerAsUser(userInfo.id); 9148 return getActiveAdminUncheckedLocked(who, userInfo.id); 9149 } 9150 } 9151 } 9152 return null; 9153 }); 9154 } 9155 9156 @Override 9157 public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent( 9158 @NonNull UserHandle userHandle) { 9159 if (!mHasFeature) { 9160 return null; 9161 } 9162 synchronized (getLockObject()) { 9163 final ComponentName doComponent = mOwners.getDeviceOwnerComponent(); 9164 final ComponentName poComponent = 9165 mOwners.getProfileOwnerComponent(userHandle.getIdentifier()); 9166 // Return test only admin if configured to do so. 9167 // TODO(b/182994391): Replace with more generic solution to override the supervision 9168 // component. 9169 if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) { 9170 if (isAdminTestOnlyLocked(doComponent, userHandle.getIdentifier())) { 9171 return doComponent; 9172 } else if (isAdminTestOnlyLocked(poComponent, userHandle.getIdentifier())) { 9173 return poComponent; 9174 } 9175 } 9176 final String supervisor = mContext.getResources().getString( 9177 com.android.internal.R.string.config_defaultSupervisionProfileOwnerComponent); 9178 if (supervisor == null) { 9179 return null; 9180 } 9181 final ComponentName supervisorComponent = ComponentName.unflattenFromString(supervisor); 9182 if (supervisorComponent == null) { 9183 return null; 9184 } 9185 if (supervisorComponent.equals(doComponent) || supervisorComponent.equals( 9186 poComponent)) { 9187 return supervisorComponent; 9188 } else { 9189 return null; 9190 } 9191 } 9192 } 9193 9194 @Override 9195 public String getProfileOwnerName(int userHandle) { 9196 if (!mHasFeature) { 9197 return null; 9198 } 9199 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 9200 return getProfileOwnerNameUnchecked(userHandle); 9201 } 9202 9203 private String getProfileOwnerNameUnchecked(int userHandle) { 9204 ComponentName profileOwner = getProfileOwnerAsUser(userHandle); 9205 if (profileOwner == null) { 9206 return null; 9207 } 9208 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 9209 } 9210 9211 private @UserIdInt int getOrganizationOwnedProfileUserId() { 9212 for (UserInfo ui : mUserManagerInternal.getUserInfos()) { 9213 if (ui.isManagedProfile() && isProfileOwnerOfOrganizationOwnedDevice(ui.id)) { 9214 return ui.id; 9215 } 9216 } 9217 return UserHandle.USER_NULL; 9218 } 9219 9220 @Override 9221 public boolean isOrganizationOwnedDeviceWithManagedProfile() { 9222 if (!mHasFeature) { 9223 return false; 9224 } 9225 return getOrganizationOwnedProfileUserId() != UserHandle.USER_NULL; 9226 } 9227 9228 @Override 9229 public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) { 9230 final CallerIdentity caller = getCallerIdentity(); 9231 ensureCallerIdentityMatchesIfNotSystem(packageName, pid, uid, caller); 9232 9233 // Verify that the specified packages matches the provided uid. 9234 if (!doesPackageMatchUid(packageName, uid)) { 9235 return false; 9236 } 9237 // A device or profile owner must also have the READ_PHONE_STATE permission to access device 9238 // identifiers. If the package being checked does not have this permission then deny access. 9239 if (!hasPermission(permission.READ_PHONE_STATE, pid, uid)) { 9240 return false; 9241 } 9242 9243 // Allow access to the device owner or delegate cert installer. 9244 ComponentName deviceOwner = getDeviceOwnerComponent(true); 9245 if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName) 9246 || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) { 9247 return true; 9248 } 9249 final int userId = UserHandle.getUserId(uid); 9250 // Allow access to the profile owner for the specified user, or delegate cert installer 9251 // But only if this is an organization-owned device. 9252 ComponentName profileOwner = getProfileOwnerAsUser(userId); 9253 final boolean isCallerProfileOwnerOrDelegate = profileOwner != null 9254 && (profileOwner.getPackageName().equals(packageName) 9255 || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL)); 9256 if (isCallerProfileOwnerOrDelegate && isProfileOwnerOfOrganizationOwnedDevice(userId)) { 9257 return true; 9258 } 9259 9260 return false; 9261 } 9262 9263 private boolean doesPackageMatchUid(String packageName, int uid) { 9264 final int userId = UserHandle.getUserId(uid); 9265 try { 9266 ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(packageName, 0, userId); 9267 // Since this call goes directly to PackageManagerService a NameNotFoundException is not 9268 // thrown but null data can be returned; if the appInfo for the specified package cannot 9269 // be found then return false to prevent crashing the app. 9270 if (appInfo == null) { 9271 Slogf.w(LOG_TAG, "appInfo could not be found for package %s", packageName); 9272 return false; 9273 } else if (uid != appInfo.uid) { 9274 String message = String.format("Package %s (uid=%d) does not match provided uid %d", 9275 packageName, appInfo.uid, uid); 9276 Slogf.w(LOG_TAG, message); 9277 throw new SecurityException(message); 9278 } 9279 } catch (RemoteException e) { 9280 // If an exception is caught obtaining the appInfo just return false to prevent crashing 9281 // apps due to an internal error. 9282 Slogf.e(LOG_TAG, e, "Exception caught obtaining appInfo for package %s", packageName); 9283 return false; 9284 } 9285 return true; 9286 } 9287 9288 private void ensureCallerIdentityMatchesIfNotSystem(String packageName, int pid, int uid, 9289 CallerIdentity caller) { 9290 // If the caller is not a system app then it should only be able to check its own device 9291 // identifier access. 9292 int callingUid = caller.getUid(); 9293 int callingPid = mInjector.binderGetCallingPid(); 9294 if (UserHandle.getAppId(callingUid) >= Process.FIRST_APPLICATION_UID 9295 && (callingUid != uid || callingPid != pid)) { 9296 String message = String.format( 9297 "Calling uid %d, pid %d cannot check device identifier access for package %s " 9298 + "(uid=%d, pid=%d)", callingUid, callingPid, packageName, uid, pid); 9299 Slogf.w(LOG_TAG, message); 9300 throw new SecurityException(message); 9301 } 9302 } 9303 9304 /** 9305 * Canonical name for a given package. 9306 */ 9307 private String getApplicationLabel(String packageName, @UserIdInt int userId) { 9308 return mInjector.binderWithCleanCallingIdentity(() -> { 9309 final Context userContext; 9310 try { 9311 UserHandle userHandle = UserHandle.of(userId); 9312 userContext = mContext.createPackageContextAsUser(packageName, /* flags= */ 0, 9313 userHandle); 9314 } catch (PackageManager.NameNotFoundException nnfe) { 9315 Slogf.w(LOG_TAG, nnfe, "%s is not installed for user %d", packageName, userId); 9316 return null; 9317 } 9318 ApplicationInfo appInfo = userContext.getApplicationInfo(); 9319 CharSequence result = null; 9320 if (appInfo != null) { 9321 result = appInfo.loadUnsafeLabel(userContext.getPackageManager()); 9322 } 9323 return result != null ? result.toString() : null; 9324 }); 9325 } 9326 9327 /** 9328 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 9329 * permission. 9330 * The profile owner can only be set before the user setup phase has completed, 9331 * except for: 9332 * - SYSTEM_UID 9333 * - adb unless hasIncompatibleAccountsOrNonAdb is true. 9334 */ 9335 private void enforceCanSetProfileOwnerLocked( 9336 CallerIdentity caller, @Nullable ComponentName owner, int userHandle, 9337 boolean hasIncompatibleAccountsOrNonAdb) { 9338 UserInfo info = getUserInfo(userHandle); 9339 if (info == null) { 9340 // User doesn't exist. 9341 throw new IllegalArgumentException( 9342 "Attempted to set profile owner for invalid userId: " + userHandle); 9343 } 9344 if (info.isGuest()) { 9345 throw new IllegalStateException("Cannot set a profile owner on a guest"); 9346 } 9347 if (mOwners.hasProfileOwner(userHandle)) { 9348 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 9349 + "is already set."); 9350 } 9351 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 9352 throw new IllegalStateException("Trying to set the profile owner, but the user " 9353 + "already has a device owner."); 9354 } 9355 if (isAdb(caller)) { 9356 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 9357 && hasIncompatibleAccountsOrNonAdb) { 9358 throw new IllegalStateException("Not allowed to set the profile owner because " 9359 + "there are already some accounts on the profile"); 9360 } 9361 return; 9362 } 9363 Preconditions.checkCallAuthorization( 9364 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 9365 9366 if ((mIsWatch || hasUserSetupCompleted(userHandle))) { 9367 Preconditions.checkState(isSystemUid(caller), 9368 "Cannot set the profile owner on a user which is already set-up"); 9369 9370 if (!mIsWatch) { 9371 // Only the default supervision profile owner can be set as profile owner after SUW 9372 final String supervisor = mContext.getResources().getString( 9373 com.android.internal.R.string 9374 .config_defaultSupervisionProfileOwnerComponent); 9375 if (supervisor == null) { 9376 throw new IllegalStateException("Unable to set profile owner post-setup, no" 9377 + "default supervisor profile owner defined"); 9378 } 9379 9380 final ComponentName supervisorComponent = ComponentName.unflattenFromString( 9381 supervisor); 9382 if (!owner.equals(supervisorComponent)) { 9383 throw new IllegalStateException("Unable to set non-default profile owner" 9384 + " post-setup " + owner); 9385 } 9386 } 9387 } 9388 } 9389 9390 /** 9391 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 9392 * permission. 9393 */ 9394 private void enforceCanSetDeviceOwnerLocked( 9395 CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int deviceOwnerUserId, 9396 boolean hasIncompatibleAccountsOrNonAdb) { 9397 if (!isAdb(caller)) { 9398 Preconditions.checkCallAuthorization( 9399 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 9400 } 9401 9402 final int code = checkDeviceOwnerProvisioningPreConditionLocked(owner, 9403 /* deviceOwnerUserId= */ deviceOwnerUserId, /* callingUserId*/ caller.getUserId(), 9404 isAdb(caller), hasIncompatibleAccountsOrNonAdb); 9405 if (code != CODE_OK) { 9406 throw new IllegalStateException( 9407 computeProvisioningErrorString(code, deviceOwnerUserId)); 9408 } 9409 } 9410 9411 private static String computeProvisioningErrorString(int code, @UserIdInt int userId) { 9412 switch (code) { 9413 case CODE_OK: 9414 return "OK"; 9415 case CODE_HAS_DEVICE_OWNER: 9416 return "Trying to set the device owner, but device owner is already set."; 9417 case CODE_USER_HAS_PROFILE_OWNER: 9418 return "Trying to set the device owner, but the user already has a profile owner."; 9419 case CODE_USER_NOT_RUNNING: 9420 return "User " + userId + " not running."; 9421 case CODE_NOT_SYSTEM_USER: 9422 return "User " + userId + " is not system user."; 9423 case CODE_USER_SETUP_COMPLETED: 9424 return "Cannot set the device owner if the device is already set-up."; 9425 case CODE_NONSYSTEM_USER_EXISTS: 9426 return "Not allowed to set the device owner because there are already several" 9427 + " users on the device."; 9428 case CODE_ACCOUNTS_NOT_EMPTY: 9429 return "Not allowed to set the device owner because there are already some accounts" 9430 + " on the device."; 9431 case CODE_HAS_PAIRED: 9432 return "Not allowed to set the device owner because this device has already " 9433 + "paired."; 9434 default: 9435 return "Unexpected @ProvisioningPreCondition: " + code; 9436 } 9437 9438 } 9439 9440 private void enforceUserUnlocked(int userId) { 9441 // Since we're doing this operation on behalf of an app, we only 9442 // want to use the actual "unlocked" state. 9443 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 9444 "User must be running and unlocked"); 9445 } 9446 9447 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 9448 if (parent) { 9449 enforceUserUnlocked(getProfileParentId(userId)); 9450 } else { 9451 enforceUserUnlocked(userId); 9452 } 9453 } 9454 9455 private boolean canManageUsers(CallerIdentity caller) { 9456 return isSystemUid(caller) || isRootUid(caller) 9457 || hasCallingOrSelfPermission(permission.MANAGE_USERS); 9458 } 9459 9460 private boolean hasPermission(String permission, int pid, int uid) { 9461 return mContext.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED; 9462 } 9463 9464 private boolean hasCallingPermission(String permission) { 9465 return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED; 9466 } 9467 9468 private boolean hasCallingOrSelfPermission(String permission) { 9469 return mContext.checkCallingOrSelfPermission(permission) 9470 == PackageManager.PERMISSION_GRANTED; 9471 } 9472 9473 private boolean hasPermissionForPreflight(CallerIdentity caller, String permission) { 9474 final int callingPid = mInjector.binderGetCallingPid(); 9475 final String packageName = mContext.getPackageName(); 9476 9477 return PermissionChecker.checkPermissionForPreflight(mContext, permission, callingPid, 9478 caller.getUid(), packageName) == PermissionChecker.PERMISSION_GRANTED; 9479 } 9480 9481 private boolean hasFullCrossUsersPermission(CallerIdentity caller, int userHandle) { 9482 return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller) 9483 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL); 9484 } 9485 9486 private boolean hasCrossUsersPermission(CallerIdentity caller, int userHandle) { 9487 return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller) 9488 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS); 9489 } 9490 9491 private boolean canUserUseLockTaskLocked(int userId) { 9492 if (isUserAffiliatedWithDeviceLocked(userId)) { 9493 return true; 9494 } 9495 9496 // Unaffiliated profile owners are not allowed to use lock when there is a device owner. 9497 if (mOwners.hasDeviceOwner()) { 9498 return false; 9499 } 9500 9501 final ComponentName profileOwner = getProfileOwnerAsUser(userId); 9502 if (profileOwner == null) { 9503 return false; 9504 } 9505 9506 // Managed profiles are not allowed to use lock task 9507 if (isManagedProfile(userId)) { 9508 return false; 9509 } 9510 9511 return true; 9512 } 9513 9514 private void enforceCanCallLockTaskLocked(CallerIdentity caller) { 9515 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 9516 9517 final int userId = caller.getUserId(); 9518 if (!canUserUseLockTaskLocked(userId)) { 9519 throw new SecurityException("User " + userId + " is not allowed to use lock task"); 9520 } 9521 } 9522 9523 private boolean isSystemUid(CallerIdentity caller) { 9524 return UserHandle.isSameApp(caller.getUid(), Process.SYSTEM_UID); 9525 } 9526 9527 private boolean isRootUid(CallerIdentity caller) { 9528 return UserHandle.isSameApp(caller.getUid(), Process.ROOT_UID); 9529 } 9530 9531 private boolean isShellUid(CallerIdentity caller) { 9532 return UserHandle.isSameApp(caller.getUid(), Process.SHELL_UID); 9533 } 9534 9535 private @UserIdInt int getCurrentForegroundUserId() { 9536 try { 9537 return mInjector.getIActivityManager().getCurrentUser().id; 9538 } catch (RemoteException e) { 9539 Slogf.wtf(LOG_TAG, "cannot get current user"); 9540 } 9541 return UserHandle.USER_NULL; 9542 } 9543 9544 @Override 9545 public List<UserHandle> listForegroundAffiliatedUsers() { 9546 checkIsDeviceOwner(getCallerIdentity()); 9547 9548 return mInjector.binderWithCleanCallingIdentity(() -> { 9549 int userId = getCurrentForegroundUserId(); 9550 boolean isAffiliated; 9551 synchronized (getLockObject()) { 9552 isAffiliated = isUserAffiliatedWithDeviceLocked(userId); 9553 } 9554 9555 if (!isAffiliated) return Collections.emptyList(); 9556 9557 List<UserHandle> users = new ArrayList<>(1); 9558 users.add(UserHandle.of(userId)); 9559 9560 return users; 9561 }); 9562 } 9563 9564 protected int getProfileParentId(int userHandle) { 9565 return mInjector.binderWithCleanCallingIdentity(() -> { 9566 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 9567 return parentUser != null ? parentUser.id : userHandle; 9568 }); 9569 } 9570 9571 private int getProfileParentUserIfRequested(int userHandle, boolean parent) { 9572 if (parent) { 9573 return getProfileParentId(userHandle); 9574 } 9575 9576 return userHandle; 9577 } 9578 9579 private int getCredentialOwner(final int userHandle, final boolean parent) { 9580 return mInjector.binderWithCleanCallingIdentity(() -> { 9581 int effectiveUserHandle = userHandle; 9582 if (parent) { 9583 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 9584 if (parentProfile != null) { 9585 effectiveUserHandle = parentProfile.id; 9586 } 9587 } 9588 return mUserManager.getCredentialOwnerProfile(effectiveUserHandle); 9589 }); 9590 } 9591 9592 private boolean isManagedProfile(int userHandle) { 9593 final UserInfo user = getUserInfo(userHandle); 9594 return user != null && user.isManagedProfile(); 9595 } 9596 9597 private void enableIfNecessary(String packageName, int userId) { 9598 try { 9599 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 9600 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId); 9601 if (ai.enabledSetting 9602 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 9603 mIPackageManager.setApplicationEnabledSetting(packageName, 9604 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 9605 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 9606 } 9607 } catch (RemoteException e) { 9608 } 9609 } 9610 9611 private void dumpPerUserData(IndentingPrintWriter pw) { 9612 int userCount = mUserData.size(); 9613 for (int i = 0; i < userCount; i++) { 9614 int userId = mUserData.keyAt(i); 9615 DevicePolicyData policy = getUserData(userId); 9616 policy.dump(pw); 9617 pw.println(); 9618 9619 if (userId == UserHandle.USER_SYSTEM) { 9620 pw.increaseIndent(); 9621 PersonalAppsSuspensionHelper.forUser(mContext, userId).dump(pw); 9622 pw.decreaseIndent(); 9623 pw.println(); 9624 } else { 9625 // pm.getUnsuspendablePackages() will fail if it's called for a different user; 9626 // as this dump is mostly useful for system user anyways, we can just ignore the 9627 // others (rather than changing the permission check in the PM method) 9628 Slogf.d(LOG_TAG, "skipping PersonalAppsSuspensionHelper.dump() for user " + userId); 9629 } 9630 } 9631 } 9632 9633 @Override 9634 protected void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) { 9635 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, printWriter)) return; 9636 9637 try (IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, " ")) { 9638 pw.println("Current Device Policy Manager state:"); 9639 pw.increaseIndent(); 9640 9641 dumpImmutableState(pw); 9642 synchronized (getLockObject()) { 9643 mOwners.dump(pw); 9644 pw.println(); 9645 mDeviceAdminServiceController.dump(pw); 9646 pw.println(); 9647 dumpPerUserData(pw); 9648 pw.println(); 9649 mConstants.dump(pw); 9650 pw.println(); 9651 mStatLogger.dump(pw); 9652 pw.println(); 9653 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 9654 pw.println(); 9655 9656 if (mPendingUserCreatedCallbackTokens.isEmpty()) { 9657 pw.println("no pending user created callback tokens"); 9658 } else { 9659 int size = mPendingUserCreatedCallbackTokens.size(); 9660 pw.printf("%d pending user created callback token%s\n", size, 9661 (size == 1 ? "" : "s")); 9662 } 9663 pw.println(); 9664 9665 mPolicyCache.dump(pw); 9666 pw.println(); 9667 mStateCache.dump(pw); 9668 pw.println(); 9669 } 9670 dumpResources(pw); 9671 } 9672 } 9673 9674 private void dumpImmutableState(IndentingPrintWriter pw) { 9675 pw.println("Immutable state:"); 9676 pw.increaseIndent(); 9677 pw.printf("mHasFeature=%b\n", mHasFeature); 9678 pw.printf("mIsWatch=%b\n", mIsWatch); 9679 pw.printf("mIsAutomotive=%b\n", mIsAutomotive); 9680 pw.printf("mHasTelephonyFeature=%b\n", mHasTelephonyFeature); 9681 pw.printf("mSafetyChecker=%s\n", mSafetyChecker); 9682 pw.decreaseIndent(); 9683 } 9684 9685 private void dumpResources(IndentingPrintWriter pw) { 9686 mOverlayPackagesProvider.dump(pw); 9687 pw.println(); 9688 9689 pw.println("Other overlayable app resources"); 9690 pw.increaseIndent(); 9691 dumpResources(pw, mContext, "cross_profile_apps", R.array.cross_profile_apps); 9692 dumpResources(pw, mContext, "vendor_cross_profile_apps", R.array.vendor_cross_profile_apps); 9693 dumpResources(pw, mContext, "config_packagesExemptFromSuspension", 9694 R.array.config_packagesExemptFromSuspension); 9695 dumpResources(pw, mContext, "policy_exempt_apps", R.array.policy_exempt_apps); 9696 dumpResources(pw, mContext, "vendor_policy_exempt_apps", R.array.vendor_policy_exempt_apps); 9697 pw.decreaseIndent(); 9698 pw.println(); 9699 } 9700 9701 static void dumpResources(IndentingPrintWriter pw, Context context, String resName, int resId) { 9702 dumpApps(pw, resName, context.getResources().getStringArray(resId)); 9703 } 9704 9705 static void dumpApps(IndentingPrintWriter pw, String name, String[] apps) { 9706 dumpApps(pw, name, Arrays.asList(apps)); 9707 } 9708 9709 static void dumpApps(IndentingPrintWriter pw, String name, List apps) { 9710 if (apps == null || apps.isEmpty()) { 9711 pw.printf("%s: empty\n", name); 9712 return; 9713 } 9714 int size = apps.size(); 9715 pw.printf("%s: %d app%s\n", name, size, size == 1 ? "" : "s"); 9716 pw.increaseIndent(); 9717 for (int i = 0; i < size; i++) { 9718 pw.printf("%d: %s\n", i, apps.get(i)); 9719 } 9720 pw.decreaseIndent(); 9721 } 9722 9723 @Override 9724 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 9725 String[] args, ShellCallback callback, ResultReceiver resultReceiver) { 9726 new DevicePolicyManagerServiceShellCommand(DevicePolicyManagerService.this).exec( 9727 this, in, out, err, args, callback, resultReceiver); 9728 9729 } 9730 9731 private String getEncryptionStatusName(int encryptionStatus) { 9732 switch (encryptionStatus) { 9733 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 9734 return "inactive"; 9735 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 9736 return "block default key"; 9737 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 9738 return "block"; 9739 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 9740 return "per-user"; 9741 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 9742 return "unsupported"; 9743 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 9744 return "activating"; 9745 default: 9746 return "unknown"; 9747 } 9748 } 9749 9750 @Override 9751 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 9752 ComponentName activity) { 9753 Objects.requireNonNull(who, "ComponentName is null"); 9754 final CallerIdentity caller = getCallerIdentity(who); 9755 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 9756 9757 final int userHandle = caller.getUserId(); 9758 synchronized (getLockObject()) { 9759 long id = mInjector.binderClearCallingIdentity(); 9760 try { 9761 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 9762 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 9763 } catch (RemoteException re) { 9764 // Shouldn't happen 9765 } finally { 9766 mInjector.binderRestoreCallingIdentity(id); 9767 } 9768 } 9769 final String activityPackage = 9770 (activity != null ? activity.getPackageName() : null); 9771 DevicePolicyEventLogger 9772 .createEvent(DevicePolicyEnums.ADD_PERSISTENT_PREFERRED_ACTIVITY) 9773 .setAdmin(who) 9774 .setStrings(activityPackage, getIntentFilterActions(filter)) 9775 .write(); 9776 } 9777 9778 @Override 9779 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 9780 Objects.requireNonNull(who, "ComponentName is null"); 9781 final CallerIdentity caller = getCallerIdentity(who); 9782 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 9783 9784 final int userHandle = caller.getUserId(); 9785 synchronized (getLockObject()) { 9786 long id = mInjector.binderClearCallingIdentity(); 9787 try { 9788 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 9789 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 9790 } catch (RemoteException re) { 9791 // Shouldn't happen 9792 } finally { 9793 mInjector.binderRestoreCallingIdentity(id); 9794 } 9795 } 9796 } 9797 9798 @Override 9799 public void setDefaultSmsApplication(ComponentName admin, String packageName, boolean parent) { 9800 Objects.requireNonNull(admin, "ComponentName is null"); 9801 9802 final CallerIdentity caller = getCallerIdentity(admin); 9803 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 9804 || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller))); 9805 if (parent) { 9806 mInjector.binderWithCleanCallingIdentity(() -> enforcePackageIsSystemPackage( 9807 packageName, getProfileParentId(mInjector.userHandleGetCallingUserId()))); 9808 } 9809 9810 mInjector.binderWithCleanCallingIdentity(() -> 9811 SmsApplication.setDefaultApplication(packageName, mContext)); 9812 } 9813 9814 @Override 9815 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 9816 String packageName) { 9817 try { 9818 setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS); 9819 } catch (IllegalArgumentException e) { 9820 return false; 9821 } 9822 return true; 9823 } 9824 9825 @Override 9826 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 9827 final List<String> delegatePackages = getDelegatePackages(admin, 9828 DELEGATION_APP_RESTRICTIONS); 9829 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 9830 } 9831 9832 @Override 9833 public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) { 9834 return isCallerDelegate(callerPackage, getCallerIdentity().getUid(), 9835 DELEGATION_APP_RESTRICTIONS); 9836 } 9837 9838 @Override 9839 public void setApplicationRestrictions(ComponentName who, String callerPackage, 9840 String packageName, Bundle settings) { 9841 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 9842 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 9843 && (isProfileOwner(caller) || isDeviceOwner(caller))) 9844 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS))); 9845 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_RESTRICTIONS); 9846 9847 mInjector.binderWithCleanCallingIdentity(() -> { 9848 mUserManager.setApplicationRestrictions(packageName, settings, 9849 caller.getUserHandle()); 9850 DevicePolicyEventLogger 9851 .createEvent(DevicePolicyEnums.SET_APPLICATION_RESTRICTIONS) 9852 .setAdmin(caller.getPackageName()) 9853 .setBoolean(/* isDelegate */ who == null) 9854 .setStrings(packageName) 9855 .write(); 9856 }); 9857 } 9858 9859 @Override 9860 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 9861 PersistableBundle args, boolean parent) { 9862 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 9863 return; 9864 } 9865 Objects.requireNonNull(admin, "admin is null"); 9866 Objects.requireNonNull(agent, "agent is null"); 9867 final int userHandle = UserHandle.getCallingUserId(); 9868 synchronized (getLockObject()) { 9869 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 9870 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 9871 checkCanExecuteOrThrowUnsafe( 9872 DevicePolicyManager.OPERATION_SET_TRUST_AGENT_CONFIGURATION); 9873 9874 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 9875 saveSettingsLocked(userHandle); 9876 } 9877 } 9878 9879 @Override 9880 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 9881 ComponentName agent, int userHandle, boolean parent) { 9882 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 9883 return null; 9884 } 9885 Objects.requireNonNull(agent, "agent null"); 9886 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 9887 9888 final CallerIdentity caller = getCallerIdentity(); 9889 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 9890 9891 synchronized (getLockObject()) { 9892 final String componentName = agent.flattenToString(); 9893 if (admin != null) { 9894 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 9895 if (ap == null) return null; 9896 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 9897 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 9898 List<PersistableBundle> result = new ArrayList<>(); 9899 result.add(trustAgentInfo.options); 9900 return result; 9901 } 9902 9903 // Return strictest policy for this user and profiles that are visible from this user. 9904 List<PersistableBundle> result = null; 9905 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 9906 // of the options. If any admin doesn't have options, discard options for the rest 9907 // and return null. 9908 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 9909 getProfileParentUserIfRequested(userHandle, parent)); 9910 boolean allAdminsHaveOptions = true; 9911 final int N = admins.size(); 9912 for (int i = 0; i < N; i++) { 9913 final ActiveAdmin active = admins.get(i); 9914 9915 final boolean disablesTrust = (active.disabledKeyguardFeatures 9916 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 9917 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 9918 if (info != null && info.options != null && !info.options.isEmpty()) { 9919 if (disablesTrust) { 9920 if (result == null) { 9921 result = new ArrayList<>(); 9922 } 9923 result.add(info.options); 9924 } else { 9925 Slogf.w(LOG_TAG, "Ignoring admin %s because it has trust options but " 9926 + "doesn't declare KEYGUARD_DISABLE_TRUST_AGENTS", active.info); 9927 } 9928 } else if (disablesTrust) { 9929 allAdminsHaveOptions = false; 9930 break; 9931 } 9932 } 9933 return allAdminsHaveOptions ? result : null; 9934 } 9935 } 9936 9937 @Override 9938 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 9939 Objects.requireNonNull(who, "ComponentName is null"); 9940 final CallerIdentity caller = getCallerIdentity(who); 9941 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 9942 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_RESTRICTIONS_PROVIDER); 9943 9944 synchronized (getLockObject()) { 9945 int userHandle = caller.getUserId(); 9946 DevicePolicyData userData = getUserData(userHandle); 9947 userData.mRestrictionsProvider = permissionProvider; 9948 saveSettingsLocked(userHandle); 9949 } 9950 } 9951 9952 @Override 9953 public ComponentName getRestrictionsProvider(int userHandle) { 9954 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 9955 String.format(NOT_SYSTEM_CALLER_MSG, "query the permission provider")); 9956 synchronized (getLockObject()) { 9957 DevicePolicyData userData = getUserData(userHandle); 9958 return userData != null ? userData.mRestrictionsProvider : null; 9959 } 9960 } 9961 9962 @Override 9963 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 9964 Objects.requireNonNull(who, "ComponentName is null"); 9965 final CallerIdentity caller = getCallerIdentity(who); 9966 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 9967 int callingUserId = caller.getUserId(); 9968 synchronized (getLockObject()) { 9969 long id = mInjector.binderClearCallingIdentity(); 9970 try { 9971 UserInfo parent = mUserManager.getProfileParent(callingUserId); 9972 if (parent == null) { 9973 Slogf.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 9974 + "parent"); 9975 return; 9976 } 9977 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 9978 mIPackageManager.addCrossProfileIntentFilter( 9979 filter, who.getPackageName(), callingUserId, parent.id, 0); 9980 } 9981 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 9982 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 9983 parent.id, callingUserId, 0); 9984 } 9985 } catch (RemoteException re) { 9986 // Shouldn't happen 9987 } finally { 9988 mInjector.binderRestoreCallingIdentity(id); 9989 } 9990 } 9991 DevicePolicyEventLogger 9992 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_INTENT_FILTER) 9993 .setAdmin(who) 9994 .setStrings(getIntentFilterActions(filter)) 9995 .setInt(flags) 9996 .write(); 9997 } 9998 9999 private static String[] getIntentFilterActions(IntentFilter filter) { 10000 if (filter == null) { 10001 return null; 10002 } 10003 final int actionsCount = filter.countActions(); 10004 final String[] actions = new String[actionsCount]; 10005 for (int i = 0; i < actionsCount; i++) { 10006 actions[i] = filter.getAction(i); 10007 } 10008 return actions; 10009 } 10010 10011 @Override 10012 public void clearCrossProfileIntentFilters(ComponentName who) { 10013 Objects.requireNonNull(who, "ComponentName is null"); 10014 final CallerIdentity caller = getCallerIdentity(who); 10015 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 10016 10017 int callingUserId = caller.getUserId(); 10018 synchronized (getLockObject()) { 10019 long id = mInjector.binderClearCallingIdentity(); 10020 try { 10021 UserInfo parent = mUserManager.getProfileParent(callingUserId); 10022 if (parent == null) { 10023 Slogf.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 10024 + "parent"); 10025 return; 10026 } 10027 // Removing those that go from the managed profile to the parent. 10028 mIPackageManager.clearCrossProfileIntentFilters( 10029 callingUserId, who.getPackageName()); 10030 // And those that go from the parent to the managed profile. 10031 // If we want to support multiple managed profiles, we will have to only remove 10032 // those that have callingUserId as their target. 10033 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 10034 } catch (RemoteException re) { 10035 // Shouldn't happen 10036 } finally { 10037 mInjector.binderRestoreCallingIdentity(id); 10038 } 10039 } 10040 } 10041 10042 /** 10043 * @return true if all packages in enabledPackages are either in the list 10044 * permittedList or are a system app. 10045 */ 10046 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 10047 List<String> permittedList, int userIdToCheck) { 10048 long id = mInjector.binderClearCallingIdentity(); 10049 try { 10050 // If we have an enabled packages list for a managed profile the packages 10051 // we should check are installed for the parent user. 10052 UserInfo user = getUserInfo(userIdToCheck); 10053 if (user.isManagedProfile()) { 10054 userIdToCheck = user.profileGroupId; 10055 } 10056 10057 for (String enabledPackage : enabledPackages) { 10058 boolean systemService = false; 10059 try { 10060 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 10061 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 10062 userIdToCheck); 10063 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10064 } catch (RemoteException e) { 10065 Slogf.i(LOG_TAG, "Can't talk to package managed", e); 10066 } 10067 if (!systemService && !permittedList.contains(enabledPackage)) { 10068 return false; 10069 } 10070 } 10071 } finally { 10072 mInjector.binderRestoreCallingIdentity(id); 10073 } 10074 return true; 10075 } 10076 10077 /** 10078 * Invoke a method in AccessibilityManager ensuring the client is removed. 10079 */ 10080 private <T> T withAccessibilityManager( 10081 int userId, Function<AccessibilityManager, T> function) { 10082 // Not using AccessibilityManager.getInstance because that guesses 10083 // at the user you require based on callingUid and caches for a given 10084 // process. 10085 final IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 10086 final IAccessibilityManager service = iBinder == null 10087 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 10088 final AccessibilityManager am = new AccessibilityManager(mContext, service, userId); 10089 try { 10090 return function.apply(am); 10091 } finally { 10092 am.removeClient(); 10093 } 10094 } 10095 10096 @Override 10097 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 10098 if (!mHasFeature) { 10099 return false; 10100 } 10101 Objects.requireNonNull(who, "ComponentName is null"); 10102 final CallerIdentity caller = getCallerIdentity(who); 10103 10104 if (packageList != null) { 10105 int userId = caller.getUserId(); 10106 final List<AccessibilityServiceInfo> enabledServices; 10107 long id = mInjector.binderClearCallingIdentity(); 10108 try { 10109 UserInfo user = getUserInfo(userId); 10110 if (user.isManagedProfile()) { 10111 userId = user.profileGroupId; 10112 } 10113 enabledServices = withAccessibilityManager(userId, 10114 am -> am.getEnabledAccessibilityServiceList(FEEDBACK_ALL_MASK)); 10115 } finally { 10116 mInjector.binderRestoreCallingIdentity(id); 10117 } 10118 10119 if (enabledServices != null) { 10120 List<String> enabledPackages = new ArrayList<>(); 10121 for (AccessibilityServiceInfo service : enabledServices) { 10122 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 10123 } 10124 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 10125 userId)) { 10126 Slogf.e(LOG_TAG, "Cannot set permitted accessibility services, " 10127 + "because it contains already enabled accesibility services."); 10128 return false; 10129 } 10130 } 10131 } 10132 10133 synchronized (getLockObject()) { 10134 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 10135 admin.permittedAccessiblityServices = packageList; 10136 saveSettingsLocked(UserHandle.getCallingUserId()); 10137 } 10138 final String[] packageArray = 10139 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null; 10140 DevicePolicyEventLogger 10141 .createEvent(DevicePolicyEnums.SET_PERMITTED_ACCESSIBILITY_SERVICES) 10142 .setAdmin(who) 10143 .setStrings(packageArray) 10144 .write(); 10145 return true; 10146 } 10147 10148 @Override 10149 public List getPermittedAccessibilityServices(ComponentName who) { 10150 if (!mHasFeature) { 10151 return null; 10152 } 10153 Objects.requireNonNull(who, "ComponentName is null"); 10154 final CallerIdentity caller = getCallerIdentity(who); 10155 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 10156 10157 synchronized (getLockObject()) { 10158 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 10159 return admin.permittedAccessiblityServices; 10160 } 10161 } 10162 10163 @Override 10164 public List getPermittedAccessibilityServicesForUser(int userId) { 10165 if (!mHasFeature) { 10166 return null; 10167 } 10168 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 10169 10170 synchronized (getLockObject()) { 10171 List<String> result = null; 10172 // If we have multiple profiles we return the intersection of the 10173 // permitted lists. This can happen in cases where we have a device 10174 // and profile owner. 10175 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 10176 for (int profileId : profileIds) { 10177 // Just loop though all admins, only device or profiles 10178 // owners can have permitted lists set. 10179 DevicePolicyData policy = getUserDataUnchecked(profileId); 10180 final int N = policy.mAdminList.size(); 10181 for (int j = 0; j < N; j++) { 10182 ActiveAdmin admin = policy.mAdminList.get(j); 10183 List<String> fromAdmin = admin.permittedAccessiblityServices; 10184 if (fromAdmin != null) { 10185 if (result == null) { 10186 result = new ArrayList<>(fromAdmin); 10187 } else { 10188 result.retainAll(fromAdmin); 10189 } 10190 } 10191 } 10192 } 10193 10194 // If we have a permitted list add all system accessibility services. 10195 if (result != null) { 10196 long id = mInjector.binderClearCallingIdentity(); 10197 try { 10198 UserInfo user = getUserInfo(userId); 10199 if (user.isManagedProfile()) { 10200 userId = user.profileGroupId; 10201 } 10202 final List<AccessibilityServiceInfo> installedServices = 10203 withAccessibilityManager(userId, 10204 AccessibilityManager::getInstalledAccessibilityServiceList); 10205 10206 if (installedServices != null) { 10207 for (AccessibilityServiceInfo service : installedServices) { 10208 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 10209 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 10210 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10211 result.add(serviceInfo.packageName); 10212 } 10213 } 10214 } 10215 } finally { 10216 mInjector.binderRestoreCallingIdentity(id); 10217 } 10218 } 10219 10220 return result; 10221 } 10222 } 10223 10224 @Override 10225 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 10226 int userHandle) { 10227 if (!mHasFeature) { 10228 return true; 10229 } 10230 Objects.requireNonNull(who, "ComponentName is null"); 10231 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 10232 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 10233 String.format(NOT_SYSTEM_CALLER_MSG, 10234 "query if an accessibility service is disabled by admin")); 10235 10236 synchronized (getLockObject()) { 10237 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 10238 if (admin == null) { 10239 return false; 10240 } 10241 if (admin.permittedAccessiblityServices == null) { 10242 return true; 10243 } 10244 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 10245 admin.permittedAccessiblityServices, userHandle); 10246 } 10247 } 10248 10249 @Override 10250 public boolean setPermittedInputMethods(ComponentName who, List packageList, 10251 boolean calledOnParentInstance) { 10252 if (!mHasFeature) { 10253 return false; 10254 } 10255 Objects.requireNonNull(who, "ComponentName is null"); 10256 10257 final CallerIdentity caller = getCallerIdentity(who); 10258 final int userId = getProfileParentUserIfRequested( 10259 caller.getUserId(), calledOnParentInstance); 10260 if (calledOnParentInstance) { 10261 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 10262 Preconditions.checkArgument(packageList == null || packageList.isEmpty(), 10263 "Permitted input methods must allow all input methods or only " 10264 + "system input methods when called on the parent instance of an " 10265 + "organization-owned device"); 10266 } else { 10267 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 10268 } 10269 10270 if (packageList != null) { 10271 List<InputMethodInfo> enabledImes = mInjector.binderWithCleanCallingIdentity(() -> 10272 InputMethodManagerInternal.get().getEnabledInputMethodListAsUser(userId)); 10273 if (enabledImes != null) { 10274 List<String> enabledPackages = new ArrayList<String>(); 10275 for (InputMethodInfo ime : enabledImes) { 10276 enabledPackages.add(ime.getPackageName()); 10277 } 10278 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 10279 userId)) { 10280 Slogf.e(LOG_TAG, "Cannot set permitted input methods, because the list of " 10281 + "permitted input methods excludes an already-enabled input method."); 10282 return false; 10283 } 10284 } 10285 } 10286 10287 synchronized (getLockObject()) { 10288 final ActiveAdmin admin = getParentOfAdminIfRequired( 10289 getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParentInstance); 10290 admin.permittedInputMethods = packageList; 10291 saveSettingsLocked(caller.getUserId()); 10292 } 10293 10294 DevicePolicyEventLogger 10295 .createEvent(DevicePolicyEnums.SET_PERMITTED_INPUT_METHODS) 10296 .setAdmin(who) 10297 .setStrings(getStringArrayForLogging(packageList, calledOnParentInstance)) 10298 .write(); 10299 return true; 10300 } 10301 10302 private String[] getStringArrayForLogging(List list, boolean calledOnParentInstance) { 10303 List<String> stringList = new ArrayList<String>(); 10304 stringList.add(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT); 10305 if (list == null) { 10306 stringList.add(NULL_STRING_ARRAY); 10307 } else { 10308 stringList.addAll((List<String>) list); 10309 } 10310 return stringList.toArray(new String[0]); 10311 } 10312 10313 @Override 10314 public List getPermittedInputMethods(ComponentName who, boolean calledOnParentInstance) { 10315 if (!mHasFeature) { 10316 return null; 10317 } 10318 Objects.requireNonNull(who, "ComponentName is null"); 10319 10320 final CallerIdentity caller = getCallerIdentity(who); 10321 if (calledOnParentInstance) { 10322 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 10323 } else { 10324 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 10325 } 10326 10327 synchronized (getLockObject()) { 10328 final ActiveAdmin admin = getParentOfAdminIfRequired( 10329 getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParentInstance); 10330 return admin.permittedInputMethods; 10331 } 10332 } 10333 10334 @Override 10335 public List getPermittedInputMethodsForCurrentUser() { 10336 final CallerIdentity caller = getCallerIdentity(); 10337 Preconditions.checkCallAuthorization(canManageUsers(caller)); 10338 10339 synchronized (getLockObject()) { 10340 List<String> result = null; 10341 // Only device or profile owners can have permitted lists set. 10342 List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(caller.getUserId()); 10343 for (ActiveAdmin admin: admins) { 10344 List<String> fromAdmin = admin.permittedInputMethods; 10345 if (fromAdmin != null) { 10346 if (result == null) { 10347 result = new ArrayList<String>(fromAdmin); 10348 } else { 10349 result.retainAll(fromAdmin); 10350 } 10351 } 10352 } 10353 10354 // If we have a permitted list add all system input methods. 10355 if (result != null) { 10356 List<InputMethodInfo> imes = InputMethodManagerInternal 10357 .get().getInputMethodListAsUser(caller.getUserId()); 10358 if (imes != null) { 10359 for (InputMethodInfo ime : imes) { 10360 ServiceInfo serviceInfo = ime.getServiceInfo(); 10361 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 10362 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10363 result.add(serviceInfo.packageName); 10364 } 10365 } 10366 } 10367 } 10368 return result; 10369 } 10370 } 10371 10372 @Override 10373 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 10374 int userHandle, boolean calledOnParentInstance) { 10375 if (!mHasFeature) { 10376 return true; 10377 } 10378 Objects.requireNonNull(who, "ComponentName is null"); 10379 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 10380 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 10381 String.format(NOT_SYSTEM_CALLER_MSG, 10382 "query if an input method is disabled by admin")); 10383 10384 synchronized (getLockObject()) { 10385 ActiveAdmin admin = getParentOfAdminIfRequired( 10386 getActiveAdminUncheckedLocked(who, userHandle), calledOnParentInstance); 10387 if (admin == null) { 10388 return false; 10389 } 10390 if (admin.permittedInputMethods == null) { 10391 return true; 10392 } 10393 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 10394 admin.permittedInputMethods, userHandle); 10395 } 10396 } 10397 10398 @Override 10399 public boolean setPermittedCrossProfileNotificationListeners( 10400 ComponentName who, List<String> packageList) { 10401 if (!mHasFeature) { 10402 return false; 10403 } 10404 Objects.requireNonNull(who, "ComponentName is null"); 10405 final CallerIdentity caller = getCallerIdentity(who); 10406 10407 if (!isManagedProfile(caller.getUserId())) { 10408 return false; 10409 } 10410 10411 synchronized (getLockObject()) { 10412 ActiveAdmin admin = getProfileOwnerLocked(caller); 10413 admin.permittedNotificationListeners = packageList; 10414 saveSettingsLocked(caller.getUserId()); 10415 } 10416 return true; 10417 } 10418 10419 @Override 10420 public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) { 10421 if (!mHasFeature) { 10422 return null; 10423 } 10424 Objects.requireNonNull(who, "ComponentName is null"); 10425 final CallerIdentity caller = getCallerIdentity(who); 10426 10427 synchronized (getLockObject()) { 10428 // API contract is to return null if there are no permitted cross-profile notification 10429 // listeners, including in Device Owner mode. 10430 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 10431 return admin.permittedNotificationListeners; 10432 } 10433 } 10434 10435 @Override 10436 public boolean isNotificationListenerServicePermitted(String packageName, int userId) { 10437 if (!mHasFeature) { 10438 return true; 10439 } 10440 10441 Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty"); 10442 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 10443 String.format(NOT_SYSTEM_CALLER_MSG, 10444 "query if a notification listener service is permitted")); 10445 10446 synchronized (getLockObject()) { 10447 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 10448 if (profileOwner == null || profileOwner.permittedNotificationListeners == null) { 10449 return true; 10450 } 10451 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 10452 profileOwner.permittedNotificationListeners, userId); 10453 10454 } 10455 } 10456 10457 private void maybeSendAdminEnabledBroadcastLocked(int userHandle) { 10458 DevicePolicyData policyData = getUserData(userHandle); 10459 if (policyData.mAdminBroadcastPending) { 10460 // Send the initialization data to profile owner and delete the data 10461 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 10462 boolean clearInitBundle = true; 10463 if (admin != null) { 10464 PersistableBundle initBundle = policyData.mInitBundle; 10465 clearInitBundle = sendAdminCommandLocked(admin, 10466 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 10467 initBundle == null ? null : new Bundle(initBundle), 10468 /* result= */ null , 10469 /* inForeground= */ true); 10470 } 10471 if (clearInitBundle) { 10472 // If there's no admin or we've successfully called the admin, clear the init bundle 10473 // otherwise, keep it around 10474 policyData.mInitBundle = null; 10475 policyData.mAdminBroadcastPending = false; 10476 saveSettingsLocked(userHandle); 10477 } 10478 } 10479 } 10480 10481 @Override 10482 public UserHandle createAndManageUser(ComponentName admin, String name, 10483 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 10484 Objects.requireNonNull(admin, "admin is null"); 10485 Objects.requireNonNull(profileOwner, "profileOwner is null"); 10486 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 10487 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 10488 + admin + " are not in the same package"); 10489 } 10490 final CallerIdentity caller = getCallerIdentity(admin); 10491 // Only allow the system user to use this method 10492 Preconditions.checkCallAuthorization(caller.getUserHandle().isSystem(), 10493 "createAndManageUser was called from non-system user"); 10494 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 10495 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CREATE_AND_MANAGE_USER); 10496 10497 final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0; 10498 final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0 10499 && UserManager.isDeviceInDemoMode(mContext); 10500 final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0; 10501 final int targetSdkVersion; 10502 10503 // Create user. 10504 UserHandle user = null; 10505 synchronized (getLockObject()) { 10506 final long id = mInjector.binderClearCallingIdentity(); 10507 try { 10508 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion( 10509 caller.getUid()); 10510 10511 // Return detail error code for checks inside 10512 // UserManagerService.createUserInternalUnchecked. 10513 DeviceStorageMonitorInternal deviceStorageMonitorInternal = 10514 LocalServices.getService(DeviceStorageMonitorInternal.class); 10515 if (deviceStorageMonitorInternal.isMemoryLow()) { 10516 if (targetSdkVersion >= Build.VERSION_CODES.P) { 10517 throw new ServiceSpecificException( 10518 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage"); 10519 } else { 10520 return null; 10521 } 10522 } 10523 if (!mUserManager.canAddMoreUsers()) { 10524 if (targetSdkVersion >= Build.VERSION_CODES.P) { 10525 throw new ServiceSpecificException( 10526 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached"); 10527 } else { 10528 return null; 10529 } 10530 } 10531 10532 int userInfoFlags = ephemeral ? UserInfo.FLAG_EPHEMERAL : 0; 10533 String userType = demo ? UserManager.USER_TYPE_FULL_DEMO 10534 : UserManager.USER_TYPE_FULL_SECONDARY; 10535 String[] disallowedPackages = null; 10536 if (!leaveAllSystemAppsEnabled) { 10537 disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin, 10538 UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray( 10539 new String[0]); 10540 } 10541 10542 Object token = new Object(); 10543 Slogf.d(LOG_TAG, "Adding new pending token: " + token); 10544 mPendingUserCreatedCallbackTokens.add(token); 10545 try { 10546 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 10547 userType, userInfoFlags, disallowedPackages, token); 10548 if (userInfo != null) { 10549 user = userInfo.getUserHandle(); 10550 } 10551 } catch (UserManager.CheckedUserOperationException e) { 10552 Slogf.e(LOG_TAG, "Couldn't createUserEvenWhenDisallowed", e); 10553 } 10554 } finally { 10555 mInjector.binderRestoreCallingIdentity(id); 10556 } 10557 } // synchronized 10558 10559 if (user == null) { 10560 if (targetSdkVersion >= Build.VERSION_CODES.P) { 10561 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN, 10562 "failed to create user"); 10563 } else { 10564 return null; 10565 } 10566 } 10567 10568 final int userHandle = user.getIdentifier(); 10569 final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED) 10570 .putExtra(Intent.EXTRA_USER_HANDLE, userHandle) 10571 .putExtra( 10572 DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED, 10573 leaveAllSystemAppsEnabled) 10574 .setPackage(getManagedProvisioningPackage(mContext)) 10575 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10576 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM); 10577 10578 final long id = mInjector.binderClearCallingIdentity(); 10579 try { 10580 manageUserUnchecked(admin, profileOwner, userHandle, adminExtras, 10581 /* showDisclaimer= */ true); 10582 10583 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 10584 Settings.Secure.putIntForUser(mContext.getContentResolver(), 10585 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 10586 } 10587 10588 return user; 10589 } catch (Throwable re) { 10590 mUserManager.removeUser(userHandle); 10591 if (targetSdkVersion >= Build.VERSION_CODES.P) { 10592 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN, 10593 re.getMessage()); 10594 } else { 10595 return null; 10596 } 10597 } finally { 10598 mInjector.binderRestoreCallingIdentity(id); 10599 } 10600 } 10601 10602 private void manageUserUnchecked(ComponentName admin, ComponentName profileOwner, 10603 @UserIdInt int userId, @Nullable PersistableBundle adminExtras, 10604 boolean showDisclaimer) { 10605 synchronized (getLockObject()) { 10606 if (VERBOSE_LOG) { 10607 Slogf.v(LOG_TAG, "manageUserUnchecked(): admin=" + admin + ", po=" + profileOwner 10608 + ", userId=" + userId + ", hasAdminExtras=" + (adminExtras != null) 10609 + ", showDisclaimer=" + showDisclaimer); 10610 } 10611 } 10612 final String adminPkg = admin.getPackageName(); 10613 try { 10614 // Install the profile owner if not present. 10615 if (!mIPackageManager.isPackageAvailable(adminPkg, userId)) { 10616 mIPackageManager.installExistingPackageAsUser(adminPkg, userId, 10617 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 10618 PackageManager.INSTALL_REASON_POLICY, 10619 /* allowlistedRestrictedPermissions= */ null); 10620 } 10621 } catch (RemoteException e) { 10622 // Does not happen, same process 10623 Slogf.wtf(LOG_TAG, e, "Failed to install admin package %s for user %d", 10624 adminPkg, userId); 10625 } 10626 10627 // Set admin. 10628 setActiveAdmin(profileOwner, /* refreshing= */ true, userId); 10629 final String ownerName = getProfileOwnerNameUnchecked( 10630 Process.myUserHandle().getIdentifier()); 10631 setProfileOwner(profileOwner, ownerName, userId); 10632 10633 synchronized (getLockObject()) { 10634 DevicePolicyData policyData = getUserData(userId); 10635 policyData.mInitBundle = adminExtras; 10636 policyData.mAdminBroadcastPending = true; 10637 policyData.mNewUserDisclaimer = showDisclaimer 10638 ? DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED 10639 : DevicePolicyData.NEW_USER_DISCLAIMER_NOT_NEEDED; 10640 saveSettingsLocked(userId); 10641 10642 } 10643 } 10644 10645 private void handleNewUserCreated(UserInfo user, @Nullable Object token) { 10646 if (VERBOSE_LOG) { 10647 Slogf.v(LOG_TAG, "handleNewUserCreated(): user=" + user.toFullString() 10648 + ", token=" + token); 10649 } 10650 10651 final int userId = user.id; 10652 if (token != null) { 10653 synchronized (getLockObject()) { 10654 if (mPendingUserCreatedCallbackTokens.contains(token)) { 10655 // Ignore because it was triggered by createAndManageUser() 10656 Slogf.d(LOG_TAG, "handleNewUserCreated(): ignoring for user " + userId 10657 + " due to token" + token); 10658 mPendingUserCreatedCallbackTokens.remove(token); 10659 return; 10660 } 10661 } 10662 } 10663 10664 if (!mOwners.hasDeviceOwner() || !user.isFull() || user.isManagedProfile()) return; 10665 10666 if (mInjector.userManagerIsHeadlessSystemUserMode()) { 10667 ComponentName admin = mOwners.getDeviceOwnerComponent(); 10668 Slogf.i(LOG_TAG, "Automatically setting profile owner (" + admin + ") on new user " 10669 + userId); 10670 manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin, 10671 /* managedUser= */ userId, /* adminExtras= */ null, /* showDisclaimer= */ true); 10672 } else { 10673 Slogf.i(LOG_TAG, "User %d added on DO mode; setting ShowNewUserDisclaimer", userId); 10674 setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED); 10675 } 10676 } 10677 10678 @Override 10679 public void resetNewUserDisclaimer() { 10680 CallerIdentity callerIdentity = getCallerIdentity(); 10681 canManageUsers(callerIdentity); 10682 10683 setShowNewUserDisclaimer(callerIdentity.getUserId(), 10684 DevicePolicyData.NEW_USER_DISCLAIMER_SHOWN); 10685 } 10686 10687 private void setShowNewUserDisclaimer(@UserIdInt int userId, String value) { 10688 Slogf.i(LOG_TAG, "Setting new user disclaimer for user " + userId + " as " + value); 10689 synchronized (getLockObject()) { 10690 DevicePolicyData policyData = getUserData(userId); 10691 policyData.mNewUserDisclaimer = value; 10692 saveSettingsLocked(userId); 10693 } 10694 } 10695 10696 private void showNewUserDisclaimerIfNecessary(@UserIdInt int userId) { 10697 boolean mustShow; 10698 synchronized (getLockObject()) { 10699 DevicePolicyData policyData = getUserData(userId); 10700 if (VERBOSE_LOG) { 10701 Slogf.v(LOG_TAG, "showNewUserDisclaimerIfNecessary(" + userId + "): " 10702 + policyData.mNewUserDisclaimer + ")"); 10703 } 10704 mustShow = DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED 10705 .equals(policyData.mNewUserDisclaimer); 10706 } 10707 if (!mustShow) return; 10708 10709 Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_NEW_USER_DISCLAIMER); 10710 10711 // TODO(b/172691310): add CTS tests to make sure disclaimer is shown 10712 Slogf.i(LOG_TAG, "Dispatching ACTION_SHOW_NEW_USER_DISCLAIMER intent"); 10713 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 10714 } 10715 10716 @Override 10717 public boolean removeUser(ComponentName who, UserHandle userHandle) { 10718 Objects.requireNonNull(who, "ComponentName is null"); 10719 Objects.requireNonNull(userHandle, "UserHandle is null"); 10720 final CallerIdentity caller = getCallerIdentity(who); 10721 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 10722 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_USER); 10723 10724 return mInjector.binderWithCleanCallingIdentity(() -> { 10725 String restriction = isManagedProfile(userHandle.getIdentifier()) 10726 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 10727 : UserManager.DISALLOW_REMOVE_USER; 10728 if (isAdminAffectedByRestriction(who, restriction, caller.getUserId())) { 10729 Slogf.w(LOG_TAG, "The device owner cannot remove a user because %s is enabled, and " 10730 + "was not set by the device owner", restriction); 10731 return false; 10732 } 10733 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 10734 }); 10735 } 10736 10737 private boolean isAdminAffectedByRestriction( 10738 ComponentName admin, String userRestriction, int userId) { 10739 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 10740 case UserManager.RESTRICTION_NOT_SET: 10741 return false; 10742 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 10743 return !isDeviceOwner(admin, userId); 10744 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 10745 return !isProfileOwner(admin, userId); 10746 default: 10747 return true; 10748 } 10749 } 10750 10751 @Override 10752 public boolean switchUser(ComponentName who, UserHandle userHandle) { 10753 Objects.requireNonNull(who, "ComponentName is null"); 10754 final CallerIdentity caller = getCallerIdentity(who); 10755 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 10756 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SWITCH_USER); 10757 10758 synchronized (getLockObject()) { 10759 long id = mInjector.binderClearCallingIdentity(); 10760 try { 10761 int userId = UserHandle.USER_SYSTEM; 10762 if (userHandle != null) { 10763 userId = userHandle.getIdentifier(); 10764 } 10765 return mInjector.getIActivityManager().switchUser(userId); 10766 } catch (RemoteException e) { 10767 Slogf.e(LOG_TAG, "Couldn't switch user", e); 10768 return false; 10769 } finally { 10770 mInjector.binderRestoreCallingIdentity(id); 10771 } 10772 } 10773 } 10774 10775 @Override 10776 public int startUserInBackground(ComponentName who, UserHandle userHandle) { 10777 Objects.requireNonNull(who, "ComponentName is null"); 10778 Objects.requireNonNull(userHandle, "UserHandle is null"); 10779 final CallerIdentity caller = getCallerIdentity(who); 10780 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 10781 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_START_USER_IN_BACKGROUND); 10782 10783 final int userId = userHandle.getIdentifier(); 10784 if (isManagedProfile(userId)) { 10785 Slogf.w(LOG_TAG, "Managed profile cannot be started in background"); 10786 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 10787 } 10788 10789 final long id = mInjector.binderClearCallingIdentity(); 10790 try { 10791 if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) { 10792 Slogf.w(LOG_TAG, "Cannot start user %d, too many users in background", userId); 10793 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS; 10794 } 10795 10796 if (mInjector.getIActivityManager().startUserInBackground(userId)) { 10797 Slogf.i(LOG_TAG, "Started used %d in background", userId); 10798 return UserManager.USER_OPERATION_SUCCESS; 10799 } else { 10800 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 10801 } 10802 } catch (RemoteException e) { 10803 // Same process, should not happen. 10804 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 10805 } finally { 10806 mInjector.binderRestoreCallingIdentity(id); 10807 } 10808 } 10809 10810 @Override 10811 public int stopUser(ComponentName who, UserHandle userHandle) { 10812 Objects.requireNonNull(who, "ComponentName is null"); 10813 Objects.requireNonNull(userHandle, "UserHandle is null"); 10814 final CallerIdentity caller = getCallerIdentity(who); 10815 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 10816 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_STOP_USER); 10817 10818 final int userId = userHandle.getIdentifier(); 10819 if (isManagedProfile(userId)) { 10820 Slogf.w(LOG_TAG, "Managed profile cannot be stopped"); 10821 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 10822 } 10823 10824 return stopUserUnchecked(userId); 10825 } 10826 10827 @Override 10828 public int logoutUser(ComponentName who) { 10829 Objects.requireNonNull(who, "ComponentName is null"); 10830 final CallerIdentity caller = getCallerIdentity(who); 10831 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 10832 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOGOUT_USER); 10833 10834 final int callingUserId = caller.getUserId(); 10835 synchronized (getLockObject()) { 10836 if (!isUserAffiliatedWithDeviceLocked(callingUserId)) { 10837 throw new SecurityException("Admin " + who + 10838 " is neither the device owner or affiliated user's profile owner."); 10839 } 10840 } 10841 10842 if (isManagedProfile(callingUserId)) { 10843 Slogf.w(LOG_TAG, "Managed profile cannot be logout"); 10844 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 10845 } 10846 10847 final long id = mInjector.binderClearCallingIdentity(); 10848 try { 10849 if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) { 10850 Slogf.w(LOG_TAG, "Failed to switch to primary user"); 10851 // This should never happen as target user is UserHandle.USER_SYSTEM 10852 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 10853 } 10854 } catch (RemoteException e) { 10855 // Same process, should not happen. 10856 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 10857 } finally { 10858 mInjector.binderRestoreCallingIdentity(id); 10859 } 10860 10861 return stopUserUnchecked(callingUserId); 10862 } 10863 10864 private int stopUserUnchecked(int userId) { 10865 final long id = mInjector.binderClearCallingIdentity(); 10866 try { 10867 switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) { 10868 case ActivityManager.USER_OP_SUCCESS: 10869 return UserManager.USER_OPERATION_SUCCESS; 10870 case ActivityManager.USER_OP_IS_CURRENT: 10871 return UserManager.USER_OPERATION_ERROR_CURRENT_USER; 10872 default: 10873 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 10874 } 10875 } catch (RemoteException e) { 10876 // Same process, should not happen. 10877 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 10878 } finally { 10879 mInjector.binderRestoreCallingIdentity(id); 10880 } 10881 } 10882 10883 @Override 10884 public List<UserHandle> getSecondaryUsers(ComponentName who) { 10885 Objects.requireNonNull(who, "ComponentName is null"); 10886 final CallerIdentity caller = getCallerIdentity(who); 10887 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 10888 10889 return mInjector.binderWithCleanCallingIdentity(() -> { 10890 final List<UserInfo> userInfos = mInjector.getUserManager().getAliveUsers(); 10891 final List<UserHandle> userHandles = new ArrayList<>(); 10892 for (UserInfo userInfo : userInfos) { 10893 UserHandle userHandle = userInfo.getUserHandle(); 10894 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) { 10895 userHandles.add(userInfo.getUserHandle()); 10896 } 10897 } 10898 return userHandles; 10899 }); 10900 } 10901 10902 @Override 10903 public boolean isEphemeralUser(ComponentName who) { 10904 Objects.requireNonNull(who, "ComponentName is null"); 10905 10906 final CallerIdentity caller = getCallerIdentity(who); 10907 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 10908 10909 return mInjector.binderWithCleanCallingIdentity( 10910 () -> mInjector.getUserManager().isUserEphemeral(caller.getUserId())); 10911 } 10912 10913 @Override 10914 public Bundle getApplicationRestrictions(ComponentName who, String callerPackage, 10915 String packageName) { 10916 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 10917 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 10918 && (isProfileOwner(caller) || isDeviceOwner(caller))) 10919 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS))); 10920 10921 return mInjector.binderWithCleanCallingIdentity(() -> { 10922 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, 10923 caller.getUserHandle()); 10924 // if no restrictions were saved, mUserManager.getApplicationRestrictions 10925 // returns null, but DPM method should return an empty Bundle as per JavaDoc 10926 return bundle != null ? bundle : Bundle.EMPTY; 10927 }); 10928 } 10929 10930 /** 10931 * Returns the apps that are non-exempt from some policies (such as suspension), and populates 10932 * the given set with the apps that are exempt. 10933 * 10934 * @param packageNames apps to check 10935 * @param outputExemptApps will be populate with subset of {@code packageNames} that is exempt 10936 * from some policy restrictions 10937 * 10938 * @return subset of {@code packageNames} that is affected by some policy restrictions. 10939 */ 10940 private String[] populateNonExemptAndExemptFromPolicyApps(String[] packageNames, 10941 Set<String> outputExemptApps) { 10942 Preconditions.checkArgument(outputExemptApps.isEmpty(), "outputExemptApps is not empty"); 10943 List<String> exemptAppsList = listPolicyExemptAppsUnchecked(); 10944 if (exemptAppsList.isEmpty()) { 10945 return packageNames; 10946 } 10947 // Using a set so contains() is O(1) 10948 Set<String> exemptApps = new HashSet<>(exemptAppsList); 10949 List<String> nonExemptApps = new ArrayList<>(packageNames.length); 10950 for (int i = 0; i < packageNames.length; i++) { 10951 String app = packageNames[i]; 10952 if (exemptApps.contains(app)) { 10953 outputExemptApps.add(app); 10954 } else { 10955 nonExemptApps.add(app); 10956 } 10957 } 10958 String[] result = new String[nonExemptApps.size()]; 10959 nonExemptApps.toArray(result); 10960 return result; 10961 } 10962 10963 @Override 10964 public String[] setPackagesSuspended(ComponentName who, String callerPackage, 10965 String[] packageNames, boolean suspended) { 10966 Objects.requireNonNull(packageNames, "array of packages cannot be null"); 10967 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 10968 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 10969 && (isProfileOwner(caller) || isDeviceOwner(caller))) 10970 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS))); 10971 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PACKAGES_SUSPENDED); 10972 10973 // Must remove the exempt apps from the input before calling PM, then add them back to 10974 // the array returned to the caller 10975 Set<String> exemptApps = new HashSet<>(); 10976 packageNames = populateNonExemptAndExemptFromPolicyApps(packageNames, exemptApps); 10977 10978 String[] nonSuspendedPackages = null; 10979 synchronized (getLockObject()) { 10980 long id = mInjector.binderClearCallingIdentity(); 10981 try { 10982 nonSuspendedPackages = mIPackageManager.setPackagesSuspendedAsUser(packageNames, 10983 suspended, null, null, null, PLATFORM_PACKAGE_NAME, caller.getUserId()); 10984 } catch (RemoteException re) { 10985 // Shouldn't happen. 10986 Slogf.e(LOG_TAG, "Failed talking to the package manager", re); 10987 } finally { 10988 mInjector.binderRestoreCallingIdentity(id); 10989 } 10990 } 10991 DevicePolicyEventLogger 10992 .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED) 10993 .setAdmin(caller.getPackageName()) 10994 .setBoolean(/* isDelegate */ who == null) 10995 .setStrings(packageNames) 10996 .write(); 10997 10998 if (nonSuspendedPackages == null) { 10999 Slogf.w(LOG_TAG, "PM failed to suspend packages (%s)", Arrays.toString(packageNames)); 11000 return packageNames; 11001 } 11002 if (exemptApps.isEmpty()) { 11003 return nonSuspendedPackages; 11004 } 11005 11006 String[] result = buildNonSuspendedPackagesUnionArray(nonSuspendedPackages, exemptApps); 11007 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Returning %s", Arrays.toString(result)); 11008 return result; 11009 } 11010 11011 /** 11012 * Returns an array containing the union of the given non-suspended packages and 11013 * exempt apps. Assumes both parameters are non-null and non-empty. 11014 */ 11015 private String[] buildNonSuspendedPackagesUnionArray(String[] nonSuspendedPackages, 11016 Set<String> exemptApps) { 11017 String[] result = new String[nonSuspendedPackages.length + exemptApps.size()]; 11018 int index = 0; 11019 for (String app : nonSuspendedPackages) { 11020 result[index++] = app; 11021 } 11022 for (String app : exemptApps) { 11023 result[index++] = app; 11024 } 11025 return result; 11026 } 11027 11028 @Override 11029 public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) { 11030 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11031 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11032 && (isProfileOwner(caller) || isDeviceOwner(caller))) 11033 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS))); 11034 11035 synchronized (getLockObject()) { 11036 long id = mInjector.binderClearCallingIdentity(); 11037 try { 11038 return mIPackageManager.isPackageSuspendedForUser(packageName, caller.getUserId()); 11039 } catch (RemoteException re) { 11040 // Shouldn't happen. 11041 Slogf.e(LOG_TAG, "Failed talking to the package manager", re); 11042 } finally { 11043 mInjector.binderRestoreCallingIdentity(id); 11044 } 11045 return false; 11046 } 11047 } 11048 11049 @Override 11050 public List<String> listPolicyExemptApps() { 11051 CallerIdentity caller = getCallerIdentity(); 11052 Preconditions.checkCallAuthorization( 11053 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS) || isDeviceOwner(caller) 11054 || isProfileOwner(caller)); 11055 11056 return listPolicyExemptAppsUnchecked(); 11057 } 11058 11059 private List<String> listPolicyExemptAppsUnchecked() { 11060 // TODO(b/181238156): decide whether it should only list the apps set by the resources, 11061 // or also the "critical" apps defined by PersonalAppsSuspensionHelper (like SMS app). 11062 // If it's the latter, refactor PersonalAppsSuspensionHelper so it (or a superclass) takes 11063 // the resources on constructor. 11064 String[] core = mContext.getResources().getStringArray(R.array.policy_exempt_apps); 11065 String[] vendor = mContext.getResources().getStringArray(R.array.vendor_policy_exempt_apps); 11066 11067 int size = core.length + vendor.length; 11068 Set<String> apps = new ArraySet<>(size); 11069 for (String app : core) { 11070 apps.add(app); 11071 } 11072 for (String app : vendor) { 11073 apps.add(app); 11074 } 11075 11076 return new ArrayList<>(apps); 11077 } 11078 11079 @Override 11080 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner, 11081 boolean parent) { 11082 Objects.requireNonNull(who, "ComponentName is null"); 11083 11084 final CallerIdentity caller = getCallerIdentity(who); 11085 11086 if (!UserRestrictionsUtils.isValidRestriction(key)) { 11087 return; 11088 } 11089 11090 int userHandle = caller.getUserId(); 11091 synchronized (getLockObject()) { 11092 final ActiveAdmin activeAdmin = getParentOfAdminIfRequired( 11093 getProfileOwnerOrDeviceOwnerLocked(caller), parent); 11094 11095 if (isDeviceOwner(caller)) { 11096 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 11097 throw new SecurityException("Device owner cannot set user restriction " + key); 11098 } 11099 Preconditions.checkArgument(!parent, 11100 "Cannot use the parent instance in Device Owner mode"); 11101 } else { 11102 boolean profileOwnerCanChangeOnItself = !parent 11103 && UserRestrictionsUtils.canProfileOwnerChange(key, userHandle); 11104 boolean orgOwnedProfileOwnerCanChangesGlobally = parent 11105 && isProfileOwnerOfOrganizationOwnedDevice(caller) 11106 && UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange( 11107 key); 11108 11109 if (!profileOwnerCanChangeOnItself && !orgOwnedProfileOwnerCanChangesGlobally) { 11110 throw new SecurityException("Profile owner cannot set user restriction " + key); 11111 } 11112 } 11113 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION); 11114 11115 // Save the restriction to ActiveAdmin. 11116 final Bundle restrictions = activeAdmin.ensureUserRestrictions(); 11117 if (enabledFromThisOwner) { 11118 restrictions.putBoolean(key, true); 11119 } else { 11120 restrictions.remove(key); 11121 } 11122 saveUserRestrictionsLocked(userHandle); 11123 } 11124 final int eventId = enabledFromThisOwner 11125 ? DevicePolicyEnums.ADD_USER_RESTRICTION 11126 : DevicePolicyEnums.REMOVE_USER_RESTRICTION; 11127 DevicePolicyEventLogger 11128 .createEvent(eventId) 11129 .setAdmin(caller.getComponentName()) 11130 .setStrings(key, parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 11131 .write(); 11132 if (SecurityLog.isLoggingEnabled()) { 11133 final int eventTag = enabledFromThisOwner 11134 ? SecurityLog.TAG_USER_RESTRICTION_ADDED 11135 : SecurityLog.TAG_USER_RESTRICTION_REMOVED; 11136 SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key); 11137 } 11138 } 11139 11140 private void saveUserRestrictionsLocked(int userId) { 11141 saveSettingsLocked(userId); 11142 pushUserRestrictions(userId); 11143 sendChangedNotification(userId); 11144 } 11145 11146 /** 11147 * Pushes the user restrictions originating from a specific user. 11148 * 11149 * If called by the profile owner of an organization-owned device, the global and local 11150 * user restrictions will be an accumulation of the global user restrictions from the profile 11151 * owner active admin and its parent active admin. The key of the local user restrictions set 11152 * will be the target user id. 11153 */ 11154 private void pushUserRestrictions(int originatingUserId) { 11155 final Bundle global; 11156 final RestrictionsSet local = new RestrictionsSet(); 11157 final boolean isDeviceOwner; 11158 synchronized (getLockObject()) { 11159 isDeviceOwner = mOwners.isDeviceOwnerUserId(originatingUserId); 11160 if (isDeviceOwner) { 11161 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 11162 if (deviceOwner == null) { 11163 return; // Shouldn't happen. 11164 } 11165 global = deviceOwner.getGlobalUserRestrictions(OWNER_TYPE_DEVICE_OWNER); 11166 local.updateRestrictions(originatingUserId, deviceOwner.getLocalUserRestrictions( 11167 OWNER_TYPE_DEVICE_OWNER)); 11168 } else { 11169 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(originatingUserId); 11170 if (profileOwner == null) { 11171 return; 11172 } 11173 global = profileOwner.getGlobalUserRestrictions(OWNER_TYPE_PROFILE_OWNER); 11174 local.updateRestrictions(originatingUserId, profileOwner.getLocalUserRestrictions( 11175 OWNER_TYPE_PROFILE_OWNER)); 11176 // Global (device-wide) and local user restrictions set by the profile owner of an 11177 // organization-owned device are stored in the parent ActiveAdmin instance. 11178 if (isProfileOwnerOfOrganizationOwnedDevice( 11179 profileOwner.getUserHandle().getIdentifier())) { 11180 // The global restrictions set on the parent ActiveAdmin instance need to be 11181 // merged with the global restrictions set on the profile owner ActiveAdmin 11182 // instance, since both are to be applied device-wide. 11183 UserRestrictionsUtils.merge(global, 11184 profileOwner.getParentActiveAdmin().getGlobalUserRestrictions( 11185 OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE)); 11186 // The local restrictions set on the parent ActiveAdmin instance are only to be 11187 // applied to the primary user. They therefore need to be added the local 11188 // restriction set with the primary user id as the key, in this case the 11189 // primary user id is the target user. 11190 local.updateRestrictions( 11191 getProfileParentId(profileOwner.getUserHandle().getIdentifier()), 11192 profileOwner.getParentActiveAdmin().getLocalUserRestrictions( 11193 OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE)); 11194 } 11195 } 11196 } 11197 mUserManagerInternal.setDevicePolicyUserRestrictions(originatingUserId, global, local, 11198 isDeviceOwner); 11199 } 11200 11201 @Override 11202 public Bundle getUserRestrictions(ComponentName who, boolean parent) { 11203 if (!mHasFeature) { 11204 return null; 11205 } 11206 Objects.requireNonNull(who, "ComponentName is null"); 11207 11208 final CallerIdentity caller = getCallerIdentity(who); 11209 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller) 11210 || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller))); 11211 11212 synchronized (getLockObject()) { 11213 final ActiveAdmin activeAdmin = getParentOfAdminIfRequired( 11214 getProfileOwnerOrDeviceOwnerLocked(caller), parent); 11215 return activeAdmin.userRestrictions; 11216 } 11217 } 11218 11219 @Override 11220 public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName, 11221 boolean hidden, boolean parent) { 11222 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11223 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11224 && (isProfileOwner(caller) || isDeviceOwner(caller))) 11225 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS))); 11226 11227 List<String> exemptApps = listPolicyExemptAppsUnchecked(); 11228 if (exemptApps.contains(packageName)) { 11229 Slogf.d(LOG_TAG, "setApplicationHidden(): ignoring %s as it's on policy-exempt list", 11230 packageName); 11231 return false; 11232 } 11233 11234 final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId(); 11235 boolean result; 11236 synchronized (getLockObject()) { 11237 if (parent) { 11238 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice( 11239 caller.getUserId()) && isManagedProfile(caller.getUserId())); 11240 // Ensure the package provided is a system package, this is to ensure that this 11241 // API cannot be used to leak if certain non-system package exists in the person 11242 // profile. 11243 mInjector.binderWithCleanCallingIdentity(() -> 11244 enforcePackageIsSystemPackage(packageName, userId)); 11245 } 11246 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_HIDDEN); 11247 11248 if (VERBOSE_LOG) { 11249 Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)", 11250 packageName, hidden, userId); 11251 } 11252 result = mInjector.binderWithCleanCallingIdentity(() -> mIPackageManager 11253 .setApplicationHiddenSettingAsUser(packageName, hidden, userId)); 11254 } 11255 DevicePolicyEventLogger 11256 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN) 11257 .setAdmin(caller.getPackageName()) 11258 .setBoolean(/* isDelegate */ who == null) 11259 .setStrings(packageName, hidden ? "hidden" : "not_hidden", 11260 parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 11261 .write(); 11262 return result; 11263 } 11264 11265 @Override 11266 public boolean isApplicationHidden(ComponentName who, String callerPackage, 11267 String packageName, boolean parent) { 11268 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11269 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11270 && (isProfileOwner(caller) || isDeviceOwner(caller))) 11271 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS))); 11272 11273 final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId(); 11274 synchronized (getLockObject()) { 11275 if (parent) { 11276 Preconditions.checkCallAuthorization( 11277 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()) 11278 && isManagedProfile(caller.getUserId())); 11279 // Ensure the package provided is a system package. 11280 mInjector.binderWithCleanCallingIdentity(() -> 11281 enforcePackageIsSystemPackage(packageName, userId)); 11282 } 11283 11284 return mInjector.binderWithCleanCallingIdentity( 11285 () -> mIPackageManager.getApplicationHiddenSettingAsUser(packageName, userId)); 11286 } 11287 } 11288 11289 private void enforcePackageIsSystemPackage(String packageName, int userId) 11290 throws RemoteException { 11291 boolean isSystem; 11292 try { 11293 isSystem = isSystemApp(mIPackageManager, packageName, userId); 11294 } catch (IllegalArgumentException e) { 11295 isSystem = false; 11296 } 11297 if (!isSystem) { 11298 throw new IllegalArgumentException("The provided package is not a system package"); 11299 } 11300 } 11301 11302 @Override 11303 public void enableSystemApp(ComponentName who, String callerPackage, String packageName) { 11304 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11305 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11306 && (isProfileOwner(caller) || isDeviceOwner(caller))) 11307 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP))); 11308 11309 synchronized (getLockObject()) { 11310 final boolean isDemo = isCurrentUserDemo(); 11311 int userId = caller.getUserId(); 11312 long id = mInjector.binderClearCallingIdentity(); 11313 try { 11314 if (VERBOSE_LOG) { 11315 Slogf.v(LOG_TAG, "installing " + packageName + " for " + userId); 11316 } 11317 11318 Preconditions.checkArgument(isDemo || isSystemApp(mIPackageManager, packageName, 11319 getProfileParentId(userId)), "Only system apps can be enabled this way"); 11320 11321 // Install the app. 11322 mIPackageManager.installExistingPackageAsUser(packageName, userId, 11323 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 11324 PackageManager.INSTALL_REASON_POLICY, null); 11325 if (isDemo) { 11326 // Ensure the app is also ENABLED for demo users. 11327 mIPackageManager.setApplicationEnabledSetting(packageName, 11328 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 11329 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 11330 } 11331 } catch (RemoteException re) { 11332 // shouldn't happen 11333 Slogf.wtf(LOG_TAG, "Failed to install " + packageName, re); 11334 } finally { 11335 mInjector.binderRestoreCallingIdentity(id); 11336 } 11337 } 11338 DevicePolicyEventLogger 11339 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP) 11340 .setAdmin(caller.getPackageName()) 11341 .setBoolean(/* isDelegate */ who == null) 11342 .setStrings(packageName) 11343 .write(); 11344 } 11345 11346 @Override 11347 public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) { 11348 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11349 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11350 && (isProfileOwner(caller) || isDeviceOwner(caller))) 11351 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP))); 11352 11353 int numberOfAppsInstalled = 0; 11354 synchronized (getLockObject()) { 11355 long id = mInjector.binderClearCallingIdentity(); 11356 try { 11357 final int parentUserId = getProfileParentId(caller.getUserId()); 11358 List<ResolveInfo> activitiesToEnable = mIPackageManager 11359 .queryIntentActivities(intent, 11360 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11361 PackageManager.MATCH_DIRECT_BOOT_AWARE 11362 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 11363 parentUserId) 11364 .getList(); 11365 11366 if (VERBOSE_LOG) { 11367 Slogf.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 11368 } 11369 if (activitiesToEnable != null) { 11370 for (ResolveInfo info : activitiesToEnable) { 11371 if (info.activityInfo != null) { 11372 String packageName = info.activityInfo.packageName; 11373 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 11374 numberOfAppsInstalled++; 11375 mIPackageManager.installExistingPackageAsUser(packageName, 11376 caller.getUserId(), 11377 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 11378 PackageManager.INSTALL_REASON_POLICY, null); 11379 } else { 11380 Slogf.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 11381 + " system app"); 11382 } 11383 } 11384 } 11385 } 11386 } catch (RemoteException e) { 11387 // shouldn't happen 11388 Slogf.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 11389 return 0; 11390 } finally { 11391 mInjector.binderRestoreCallingIdentity(id); 11392 } 11393 } 11394 DevicePolicyEventLogger 11395 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP_WITH_INTENT) 11396 .setAdmin(caller.getPackageName()) 11397 .setBoolean(/* isDelegate */ who == null) 11398 .setStrings(intent.getAction()) 11399 .write(); 11400 return numberOfAppsInstalled; 11401 } 11402 11403 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 11404 throws RemoteException { 11405 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 11406 userId); 11407 if (appInfo == null) { 11408 throw new IllegalArgumentException("The application " + packageName + 11409 " is not present on this device"); 11410 } 11411 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11412 } 11413 11414 @Override 11415 public boolean installExistingPackage(ComponentName who, String callerPackage, 11416 String packageName) { 11417 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11418 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11419 && (isProfileOwner(caller) || isDeviceOwner(caller))) 11420 || (caller.hasPackage() 11421 && isCallerDelegate(caller, DELEGATION_INSTALL_EXISTING_PACKAGE))); 11422 11423 boolean result; 11424 synchronized (getLockObject()) { 11425 Preconditions.checkCallAuthorization( 11426 isUserAffiliatedWithDeviceLocked(caller.getUserId()), 11427 "Admin %s is neither the device owner or " 11428 + "affiliated user's profile owner.", who); 11429 final long id = mInjector.binderClearCallingIdentity(); 11430 try { 11431 if (VERBOSE_LOG) { 11432 Slogf.v(LOG_TAG, "installing " + packageName + " for " + caller.getUserId()); 11433 } 11434 11435 // Install the package. 11436 result = mIPackageManager.installExistingPackageAsUser(packageName, 11437 caller.getUserId(), 11438 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 11439 PackageManager.INSTALL_REASON_POLICY, null) 11440 == PackageManager.INSTALL_SUCCEEDED; 11441 } catch (RemoteException re) { 11442 // shouldn't happen 11443 return false; 11444 } finally { 11445 mInjector.binderRestoreCallingIdentity(id); 11446 } 11447 } 11448 if (result) { 11449 DevicePolicyEventLogger 11450 .createEvent(DevicePolicyEnums.INSTALL_EXISTING_PACKAGE) 11451 .setAdmin(caller.getPackageName()) 11452 .setBoolean(/* isDelegate */ who == null) 11453 .setStrings(packageName) 11454 .write(); 11455 } 11456 return result; 11457 } 11458 11459 @Override 11460 public void setAccountManagementDisabled(ComponentName who, String accountType, 11461 boolean disabled, boolean parent) { 11462 if (!mHasFeature) { 11463 return; 11464 } 11465 Objects.requireNonNull(who, "ComponentName is null"); 11466 final CallerIdentity caller = getCallerIdentity(who); 11467 synchronized (getLockObject()) { 11468 /* 11469 * When called on the parent DPM instance (parent == true), affects active admin 11470 * selection in two ways: 11471 * * The ActiveAdmin must be of an org-owned profile owner. 11472 * * The parent ActiveAdmin instance should be used for managing the restriction. 11473 */ 11474 final ActiveAdmin ap; 11475 if (parent) { 11476 ap = getParentOfAdminIfRequired(getOrganizationOwnedProfileOwnerLocked(caller), 11477 parent); 11478 } else { 11479 ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller), parent); 11480 } 11481 11482 if (disabled) { 11483 ap.accountTypesWithManagementDisabled.add(accountType); 11484 } else { 11485 ap.accountTypesWithManagementDisabled.remove(accountType); 11486 } 11487 saveSettingsLocked(UserHandle.getCallingUserId()); 11488 } 11489 } 11490 11491 @Override 11492 public String[] getAccountTypesWithManagementDisabled() { 11493 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId(), false); 11494 } 11495 11496 @Override 11497 public String[] getAccountTypesWithManagementDisabledAsUser(int userId, boolean parent) { 11498 if (!mHasFeature) { 11499 return null; 11500 } 11501 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 11502 11503 final CallerIdentity caller = getCallerIdentity(); 11504 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 11505 11506 synchronized (getLockObject()) { 11507 final ArraySet<String> resultSet = new ArraySet<>(); 11508 11509 if (!parent) { 11510 final DevicePolicyData policy = getUserData(userId); 11511 for (ActiveAdmin admin : policy.mAdminList) { 11512 resultSet.addAll(admin.accountTypesWithManagementDisabled); 11513 } 11514 } 11515 11516 // Check if there's a profile owner of an org-owned device and the method is called for 11517 // the parent user of this profile owner. 11518 final ActiveAdmin orgOwnedAdmin = 11519 getProfileOwnerOfOrganizationOwnedDeviceLocked(userId); 11520 final boolean shouldGetParentAccounts = orgOwnedAdmin != null && (parent 11521 || UserHandle.getUserId(orgOwnedAdmin.getUid()) != userId); 11522 if (shouldGetParentAccounts) { 11523 resultSet.addAll( 11524 orgOwnedAdmin.getParentActiveAdmin().accountTypesWithManagementDisabled); 11525 } 11526 return resultSet.toArray(new String[resultSet.size()]); 11527 } 11528 } 11529 11530 @Override 11531 public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName, 11532 boolean uninstallBlocked) { 11533 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11534 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11535 && (isProfileOwner(caller) || isDeviceOwner(caller))) 11536 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_BLOCK_UNINSTALL))); 11537 11538 final int userId = caller.getUserId(); 11539 synchronized (getLockObject()) { 11540 long id = mInjector.binderClearCallingIdentity(); 11541 try { 11542 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 11543 } catch (RemoteException re) { 11544 // Shouldn't happen. 11545 Slogf.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 11546 } finally { 11547 mInjector.binderRestoreCallingIdentity(id); 11548 } 11549 } 11550 if (uninstallBlocked) { 11551 final PackageManagerInternal pmi = mInjector.getPackageManagerInternal(); 11552 pmi.removeNonSystemPackageSuspensions(packageName, userId); 11553 pmi.removeDistractingPackageRestrictions(packageName, userId); 11554 pmi.flushPackageRestrictions(userId); 11555 } 11556 DevicePolicyEventLogger 11557 .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED) 11558 .setAdmin(caller.getPackageName()) 11559 .setBoolean(/* isDelegate */ who == null) 11560 .setStrings(packageName) 11561 .write(); 11562 } 11563 11564 @Override 11565 public boolean isUninstallBlocked(ComponentName who, String packageName) { 11566 // This function should return true if and only if the package is blocked by 11567 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 11568 // when the package is a system app, or when it is an active device admin. 11569 final int userId = UserHandle.getCallingUserId(); 11570 11571 synchronized (getLockObject()) { 11572 //TODO: This is a silly access control check. Remove. 11573 if (who != null) { 11574 final CallerIdentity caller = getCallerIdentity(who); 11575 Preconditions.checkCallAuthorization( 11576 isProfileOwner(caller) || isDeviceOwner(caller)); 11577 } 11578 long id = mInjector.binderClearCallingIdentity(); 11579 try { 11580 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 11581 } catch (RemoteException re) { 11582 // Shouldn't happen. 11583 Slogf.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 11584 } finally { 11585 mInjector.binderRestoreCallingIdentity(id); 11586 } 11587 } 11588 return false; 11589 } 11590 11591 @Override 11592 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 11593 if (!mHasFeature) { 11594 return; 11595 } 11596 Objects.requireNonNull(who, "ComponentName is null"); 11597 final CallerIdentity caller = getCallerIdentity(who); 11598 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 11599 11600 synchronized (getLockObject()) { 11601 ActiveAdmin admin = getProfileOwnerLocked(caller); 11602 if (admin.disableCallerId != disabled) { 11603 admin.disableCallerId = disabled; 11604 saveSettingsLocked(caller.getUserId()); 11605 } 11606 } 11607 DevicePolicyEventLogger 11608 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALLER_ID_DISABLED) 11609 .setAdmin(who) 11610 .setBoolean(disabled) 11611 .write(); 11612 } 11613 11614 @Override 11615 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 11616 if (!mHasFeature) { 11617 return false; 11618 } 11619 Objects.requireNonNull(who, "ComponentName is null"); 11620 final CallerIdentity caller = getCallerIdentity(who); 11621 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 11622 11623 synchronized (getLockObject()) { 11624 ActiveAdmin admin = getProfileOwnerLocked(caller); 11625 return admin.disableCallerId; 11626 } 11627 } 11628 11629 @Override 11630 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 11631 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 11632 11633 final CallerIdentity caller = getCallerIdentity(); 11634 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)); 11635 11636 synchronized (getLockObject()) { 11637 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 11638 return (admin != null) ? admin.disableCallerId : false; 11639 } 11640 } 11641 11642 @Override 11643 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 11644 if (!mHasFeature) { 11645 return; 11646 } 11647 Objects.requireNonNull(who, "ComponentName is null"); 11648 final CallerIdentity caller = getCallerIdentity(who); 11649 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 11650 11651 synchronized (getLockObject()) { 11652 ActiveAdmin admin = getProfileOwnerLocked(caller); 11653 if (admin.disableContactsSearch != disabled) { 11654 admin.disableContactsSearch = disabled; 11655 saveSettingsLocked(caller.getUserId()); 11656 } 11657 } 11658 DevicePolicyEventLogger 11659 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED) 11660 .setAdmin(who) 11661 .setBoolean(disabled) 11662 .write(); 11663 } 11664 11665 @Override 11666 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 11667 if (!mHasFeature) { 11668 return false; 11669 } 11670 Objects.requireNonNull(who, "ComponentName is null"); 11671 final CallerIdentity caller = getCallerIdentity(who); 11672 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 11673 11674 synchronized (getLockObject()) { 11675 ActiveAdmin admin = getProfileOwnerLocked(caller); 11676 return admin.disableContactsSearch; 11677 } 11678 } 11679 11680 @Override 11681 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 11682 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 11683 11684 final CallerIdentity caller = getCallerIdentity(); 11685 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)); 11686 11687 synchronized (getLockObject()) { 11688 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 11689 return (admin != null) ? admin.disableContactsSearch : false; 11690 } 11691 } 11692 11693 @Override 11694 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 11695 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 11696 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 11697 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 11698 final int callingUserId = UserHandle.getCallingUserId(); 11699 11700 mInjector.binderWithCleanCallingIdentity(() -> { 11701 synchronized (getLockObject()) { 11702 final int managedUserId = getManagedUserId(callingUserId); 11703 if (managedUserId < 0) { 11704 return; 11705 } 11706 if (isCrossProfileQuickContactDisabled(managedUserId)) { 11707 if (VERBOSE_LOG) { 11708 Slogf.v(LOG_TAG, "Cross-profile contacts access disabled for user %d", 11709 managedUserId); 11710 } 11711 return; 11712 } 11713 ContactsInternal.startQuickContactWithErrorToastForUser( 11714 mContext, intent, new UserHandle(managedUserId)); 11715 } 11716 }); 11717 } 11718 11719 /** 11720 * @return true if cross-profile QuickContact is disabled 11721 */ 11722 private boolean isCrossProfileQuickContactDisabled(@UserIdInt int userId) { 11723 return getCrossProfileCallerIdDisabledForUser(userId) 11724 && getCrossProfileContactsSearchDisabledForUser(userId); 11725 } 11726 11727 /** 11728 * @return the user ID of the managed user that is linked to the current user, if any. 11729 * Otherwise -1. 11730 */ 11731 public int getManagedUserId(@UserIdInt int callingUserId) { 11732 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "getManagedUserId: callingUserId=%d", callingUserId); 11733 11734 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 11735 if (ui.id == callingUserId || !ui.isManagedProfile()) { 11736 continue; // Caller user self, or not a managed profile. Skip. 11737 } 11738 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Managed user=%d", ui.id); 11739 return ui.id; 11740 } 11741 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Managed user not found."); 11742 return -1; 11743 } 11744 11745 @Override 11746 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 11747 if (!mHasFeature) { 11748 return; 11749 } 11750 Objects.requireNonNull(who, "ComponentName is null"); 11751 11752 final CallerIdentity caller = getCallerIdentity(who); 11753 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 11754 11755 synchronized (getLockObject()) { 11756 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 11757 if (admin.disableBluetoothContactSharing != disabled) { 11758 admin.disableBluetoothContactSharing = disabled; 11759 saveSettingsLocked(caller.getUserId()); 11760 } 11761 } 11762 DevicePolicyEventLogger 11763 .createEvent(DevicePolicyEnums.SET_BLUETOOTH_CONTACT_SHARING_DISABLED) 11764 .setAdmin(who) 11765 .setBoolean(disabled) 11766 .write(); 11767 } 11768 11769 @Override 11770 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 11771 if (!mHasFeature) { 11772 return false; 11773 } 11774 Objects.requireNonNull(who, "ComponentName is null"); 11775 11776 final CallerIdentity caller = getCallerIdentity(who); 11777 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 11778 11779 synchronized (getLockObject()) { 11780 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 11781 return admin.disableBluetoothContactSharing; 11782 } 11783 } 11784 11785 @Override 11786 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 11787 // TODO: Should there be a check to make sure this relationship is 11788 // within a profile group? 11789 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 11790 synchronized (getLockObject()) { 11791 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 11792 return (admin != null) ? admin.disableBluetoothContactSharing : false; 11793 } 11794 } 11795 11796 @Override 11797 public void setSecondaryLockscreenEnabled(ComponentName who, boolean enabled) { 11798 Objects.requireNonNull(who, "ComponentName is null"); 11799 11800 // Check can set secondary lockscreen enabled 11801 final CallerIdentity caller = getCallerIdentity(who); 11802 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 11803 Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()), 11804 "User %d is not allowed to call setSecondaryLockscreenEnabled", 11805 caller.getUserId()); 11806 11807 synchronized (getLockObject()) { 11808 // Allow testOnly admins to bypass supervision config requirement. 11809 Preconditions.checkCallAuthorization(isAdminTestOnlyLocked(who, caller.getUserId()) 11810 || isDefaultSupervisor(caller), "Admin %s is not the " 11811 + "default supervision component", caller.getComponentName()); 11812 DevicePolicyData policy = getUserData(caller.getUserId()); 11813 policy.mSecondaryLockscreenEnabled = enabled; 11814 saveSettingsLocked(caller.getUserId()); 11815 } 11816 } 11817 11818 @Override 11819 public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) { 11820 synchronized (getLockObject()) { 11821 return getUserData(userHandle.getIdentifier()).mSecondaryLockscreenEnabled; 11822 } 11823 } 11824 11825 private boolean isDefaultSupervisor(CallerIdentity caller) { 11826 final String supervisor = mContext.getResources().getString( 11827 com.android.internal.R.string.config_defaultSupervisionProfileOwnerComponent); 11828 if (supervisor == null) { 11829 return false; 11830 } 11831 final ComponentName supervisorComponent = ComponentName.unflattenFromString(supervisor); 11832 return caller.getComponentName().equals(supervisorComponent); 11833 } 11834 11835 @Override 11836 public void setPreferentialNetworkServiceEnabled(boolean enabled) { 11837 if (!mHasFeature) { 11838 return; 11839 } 11840 final CallerIdentity caller = getCallerIdentity(); 11841 Preconditions.checkCallAuthorization(isProfileOwner(caller), 11842 "Caller is not profile owner;" 11843 + " only profile owner may control the preferntial network service"); 11844 synchronized (getLockObject()) { 11845 final ActiveAdmin requiredAdmin = getProfileOwnerAdminLocked( 11846 caller.getUserId()); 11847 if (requiredAdmin != null 11848 && requiredAdmin.mPreferentialNetworkServiceEnabled != enabled) { 11849 requiredAdmin.mPreferentialNetworkServiceEnabled = enabled; 11850 saveSettingsLocked(caller.getUserId()); 11851 } 11852 } 11853 updateNetworkPreferenceForUser(caller.getUserId(), enabled); 11854 DevicePolicyEventLogger 11855 .createEvent(DevicePolicyEnums.SET_PREFERENTIAL_NETWORK_SERVICE_ENABLED) 11856 .setBoolean(enabled) 11857 .write(); 11858 } 11859 11860 @Override 11861 public boolean isPreferentialNetworkServiceEnabled(int userHandle) { 11862 if (!mHasFeature) { 11863 return false; 11864 } 11865 11866 final CallerIdentity caller = getCallerIdentity(); 11867 Preconditions.checkCallAuthorization(isProfileOwner(caller), 11868 "Caller is not profile owner"); 11869 synchronized (getLockObject()) { 11870 final ActiveAdmin requiredAdmin = getProfileOwnerAdminLocked(userHandle); 11871 if (requiredAdmin != null) { 11872 return requiredAdmin.mPreferentialNetworkServiceEnabled; 11873 } else { 11874 return false; 11875 } 11876 } 11877 } 11878 11879 @Override 11880 public void setLockTaskPackages(ComponentName who, String[] packages) 11881 throws SecurityException { 11882 Objects.requireNonNull(who, "ComponentName is null"); 11883 Objects.requireNonNull(packages, "packages is null"); 11884 final CallerIdentity caller = getCallerIdentity(who); 11885 11886 synchronized (getLockObject()) { 11887 enforceCanCallLockTaskLocked(caller); 11888 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_PACKAGES); 11889 final int userHandle = caller.getUserId(); 11890 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 11891 } 11892 } 11893 11894 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 11895 DevicePolicyData policy = getUserData(userHandle); 11896 policy.mLockTaskPackages = packages; 11897 11898 // Store the settings persistently. 11899 saveSettingsLocked(userHandle); 11900 updateLockTaskPackagesLocked(packages, userHandle); 11901 } 11902 11903 @Override 11904 public String[] getLockTaskPackages(ComponentName who) { 11905 Objects.requireNonNull(who, "ComponentName is null"); 11906 final CallerIdentity caller = getCallerIdentity(who); 11907 final int userHandle = caller.getUserId(); 11908 11909 synchronized (getLockObject()) { 11910 enforceCanCallLockTaskLocked(caller); 11911 final List<String> packages = getUserData(userHandle).mLockTaskPackages; 11912 return packages.toArray(new String[packages.size()]); 11913 } 11914 } 11915 11916 @Override 11917 public boolean isLockTaskPermitted(String pkg) { 11918 // Check policy-exempt apps first, as it doesn't require the lock 11919 if (listPolicyExemptAppsUnchecked().contains(pkg)) { 11920 if (VERBOSE_LOG) { 11921 Slogf.v(LOG_TAG, "isLockTaskPermitted(%s): returning true for policy-exempt app", 11922 pkg); 11923 } 11924 return true; 11925 } 11926 11927 final int userId = mInjector.userHandleGetCallingUserId(); 11928 synchronized (getLockObject()) { 11929 return getUserData(userId).mLockTaskPackages.contains(pkg); 11930 } 11931 } 11932 11933 @Override 11934 public void setLockTaskFeatures(ComponentName who, int flags) { 11935 Objects.requireNonNull(who, "ComponentName is null"); 11936 11937 // Throw if Overview is used without Home. 11938 boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0; 11939 boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0; 11940 Preconditions.checkArgument(hasHome || !hasOverview, 11941 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME"); 11942 boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0; 11943 Preconditions.checkArgument(hasHome || !hasNotification, 11944 "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME"); 11945 11946 final CallerIdentity caller = getCallerIdentity(who); 11947 final int userHandle = caller.getUserId(); 11948 synchronized (getLockObject()) { 11949 enforceCanCallLockTaskLocked(caller); 11950 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_FEATURES); 11951 setLockTaskFeaturesLocked(userHandle, flags); 11952 } 11953 } 11954 11955 private void setLockTaskFeaturesLocked(int userHandle, int flags) { 11956 DevicePolicyData policy = getUserData(userHandle); 11957 policy.mLockTaskFeatures = flags; 11958 saveSettingsLocked(userHandle); 11959 updateLockTaskFeaturesLocked(flags, userHandle); 11960 } 11961 11962 @Override 11963 public int getLockTaskFeatures(ComponentName who) { 11964 Objects.requireNonNull(who, "ComponentName is null"); 11965 final CallerIdentity caller = getCallerIdentity(who); 11966 final int userHandle = caller.getUserId(); 11967 synchronized (getLockObject()) { 11968 enforceCanCallLockTaskLocked(caller); 11969 return getUserData(userHandle).mLockTaskFeatures; 11970 } 11971 } 11972 11973 private void maybeClearLockTaskPolicyLocked() { 11974 mInjector.binderWithCleanCallingIdentity(() -> { 11975 final List<UserInfo> userInfos = mUserManager.getAliveUsers(); 11976 for (int i = userInfos.size() - 1; i >= 0; i--) { 11977 int userId = userInfos.get(i).id; 11978 if (canUserUseLockTaskLocked(userId)) { 11979 continue; 11980 } 11981 11982 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages; 11983 if (!lockTaskPackages.isEmpty()) { 11984 Slogf.d(LOG_TAG, 11985 "User id " + userId + " not affiliated. Clearing lock task packages"); 11986 setLockTaskPackagesLocked(userId, Collections.<String>emptyList()); 11987 } 11988 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures; 11989 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){ 11990 Slogf.d(LOG_TAG, 11991 "User id " + userId + " not affiliated. Clearing lock task features"); 11992 setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE); 11993 } 11994 } 11995 }); 11996 } 11997 11998 @Override 11999 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 12000 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 12001 String.format(NOT_SYSTEM_CALLER_MSG, "call notifyLockTaskModeChanged")); 12002 synchronized (getLockObject()) { 12003 final DevicePolicyData policy = getUserData(userHandle); 12004 12005 if (policy.mStatusBarDisabled) { 12006 // Status bar is managed by LockTaskController during LockTask, so we cancel this 12007 // policy when LockTask starts, and reapply it when LockTask ends 12008 setStatusBarDisabledInternal(!isEnabled, userHandle); 12009 } 12010 12011 Bundle adminExtras = new Bundle(); 12012 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 12013 for (ActiveAdmin admin : policy.mAdminList) { 12014 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 12015 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 12016 if (ownsDevice || ownsProfile) { 12017 if (isEnabled) { 12018 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 12019 adminExtras, null); 12020 } else { 12021 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 12022 } 12023 DevicePolicyEventLogger 12024 .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED) 12025 .setAdmin(admin.info.getPackageName()) 12026 .setBoolean(isEnabled) 12027 .setStrings(pkg) 12028 .write(); 12029 } 12030 } 12031 } 12032 } 12033 12034 @Override 12035 public void setGlobalSetting(ComponentName who, String setting, String value) { 12036 Objects.requireNonNull(who, "ComponentName is null"); 12037 final CallerIdentity caller = getCallerIdentity(who); 12038 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 12039 12040 DevicePolicyEventLogger 12041 .createEvent(DevicePolicyEnums.SET_GLOBAL_SETTING) 12042 .setAdmin(who) 12043 .setStrings(setting, value) 12044 .write(); 12045 12046 synchronized (getLockObject()) { 12047 // Some settings are no supported any more. However we do not want to throw a 12048 // SecurityException to avoid breaking apps. 12049 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 12050 Slogf.i(LOG_TAG, "Global setting no longer supported: %s", setting); 12051 return; 12052 } 12053 12054 if (!GLOBAL_SETTINGS_ALLOWLIST.contains(setting) 12055 && !UserManager.isDeviceInDemoMode(mContext)) { 12056 throw new SecurityException(String.format( 12057 "Permission denial: device owners cannot update %1$s", setting)); 12058 } 12059 12060 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 12061 // ignore if it contradicts an existing policy 12062 long timeMs = getMaximumTimeToLock( 12063 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 12064 if (timeMs > 0 && timeMs < Long.MAX_VALUE) { 12065 return; 12066 } 12067 } 12068 12069 mInjector.binderWithCleanCallingIdentity( 12070 () -> mInjector.settingsGlobalPutString(setting, value)); 12071 } 12072 } 12073 12074 @Override 12075 public void setSystemSetting(ComponentName who, String setting, String value) { 12076 Objects.requireNonNull(who, "ComponentName is null"); 12077 Preconditions.checkStringNotEmpty(setting, "String setting is null or empty"); 12078 final CallerIdentity caller = getCallerIdentity(who); 12079 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 12080 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_SETTING); 12081 12082 synchronized (getLockObject()) { 12083 if (!SYSTEM_SETTINGS_ALLOWLIST.contains(setting)) { 12084 throw new SecurityException(String.format( 12085 "Permission denial: device owners cannot update %1$s", setting)); 12086 } 12087 12088 mInjector.binderWithCleanCallingIdentity(() -> 12089 mInjector.settingsSystemPutStringForUser(setting, value, caller.getUserId())); 12090 } 12091 } 12092 12093 @Override 12094 public void setConfiguredNetworksLockdownState(ComponentName who, boolean lockdown) { 12095 if (!mHasFeature) { 12096 return; 12097 } 12098 Preconditions.checkNotNull(who, "ComponentName is null"); 12099 12100 final CallerIdentity caller = getCallerIdentity(who); 12101 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 12102 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 12103 12104 mInjector.binderWithCleanCallingIdentity(() -> 12105 mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 12106 lockdown ? 1 : 0)); 12107 12108 DevicePolicyEventLogger 12109 .createEvent(DevicePolicyEnums.ALLOW_MODIFICATION_OF_ADMIN_CONFIGURED_NETWORKS) 12110 .setAdmin(caller.getComponentName()) 12111 .setBoolean(lockdown) 12112 .write(); 12113 } 12114 12115 @Override 12116 public boolean hasLockdownAdminConfiguredNetworks(ComponentName who) { 12117 if (!mHasFeature) { 12118 return false; 12119 } 12120 Preconditions.checkNotNull(who, "ComponentName is null"); 12121 12122 final CallerIdentity caller = getCallerIdentity(who); 12123 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 12124 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 12125 12126 return mInjector.binderWithCleanCallingIdentity(() -> 12127 mInjector.settingsGlobalGetInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) > 0); 12128 } 12129 12130 @Override 12131 public void setLocationEnabled(ComponentName who, boolean locationEnabled) { 12132 Preconditions.checkNotNull(who, "ComponentName is null"); 12133 12134 final CallerIdentity caller = getCallerIdentity(who); 12135 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 12136 12137 UserHandle userHandle = caller.getUserHandle(); 12138 if (mIsAutomotive && !locationEnabled) { 12139 Slogf.i(LOG_TAG, "setLocationEnabled(%s, %b): ignoring for user %s on automotive build", 12140 who.flattenToShortString(), locationEnabled, userHandle); 12141 return; 12142 } 12143 12144 mInjector.binderWithCleanCallingIdentity(() -> { 12145 boolean wasLocationEnabled = mInjector.getLocationManager().isLocationEnabledForUser( 12146 userHandle); 12147 Slogf.v(LOG_TAG, "calling locationMgr.setLocationEnabledForUser(%b, %s) when it was %b", 12148 locationEnabled, userHandle, wasLocationEnabled); 12149 mInjector.getLocationManager().setLocationEnabledForUser(locationEnabled, userHandle); 12150 12151 // make a best effort to only show the notification if the admin is actually enabling 12152 // location. this is subject to race conditions with settings changes, but those are 12153 // unlikely to realistically interfere 12154 if (locationEnabled && !wasLocationEnabled) { 12155 showLocationSettingsEnabledNotification(userHandle); 12156 } 12157 }); 12158 12159 DevicePolicyEventLogger 12160 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING) 12161 .setAdmin(who) 12162 .setStrings(Settings.Secure.LOCATION_MODE, Integer.toString( 12163 locationEnabled ? Settings.Secure.LOCATION_MODE_ON 12164 : Settings.Secure.LOCATION_MODE_OFF)) 12165 .write(); 12166 } 12167 12168 private void showLocationSettingsEnabledNotification(UserHandle user) { 12169 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) 12170 .addFlags(FLAG_ACTIVITY_NEW_TASK); 12171 // Fill the component explicitly to prevent the PendingIntent from being intercepted 12172 // and fired with crafted target. b/155183624 12173 ActivityInfo targetInfo = intent.resolveActivityInfo( 12174 mInjector.getPackageManager(user.getIdentifier()), 12175 PackageManager.MATCH_SYSTEM_ONLY); 12176 if (targetInfo != null) { 12177 intent.setComponent(targetInfo.getComponentName()); 12178 } else { 12179 Slogf.wtf(LOG_TAG, "Failed to resolve intent for location settings"); 12180 } 12181 12182 // Simple notification clicks are immutable 12183 PendingIntent locationSettingsIntent = mInjector.pendingIntentGetActivityAsUser(mContext, 0, 12184 intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE, null, 12185 user); 12186 Notification notification = new Notification.Builder(mContext, 12187 SystemNotificationChannels.DEVICE_ADMIN) 12188 .setSmallIcon(R.drawable.ic_info_outline) 12189 .setContentTitle(mContext.getString(R.string.location_changed_notification_title)) 12190 .setContentText(mContext.getString(R.string.location_changed_notification_text)) 12191 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 12192 .setShowWhen(true) 12193 .setContentIntent(locationSettingsIntent) 12194 .setAutoCancel(true) 12195 .build(); 12196 mInjector.getNotificationManager().notify(SystemMessage.NOTE_LOCATION_CHANGED, 12197 notification); 12198 } 12199 12200 @Override 12201 public boolean setTime(ComponentName who, long millis) { 12202 Objects.requireNonNull(who, "ComponentName is null"); 12203 12204 final CallerIdentity caller = getCallerIdentity(who); 12205 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 12206 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 12207 12208 // Don't allow set time when auto time is on. 12209 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) { 12210 return false; 12211 } 12212 DevicePolicyEventLogger 12213 .createEvent(DevicePolicyEnums.SET_TIME) 12214 .setAdmin(caller.getComponentName()) 12215 .write(); 12216 mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis)); 12217 return true; 12218 } 12219 12220 @Override 12221 public boolean setTimeZone(ComponentName who, String timeZone) { 12222 Objects.requireNonNull(who, "ComponentName is null"); 12223 12224 final CallerIdentity caller = getCallerIdentity(who); 12225 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 12226 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 12227 12228 // Don't allow set timezone when auto timezone is on. 12229 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) { 12230 return false; 12231 } 12232 mInjector.binderWithCleanCallingIdentity(() -> 12233 mInjector.getAlarmManager().setTimeZone(timeZone)); 12234 12235 DevicePolicyEventLogger 12236 .createEvent(DevicePolicyEnums.SET_TIME_ZONE) 12237 .setAdmin(caller.getComponentName()) 12238 .write(); 12239 return true; 12240 } 12241 12242 @Override 12243 public void setSecureSetting(ComponentName who, String setting, String value) { 12244 Objects.requireNonNull(who, "ComponentName is null"); 12245 final CallerIdentity caller = getCallerIdentity(who); 12246 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 12247 12248 int callingUserId = caller.getUserId(); 12249 synchronized (getLockObject()) { 12250 if (isDeviceOwner(who, callingUserId)) { 12251 if (!SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.contains(setting) 12252 && !isCurrentUserDemo()) { 12253 throw new SecurityException(String.format( 12254 "Permission denial: Device owners cannot update %1$s", setting)); 12255 } 12256 } else if (!SECURE_SETTINGS_ALLOWLIST.contains(setting) && !isCurrentUserDemo()) { 12257 throw new SecurityException(String.format( 12258 "Permission denial: Profile owners cannot update %1$s", setting)); 12259 } 12260 if (setting.equals(Settings.Secure.LOCATION_MODE) 12261 && isSetSecureSettingLocationModeCheckEnabled(who.getPackageName(), 12262 callingUserId)) { 12263 throw new UnsupportedOperationException(Settings.Secure.LOCATION_MODE + " is " 12264 + "deprecated. Please use setLocationEnabled() instead."); 12265 } 12266 if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) { 12267 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) { 12268 throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS 12269 + " is deprecated. Please use one of the user restrictions " 12270 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or " 12271 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY + " instead."); 12272 } 12273 if (!mUserManager.isManagedProfile(callingUserId)) { 12274 Slogf.e(LOG_TAG, "Ignoring setSecureSetting request for " 12275 + setting + ". User restriction " 12276 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or " 12277 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY 12278 + " should be used instead."); 12279 } else { 12280 try { 12281 setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 12282 (Integer.parseInt(value) == 0) ? true : false, /* parent */ false); 12283 DevicePolicyEventLogger 12284 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING) 12285 .setAdmin(who) 12286 .setStrings(setting, value) 12287 .write(); 12288 } catch (NumberFormatException exc) { 12289 Slogf.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting); 12290 } 12291 } 12292 return; 12293 } 12294 mInjector.binderWithCleanCallingIdentity(() -> { 12295 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) { 12296 final String currentValue = mInjector.settingsSecureGetStringForUser( 12297 Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId); 12298 if (!TextUtils.equals(currentValue, value)) { 12299 // Tell the content observer that the next change will be due to the owner 12300 // changing the value. There is a small race condition here that we cannot 12301 // avoid: Change notifications are sent asynchronously, so it is possible 12302 // that there are prior notifications queued up before the one we are about 12303 // to trigger. This is a corner case that will have no impact in practice. 12304 mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId); 12305 } 12306 getUserData(callingUserId).mCurrentInputMethodSet = true; 12307 saveSettingsLocked(callingUserId); 12308 } 12309 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 12310 // Notify the user if it's the location mode setting that's been set, to any value 12311 // other than 'off'. 12312 if (setting.equals(Settings.Secure.LOCATION_MODE) 12313 && (Integer.parseInt(value) != 0)) { 12314 showLocationSettingsEnabledNotification(UserHandle.of(callingUserId)); 12315 } 12316 }); 12317 } 12318 DevicePolicyEventLogger 12319 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING) 12320 .setAdmin(who) 12321 .setStrings(setting, value) 12322 .write(); 12323 } 12324 12325 private boolean isSetSecureSettingLocationModeCheckEnabled(String packageName, int userId) { 12326 return mInjector.isChangeEnabled(USE_SET_LOCATION_ENABLED, packageName, userId); 12327 } 12328 12329 @Override 12330 public void setMasterVolumeMuted(ComponentName who, boolean on) { 12331 Objects.requireNonNull(who, "ComponentName is null"); 12332 final CallerIdentity caller = getCallerIdentity(who); 12333 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 12334 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_MASTER_VOLUME_MUTED); 12335 12336 synchronized (getLockObject()) { 12337 setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on, /* parent */ false); 12338 DevicePolicyEventLogger 12339 .createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED) 12340 .setAdmin(who) 12341 .setBoolean(on) 12342 .write(); 12343 } 12344 } 12345 12346 @Override 12347 public boolean isMasterVolumeMuted(ComponentName who) { 12348 Objects.requireNonNull(who, "ComponentName is null"); 12349 final CallerIdentity caller = getCallerIdentity(who); 12350 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 12351 12352 synchronized (getLockObject()) { 12353 AudioManager audioManager = 12354 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 12355 return audioManager.isMasterMute(); 12356 } 12357 } 12358 12359 @Override 12360 public void setUserIcon(ComponentName who, Bitmap icon) { 12361 Objects.requireNonNull(who, "ComponentName is null"); 12362 final CallerIdentity caller = getCallerIdentity(who); 12363 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 12364 12365 synchronized (getLockObject()) { 12366 mInjector.binderWithCleanCallingIdentity( 12367 () -> mUserManagerInternal.setUserIcon(caller.getUserId(), icon)); 12368 } 12369 DevicePolicyEventLogger 12370 .createEvent(DevicePolicyEnums.SET_USER_ICON) 12371 .setAdmin(who) 12372 .write(); 12373 } 12374 12375 @Override 12376 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 12377 Objects.requireNonNull(who, "ComponentName is null"); 12378 final CallerIdentity caller = getCallerIdentity(who); 12379 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 12380 12381 final int userId = caller.getUserId(); 12382 synchronized (getLockObject()) { 12383 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId), 12384 String.format( 12385 "Admin %s is neither the device owner or affiliated user's profile " 12386 + "owner.", who)); 12387 } 12388 if (isManagedProfile(userId)) { 12389 throw new SecurityException("Managed profile cannot disable keyguard"); 12390 } 12391 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEYGUARD_DISABLED); 12392 12393 long ident = mInjector.binderClearCallingIdentity(); 12394 try { 12395 // disallow disabling the keyguard if a password is currently set 12396 if (disabled && mLockPatternUtils.isSecure(userId)) { 12397 return false; 12398 } 12399 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 12400 if (disabled) { 12401 mInjector 12402 .getIWindowManager() 12403 .dismissKeyguard(null /* callback */, null /* message */); 12404 } 12405 DevicePolicyEventLogger 12406 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED) 12407 .setAdmin(who) 12408 .setBoolean(disabled) 12409 .write(); 12410 } catch (RemoteException e) { 12411 // Same process, does not happen. 12412 } finally { 12413 mInjector.binderRestoreCallingIdentity(ident); 12414 } 12415 return true; 12416 } 12417 12418 @Override 12419 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 12420 final CallerIdentity caller = getCallerIdentity(who); 12421 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 12422 12423 int userId = caller.getUserId(); 12424 synchronized (getLockObject()) { 12425 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId), 12426 "Admin " + who 12427 + " is neither the device owner or affiliated user's profile owner."); 12428 if (isManagedProfile(userId)) { 12429 throw new SecurityException("Managed profile cannot disable status bar"); 12430 } 12431 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_STATUS_BAR_DISABLED); 12432 12433 DevicePolicyData policy = getUserData(userId); 12434 if (policy.mStatusBarDisabled != disabled) { 12435 boolean isLockTaskMode = false; 12436 try { 12437 isLockTaskMode = mInjector.getIActivityTaskManager().getLockTaskModeState() 12438 != LOCK_TASK_MODE_NONE; 12439 } catch (RemoteException e) { 12440 Slogf.e(LOG_TAG, "Failed to get LockTask mode"); 12441 } 12442 if (!isLockTaskMode) { 12443 if (!setStatusBarDisabledInternal(disabled, userId)) { 12444 return false; 12445 } 12446 } 12447 policy.mStatusBarDisabled = disabled; 12448 saveSettingsLocked(userId); 12449 } 12450 } 12451 DevicePolicyEventLogger 12452 .createEvent(DevicePolicyEnums.SET_STATUS_BAR_DISABLED) 12453 .setAdmin(who) 12454 .setBoolean(disabled) 12455 .write(); 12456 return true; 12457 } 12458 12459 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 12460 long ident = mInjector.binderClearCallingIdentity(); 12461 try { 12462 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 12463 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 12464 if (statusBarService != null) { 12465 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 12466 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 12467 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 12468 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 12469 return true; 12470 } 12471 } catch (RemoteException e) { 12472 Slogf.e(LOG_TAG, "Failed to disable the status bar", e); 12473 } finally { 12474 mInjector.binderRestoreCallingIdentity(ident); 12475 } 12476 return false; 12477 } 12478 12479 /** 12480 * We need to update the internal state of whether a user has completed setup or a 12481 * device has paired once. After that, we ignore any changes that reset the 12482 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 12483 * as we don't trust any apps that might try to reset them. 12484 * <p> 12485 * Unfortunately, we don't know which user's setup state was changed, so we write all of 12486 * them. 12487 */ 12488 void updateUserSetupCompleteAndPaired() { 12489 List<UserInfo> users = mUserManager.getAliveUsers(); 12490 final int N = users.size(); 12491 for (int i = 0; i < N; i++) { 12492 int userHandle = users.get(i).id; 12493 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 12494 userHandle) != 0) { 12495 DevicePolicyData policy = getUserData(userHandle); 12496 if (!policy.mUserSetupComplete) { 12497 policy.mUserSetupComplete = true; 12498 if (userHandle == UserHandle.USER_SYSTEM) { 12499 mStateCache.setDeviceProvisioned(true); 12500 } 12501 synchronized (getLockObject()) { 12502 saveSettingsLocked(userHandle); 12503 } 12504 } 12505 } 12506 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 12507 userHandle) != 0) { 12508 DevicePolicyData policy = getUserData(userHandle); 12509 if (!policy.mPaired) { 12510 policy.mPaired = true; 12511 synchronized (getLockObject()) { 12512 saveSettingsLocked(userHandle); 12513 } 12514 } 12515 } 12516 } 12517 } 12518 12519 private class SetupContentObserver extends ContentObserver { 12520 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 12521 Settings.Secure.USER_SETUP_COMPLETE); 12522 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 12523 Settings.Global.DEVICE_PROVISIONED); 12524 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 12525 private final Uri mDefaultImeChanged = Settings.Secure.getUriFor( 12526 Settings.Secure.DEFAULT_INPUT_METHOD); 12527 12528 @GuardedBy("getLockObject()") 12529 private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>(); 12530 12531 public SetupContentObserver(Handler handler) { 12532 super(handler); 12533 } 12534 12535 void register() { 12536 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 12537 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 12538 if (mIsWatch) { 12539 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 12540 } 12541 mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL); 12542 } 12543 12544 @GuardedBy("getLockObject()") 12545 private void addPendingChangeByOwnerLocked(int userId) { 12546 mUserIdsWithPendingChangesByOwner.add(userId); 12547 } 12548 12549 @Override 12550 public void onChange(boolean selfChange, Uri uri, int userId) { 12551 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 12552 updateUserSetupCompleteAndPaired(); 12553 } else if (mDeviceProvisioned.equals(uri)) { 12554 synchronized (getLockObject()) { 12555 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 12556 // is delayed until device is marked as provisioned. 12557 setDeviceOwnershipSystemPropertyLocked(); 12558 } 12559 } else if (mDefaultImeChanged.equals(uri)) { 12560 synchronized (getLockObject()) { 12561 if (mUserIdsWithPendingChangesByOwner.contains(userId)) { 12562 // This change notification was triggered by the owner changing the current 12563 // IME. Ignore it. 12564 mUserIdsWithPendingChangesByOwner.remove(userId); 12565 } else { 12566 // This change notification was triggered by the user manually changing the 12567 // current IME. 12568 getUserData(userId).mCurrentInputMethodSet = false; 12569 saveSettingsLocked(userId); 12570 } 12571 } 12572 } 12573 } 12574 } 12575 12576 private class DevicePolicyConstantsObserver extends ContentObserver { 12577 final Uri mConstantsUri = 12578 Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS); 12579 12580 DevicePolicyConstantsObserver(Handler handler) { 12581 super(handler); 12582 } 12583 12584 void register() { 12585 mInjector.registerContentObserver( 12586 mConstantsUri, /* notifyForDescendents= */ false, this, UserHandle.USER_ALL); 12587 } 12588 12589 @Override 12590 public void onChange(boolean selfChange, Uri uri, int userId) { 12591 mConstants = loadConstants(); 12592 12593 mInjector.binderWithCleanCallingIdentity(() -> { 12594 final Intent intent = new Intent( 12595 DevicePolicyManager.ACTION_DEVICE_POLICY_CONSTANTS_CHANGED); 12596 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 12597 final List<UserInfo> users = mUserManager.getAliveUsers(); 12598 for (int i = 0; i < users.size(); i++) { 12599 mContext.sendBroadcastAsUser(intent, UserHandle.of(users.get(i).id)); 12600 } 12601 }); 12602 } 12603 } 12604 12605 @VisibleForTesting 12606 final class LocalService extends DevicePolicyManagerInternal 12607 implements DevicePolicyManagerLiteInternal { 12608 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 12609 12610 @Override 12611 public List<String> getCrossProfileWidgetProviders(int profileId) { 12612 synchronized (getLockObject()) { 12613 if (mOwners == null) { 12614 return Collections.emptyList(); 12615 } 12616 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 12617 if (ownerComponent == null) { 12618 return Collections.emptyList(); 12619 } 12620 12621 DevicePolicyData policy = getUserDataUnchecked(profileId); 12622 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 12623 12624 if (admin == null || admin.crossProfileWidgetProviders == null 12625 || admin.crossProfileWidgetProviders.isEmpty()) { 12626 return Collections.emptyList(); 12627 } 12628 12629 return admin.crossProfileWidgetProviders; 12630 } 12631 } 12632 12633 @Override 12634 public void addOnCrossProfileWidgetProvidersChangeListener( 12635 OnCrossProfileWidgetProvidersChangeListener listener) { 12636 synchronized (getLockObject()) { 12637 if (mWidgetProviderListeners == null) { 12638 mWidgetProviderListeners = new ArrayList<>(); 12639 } 12640 if (!mWidgetProviderListeners.contains(listener)) { 12641 mWidgetProviderListeners.add(listener); 12642 } 12643 } 12644 } 12645 12646 @Override 12647 public boolean isActiveDeviceOwner(int uid) { 12648 return isDeviceOwner(new CallerIdentity(uid, null, null)); 12649 } 12650 12651 @Override 12652 public boolean isActiveProfileOwner(int uid) { 12653 return isProfileOwner(new CallerIdentity(uid, null, null)); 12654 } 12655 12656 @Override 12657 public boolean isActiveSupervisionApp(int uid) { 12658 if (!isProfileOwner(new CallerIdentity(uid, null, null))) { 12659 return false; 12660 } 12661 synchronized (getLockObject()) { 12662 final ActiveAdmin admin = getProfileOwnerAdminLocked(UserHandle.getUserId(uid)); 12663 if (admin == null) { 12664 return false; 12665 } 12666 12667 final String supervisionString = mContext.getResources().getString( 12668 com.android.internal.R.string 12669 .config_defaultSupervisionProfileOwnerComponent); 12670 if (supervisionString == null) { 12671 return false; 12672 } 12673 12674 final ComponentName supervisorComponent = ComponentName.unflattenFromString( 12675 supervisionString); 12676 return admin.info.getComponent().equals(supervisorComponent); 12677 } 12678 } 12679 12680 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 12681 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 12682 synchronized (getLockObject()) { 12683 listeners = new ArrayList<>(mWidgetProviderListeners); 12684 } 12685 final int listenerCount = listeners.size(); 12686 for (int i = 0; i < listenerCount; i++) { 12687 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 12688 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 12689 } 12690 } 12691 12692 @Override 12693 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 12694 // This method is called from AM with its lock held, so don't take the DPMS lock. 12695 // b/29242568 12696 12697 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 12698 if (profileOwner != null) { 12699 return DevicePolicyManagerService.this 12700 .createShowAdminSupportIntent(profileOwner, userId); 12701 } 12702 12703 final Pair<Integer, ComponentName> deviceOwner = 12704 mOwners.getDeviceOwnerUserIdAndComponent(); 12705 if (deviceOwner != null && deviceOwner.first == userId) { 12706 return DevicePolicyManagerService.this 12707 .createShowAdminSupportIntent(deviceOwner.second, userId); 12708 } 12709 12710 // We're not specifying the device admin because there isn't one. 12711 if (useDefaultIfNoAdmin) { 12712 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 12713 } 12714 return null; 12715 } 12716 12717 @Override 12718 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 12719 final long ident = mInjector.binderClearCallingIdentity(); 12720 try { 12721 final List<UserManager.EnforcingUser> sources = mUserManager 12722 .getUserRestrictionSources(userRestriction, UserHandle.of(userId)); 12723 if (sources == null || sources.isEmpty()) { 12724 // The restriction is not enforced. 12725 return null; 12726 } else if (sources.size() > 1) { 12727 // In this case, we'll show an admin support dialog that does not 12728 // specify the admin. 12729 // TODO(b/128928355): if this restriction is enforced by multiple DPCs, return 12730 // the admin for the calling user. 12731 return DevicePolicyManagerService.this.createShowAdminSupportIntent( 12732 null, userId); 12733 } 12734 final UserManager.EnforcingUser enforcingUser = sources.get(0); 12735 final int sourceType = enforcingUser.getUserRestrictionSource(); 12736 final int enforcingUserId = enforcingUser.getUserHandle().getIdentifier(); 12737 if (sourceType == UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) { 12738 // Restriction was enforced by PO 12739 final ComponentName profileOwner = mOwners.getProfileOwnerComponent( 12740 enforcingUserId); 12741 if (profileOwner != null) { 12742 return DevicePolicyManagerService.this.createShowAdminSupportIntent( 12743 profileOwner, enforcingUserId); 12744 } 12745 } else if (sourceType == UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) { 12746 // Restriction was enforced by DO 12747 final Pair<Integer, ComponentName> deviceOwner = 12748 mOwners.getDeviceOwnerUserIdAndComponent(); 12749 if (deviceOwner != null) { 12750 return DevicePolicyManagerService.this.createShowAdminSupportIntent( 12751 deviceOwner.second, deviceOwner.first); 12752 } 12753 } else if (sourceType == UserManager.RESTRICTION_SOURCE_SYSTEM) { 12754 /* 12755 * In this case, the user restriction is enforced by the system. 12756 * So we won't show an admin support intent, even if it is also 12757 * enforced by a profile/device owner. 12758 */ 12759 return null; 12760 } 12761 } finally { 12762 mInjector.binderRestoreCallingIdentity(ident); 12763 } 12764 return null; 12765 } 12766 12767 @Override 12768 public boolean isUserAffiliatedWithDevice(int userId) { 12769 return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId); 12770 } 12771 12772 @Override 12773 public boolean canSilentlyInstallPackage(String callerPackage, int callerUid) { 12774 if (callerPackage == null) { 12775 return false; 12776 } 12777 if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid)) 12778 && (isActiveProfileOwner(callerUid) 12779 || isActiveDeviceOwner(callerUid))) { 12780 // device owner or a profile owner affiliated with the device owner 12781 return true; 12782 } 12783 return false; 12784 } 12785 12786 @Override 12787 public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) { 12788 mInjector.binderWithCleanCallingIdentity(() -> { 12789 synchronized (getLockObject()) { 12790 updateMaximumTimeToLockLocked(userId); 12791 updatePasswordQualityCacheForUserGroup(userId); 12792 } 12793 }); 12794 DevicePolicyEventLogger 12795 .createEvent(DevicePolicyEnums.SEPARATE_PROFILE_CHALLENGE_CHANGED) 12796 .setBoolean(isSeparateProfileChallengeEnabled(userId)) 12797 .write(); 12798 } 12799 12800 @Override 12801 public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) { 12802 synchronized (getLockObject()) { 12803 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING, 12804 UserHandle.of(userId))) { 12805 Slogf.e(LOG_TAG, "printing is enabled for user %d", userId); 12806 return null; 12807 } 12808 String ownerPackage = mOwners.getProfileOwnerPackage(userId); 12809 if (ownerPackage == null) { 12810 ownerPackage = mOwners.getDeviceOwnerPackageName(); 12811 } 12812 final String packageName = ownerPackage; 12813 PackageManager pm = mInjector.getPackageManager(); 12814 PackageInfo packageInfo = mInjector.binderWithCleanCallingIdentity(() -> { 12815 try { 12816 return pm.getPackageInfo(packageName, 0); 12817 } catch (NameNotFoundException e) { 12818 Slogf.e(LOG_TAG, "getPackageInfo error", e); 12819 return null; 12820 } 12821 }); 12822 if (packageInfo == null) { 12823 Slogf.e(LOG_TAG, "packageInfo is inexplicably null"); 12824 return null; 12825 } 12826 ApplicationInfo appInfo = packageInfo.applicationInfo; 12827 if (appInfo == null) { 12828 Slogf.e(LOG_TAG, "appInfo is inexplicably null"); 12829 return null; 12830 } 12831 CharSequence appLabel = pm.getApplicationLabel(appInfo); 12832 if (appLabel == null) { 12833 Slogf.e(LOG_TAG, "appLabel is inexplicably null"); 12834 return null; 12835 } 12836 return ((Context) ActivityThread.currentActivityThread().getSystemUiContext()) 12837 .getResources().getString(R.string.printing_disabled_by, appLabel); 12838 } 12839 } 12840 12841 @Override 12842 protected DevicePolicyCache getDevicePolicyCache() { 12843 return mPolicyCache; 12844 } 12845 12846 @Override 12847 protected DeviceStateCache getDeviceStateCache() { 12848 return mStateCache; 12849 } 12850 12851 @Override 12852 public List<String> getAllCrossProfilePackages() { 12853 return DevicePolicyManagerService.this.getAllCrossProfilePackages(); 12854 } 12855 12856 @Override 12857 public List<String> getDefaultCrossProfilePackages() { 12858 return DevicePolicyManagerService.this.getDefaultCrossProfilePackages(); 12859 } 12860 12861 /** 12862 * Sends the {@code intent} to the packages with cross profile capabilities. 12863 * 12864 * <p>This means the application must have the {@code crossProfile} property and 12865 * and at least one of the following permissions: 12866 * 12867 * <ul> 12868 * <li>{@link android.Manifest.permission.INTERACT_ACROSS_PROFILES} 12869 * <li>{@link android.Manifest.permission.INTERACT_ACROSS_USERS} 12870 * <li>{@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission or the 12871 * {@link AppOpsManager.OP_INTERACT_ACROSS_PROFILES} app operation authorization. 12872 * </ul> 12873 * 12874 * <p>Note: The intent itself is not modified but copied before use. 12875 * 12876 * @param intent Template for the intent sent to the packages. 12877 * @param parentHandle Handle of the user that will receive the intents. 12878 * @param requiresPermission If false, all packages with the {@code crossProfile} property 12879 * will receive the intent. 12880 */ 12881 @Override 12882 public void broadcastIntentToCrossProfileManifestReceiversAsUser(Intent intent, 12883 UserHandle parentHandle, boolean requiresPermission) { 12884 Objects.requireNonNull(intent); 12885 Objects.requireNonNull(parentHandle); 12886 final int userId = parentHandle.getIdentifier(); 12887 Slogf.i(LOG_TAG, "Sending %s broadcast to manifest receivers.", intent.getAction()); 12888 try { 12889 final List<ResolveInfo> receivers = mIPackageManager.queryIntentReceivers( 12890 intent, /* resolvedType= */ null, 12891 STOCK_PM_FLAGS, parentHandle.getIdentifier()).getList(); 12892 for (ResolveInfo receiver : receivers) { 12893 final String packageName = receiver.getComponentInfo().packageName; 12894 if (checkCrossProfilePackagePermissions(packageName, userId, 12895 requiresPermission) 12896 || checkModifyQuietModePermission(packageName, userId)) { 12897 Slogf.i(LOG_TAG, "Sending %s broadcast to %s.", intent.getAction(), 12898 packageName); 12899 final Intent packageIntent = new Intent(intent) 12900 .setComponent(receiver.getComponentInfo().getComponentName()) 12901 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 12902 mContext.sendBroadcastAsUser(packageIntent, parentHandle); 12903 } 12904 } 12905 } catch (RemoteException ex) { 12906 Slogf.w(LOG_TAG, "Cannot get list of broadcast receivers for %s because: %s.", 12907 intent.getAction(), ex); 12908 } 12909 } 12910 12911 /** 12912 * Checks whether the package {@code packageName} has the {@code MODIFY_QUIET_MODE} 12913 * permission granted for the user {@code userId}. 12914 */ 12915 private boolean checkModifyQuietModePermission(String packageName, @UserIdInt int userId) { 12916 try { 12917 final int uid = Objects.requireNonNull( 12918 mInjector.getPackageManager().getApplicationInfoAsUser( 12919 Objects.requireNonNull(packageName), /* flags= */ 0, userId)).uid; 12920 return PackageManager.PERMISSION_GRANTED 12921 == ActivityManager.checkComponentPermission( 12922 android.Manifest.permission.MODIFY_QUIET_MODE, uid, /* owningUid= */ 12923 -1, /* exported= */ true); 12924 } catch (NameNotFoundException ex) { 12925 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.", 12926 packageName); 12927 return false; 12928 } 12929 } 12930 12931 /** 12932 * Checks whether the package {@code packageName} has the required permissions to receive 12933 * cross-profile broadcasts on behalf of the user {@code userId}. 12934 */ 12935 private boolean checkCrossProfilePackagePermissions(String packageName, 12936 @UserIdInt int userId, boolean requiresPermission) { 12937 final PackageManagerInternal pmInternal = LocalServices.getService( 12938 PackageManagerInternal.class); 12939 final AndroidPackage androidPackage = pmInternal.getPackage(packageName); 12940 if (androidPackage == null || !androidPackage.isCrossProfile()) { 12941 return false; 12942 } 12943 if (!requiresPermission) { 12944 return true; 12945 } 12946 if (!isPackageEnabled(packageName, userId)) { 12947 return false; 12948 } 12949 try { 12950 final CrossProfileAppsInternal crossProfileAppsService = LocalServices.getService( 12951 CrossProfileAppsInternal.class); 12952 return crossProfileAppsService.verifyPackageHasInteractAcrossProfilePermission( 12953 packageName, userId); 12954 } catch (NameNotFoundException ex) { 12955 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.", 12956 packageName); 12957 return false; 12958 } 12959 } 12960 12961 private boolean isPackageEnabled(String packageName, @UserIdInt int userId) { 12962 final int callingUid = Binder.getCallingUid(); 12963 final long ident = Binder.clearCallingIdentity(); 12964 try { 12965 final PackageInfo info = mInjector.getPackageManagerInternal() 12966 .getPackageInfo( 12967 packageName, 12968 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 12969 callingUid, 12970 userId); 12971 return info != null && info.applicationInfo.enabled; 12972 } finally { 12973 Binder.restoreCallingIdentity(ident); 12974 } 12975 } 12976 12977 @Override 12978 public ComponentName getProfileOwnerAsUser(@UserIdInt int userId) { 12979 return DevicePolicyManagerService.this.getProfileOwnerAsUser(userId); 12980 } 12981 12982 @Override 12983 public int getDeviceOwnerUserId() { 12984 return DevicePolicyManagerService.this.getDeviceOwnerUserId(); 12985 } 12986 12987 @Override 12988 public boolean isDeviceOrProfileOwnerInCallingUser(String packageName) { 12989 return isDeviceOwnerInCallingUser(packageName) 12990 || isProfileOwnerInCallingUser(packageName); 12991 } 12992 12993 private boolean isDeviceOwnerInCallingUser(String packageName) { 12994 final ComponentName deviceOwnerInCallingUser = 12995 DevicePolicyManagerService.this.getDeviceOwnerComponent( 12996 /* callingUserOnly= */ true); 12997 return deviceOwnerInCallingUser != null 12998 && packageName.equals(deviceOwnerInCallingUser.getPackageName()); 12999 } 13000 13001 private boolean isProfileOwnerInCallingUser(String packageName) { 13002 final ComponentName profileOwnerInCallingUser = 13003 getProfileOwnerAsUser(UserHandle.getCallingUserId()); 13004 return profileOwnerInCallingUser != null 13005 && packageName.equals(profileOwnerInCallingUser.getPackageName()); 13006 } 13007 13008 @Override 13009 public boolean supportsResetOp(int op) { 13010 return op == AppOpsManager.OP_INTERACT_ACROSS_PROFILES 13011 && LocalServices.getService(CrossProfileAppsInternal.class) != null; 13012 } 13013 13014 @Override 13015 public void resetOp(int op, String packageName, @UserIdInt int userId) { 13016 if (op != AppOpsManager.OP_INTERACT_ACROSS_PROFILES) { 13017 throw new IllegalArgumentException("Unsupported op for DPM reset: " + op); 13018 } 13019 LocalServices.getService(CrossProfileAppsInternal.class) 13020 .setInteractAcrossProfilesAppOp( 13021 packageName, findInteractAcrossProfilesResetMode(packageName), userId); 13022 } 13023 13024 @Override 13025 public void notifyUnsafeOperationStateChanged(DevicePolicySafetyChecker checker, int reason, 13026 boolean isSafe) { 13027 // TODO(b/178494483): use EventLog instead 13028 // TODO(b/178494483): log metrics? 13029 if (VERBOSE_LOG) { 13030 Slogf.v(LOG_TAG, "notifyUnsafeOperationStateChanged(): %s=%b", 13031 DevicePolicyManager.operationSafetyReasonToString(reason), isSafe); 13032 } 13033 Preconditions.checkArgument(mSafetyChecker == checker, 13034 "invalid checker: should be %s, was %s", mSafetyChecker, checker); 13035 13036 Bundle extras = new Bundle(); 13037 extras.putInt(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_REASON, reason); 13038 extras.putBoolean(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_STATE, isSafe); 13039 13040 if (mOwners.hasDeviceOwner()) { 13041 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying DO"); 13042 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED, 13043 extras); 13044 } 13045 for (int profileOwnerId : mOwners.getProfileOwnerKeys()) { 13046 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying PO for user " + profileOwnerId); 13047 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED, 13048 extras, profileOwnerId); 13049 } 13050 } 13051 13052 private @Mode int findInteractAcrossProfilesResetMode(String packageName) { 13053 return getDefaultCrossProfilePackages().contains(packageName) 13054 ? AppOpsManager.MODE_ALLOWED 13055 : AppOpsManager.opToDefaultMode(AppOpsManager.OP_INTERACT_ACROSS_PROFILES); 13056 } 13057 } 13058 13059 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) { 13060 // This method is called with AMS lock held, so don't take DPMS lock 13061 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 13062 intent.putExtra(Intent.EXTRA_USER_ID, userId); 13063 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin); 13064 intent.setFlags(FLAG_ACTIVITY_NEW_TASK); 13065 return intent; 13066 } 13067 13068 @Override 13069 public Intent createAdminSupportIntent(String restriction) { 13070 Objects.requireNonNull(restriction); 13071 final CallerIdentity caller = getCallerIdentity(); 13072 Intent intent = null; 13073 if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) || 13074 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) { 13075 synchronized (getLockObject()) { 13076 final DevicePolicyData policy = getUserData(caller.getUserId()); 13077 final int N = policy.mAdminList.size(); 13078 for (int i = 0; i < N; i++) { 13079 final ActiveAdmin admin = policy.mAdminList.get(i); 13080 if ((admin.disableCamera && 13081 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) || 13082 (admin.disableScreenCapture && DevicePolicyManager 13083 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) { 13084 intent = createShowAdminSupportIntent(admin.info.getComponent(), 13085 caller.getUserId()); 13086 break; 13087 } 13088 } 13089 // For the camera, a device owner on a different user can disable it globally, 13090 // so we need an additional check. 13091 if (intent == null 13092 && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) { 13093 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 13094 if (admin != null && admin.disableCamera) { 13095 intent = createShowAdminSupportIntent(admin.info.getComponent(), 13096 mOwners.getDeviceOwnerUserId()); 13097 } 13098 } 13099 } 13100 } else { 13101 // if valid, |restriction| can only be a user restriction 13102 intent = mLocalService.createUserRestrictionSupportIntent(caller.getUserId(), 13103 restriction); 13104 } 13105 if (intent != null) { 13106 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction); 13107 } 13108 return intent; 13109 } 13110 13111 /** 13112 * Returns true if specified admin is allowed to limit passwords and has a 13113 * {@code mPasswordPolicy.quality} of at least {@code minPasswordQuality} 13114 */ 13115 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 13116 if (admin.mPasswordPolicy.quality < minPasswordQuality) { 13117 return false; 13118 } 13119 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 13120 } 13121 13122 @Override 13123 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 13124 if (policy != null) { 13125 // throws exception if policy type is invalid 13126 policy.validateType(); 13127 // throws exception if freeze period is invalid 13128 policy.validateFreezePeriods(); 13129 Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 13130 // throws exception if freeze period is incompatible with previous freeze period record 13131 policy.validateAgainstPreviousFreezePeriod(record.first, record.second, 13132 LocalDate.now()); 13133 } 13134 final CallerIdentity caller = getCallerIdentity(who); 13135 13136 synchronized (getLockObject()) { 13137 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller) 13138 || isDeviceOwner(caller)); 13139 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_UPDATE_POLICY); 13140 13141 if (policy == null) { 13142 mOwners.clearSystemUpdatePolicy(); 13143 } else { 13144 mOwners.setSystemUpdatePolicy(policy); 13145 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false); 13146 } 13147 mOwners.writeDeviceOwner(); 13148 } 13149 mInjector.binderWithCleanCallingIdentity(() -> mContext.sendBroadcastAsUser( 13150 new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM)); 13151 DevicePolicyEventLogger 13152 .createEvent(DevicePolicyEnums.SET_SYSTEM_UPDATE_POLICY) 13153 .setAdmin(who) 13154 .setInt(policy != null ? policy.getPolicyType() : 0) 13155 .write(); 13156 } 13157 13158 @Override 13159 public SystemUpdatePolicy getSystemUpdatePolicy() { 13160 synchronized (getLockObject()) { 13161 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 13162 if (policy != null && !policy.isValid()) { 13163 Slogf.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 13164 return null; 13165 } 13166 return policy; 13167 } 13168 } 13169 13170 private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) { 13171 return (!date.isBefore(range.first) && !date.isAfter(range.second)); 13172 } 13173 13174 /** 13175 * keeps track of the last continuous period when the system is under OTA freeze. 13176 * 13177 * DPMS keeps track of the previous dates during which OTA was freezed as a result of an 13178 * system update policy with freeze periods in effect. This is needed to make robust 13179 * validation on new system update polices, for example to prevent the OTA from being 13180 * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period 13181 * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting 13182 * a new freeze period after a few days. 13183 * 13184 * @param saveIfChanged whether to persist the result on disk if freeze period record is 13185 * updated. This should only be set to {@code false} if there is a guaranteed 13186 * mOwners.writeDeviceOwner() later in the control flow to reduce the number of 13187 * disk writes. Otherwise you risk inconsistent on-disk state. 13188 * 13189 * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod 13190 */ 13191 private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) { 13192 Slogf.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord"); 13193 synchronized (getLockObject()) { 13194 final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 13195 if (policy == null) { 13196 return; 13197 } 13198 final LocalDate now = LocalDate.now(); 13199 final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now); 13200 if (currentPeriod == null) { 13201 return; 13202 } 13203 final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 13204 final LocalDate start = record.first; 13205 final LocalDate end = record.second; 13206 final boolean changed; 13207 if (end == null || start == null) { 13208 // Start a new period if there is none at the moment 13209 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 13210 } else if (now.equals(end.plusDays(1))) { 13211 // Extend the existing period 13212 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 13213 } else if (now.isAfter(end.plusDays(1))) { 13214 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) { 13215 // The device might be off for some period. If the past freeze record 13216 // is within range of the current freeze period, assume the device was off 13217 // during the period [end, now] and extend the freeze record to [start, now]. 13218 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 13219 } else { 13220 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 13221 } 13222 } else if (now.isBefore(start)) { 13223 // Systm clock was adjusted backwards, restart record 13224 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 13225 } else /* start <= now <= end */ { 13226 changed = false; 13227 } 13228 if (changed && saveIfChanged) { 13229 mOwners.writeDeviceOwner(); 13230 } 13231 } 13232 } 13233 13234 @Override 13235 public void clearSystemUpdatePolicyFreezePeriodRecord() { 13236 Preconditions.checkCallAuthorization(isAdb(getCallerIdentity()) 13237 || hasCallingOrSelfPermission(permission.CLEAR_FREEZE_PERIOD), 13238 "Caller must be shell, or hold CLEAR_FREEZE_PERIOD permission to call " 13239 + "clearSystemUpdatePolicyFreezePeriodRecord"); 13240 synchronized (getLockObject()) { 13241 // Print out current record to help diagnosed CTS failures 13242 Slogf.i(LOG_TAG, "Clear freeze period record: " 13243 + mOwners.getSystemUpdateFreezePeriodRecordAsString()); 13244 if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) { 13245 mOwners.writeDeviceOwner(); 13246 } 13247 } 13248 } 13249 13250 /** 13251 * Checks if any of the packages associated with the UID of the app provided is that 13252 * of the device owner. 13253 * @param appUid UID of the app to check. 13254 * @return {@code true} if any of the packages are the device owner, {@code false} otherwise. 13255 */ 13256 private boolean isUidDeviceOwnerLocked(int appUid) { 13257 ensureLocked(); 13258 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 13259 .getPackageName(); 13260 try { 13261 String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(appUid); 13262 if (pkgs == null) { 13263 return false; 13264 } 13265 13266 for (String pkg : pkgs) { 13267 if (deviceOwnerPackageName.equals(pkg)) { 13268 return true; 13269 } 13270 } 13271 } catch (RemoteException e) { 13272 return false; 13273 } 13274 return false; 13275 } 13276 13277 @Override 13278 public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) { 13279 Preconditions.checkCallAuthorization( 13280 hasCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE), 13281 "Only the system update service can broadcast update information"); 13282 13283 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 13284 Slogf.w(LOG_TAG, "Only the system update service in the system user can broadcast " 13285 + "update information."); 13286 return; 13287 } 13288 13289 if (!mOwners.saveSystemUpdateInfo(info)) { 13290 // Pending system update hasn't changed, don't send duplicate notification. 13291 return; 13292 } 13293 13294 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE) 13295 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 13296 info == null ? -1 : info.getReceivedTime()); 13297 13298 mInjector.binderWithCleanCallingIdentity(() -> { 13299 synchronized (getLockObject()) { 13300 // Broadcast to device owner first if there is one. 13301 if (mOwners.hasDeviceOwner()) { 13302 final UserHandle deviceOwnerUser = 13303 UserHandle.of(mOwners.getDeviceOwnerUserId()); 13304 intent.setComponent(mOwners.getDeviceOwnerComponent()); 13305 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 13306 } 13307 } 13308 // Get running users. 13309 final int runningUserIds[]; 13310 try { 13311 runningUserIds = mInjector.getIActivityManager().getRunningUserIds(); 13312 } catch (RemoteException e) { 13313 // Shouldn't happen. 13314 Slogf.e(LOG_TAG, "Could not retrieve the list of running users", e); 13315 return; 13316 } 13317 // Send broadcasts to corresponding profile owners if any. 13318 for (final int userId : runningUserIds) { 13319 synchronized (getLockObject()) { 13320 final ComponentName profileOwnerPackage = 13321 mOwners.getProfileOwnerComponent(userId); 13322 if (profileOwnerPackage != null) { 13323 intent.setComponent(profileOwnerPackage); 13324 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 13325 } 13326 } 13327 } 13328 }); 13329 } 13330 13331 @Override 13332 public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) { 13333 Objects.requireNonNull(admin, "ComponentName is null"); 13334 13335 final CallerIdentity caller = getCallerIdentity(admin); 13336 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 13337 13338 return mOwners.getSystemUpdateInfo(); 13339 } 13340 13341 @Override 13342 public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) { 13343 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 13344 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 13345 && (isProfileOwner(caller) || isDeviceOwner(caller))) 13346 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT))); 13347 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_POLICY); 13348 13349 final int forUser = caller.getUserId(); 13350 synchronized (getLockObject()) { 13351 DevicePolicyData userPolicy = getUserData(forUser); 13352 if (userPolicy.mPermissionPolicy != policy) { 13353 userPolicy.mPermissionPolicy = policy; 13354 mPolicyCache.setPermissionPolicy(forUser, policy); 13355 saveSettingsLocked(forUser); 13356 } 13357 } 13358 DevicePolicyEventLogger 13359 .createEvent(DevicePolicyEnums.SET_PERMISSION_POLICY) 13360 .setAdmin(caller.getPackageName()) 13361 .setInt(policy) 13362 .setBoolean(/* isDelegate */ admin == null) 13363 .write(); 13364 } 13365 13366 private void updatePermissionPolicyCache(int userId) { 13367 synchronized (getLockObject()) { 13368 DevicePolicyData userPolicy = getUserData(userId); 13369 mPolicyCache.setPermissionPolicy(userId, userPolicy.mPermissionPolicy); 13370 } 13371 } 13372 13373 @Override 13374 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 13375 int userId = UserHandle.getCallingUserId(); 13376 return mPolicyCache.getPermissionPolicy(userId); 13377 } 13378 13379 @Override 13380 public void setPermissionGrantState(ComponentName admin, String callerPackage, 13381 String packageName, String permission, int grantState, RemoteCallback callback) 13382 throws RemoteException { 13383 Objects.requireNonNull(callback); 13384 13385 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 13386 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 13387 && (isProfileOwner(caller) || isDeviceOwner(caller))) 13388 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT))); 13389 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_GRANT_STATE); 13390 13391 synchronized (getLockObject()) { 13392 long ident = mInjector.binderClearCallingIdentity(); 13393 try { 13394 boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId()) 13395 >= android.os.Build.VERSION_CODES.Q; 13396 if (!isPostQAdmin) { 13397 // Legacy admins assume that they cannot control pre-M apps 13398 if (getTargetSdk(packageName, caller.getUserId()) 13399 < android.os.Build.VERSION_CODES.M) { 13400 callback.sendResult(null); 13401 return; 13402 } 13403 } 13404 try { 13405 if (!isRuntimePermission(permission)) { 13406 callback.sendResult(null); 13407 return; 13408 } 13409 } catch (NameNotFoundException e) { 13410 throw new RemoteException("Cannot check if " + permission 13411 + "is a runtime permission", e, false, true); 13412 } 13413 13414 if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 13415 || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED 13416 || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) { 13417 AdminPermissionControlParams permissionParams = 13418 new AdminPermissionControlParams(packageName, permission, grantState, 13419 canAdminGrantSensorsPermissionsForUser(caller.getUserId())); 13420 mInjector.getPermissionControllerManager(caller.getUserHandle()) 13421 .setRuntimePermissionGrantStateByDeviceAdmin(caller.getPackageName(), 13422 permissionParams, mContext.getMainExecutor(), 13423 (permissionWasSet) -> { 13424 if (isPostQAdmin && !permissionWasSet) { 13425 callback.sendResult(null); 13426 return; 13427 } 13428 13429 DevicePolicyEventLogger 13430 .createEvent(DevicePolicyEnums 13431 .SET_PERMISSION_GRANT_STATE) 13432 .setAdmin(caller.getPackageName()) 13433 .setStrings(permission) 13434 .setInt(grantState) 13435 .setBoolean(/* isDelegate */ admin == null) 13436 .write(); 13437 13438 callback.sendResult(Bundle.EMPTY); 13439 }); 13440 } 13441 } catch (SecurityException e) { 13442 Slogf.e(LOG_TAG, "Could not set permission grant state", e); 13443 13444 callback.sendResult(null); 13445 } finally { 13446 mInjector.binderRestoreCallingIdentity(ident); 13447 } 13448 } 13449 } 13450 13451 @Override 13452 public int getPermissionGrantState(ComponentName admin, String callerPackage, 13453 String packageName, String permission) throws RemoteException { 13454 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 13455 Preconditions.checkCallAuthorization(isSystemUid(caller) || (caller.hasAdminComponent() 13456 && (isProfileOwner(caller) || isDeviceOwner(caller))) 13457 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT))); 13458 13459 synchronized (getLockObject()) { 13460 return mInjector.binderWithCleanCallingIdentity(() -> { 13461 int granted; 13462 if (getTargetSdk(caller.getPackageName(), caller.getUserId()) 13463 < android.os.Build.VERSION_CODES.Q) { 13464 // The per-Q behavior was to not check the app-ops state. 13465 granted = mIPackageManager.checkPermission(permission, packageName, 13466 caller.getUserId()); 13467 } else { 13468 try { 13469 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 13470 caller.getUserId()); 13471 if (PermissionChecker.checkPermissionForPreflight(mContext, permission, 13472 PermissionChecker.PID_UNKNOWN, uid, packageName) 13473 != PermissionChecker.PERMISSION_GRANTED) { 13474 granted = PackageManager.PERMISSION_DENIED; 13475 } else { 13476 granted = PackageManager.PERMISSION_GRANTED; 13477 } 13478 } catch (NameNotFoundException e) { 13479 throw new RemoteException("Cannot check if " + permission 13480 + "is a runtime permission", e, false, true); 13481 } 13482 } 13483 int permFlags = mInjector.getPackageManager().getPermissionFlags( 13484 permission, packageName, caller.getUserHandle()); 13485 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 13486 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 13487 // Not controlled by policy 13488 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 13489 } else { 13490 // Policy controlled so return result based on permission grant state 13491 return granted == PackageManager.PERMISSION_GRANTED 13492 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 13493 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 13494 } 13495 }); 13496 } 13497 } 13498 13499 boolean isPackageInstalledForUser(String packageName, int userHandle) { 13500 return mInjector.binderWithCleanCallingIdentity(() -> { 13501 try { 13502 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 13503 userHandle); 13504 return (pi != null) && (pi.applicationInfo.flags != 0); 13505 } catch (RemoteException re) { 13506 throw new RuntimeException("Package manager has died", re); 13507 } 13508 }); 13509 } 13510 13511 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException { 13512 final PackageManager packageManager = mInjector.getPackageManager(); 13513 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0); 13514 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 13515 == PermissionInfo.PROTECTION_DANGEROUS; 13516 } 13517 13518 @Override 13519 public boolean isProvisioningAllowed(String action, String packageName) { 13520 Objects.requireNonNull(packageName); 13521 13522 final CallerIdentity caller = getCallerIdentity(); 13523 final long ident = mInjector.binderClearCallingIdentity(); 13524 try { 13525 final List<String> callerUidPackageNames = Arrays.asList( 13526 mInjector.getPackageManager().getPackagesForUid(caller.getUid())); 13527 Preconditions.checkArgument(callerUidPackageNames.contains(packageName), 13528 "Caller uid doesn't match the one for the provided package."); 13529 } finally { 13530 mInjector.binderRestoreCallingIdentity(ident); 13531 } 13532 13533 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK; 13534 } 13535 13536 @Override 13537 public int checkProvisioningPreCondition(String action, String packageName) { 13538 Objects.requireNonNull(packageName, "packageName is null"); 13539 13540 Preconditions.checkCallAuthorization( 13541 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 13542 13543 return checkProvisioningPreConditionSkipPermission(action, packageName); 13544 } 13545 13546 private int checkProvisioningPreConditionSkipPermission(String action, 13547 String packageName) { 13548 if (!mHasFeature) { 13549 logMissingFeatureAction("Cannot check provisioning for action " + action); 13550 return CODE_DEVICE_ADMIN_NOT_SUPPORTED; 13551 } 13552 if (!isProvisioningAllowed()) { 13553 return CODE_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS; 13554 } 13555 final int code = checkProvisioningPreConditionSkipPermissionNoLog(action, packageName); 13556 if (code != CODE_OK) { 13557 Slogf.d(LOG_TAG, "checkProvisioningPreCondition(" + action + ", " + packageName 13558 + ") failed: " 13559 + computeProvisioningErrorString(code, mInjector.userHandleGetCallingUserId())); 13560 } 13561 return code; 13562 } 13563 13564 /** 13565 * Checks if provisioning is allowed during regular usage (non-developer/CTS). This could 13566 * return {@code false} if the device has an overlaid config value set to false. If not set, 13567 * the default is true. 13568 */ 13569 private boolean isProvisioningAllowed() { 13570 boolean isDeveloperMode = isDeveloperMode(mContext); 13571 boolean isProvisioningAllowedForNormalUsers = SystemProperties.getBoolean( 13572 ALLOW_USER_PROVISIONING_KEY, /* defValue= */ true); 13573 13574 return isDeveloperMode || isProvisioningAllowedForNormalUsers; 13575 } 13576 13577 private static boolean isDeveloperMode(Context context) { 13578 return Global.getInt(context.getContentResolver(), Global.ADB_ENABLED, 0) > 0; 13579 } 13580 13581 private int checkProvisioningPreConditionSkipPermissionNoLog(String action, 13582 String packageName) { 13583 final int callingUserId = mInjector.userHandleGetCallingUserId(); 13584 if (action != null) { 13585 switch (action) { 13586 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 13587 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 13588 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 13589 case DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE: 13590 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 13591 } 13592 } 13593 throw new IllegalArgumentException("Unknown provisioning action " + action); 13594 } 13595 13596 /** 13597 * The device owner can only be set before the setup phase of the primary user has completed, 13598 * except for adb command if no accounts or additional users are present on the device. 13599 */ 13600 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 13601 @UserIdInt int deviceOwnerUserId, @UserIdInt int callingUserId, boolean isAdb, 13602 boolean hasIncompatibleAccountsOrNonAdb) { 13603 if (mOwners.hasDeviceOwner()) { 13604 return CODE_HAS_DEVICE_OWNER; 13605 } 13606 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 13607 return CODE_USER_HAS_PROFILE_OWNER; 13608 } 13609 13610 boolean isHeadlessSystemUserMode = mInjector.userManagerIsHeadlessSystemUserMode(); 13611 // System user is always running in headless system user mode. 13612 if (!isHeadlessSystemUserMode 13613 && !mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 13614 return CODE_USER_NOT_RUNNING; 13615 } 13616 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 13617 return CODE_HAS_PAIRED; 13618 } 13619 13620 if (isHeadlessSystemUserMode) { 13621 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 13622 Slogf.e(LOG_TAG, "In headless system user mode, " 13623 + "device owner can only be set on headless system user."); 13624 return CODE_NOT_SYSTEM_USER; 13625 } 13626 } 13627 13628 if (isAdb) { 13629 // If shell command runs after user setup completed check device status. Otherwise, OK. 13630 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 13631 // In non-headless system user mode, DO can be setup only if 13632 // there's no non-system user. 13633 // In headless system user mode, DO can be setup only if there are 13634 // two users: the headless system user and the foreground user. 13635 // If there could be multiple foreground users, this constraint should be modified. 13636 13637 int maxNumberOfExistingUsers = isHeadlessSystemUserMode ? 2 : 1; 13638 if (mUserManager.getUserCount() > maxNumberOfExistingUsers) { 13639 return CODE_NONSYSTEM_USER_EXISTS; 13640 } 13641 13642 int currentForegroundUser = getCurrentForegroundUserId(); 13643 if (callingUserId != currentForegroundUser 13644 && mInjector.userManagerIsHeadlessSystemUserMode() 13645 && currentForegroundUser == UserHandle.USER_SYSTEM) { 13646 Slogf.wtf(LOG_TAG, "In headless system user mode, " 13647 + "current user cannot be system user when setting device owner"); 13648 return CODE_SYSTEM_USER; 13649 } 13650 if (hasIncompatibleAccountsOrNonAdb) { 13651 return CODE_ACCOUNTS_NOT_EMPTY; 13652 } 13653 } 13654 return CODE_OK; 13655 } else { 13656 // DO has to be user 0 13657 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 13658 return CODE_NOT_SYSTEM_USER; 13659 } 13660 // Only provision DO before setup wizard completes 13661 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 13662 return CODE_USER_SETUP_COMPLETED; 13663 } 13664 return CODE_OK; 13665 } 13666 } 13667 13668 private int checkDeviceOwnerProvisioningPreCondition(@UserIdInt int callingUserId) { 13669 synchronized (getLockObject()) { 13670 final int deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode() 13671 ? UserHandle.USER_SYSTEM 13672 : callingUserId; 13673 Slogf.i(LOG_TAG, "Calling user %d, device owner will be set on user %d", 13674 callingUserId, deviceOwnerUserId); 13675 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb. 13676 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 13677 deviceOwnerUserId, callingUserId, /* isAdb= */ false, 13678 /* hasIncompatibleAccountsOrNonAdb=*/ true); 13679 } 13680 } 13681 13682 private int checkManagedProfileProvisioningPreCondition(String packageName, 13683 @UserIdInt int callingUserId) { 13684 if (!hasFeatureManagedUsers()) { 13685 return CODE_MANAGED_USERS_NOT_SUPPORTED; 13686 } 13687 if (getProfileOwnerAsUser(callingUserId) != null) { 13688 // Managed user cannot have a managed profile. 13689 return CODE_USER_HAS_PROFILE_OWNER; 13690 } 13691 13692 final long ident = mInjector.binderClearCallingIdentity(); 13693 try { 13694 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 13695 final boolean hasDeviceOwner; 13696 synchronized (getLockObject()) { 13697 hasDeviceOwner = getDeviceOwnerAdminLocked() != null; 13698 } 13699 13700 final boolean addingProfileRestricted = mUserManager.hasUserRestriction( 13701 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserHandle); 13702 13703 if (mUserManager.getUserInfo(callingUserId).isProfile()) { 13704 Slogf.i(LOG_TAG, "Calling user %d is a profile, cannot add another.", 13705 callingUserId); 13706 // The check is called from inside a managed profile. A managed profile cannot 13707 // be provisioned from within another managed profile. 13708 return CODE_CANNOT_ADD_MANAGED_PROFILE; 13709 } 13710 13711 // If there's a device owner, the restriction on adding a managed profile must be set. 13712 if (hasDeviceOwner && !addingProfileRestricted) { 13713 Slogf.wtf(LOG_TAG, "Has a device owner but no restriction on adding a profile."); 13714 } 13715 13716 // Do not allow adding a managed profile if there's a restriction. 13717 if (addingProfileRestricted) { 13718 Slogf.i(LOG_TAG, "Adding a profile is restricted: User %s Has device owner? %b", 13719 callingUserHandle, hasDeviceOwner); 13720 return CODE_CANNOT_ADD_MANAGED_PROFILE; 13721 } 13722 13723 // Bail out if we are trying to provision a work profile but one already exists. 13724 if (!mUserManager.canAddMoreManagedProfiles( 13725 callingUserId, /* allowedToRemoveOne= */ false)) { 13726 Slogf.i(LOG_TAG, "A work profile already exists."); 13727 return CODE_CANNOT_ADD_MANAGED_PROFILE; 13728 } 13729 } finally { 13730 mInjector.binderRestoreCallingIdentity(ident); 13731 } 13732 return CODE_OK; 13733 } 13734 13735 private void checkIsDeviceOwner(CallerIdentity caller) { 13736 Preconditions.checkCallAuthorization(isDeviceOwner(caller), caller.getUid() 13737 + " is not device owner"); 13738 } 13739 13740 /** 13741 * Return device owner or profile owner set on a given user. 13742 */ 13743 private @Nullable ComponentName getOwnerComponent(int userId) { 13744 synchronized (getLockObject()) { 13745 if (mOwners.getDeviceOwnerUserId() == userId) { 13746 return mOwners.getDeviceOwnerComponent(); 13747 } 13748 if (mOwners.hasProfileOwner(userId)) { 13749 return mOwners.getProfileOwnerComponent(userId); 13750 } 13751 } 13752 return null; 13753 } 13754 13755 private boolean hasFeatureManagedUsers() { 13756 try { 13757 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 13758 } catch (RemoteException e) { 13759 return false; 13760 } 13761 } 13762 13763 @Override 13764 public String getWifiMacAddress(ComponentName admin) { 13765 Objects.requireNonNull(admin, "ComponentName is null"); 13766 13767 final CallerIdentity caller = getCallerIdentity(admin); 13768 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 13769 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 13770 13771 return mInjector.binderWithCleanCallingIdentity(() -> { 13772 String[] macAddresses = mInjector.getWifiManager().getFactoryMacAddresses(); 13773 if (macAddresses == null) { 13774 return null; 13775 } 13776 DevicePolicyEventLogger 13777 .createEvent(DevicePolicyEnums.GET_WIFI_MAC_ADDRESS) 13778 .setAdmin(caller.getComponentName()) 13779 .write(); 13780 return macAddresses.length > 0 ? macAddresses[0] : null; 13781 }); 13782 } 13783 13784 /** 13785 * Returns the target sdk version number that the given packageName was built for 13786 * in the given user. 13787 */ 13788 private int getTargetSdk(String packageName, int userId) { 13789 final ApplicationInfo ai; 13790 try { 13791 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 13792 return ai == null ? 0 : ai.targetSdkVersion; 13793 } catch (RemoteException e) { 13794 // Shouldn't happen 13795 return 0; 13796 } 13797 } 13798 13799 @Override 13800 public boolean isManagedProfile(ComponentName admin) { 13801 Objects.requireNonNull(admin, "ComponentName is null"); 13802 13803 final CallerIdentity caller = getCallerIdentity(admin); 13804 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 13805 13806 return isManagedProfile(caller.getUserId()); 13807 } 13808 13809 @Override 13810 public void reboot(ComponentName admin) { 13811 Objects.requireNonNull(admin, "ComponentName is null"); 13812 final CallerIdentity caller = getCallerIdentity(admin); 13813 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 13814 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REBOOT); 13815 mInjector.binderWithCleanCallingIdentity(() -> { 13816 // Make sure there are no ongoing calls on the device. 13817 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 13818 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 13819 } 13820 DevicePolicyEventLogger 13821 .createEvent(DevicePolicyEnums.REBOOT) 13822 .setAdmin(admin) 13823 .write(); 13824 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 13825 }); 13826 } 13827 13828 @Override 13829 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 13830 if (!mHasFeature) { 13831 return; 13832 } 13833 Objects.requireNonNull(who, "ComponentName is null"); 13834 final CallerIdentity caller = getCallerIdentity(who); 13835 synchronized (getLockObject()) { 13836 ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid()); 13837 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 13838 admin.shortSupportMessage = message; 13839 saveSettingsLocked(caller.getUserId()); 13840 } 13841 } 13842 DevicePolicyEventLogger 13843 .createEvent(DevicePolicyEnums.SET_SHORT_SUPPORT_MESSAGE) 13844 .setAdmin(who) 13845 .write(); 13846 } 13847 13848 @Override 13849 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 13850 if (!mHasFeature) { 13851 return null; 13852 } 13853 Objects.requireNonNull(who, "ComponentName is null"); 13854 final CallerIdentity caller = getCallerIdentity(who); 13855 synchronized (getLockObject()) { 13856 ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid()); 13857 return admin.shortSupportMessage; 13858 } 13859 } 13860 13861 @Override 13862 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 13863 if (!mHasFeature) { 13864 return; 13865 } 13866 Objects.requireNonNull(who, "ComponentName is null"); 13867 final CallerIdentity caller = getCallerIdentity(who); 13868 synchronized (getLockObject()) { 13869 ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid()); 13870 if (!TextUtils.equals(admin.longSupportMessage, message)) { 13871 admin.longSupportMessage = message; 13872 saveSettingsLocked(caller.getUserId()); 13873 } 13874 } 13875 DevicePolicyEventLogger 13876 .createEvent(DevicePolicyEnums.SET_LONG_SUPPORT_MESSAGE) 13877 .setAdmin(who) 13878 .write(); 13879 } 13880 13881 @Override 13882 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 13883 if (!mHasFeature) { 13884 return null; 13885 } 13886 Objects.requireNonNull(who, "ComponentName is null"); 13887 final CallerIdentity caller = getCallerIdentity(who); 13888 synchronized (getLockObject()) { 13889 ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid()); 13890 return admin.longSupportMessage; 13891 } 13892 } 13893 13894 @Override 13895 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 13896 if (!mHasFeature) { 13897 return null; 13898 } 13899 Objects.requireNonNull(who, "ComponentName is null"); 13900 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 13901 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user")); 13902 13903 synchronized (getLockObject()) { 13904 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 13905 if (admin != null) { 13906 return admin.shortSupportMessage; 13907 } 13908 } 13909 return null; 13910 } 13911 13912 @Override 13913 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 13914 if (!mHasFeature) { 13915 return null; 13916 } 13917 Objects.requireNonNull(who, "ComponentName is null"); 13918 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 13919 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user")); 13920 13921 synchronized (getLockObject()) { 13922 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 13923 if (admin != null) { 13924 return admin.longSupportMessage; 13925 } 13926 } 13927 return null; 13928 } 13929 13930 @Override 13931 public void setOrganizationColor(@NonNull ComponentName who, int color) { 13932 if (!mHasFeature) { 13933 return; 13934 } 13935 Objects.requireNonNull(who, "ComponentName is null"); 13936 13937 final CallerIdentity caller = getCallerIdentity(who); 13938 Preconditions.checkCallingUser(isManagedProfile(caller.getUserId())); 13939 13940 synchronized (getLockObject()) { 13941 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 13942 admin.organizationColor = color; 13943 saveSettingsLocked(caller.getUserId()); 13944 } 13945 DevicePolicyEventLogger 13946 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_COLOR) 13947 .setAdmin(caller.getComponentName()) 13948 .write(); 13949 } 13950 13951 @Override 13952 public void setOrganizationColorForUser(int color, int userId) { 13953 if (!mHasFeature) { 13954 return; 13955 } 13956 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 13957 13958 final CallerIdentity caller = getCallerIdentity(); 13959 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 13960 Preconditions.checkCallAuthorization(canManageUsers(caller)); 13961 Preconditions.checkCallAuthorization(isManagedProfile(userId), "You can not " 13962 + "set organization color outside a managed profile, userId = %d", userId); 13963 13964 synchronized (getLockObject()) { 13965 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 13966 admin.organizationColor = color; 13967 saveSettingsLocked(userId); 13968 } 13969 } 13970 13971 @Override 13972 public int getOrganizationColor(@NonNull ComponentName who) { 13973 if (!mHasFeature) { 13974 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 13975 } 13976 Objects.requireNonNull(who, "ComponentName is null"); 13977 13978 final CallerIdentity caller = getCallerIdentity(who); 13979 Preconditions.checkCallingUser(isManagedProfile(caller.getUserId())); 13980 13981 synchronized (getLockObject()) { 13982 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 13983 return admin.organizationColor; 13984 } 13985 } 13986 13987 @Override 13988 public int getOrganizationColorForUser(int userHandle) { 13989 if (!mHasFeature) { 13990 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 13991 } 13992 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 13993 13994 final CallerIdentity caller = getCallerIdentity(); 13995 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 13996 Preconditions.checkCallAuthorization(isManagedProfile(userHandle), "You can " 13997 + "not get organization color outside a managed profile, userId = %d", userHandle); 13998 13999 synchronized (getLockObject()) { 14000 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 14001 return (profileOwner != null) 14002 ? profileOwner.organizationColor 14003 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 14004 } 14005 } 14006 14007 @Override 14008 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 14009 if (!mHasFeature) { 14010 return; 14011 } 14012 Objects.requireNonNull(who, "ComponentName is null"); 14013 final CallerIdentity caller = getCallerIdentity(who); 14014 14015 synchronized (getLockObject()) { 14016 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14017 if (!TextUtils.equals(admin.organizationName, text)) { 14018 admin.organizationName = (text == null || text.length() == 0) 14019 ? null : text.toString(); 14020 saveSettingsLocked(caller.getUserId()); 14021 } 14022 } 14023 } 14024 14025 @Override 14026 public CharSequence getOrganizationName(@NonNull ComponentName who) { 14027 if (!mHasFeature) { 14028 return null; 14029 } 14030 Objects.requireNonNull(who, "ComponentName is null"); 14031 14032 final CallerIdentity caller = getCallerIdentity(who); 14033 Preconditions.checkCallingUser(isManagedProfile(caller.getUserId())); 14034 14035 synchronized (getLockObject()) { 14036 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14037 return admin.organizationName; 14038 } 14039 } 14040 14041 @Override 14042 public CharSequence getDeviceOwnerOrganizationName() { 14043 if (!mHasFeature) { 14044 return null; 14045 } 14046 final CallerIdentity caller = getCallerIdentity(); 14047 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || canManageUsers(caller)); 14048 synchronized (getLockObject()) { 14049 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 14050 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 14051 } 14052 } 14053 14054 @Override 14055 public CharSequence getOrganizationNameForUser(int userHandle) { 14056 if (!mHasFeature) { 14057 return null; 14058 } 14059 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 14060 14061 final CallerIdentity caller = getCallerIdentity(); 14062 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 14063 Preconditions.checkCallAuthorization(isManagedProfile(userHandle), 14064 "You can not get organization name outside a managed profile, userId = %d", 14065 userHandle); 14066 14067 synchronized (getLockObject()) { 14068 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 14069 return (profileOwner != null) 14070 ? profileOwner.organizationName 14071 : null; 14072 } 14073 } 14074 14075 @Override 14076 public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) { 14077 Objects.requireNonNull(who); 14078 Objects.requireNonNull(packageNames); 14079 final CallerIdentity caller = getCallerIdentity(who); 14080 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller), 14081 "Admin %s does not own the profile", caller.getComponentName()); 14082 14083 if (!mHasFeature) { 14084 return packageNames; 14085 } 14086 synchronized (getLockObject()) { 14087 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14088 return mInjector.binderWithCleanCallingIdentity(() -> { 14089 final List<String> excludedPkgs = removeInvalidPkgsForMeteredDataRestriction( 14090 caller.getUserId(), packageNames); 14091 admin.meteredDisabledPackages = packageNames; 14092 pushMeteredDisabledPackagesLocked(caller.getUserId()); 14093 saveSettingsLocked(caller.getUserId()); 14094 return excludedPkgs; 14095 }); 14096 } 14097 } 14098 14099 private List<String> removeInvalidPkgsForMeteredDataRestriction( 14100 int userId, List<String> pkgNames) { 14101 final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId); 14102 final List<String> excludedPkgs = new ArrayList<>(); 14103 for (int i = pkgNames.size() - 1; i >= 0; --i) { 14104 final String pkgName = pkgNames.get(i); 14105 // If the package is an active admin, don't restrict it. 14106 if (activeAdmins.contains(pkgName)) { 14107 excludedPkgs.add(pkgName); 14108 continue; 14109 } 14110 // If the package doesn't exist, don't restrict it. 14111 try { 14112 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) { 14113 excludedPkgs.add(pkgName); 14114 } 14115 } catch (RemoteException e) { 14116 // Should not happen 14117 } 14118 } 14119 pkgNames.removeAll(excludedPkgs); 14120 return excludedPkgs; 14121 } 14122 14123 @Override 14124 public List<String> getMeteredDataDisabledPackages(ComponentName who) { 14125 Objects.requireNonNull(who); 14126 14127 if (!mHasFeature) { 14128 return new ArrayList<>(); 14129 } 14130 final CallerIdentity caller = getCallerIdentity(who); 14131 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller), 14132 "Admin %s does not own the profile", caller.getComponentName()); 14133 14134 synchronized (getLockObject()) { 14135 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14136 return admin.meteredDisabledPackages == null 14137 ? new ArrayList<>() : admin.meteredDisabledPackages; 14138 } 14139 } 14140 14141 @Override 14142 public boolean isMeteredDataDisabledPackageForUser(ComponentName who, 14143 String packageName, int userId) { 14144 Objects.requireNonNull(who); 14145 14146 if (!mHasFeature) { 14147 return false; 14148 } 14149 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 14150 String.format(NOT_SYSTEM_CALLER_MSG, "query restricted pkgs for a specific user")); 14151 14152 synchronized (getLockObject()) { 14153 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 14154 if (admin != null && admin.meteredDisabledPackages != null) { 14155 return admin.meteredDisabledPackages.contains(packageName); 14156 } 14157 } 14158 return false; 14159 } 14160 14161 @Override 14162 public void markProfileOwnerOnOrganizationOwnedDevice(ComponentName who, int userId) { 14163 if (!mHasFeature) { 14164 return; 14165 } 14166 // As the caller is the system, it must specify the component name of the profile owner 14167 // as a safety check. 14168 Objects.requireNonNull(who); 14169 14170 final CallerIdentity caller = getCallerIdentity(); 14171 // Only adb or system apps with the right permission can mark a profile owner on 14172 // organization-owned device. 14173 if (!(isAdb(caller) || hasCallingPermission(permission.MARK_DEVICE_ORGANIZATION_OWNED) 14174 || hasCallingPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS))) { 14175 throw new SecurityException( 14176 "Only the system can mark a profile owner of organization-owned device."); 14177 } 14178 14179 if (isAdb(caller)) { 14180 if (hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, who)) { 14181 throw new SecurityException( 14182 "Can only be called from ADB if the device has no accounts."); 14183 } 14184 } else { 14185 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 14186 throw new IllegalStateException( 14187 "Cannot mark profile owner as managing an organization-owned device after" 14188 + " set-up"); 14189 } 14190 } 14191 14192 // Grant access under lock. 14193 synchronized (getLockObject()) { 14194 markProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(who, userId); 14195 } 14196 } 14197 14198 @GuardedBy("getLockObject()") 14199 private void markProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked( 14200 ComponentName who, int userId) { 14201 // Make sure that the user has a profile owner and that the specified 14202 // component is the profile owner of that user. 14203 if (!isProfileOwner(who, userId)) { 14204 throw new IllegalArgumentException(String.format( 14205 "Component %s is not a Profile Owner of user %d", 14206 who.flattenToString(), userId)); 14207 } 14208 14209 Slogf.i(LOG_TAG, "Marking %s as profile owner on organization-owned device for user %d", 14210 who.flattenToString(), userId); 14211 14212 // First, set restriction on removing the profile. 14213 mInjector.binderWithCleanCallingIdentity(() -> { 14214 // Clear restriction as user. 14215 final UserHandle parentUser = mUserManager.getProfileParent(UserHandle.of(userId)); 14216 if (parentUser == null) { 14217 throw new IllegalStateException(String.format("User %d is not a profile", userId)); 14218 } 14219 if (!parentUser.isSystem()) { 14220 throw new IllegalStateException( 14221 String.format("Only the profile owner of a managed profile on the" 14222 + " primary user can be granted access to device identifiers, not" 14223 + " on user %d", parentUser.getIdentifier())); 14224 } 14225 14226 mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, true, 14227 parentUser); 14228 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true, 14229 parentUser); 14230 }); 14231 14232 // markProfileOwnerOfOrganizationOwnedDevice will trigger writing of the profile owner 14233 // data, no need to do it manually. 14234 mOwners.markProfileOwnerOfOrganizationOwnedDevice(userId); 14235 } 14236 14237 private void pushMeteredDisabledPackagesLocked(int userId) { 14238 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages( 14239 getMeteredDisabledPackagesLocked(userId), userId); 14240 } 14241 14242 private Set<String> getMeteredDisabledPackagesLocked(int userId) { 14243 final ComponentName who = getOwnerComponent(userId); 14244 final Set<String> restrictedPkgs = new ArraySet<>(); 14245 if (who != null) { 14246 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 14247 if (admin != null && admin.meteredDisabledPackages != null) { 14248 restrictedPkgs.addAll(admin.meteredDisabledPackages); 14249 } 14250 } 14251 return restrictedPkgs; 14252 } 14253 14254 @Override 14255 public void setAffiliationIds(ComponentName admin, List<String> ids) { 14256 if (!mHasFeature) { 14257 return; 14258 } 14259 if (ids == null) { 14260 throw new IllegalArgumentException("ids must not be null"); 14261 } 14262 for (String id : ids) { 14263 if (TextUtils.isEmpty(id)) { 14264 throw new IllegalArgumentException("ids must not contain empty string"); 14265 } 14266 } 14267 14268 final Set<String> affiliationIds = new ArraySet<>(ids); 14269 final CallerIdentity caller = getCallerIdentity(admin); 14270 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 14271 final int callingUserId = caller.getUserId(); 14272 14273 synchronized (getLockObject()) { 14274 getUserData(callingUserId).mAffiliationIds = affiliationIds; 14275 saveSettingsLocked(callingUserId); 14276 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 14277 // Affiliation ids specified by the device owner are additionally stored in 14278 // UserHandle.USER_SYSTEM's DevicePolicyData. 14279 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 14280 saveSettingsLocked(UserHandle.USER_SYSTEM); 14281 } 14282 14283 // Affiliation status for any user, not just the calling user, might have changed. 14284 // The device owner user will still be affiliated after changing its affiliation ids, 14285 // but as a result of that other users might become affiliated or un-affiliated. 14286 maybePauseDeviceWideLoggingLocked(); 14287 maybeResumeDeviceWideLoggingLocked(); 14288 maybeClearLockTaskPolicyLocked(); 14289 } 14290 } 14291 14292 @Override 14293 public List<String> getAffiliationIds(ComponentName admin) { 14294 if (!mHasFeature) { 14295 return Collections.emptyList(); 14296 } 14297 14298 Objects.requireNonNull(admin); 14299 final CallerIdentity caller = getCallerIdentity(admin); 14300 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 14301 14302 synchronized (getLockObject()) { 14303 return new ArrayList<String>(getUserData(caller.getUserId()).mAffiliationIds); 14304 } 14305 } 14306 14307 @Override 14308 public boolean isCallingUserAffiliated() { 14309 if (!mHasFeature) { 14310 return false; 14311 } 14312 14313 synchronized (getLockObject()) { 14314 return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId()); 14315 } 14316 } 14317 14318 @Override 14319 public boolean isAffiliatedUser(@UserIdInt int userId) { 14320 if (!mHasFeature) { 14321 return false; 14322 } 14323 final CallerIdentity caller = getCallerIdentity(); 14324 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)); 14325 14326 return isUserAffiliatedWithDeviceLocked(userId); 14327 } 14328 14329 private boolean isUserAffiliatedWithDeviceLocked(@UserIdInt int userId) { 14330 if (!mOwners.hasDeviceOwner()) { 14331 return false; 14332 } 14333 if (userId == UserHandle.USER_SYSTEM) { 14334 // The system user is always affiliated in a DO device, 14335 // even if in headless system user mode. 14336 return true; 14337 } 14338 if (userId == mOwners.getDeviceOwnerUserId()) { 14339 // The user that the DO is installed on is always affiliated with the device. 14340 return true; 14341 } 14342 14343 final ComponentName profileOwner = getProfileOwnerAsUser(userId); 14344 if (profileOwner == null) { 14345 return false; 14346 } 14347 14348 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 14349 final Set<String> deviceAffiliationIds = 14350 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 14351 for (String id : userAffiliationIds) { 14352 if (deviceAffiliationIds.contains(id)) { 14353 return true; 14354 } 14355 } 14356 return false; 14357 } 14358 14359 private boolean areAllUsersAffiliatedWithDeviceLocked() { 14360 return mInjector.binderWithCleanCallingIdentity(() -> { 14361 final List<UserInfo> userInfos = mUserManager.getAliveUsers(); 14362 for (int i = 0; i < userInfos.size(); i++) { 14363 int userId = userInfos.get(i).id; 14364 if (!isUserAffiliatedWithDeviceLocked(userId)) { 14365 Slogf.d(LOG_TAG, "User id " + userId + " not affiliated."); 14366 return false; 14367 } 14368 } 14369 return true; 14370 }); 14371 } 14372 14373 private @UserIdInt int getSecurityLoggingEnabledUser() { 14374 synchronized (getLockObject()) { 14375 if (mOwners.hasDeviceOwner()) { 14376 return UserHandle.USER_ALL; 14377 } 14378 } 14379 return getOrganizationOwnedProfileUserId(); 14380 } 14381 14382 @Override 14383 public void setSecurityLoggingEnabled(ComponentName admin, String packageName, 14384 boolean enabled) { 14385 if (!mHasFeature) { 14386 return; 14387 } 14388 final CallerIdentity caller = getCallerIdentity(admin, packageName); 14389 14390 synchronized (getLockObject()) { 14391 if (admin != null) { 14392 Preconditions.checkCallAuthorization( 14393 isProfileOwnerOfOrganizationOwnedDevice(caller) 14394 || isDeviceOwner(caller)); 14395 } else { 14396 // A delegate app passes a null admin component, which is expected 14397 Preconditions.checkCallAuthorization( 14398 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING)); 14399 } 14400 14401 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 14402 return; 14403 } 14404 mInjector.securityLogSetLoggingEnabledProperty(enabled); 14405 if (enabled) { 14406 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser()); 14407 maybePauseDeviceWideLoggingLocked(); 14408 } else { 14409 mSecurityLogMonitor.stop(); 14410 } 14411 } 14412 DevicePolicyEventLogger 14413 .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED) 14414 .setAdmin(admin) 14415 .setBoolean(enabled) 14416 .write(); 14417 } 14418 14419 @Override 14420 public boolean isSecurityLoggingEnabled(ComponentName admin, String packageName) { 14421 if (!mHasFeature) { 14422 return false; 14423 } 14424 14425 synchronized (getLockObject()) { 14426 if (!isSystemUid(getCallerIdentity())) { 14427 final CallerIdentity caller = getCallerIdentity(admin, packageName); 14428 if (admin != null) { 14429 Preconditions.checkCallAuthorization( 14430 isProfileOwnerOfOrganizationOwnedDevice(caller) 14431 || isDeviceOwner(caller)); 14432 } else { 14433 // A delegate app passes a null admin component, which is expected 14434 Preconditions.checkCallAuthorization( 14435 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING)); 14436 } 14437 } 14438 return mInjector.securityLogGetLoggingEnabledProperty(); 14439 } 14440 } 14441 14442 private void recordSecurityLogRetrievalTime() { 14443 synchronized (getLockObject()) { 14444 final long currentTime = System.currentTimeMillis(); 14445 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 14446 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 14447 policyData.mLastSecurityLogRetrievalTime = currentTime; 14448 saveSettingsLocked(UserHandle.USER_SYSTEM); 14449 } 14450 } 14451 } 14452 14453 @Override 14454 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin, 14455 String packageName) { 14456 if (!mHasFeature) { 14457 return null; 14458 } 14459 14460 final CallerIdentity caller = getCallerIdentity(admin, packageName); 14461 if (admin != null) { 14462 Preconditions.checkCallAuthorization( 14463 isProfileOwnerOfOrganizationOwnedDevice(caller) 14464 || isDeviceOwner(caller)); 14465 } else { 14466 // A delegate app passes a null admin component, which is expected 14467 Preconditions.checkCallAuthorization( 14468 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING)); 14469 } 14470 14471 Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile() 14472 || areAllUsersAffiliatedWithDeviceLocked()); 14473 14474 DevicePolicyEventLogger 14475 .createEvent(DevicePolicyEnums.RETRIEVE_PRE_REBOOT_SECURITY_LOGS) 14476 .setAdmin(caller.getComponentName()) 14477 .write(); 14478 14479 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs) 14480 || !mInjector.securityLogGetLoggingEnabledProperty()) { 14481 return null; 14482 } 14483 14484 recordSecurityLogRetrievalTime(); 14485 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 14486 try { 14487 SecurityLog.readPreviousEvents(output); 14488 int enabledUser = getSecurityLoggingEnabledUser(); 14489 if (enabledUser != UserHandle.USER_ALL) { 14490 SecurityLog.redactEvents(output, enabledUser); 14491 } 14492 return new ParceledListSlice<SecurityEvent>(output); 14493 } catch (IOException e) { 14494 Slogf.w(LOG_TAG, "Fail to read previous events" , e); 14495 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 14496 } 14497 } 14498 14499 @Override 14500 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin, 14501 String packageName) { 14502 if (!mHasFeature) { 14503 return null; 14504 } 14505 14506 final CallerIdentity caller = getCallerIdentity(admin, packageName); 14507 if (admin != null) { 14508 Preconditions.checkCallAuthorization( 14509 isProfileOwnerOfOrganizationOwnedDevice(caller) 14510 || isDeviceOwner(caller)); 14511 } else { 14512 // A delegate app passes a null admin component, which is expected 14513 Preconditions.checkCallAuthorization( 14514 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING)); 14515 } 14516 Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile() 14517 || areAllUsersAffiliatedWithDeviceLocked()); 14518 14519 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 14520 return null; 14521 } 14522 14523 recordSecurityLogRetrievalTime(); 14524 14525 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 14526 DevicePolicyEventLogger 14527 .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS) 14528 .setAdmin(caller.getComponentName()) 14529 .write(); 14530 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 14531 } 14532 14533 @Override 14534 public long forceSecurityLogs() { 14535 Preconditions.checkCallAuthorization(isAdb(getCallerIdentity()) 14536 || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS), 14537 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call " 14538 + "forceSecurityLogs"); 14539 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 14540 throw new IllegalStateException("logging is not available"); 14541 } 14542 return mSecurityLogMonitor.forceLogs(); 14543 } 14544 14545 @Override 14546 public boolean isUninstallInQueue(final String packageName) { 14547 final CallerIdentity caller = getCallerIdentity(); 14548 Preconditions.checkCallAuthorization( 14549 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 14550 14551 Pair<String, Integer> packageUserPair = new Pair<>(packageName, caller.getUserId()); 14552 synchronized (getLockObject()) { 14553 return mPackagesToRemove.contains(packageUserPair); 14554 } 14555 } 14556 14557 @Override 14558 public void uninstallPackageWithActiveAdmins(final String packageName) { 14559 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 14560 14561 final CallerIdentity caller = getCallerIdentity(); 14562 Preconditions.checkCallAuthorization( 14563 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 14564 14565 final int userId = caller.getUserId(); 14566 enforceUserUnlocked(userId); 14567 14568 final ComponentName profileOwner = getProfileOwnerAsUser(userId); 14569 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 14570 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 14571 } 14572 14573 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 14574 if (getDeviceOwnerUserId() == userId && deviceOwner != null 14575 && packageName.equals(deviceOwner.getPackageName())) { 14576 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 14577 } 14578 14579 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 14580 synchronized (getLockObject()) { 14581 mPackagesToRemove.add(packageUserPair); 14582 } 14583 14584 // All active admins on the user. 14585 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 14586 14587 // Active admins in the target package. 14588 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 14589 if (allActiveAdmins != null) { 14590 for (ComponentName activeAdmin : allActiveAdmins) { 14591 if (packageName.equals(activeAdmin.getPackageName())) { 14592 packageActiveAdmins.add(activeAdmin); 14593 removeActiveAdmin(activeAdmin, userId); 14594 } 14595 } 14596 } 14597 if (packageActiveAdmins.size() == 0) { 14598 startUninstallIntent(packageName, userId); 14599 } else { 14600 mHandler.postDelayed(new Runnable() { 14601 @Override 14602 public void run() { 14603 for (ComponentName activeAdmin : packageActiveAdmins) { 14604 removeAdminArtifacts(activeAdmin, userId); 14605 } 14606 startUninstallIntent(packageName, userId); 14607 } 14608 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 14609 } 14610 } 14611 14612 @Override 14613 public boolean isDeviceProvisioned() { 14614 final CallerIdentity caller = getCallerIdentity(); 14615 Preconditions.checkCallAuthorization(canManageUsers(caller)); 14616 14617 synchronized (getLockObject()) { 14618 return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete; 14619 } 14620 } 14621 14622 private boolean isCurrentUserDemo() { 14623 if (UserManager.isDeviceInDemoMode(mContext)) { 14624 final int userId = mInjector.userHandleGetCallingUserId(); 14625 return mInjector.binderWithCleanCallingIdentity( 14626 () -> mUserManager.getUserInfo(userId).isDemo()); 14627 } 14628 return false; 14629 } 14630 14631 private void removePackageIfRequired(final String packageName, final int userId) { 14632 if (!packageHasActiveAdmins(packageName, userId)) { 14633 // Will not do anything if uninstall was not requested or was already started. 14634 startUninstallIntent(packageName, userId); 14635 } 14636 } 14637 14638 private void startUninstallIntent(final String packageName, final int userId) { 14639 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 14640 synchronized (getLockObject()) { 14641 if (!mPackagesToRemove.contains(packageUserPair)) { 14642 // Do nothing if uninstall was not requested or was already started. 14643 return; 14644 } 14645 mPackagesToRemove.remove(packageUserPair); 14646 } 14647 if (!isPackageInstalledForUser(packageName, userId)) { 14648 // Package does not exist. Nothing to do. 14649 return; 14650 } 14651 14652 try { // force stop the package before uninstalling 14653 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 14654 } catch (RemoteException re) { 14655 Slogf.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 14656 } 14657 final Uri packageURI = Uri.parse("package:" + packageName); 14658 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 14659 uninstallIntent.setFlags(FLAG_ACTIVITY_NEW_TASK); 14660 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 14661 } 14662 14663 /** 14664 * Removes the admin from the policy. Ideally called after the admin's 14665 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 14666 * 14667 * @param adminReceiver The admin to remove 14668 * @param userHandle The user for which this admin has to be removed. 14669 */ 14670 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 14671 synchronized (getLockObject()) { 14672 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 14673 if (admin == null) { 14674 return; 14675 } 14676 final DevicePolicyData policy = getUserData(userHandle); 14677 final boolean doProxyCleanup = admin.info.usesPolicy( 14678 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 14679 policy.mAdminList.remove(admin); 14680 policy.mAdminMap.remove(adminReceiver); 14681 policy.validatePasswordOwner(); 14682 if (doProxyCleanup) { 14683 resetGlobalProxyLocked(policy); 14684 } 14685 pushActiveAdminPackagesLocked(userHandle); 14686 pushMeteredDisabledPackagesLocked(userHandle); 14687 saveSettingsLocked(userHandle); 14688 updateMaximumTimeToLockLocked(userHandle); 14689 policy.mRemovingAdmins.remove(adminReceiver); 14690 14691 Slogf.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 14692 } 14693 // The removed admin might have disabled camera, so update user 14694 // restrictions. 14695 pushUserRestrictions(userHandle); 14696 } 14697 14698 @Override 14699 public void setDeviceProvisioningConfigApplied() { 14700 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 14701 14702 synchronized (getLockObject()) { 14703 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 14704 policy.mDeviceProvisioningConfigApplied = true; 14705 saveSettingsLocked(UserHandle.USER_SYSTEM); 14706 } 14707 } 14708 14709 @Override 14710 public boolean isDeviceProvisioningConfigApplied() { 14711 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 14712 14713 synchronized (getLockObject()) { 14714 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 14715 return policy.mDeviceProvisioningConfigApplied; 14716 } 14717 } 14718 14719 /** 14720 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 14721 * 14722 * It's added for testing only. Please use this API carefully if it's used by other system app 14723 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 14724 * apps. 14725 */ 14726 @Override 14727 public void forceUpdateUserSetupComplete(@UserIdInt int userId) { 14728 Preconditions.checkCallAuthorization( 14729 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 14730 14731 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 14732 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 14733 DevicePolicyData policy = getUserData(userId); 14734 policy.mUserSetupComplete = isUserCompleted; 14735 mStateCache.setDeviceProvisioned(isUserCompleted); 14736 synchronized (getLockObject()) { 14737 saveSettingsLocked(userId); 14738 } 14739 } 14740 14741 @Override 14742 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 14743 if (!mHasFeature) { 14744 return; 14745 } 14746 Objects.requireNonNull(admin, "ComponentName is null"); 14747 14748 final CallerIdentity caller = getCallerIdentity(admin); 14749 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 14750 14751 toggleBackupServiceActive(caller.getUserId(), enabled); 14752 } 14753 14754 @Override 14755 public boolean isBackupServiceEnabled(ComponentName admin) { 14756 if (!mHasFeature) { 14757 return true; 14758 } 14759 Objects.requireNonNull(admin, "ComponentName is null"); 14760 14761 final CallerIdentity caller = getCallerIdentity(admin); 14762 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 14763 14764 return mInjector.binderWithCleanCallingIdentity(() -> { 14765 synchronized (getLockObject()) { 14766 try { 14767 IBackupManager ibm = mInjector.getIBackupManager(); 14768 return ibm != null && ibm.isBackupServiceActive(caller.getUserId()); 14769 } catch (RemoteException e) { 14770 throw new IllegalStateException("Failed requesting backup service state.", e); 14771 } 14772 } 14773 }); 14774 } 14775 14776 @Override 14777 public boolean bindDeviceAdminServiceAsUser( 14778 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 14779 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 14780 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 14781 if (!mHasFeature) { 14782 return false; 14783 } 14784 Objects.requireNonNull(admin); 14785 Objects.requireNonNull(caller); 14786 Objects.requireNonNull(serviceIntent); 14787 Preconditions.checkArgument( 14788 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 14789 "Service intent must be explicit (with a package name or component): " 14790 + serviceIntent); 14791 Objects.requireNonNull(connection); 14792 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 14793 "target user id must be different from the calling user id"); 14794 14795 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 14796 throw new SecurityException("Not allowed to bind to target user id"); 14797 } 14798 14799 final String targetPackage; 14800 synchronized (getLockObject()) { 14801 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 14802 } 14803 14804 final long callingIdentity = mInjector.binderClearCallingIdentity(); 14805 try { 14806 // Validate and sanitize the incoming service intent. 14807 final Intent sanitizedIntent = 14808 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 14809 if (sanitizedIntent == null) { 14810 // Fail, cannot lookup the target service. 14811 return false; 14812 } 14813 // Ask ActivityManager to bind it. Notice that we are binding the service with the 14814 // caller app instead of DevicePolicyManagerService. 14815 return mInjector.getIActivityManager().bindService( 14816 caller, activtiyToken, serviceIntent, 14817 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 14818 connection, flags, mContext.getOpPackageName(), 14819 targetUserId) != 0; 14820 } catch (RemoteException ex) { 14821 // Same process, should not happen. 14822 } finally { 14823 mInjector.binderRestoreCallingIdentity(callingIdentity); 14824 } 14825 14826 // Failed to bind. 14827 return false; 14828 } 14829 14830 @Override 14831 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 14832 if (!mHasFeature) { 14833 return Collections.emptyList(); 14834 } 14835 Objects.requireNonNull(admin); 14836 final CallerIdentity caller = getCallerIdentity(admin); 14837 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 14838 14839 synchronized (getLockObject()) { 14840 final int callingUserId = caller.getUserId(); 14841 return mInjector.binderWithCleanCallingIdentity(() -> { 14842 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 14843 if (!isDeviceOwner(admin, callingUserId)) { 14844 // Profile owners can only bind to the device owner. 14845 if (canUserBindToDeviceOwnerLocked(callingUserId)) { 14846 targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId())); 14847 } 14848 } else { 14849 // Caller is the device owner: Look for profile owners that it can bind to. 14850 final List<UserInfo> userInfos = mUserManager.getAliveUsers(); 14851 for (int i = 0; i < userInfos.size(); i++) { 14852 final int userId = userInfos.get(i).id; 14853 if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) { 14854 targetUsers.add(UserHandle.of(userId)); 14855 } 14856 } 14857 } 14858 14859 return targetUsers; 14860 }); 14861 } 14862 } 14863 14864 private boolean canUserBindToDeviceOwnerLocked(int userId) { 14865 // There has to be a device owner, under another user id. 14866 if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) { 14867 return false; 14868 } 14869 14870 // The user must have a profile owner that belongs to the same package as the device owner. 14871 if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals( 14872 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) { 14873 return false; 14874 } 14875 14876 // The user must be affiliated. 14877 return isUserAffiliatedWithDeviceLocked(userId); 14878 } 14879 14880 /** 14881 * Return true if a given user has any accounts that'll prevent installing a device or profile 14882 * owner {@code owner}. 14883 * - If the user has no accounts, then return false. 14884 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 14885 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 14886 * ..._DISALLOWED, return true. 14887 * - Otherwise return false. 14888 * 14889 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used 14890 * when the caller is not ADB. 14891 * 14892 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 14893 */ 14894 private boolean hasIncompatibleAccountsOrNonAdbNoLock(CallerIdentity caller, 14895 int userId, @Nullable ComponentName owner) { 14896 if (!isAdb(caller)) { 14897 return true; 14898 } 14899 wtfIfInLock(); 14900 14901 return mInjector.binderWithCleanCallingIdentity(() -> { 14902 final AccountManager am = AccountManager.get(mContext); 14903 final Account accounts[] = am.getAccountsAsUser(userId); 14904 if (accounts.length == 0) { 14905 return false; 14906 } 14907 synchronized (getLockObject()) { 14908 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 14909 Slogf.w(LOG_TAG, 14910 "Non test-only owner can't be installed with existing accounts."); 14911 return true; 14912 } 14913 } 14914 14915 final String[] feature_allow = 14916 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 14917 final String[] feature_disallow = 14918 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 14919 14920 boolean compatible = true; 14921 for (Account account : accounts) { 14922 if (hasAccountFeatures(am, account, feature_disallow)) { 14923 Slogf.e(LOG_TAG, "%s has %s", account, feature_disallow[0]); 14924 compatible = false; 14925 break; 14926 } 14927 if (!hasAccountFeatures(am, account, feature_allow)) { 14928 Slogf.e(LOG_TAG, "%s doesn't have %s", account, feature_allow[0]); 14929 compatible = false; 14930 break; 14931 } 14932 } 14933 if (compatible) { 14934 Slogf.w(LOG_TAG, "All accounts are compatible"); 14935 } else { 14936 Slogf.e(LOG_TAG, "Found incompatible accounts"); 14937 } 14938 return !compatible; 14939 }); 14940 } 14941 14942 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 14943 try { 14944 return am.hasFeatures(account, features, null, null).getResult(); 14945 } catch (Exception e) { 14946 Slogf.w(LOG_TAG, "Failed to get account feature", e); 14947 return false; 14948 } 14949 } 14950 14951 private boolean isAdb(CallerIdentity caller) { 14952 return isShellUid(caller) || isRootUid(caller); 14953 } 14954 14955 @Override 14956 public void setNetworkLoggingEnabled(@Nullable ComponentName admin, 14957 @NonNull String packageName, boolean enabled) { 14958 if (!mHasFeature) { 14959 return; 14960 } 14961 final CallerIdentity caller = getCallerIdentity(admin, packageName); 14962 final boolean isManagedProfileOwner = isProfileOwner(caller) 14963 && isManagedProfile(caller.getUserId()); 14964 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 14965 && (isDeviceOwner(caller) || isManagedProfileOwner)) 14966 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING))); 14967 14968 synchronized (getLockObject()) { 14969 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 14970 // already in the requested state 14971 return; 14972 } 14973 final ActiveAdmin activeAdmin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId()); 14974 activeAdmin.isNetworkLoggingEnabled = enabled; 14975 if (!enabled) { 14976 activeAdmin.numNetworkLoggingNotifications = 0; 14977 activeAdmin.lastNetworkLoggingNotificationTimeMs = 0; 14978 } 14979 saveSettingsLocked(caller.getUserId()); 14980 setNetworkLoggingActiveInternal(enabled); 14981 14982 DevicePolicyEventLogger 14983 .createEvent(DevicePolicyEnums.SET_NETWORK_LOGGING_ENABLED) 14984 .setAdmin(caller.getPackageName()) 14985 .setBoolean(/* isDelegate */ admin == null) 14986 .setInt(enabled ? 1 : 0) 14987 .setStrings(isManagedProfileOwner 14988 ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER) 14989 .write(); 14990 } 14991 } 14992 14993 private void setNetworkLoggingActiveInternal(boolean active) { 14994 mInjector.binderWithCleanCallingIdentity(() -> { 14995 boolean shouldSendNotification = false; 14996 synchronized (getLockObject()) { 14997 if (active) { 14998 if (mNetworkLogger == null) { 14999 final int affectedUserId = getNetworkLoggingAffectedUser(); 15000 mNetworkLogger = new NetworkLogger(this, 15001 mInjector.getPackageManagerInternal(), 15002 affectedUserId == UserHandle.USER_SYSTEM 15003 ? UserHandle.USER_ALL : affectedUserId); 15004 } 15005 if (!mNetworkLogger.startNetworkLogging()) { 15006 mNetworkLogger = null; 15007 Slogf.wtf(LOG_TAG, "Network logging could not be started due to the logging" 15008 + " service not being available yet."); 15009 } 15010 maybePauseDeviceWideLoggingLocked(); 15011 shouldSendNotification = shouldSendNetworkLoggingNotificationLocked(); 15012 } else { 15013 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 15014 Slogf.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 15015 + " service not being available yet."); 15016 } 15017 mNetworkLogger = null; 15018 } 15019 } 15020 if (active) { 15021 if (shouldSendNotification) { 15022 mHandler.post(() -> sendNetworkLoggingNotification()); 15023 } 15024 } else { 15025 mHandler.post(() -> mInjector.getNotificationManager().cancel( 15026 SystemMessage.NOTE_NETWORK_LOGGING)); 15027 } 15028 }); 15029 } 15030 15031 private @UserIdInt int getNetworkLoggingAffectedUser() { 15032 synchronized (getLockObject()) { 15033 if (mOwners.hasDeviceOwner()) { 15034 return mOwners.getDeviceOwnerUserId(); 15035 } else { 15036 return mInjector.binderWithCleanCallingIdentity( 15037 () -> getManagedUserId(UserHandle.USER_SYSTEM)); 15038 } 15039 } 15040 } 15041 15042 private ActiveAdmin getNetworkLoggingControllingAdminLocked() { 15043 int affectedUserId = getNetworkLoggingAffectedUser(); 15044 if (affectedUserId < 0) { 15045 return null; 15046 } 15047 return getDeviceOrProfileOwnerAdminLocked(affectedUserId); 15048 } 15049 15050 @Override 15051 public long forceNetworkLogs() { 15052 Preconditions.checkCallAuthorization(isAdb(getCallerIdentity()) 15053 || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS), 15054 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call " 15055 + "forceNetworkLogs"); 15056 synchronized (getLockObject()) { 15057 if (!isNetworkLoggingEnabledInternalLocked()) { 15058 throw new IllegalStateException("logging is not available"); 15059 } 15060 if (mNetworkLogger != null) { 15061 return mInjector.binderWithCleanCallingIdentity( 15062 () -> mNetworkLogger.forceBatchFinalization()); 15063 } 15064 return 0; 15065 } 15066 } 15067 15068 /** Pauses security and network logging if there are unaffiliated users on the device */ 15069 @GuardedBy("getLockObject()") 15070 private void maybePauseDeviceWideLoggingLocked() { 15071 if (!areAllUsersAffiliatedWithDeviceLocked()) { 15072 if (mOwners.hasDeviceOwner()) { 15073 Slogf.i(LOG_TAG, "There are unaffiliated users, network logging will be " 15074 + "paused if enabled."); 15075 if (mNetworkLogger != null) { 15076 mNetworkLogger.pause(); 15077 } 15078 } 15079 if (!isOrganizationOwnedDeviceWithManagedProfile()) { 15080 Slogf.i(LOG_TAG, "Not org-owned managed profile device, security logging will be " 15081 + "paused if enabled."); 15082 mSecurityLogMonitor.pause(); 15083 } 15084 } 15085 } 15086 15087 /** Resumes security and network logging (if they are enabled) if all users are affiliated */ 15088 @GuardedBy("getLockObject()") 15089 private void maybeResumeDeviceWideLoggingLocked() { 15090 boolean allUsersAffiliated = areAllUsersAffiliatedWithDeviceLocked(); 15091 boolean orgOwnedProfileDevice = isOrganizationOwnedDeviceWithManagedProfile(); 15092 mInjector.binderWithCleanCallingIdentity(() -> { 15093 if (allUsersAffiliated || orgOwnedProfileDevice) { 15094 mSecurityLogMonitor.resume(); 15095 } 15096 // If there is no device owner, then per-user network logging may be enabled for the 15097 // managed profile. In which case, all users do not need to be affiliated. 15098 if (allUsersAffiliated || !mOwners.hasDeviceOwner()) { 15099 if (mNetworkLogger != null) { 15100 mNetworkLogger.resume(); 15101 } 15102 } 15103 }); 15104 } 15105 15106 /** Deletes any security and network logs that might have been collected so far */ 15107 @GuardedBy("getLockObject()") 15108 private void discardDeviceWideLogsLocked() { 15109 mSecurityLogMonitor.discardLogs(); 15110 if (mNetworkLogger != null) { 15111 mNetworkLogger.discardLogs(); 15112 } 15113 // TODO: We should discard pre-boot security logs here too, as otherwise those 15114 // logs (which might contain data from the user just removed) will be 15115 // available after next boot. 15116 } 15117 15118 @Override 15119 public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin, 15120 @NonNull String packageName) { 15121 if (!mHasFeature) { 15122 return false; 15123 } 15124 final CallerIdentity caller = getCallerIdentity(admin, packageName); 15125 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 15126 && (isDeviceOwner(caller) 15127 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId())))) 15128 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)) 15129 || hasCallingOrSelfPermission(permission.MANAGE_USERS)); 15130 15131 synchronized (getLockObject()) { 15132 return isNetworkLoggingEnabledInternalLocked(); 15133 } 15134 } 15135 15136 private boolean isNetworkLoggingEnabledInternalLocked() { 15137 ActiveAdmin activeAdmin = getNetworkLoggingControllingAdminLocked(); 15138 return (activeAdmin != null) && activeAdmin.isNetworkLoggingEnabled; 15139 } 15140 15141 /* 15142 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 15143 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 15144 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 15145 * 15146 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 15147 */ 15148 @Override 15149 public List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin, 15150 @NonNull String packageName, long batchToken) { 15151 if (!mHasFeature) { 15152 return null; 15153 } 15154 final CallerIdentity caller = getCallerIdentity(admin, packageName); 15155 final boolean isManagedProfileOwner = isProfileOwner(caller) 15156 && isManagedProfile(caller.getUserId()); 15157 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 15158 && (isDeviceOwner(caller) || isManagedProfileOwner)) 15159 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING))); 15160 if (mOwners.hasDeviceOwner()) { 15161 checkAllUsersAreAffiliatedWithDevice(); 15162 } 15163 15164 synchronized (getLockObject()) { 15165 if (mNetworkLogger == null || !isNetworkLoggingEnabledInternalLocked()) { 15166 return null; 15167 } 15168 DevicePolicyEventLogger 15169 .createEvent(DevicePolicyEnums.RETRIEVE_NETWORK_LOGS) 15170 .setAdmin(caller.getPackageName()) 15171 .setBoolean(/* isDelegate */ admin == null) 15172 .setStrings(isManagedProfileOwner 15173 ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER) 15174 .write(); 15175 15176 final long currentTime = System.currentTimeMillis(); 15177 DevicePolicyData policyData = getUserData(caller.getUserId()); 15178 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 15179 policyData.mLastNetworkLogsRetrievalTime = currentTime; 15180 saveSettingsLocked(caller.getUserId()); 15181 } 15182 return mNetworkLogger.retrieveLogs(batchToken); 15183 } 15184 } 15185 15186 /** 15187 * Returns whether it's time to post another network logging notification. When returning true, 15188 * this method has the side-effect of updating the recorded last network logging notification 15189 * time to now. 15190 */ 15191 private boolean shouldSendNetworkLoggingNotificationLocked() { 15192 ensureLocked(); 15193 // Send a network logging notification if the admin is a device owner, not profile owner. 15194 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 15195 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 15196 return false; 15197 } 15198 if (deviceOwner.numNetworkLoggingNotifications 15199 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 15200 return false; 15201 } 15202 final long now = System.currentTimeMillis(); 15203 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 15204 return false; 15205 } 15206 deviceOwner.numNetworkLoggingNotifications++; 15207 if (deviceOwner.numNetworkLoggingNotifications 15208 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 15209 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 15210 } else { 15211 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 15212 } 15213 saveSettingsLocked(deviceOwner.getUserHandle().getIdentifier()); 15214 return true; 15215 } 15216 15217 private void sendNetworkLoggingNotification() { 15218 final PackageManagerInternal pm = mInjector.getPackageManagerInternal(); 15219 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 15220 intent.setPackage(pm.getSystemUiServiceComponent().getPackageName()); 15221 // Simple notification clicks are immutable 15222 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 15223 PendingIntent.FLAG_IMMUTABLE, UserHandle.CURRENT); 15224 Notification notification = 15225 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 15226 .setSmallIcon(R.drawable.ic_info_outline) 15227 .setContentTitle(mContext.getString(R.string.network_logging_notification_title)) 15228 .setContentText(mContext.getString(R.string.network_logging_notification_text)) 15229 .setTicker(mContext.getString(R.string.network_logging_notification_title)) 15230 .setShowWhen(true) 15231 .setContentIntent(pendingIntent) 15232 .setStyle(new Notification.BigTextStyle() 15233 .bigText(mContext.getString(R.string.network_logging_notification_text))) 15234 .build(); 15235 mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification); 15236 } 15237 15238 /** 15239 * Return the package name of owner in a given user. 15240 */ 15241 private String getOwnerPackageNameForUserLocked(int userId) { 15242 return mOwners.getDeviceOwnerUserId() == userId 15243 ? mOwners.getDeviceOwnerPackageName() 15244 : mOwners.getProfileOwnerPackage(userId); 15245 } 15246 15247 /** 15248 * @param rawIntent Original service intent specified by caller. It must be explicit. 15249 * @param expectedPackageName The expected package name of the resolved service. 15250 * @return Intent that have component explicitly set. {@code null} if no service is resolved 15251 * with the given intent. 15252 * @throws SecurityException if the intent is resolved to an invalid service. 15253 */ 15254 private Intent createCrossUserServiceIntent( 15255 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 15256 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 15257 ResolveInfo info = mIPackageManager.resolveService( 15258 rawIntent, 15259 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 15260 0, // flags 15261 targetUserId); 15262 if (info == null || info.serviceInfo == null) { 15263 Slogf.e(LOG_TAG, "Fail to look up the service: %s or user %d is not running", rawIntent, 15264 targetUserId); 15265 return null; 15266 } 15267 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 15268 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 15269 } 15270 // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release. 15271 if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) { 15272 throw new SecurityException( 15273 "Service must be protected by BIND_DEVICE_ADMIN permission"); 15274 } 15275 // It is the system server to bind the service, it would be extremely dangerous if it 15276 // can be exploited to bind any service. Set the component explicitly to make sure we 15277 // do not bind anything accidentally. 15278 rawIntent.setComponent(info.serviceInfo.getComponentName()); 15279 return rawIntent; 15280 } 15281 15282 @Override getLastSecurityLogRetrievalTime()15283 public long getLastSecurityLogRetrievalTime() { 15284 final CallerIdentity caller = getCallerIdentity(); 15285 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || canManageUsers(caller)); 15286 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 15287 } 15288 15289 @Override getLastBugReportRequestTime()15290 public long getLastBugReportRequestTime() { 15291 final CallerIdentity caller = getCallerIdentity(); 15292 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || canManageUsers(caller)); 15293 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 15294 } 15295 15296 @Override getLastNetworkLogRetrievalTime()15297 public long getLastNetworkLogRetrievalTime() { 15298 final CallerIdentity caller = getCallerIdentity(); 15299 15300 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 15301 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId())) 15302 || canManageUsers(caller)); 15303 final int affectedUserId = getNetworkLoggingAffectedUser(); 15304 return affectedUserId >= 0 ? getUserData(affectedUserId).mLastNetworkLogsRetrievalTime : -1; 15305 } 15306 15307 @Override setResetPasswordToken(ComponentName admin, byte[] token)15308 public boolean setResetPasswordToken(ComponentName admin, byte[] token) { 15309 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 15310 return false; 15311 } 15312 if (token == null || token.length < 32) { 15313 throw new IllegalArgumentException("token must be at least 32-byte long"); 15314 } 15315 final CallerIdentity caller = getCallerIdentity(admin); 15316 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 15317 15318 synchronized (getLockObject()) { 15319 final int userHandle = caller.getUserId(); 15320 15321 DevicePolicyData policy = getUserData(userHandle); 15322 return mInjector.binderWithCleanCallingIdentity(() -> { 15323 if (policy.mPasswordTokenHandle != 0) { 15324 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle); 15325 } 15326 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, 15327 userHandle, /*EscrowTokenStateChangeCallback*/ null); 15328 saveSettingsLocked(userHandle); 15329 return policy.mPasswordTokenHandle != 0; 15330 }); 15331 } 15332 } 15333 15334 @Override 15335 public boolean clearResetPasswordToken(ComponentName admin) { 15336 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 15337 return false; 15338 } 15339 final CallerIdentity caller = getCallerIdentity(admin); 15340 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 15341 15342 synchronized (getLockObject()) { 15343 final int userHandle = caller.getUserId(); 15344 15345 DevicePolicyData policy = getUserData(userHandle); 15346 if (policy.mPasswordTokenHandle != 0) { 15347 return mInjector.binderWithCleanCallingIdentity(() -> { 15348 boolean result = mLockPatternUtils.removeEscrowToken( 15349 policy.mPasswordTokenHandle, userHandle); 15350 policy.mPasswordTokenHandle = 0; 15351 saveSettingsLocked(userHandle); 15352 return result; 15353 }); 15354 } 15355 } 15356 return false; 15357 } 15358 15359 @Override 15360 public boolean isResetPasswordTokenActive(ComponentName admin) { 15361 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 15362 return false; 15363 } 15364 final CallerIdentity caller = getCallerIdentity(admin); 15365 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 15366 15367 synchronized (getLockObject()) { 15368 return isResetPasswordTokenActiveForUserLocked(caller.getUserId()); 15369 } 15370 } 15371 15372 private boolean isResetPasswordTokenActiveForUserLocked(int userHandle) { 15373 DevicePolicyData policy = getUserData(userHandle); 15374 if (policy.mPasswordTokenHandle != 0) { 15375 return mInjector.binderWithCleanCallingIdentity(() -> 15376 mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle, userHandle)); 15377 } 15378 return false; 15379 } 15380 15381 @Override 15382 public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, 15383 int flags) { 15384 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 15385 return false; 15386 } 15387 Objects.requireNonNull(token); 15388 15389 final CallerIdentity caller = getCallerIdentity(admin); 15390 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 15391 15392 synchronized (getLockObject()) { 15393 DevicePolicyData policy = getUserData(caller.getUserId()); 15394 if (policy.mPasswordTokenHandle != 0) { 15395 final String password = passwordOrNull != null ? passwordOrNull : ""; 15396 final boolean result = resetPasswordInternal(password, policy.mPasswordTokenHandle, 15397 token, flags, caller); 15398 if (result) { 15399 DevicePolicyEventLogger 15400 .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN) 15401 .setAdmin(caller.getComponentName()) 15402 .write(); 15403 } 15404 return result; 15405 } else { 15406 Slogf.w(LOG_TAG, "No saved token handle"); 15407 } 15408 } 15409 return false; 15410 } 15411 15412 @Override 15413 public boolean isCurrentInputMethodSetByOwner() { 15414 final CallerIdentity caller = getCallerIdentity(); 15415 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 15416 || isProfileOwner(caller) || isSystemUid(caller), 15417 "Only profile owner, device owner and system may call this method."); 15418 return getUserData(caller.getUserId()).mCurrentInputMethodSet; 15419 } 15420 15421 @Override 15422 public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) { 15423 final int userId = user.getIdentifier(); 15424 final CallerIdentity caller = getCallerIdentity(); 15425 Preconditions.checkCallAuthorization((userId == caller.getUserId()) 15426 || isProfileOwner(caller) || isDeviceOwner(caller) 15427 || hasFullCrossUsersPermission(caller, userId)); 15428 15429 synchronized (getLockObject()) { 15430 return new StringParceledListSlice( 15431 new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts)); 15432 } 15433 } 15434 15435 @Override 15436 public void clearApplicationUserData(ComponentName admin, String packageName, 15437 IPackageDataObserver callback) { 15438 Objects.requireNonNull(admin, "ComponentName is null"); 15439 Objects.requireNonNull(packageName, "packageName is null"); 15440 Objects.requireNonNull(callback, "callback is null"); 15441 15442 final CallerIdentity caller = getCallerIdentity(admin); 15443 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 15444 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CLEAR_APPLICATION_USER_DATA); 15445 15446 long ident = mInjector.binderClearCallingIdentity(); 15447 try { 15448 ActivityManager.getService().clearApplicationUserData(packageName, false, callback, 15449 caller.getUserId()); 15450 } catch(RemoteException re) { 15451 // Same process, should not happen. 15452 } catch (SecurityException se) { 15453 // This can happen e.g. for device admin packages, do not throw out the exception, 15454 // because callers have no means to know beforehand for which packages this might 15455 // happen. If so, we send back that removal failed. 15456 Slogf.w(LOG_TAG, "Not allowed to clear application user data for package " 15457 + packageName, se); 15458 try { 15459 callback.onRemoveCompleted(packageName, false); 15460 } catch (RemoteException re) { 15461 // Caller is no longer available, ignore 15462 } 15463 } finally { 15464 mInjector.binderRestoreCallingIdentity(ident); 15465 } 15466 } 15467 15468 @Override 15469 public void setLogoutEnabled(ComponentName admin, boolean enabled) { 15470 if (!mHasFeature) { 15471 return; 15472 } 15473 Objects.requireNonNull(admin, "ComponentName is null"); 15474 final CallerIdentity caller = getCallerIdentity(admin); 15475 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15476 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOGOUT_ENABLED); 15477 15478 synchronized (getLockObject()) { 15479 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 15480 if (deviceOwner.isLogoutEnabled == enabled) { 15481 // already in the requested state 15482 return; 15483 } 15484 deviceOwner.isLogoutEnabled = enabled; 15485 saveSettingsLocked(caller.getUserId()); 15486 } 15487 } 15488 15489 @Override 15490 public boolean isLogoutEnabled() { 15491 if (!mHasFeature) { 15492 return false; 15493 } 15494 synchronized (getLockObject()) { 15495 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 15496 return (deviceOwner != null) && deviceOwner.isLogoutEnabled; 15497 } 15498 } 15499 15500 @Override 15501 public List<String> getDisallowedSystemApps(ComponentName admin, int userId, 15502 String provisioningAction) throws RemoteException { 15503 Preconditions.checkCallAuthorization( 15504 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 15505 15506 return new ArrayList<>( 15507 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction)); 15508 } 15509 15510 @Override 15511 public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target, 15512 @Nullable PersistableBundle bundle) { 15513 if (!mHasFeature) { 15514 return; 15515 } 15516 Objects.requireNonNull(admin, "ComponentName is null"); 15517 Objects.requireNonNull(target, "Target cannot be null."); 15518 Preconditions.checkArgument(!admin.equals(target), 15519 "Provided administrator and target are the same object."); 15520 Preconditions.checkArgument(!admin.getPackageName().equals(target.getPackageName()), 15521 "Provided administrator and target have the same package name."); 15522 15523 final CallerIdentity caller = getCallerIdentity(admin); 15524 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)); 15525 15526 final int callingUserId = caller.getUserId(); 15527 final DevicePolicyData policy = getUserData(callingUserId); 15528 final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId, 15529 /* throwForMissingPermission= */ true); 15530 checkActiveAdminPrecondition(target, incomingDeviceInfo, policy); 15531 Preconditions.checkArgument(incomingDeviceInfo.supportsTransferOwnership(), 15532 "Provided target does not support ownership transfer."); 15533 15534 final long id = mInjector.binderClearCallingIdentity(); 15535 String ownerType = null; 15536 try { 15537 synchronized (getLockObject()) { 15538 /* 15539 * We must ensure the whole process is atomic to prevent the device from ending up 15540 * in an invalid state (e.g. no active admin). This could happen if the device 15541 * is rebooted or work mode is turned off mid-transfer. 15542 * In order to guarantee atomicity, we: 15543 * 15544 * 1. Save an atomic journal file describing the transfer process 15545 * 2. Perform the transfer itself 15546 * 3. Delete the journal file 15547 * 15548 * That way if the journal file exists on device boot, we know that the transfer 15549 * must be reverted back to the original administrator. This logic is implemented in 15550 * revertTransferOwnershipIfNecessaryLocked. 15551 * */ 15552 if (bundle == null) { 15553 bundle = new PersistableBundle(); 15554 } 15555 if (isProfileOwner(caller)) { 15556 ownerType = ADMIN_TYPE_PROFILE_OWNER; 15557 prepareTransfer(admin, target, bundle, callingUserId, 15558 ADMIN_TYPE_PROFILE_OWNER); 15559 transferProfileOwnershipLocked(admin, target, callingUserId); 15560 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 15561 getTransferOwnershipAdminExtras(bundle), callingUserId); 15562 postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId); 15563 if (isUserAffiliatedWithDeviceLocked(callingUserId)) { 15564 notifyAffiliatedProfileTransferOwnershipComplete(callingUserId); 15565 } 15566 } else if (isDeviceOwner(caller)) { 15567 ownerType = ADMIN_TYPE_DEVICE_OWNER; 15568 prepareTransfer(admin, target, bundle, callingUserId, 15569 ADMIN_TYPE_DEVICE_OWNER); 15570 transferDeviceOwnershipLocked(admin, target, callingUserId); 15571 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 15572 getTransferOwnershipAdminExtras(bundle)); 15573 postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId); 15574 } 15575 } 15576 } finally { 15577 mInjector.binderRestoreCallingIdentity(id); 15578 } 15579 DevicePolicyEventLogger 15580 .createEvent(DevicePolicyEnums.TRANSFER_OWNERSHIP) 15581 .setAdmin(admin) 15582 .setStrings(target.getPackageName(), ownerType) 15583 .write(); 15584 } 15585 15586 private void prepareTransfer(ComponentName admin, ComponentName target, 15587 PersistableBundle bundle, int callingUserId, String adminType) { 15588 saveTransferOwnershipBundleLocked(bundle, callingUserId); 15589 mTransferOwnershipMetadataManager.saveMetadataFile( 15590 new TransferOwnershipMetadataManager.Metadata(admin, target, 15591 callingUserId, adminType)); 15592 } 15593 15594 private void postTransfer(String broadcast, int callingUserId) { 15595 deleteTransferOwnershipMetadataFileLocked(); 15596 sendOwnerChangedBroadcast(broadcast, callingUserId); 15597 } 15598 15599 private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) { 15600 final Bundle extras = new Bundle(); 15601 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId)); 15602 sendDeviceOwnerCommand( 15603 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras); 15604 } 15605 15606 /** 15607 * Transfers the profile owner for user with id profileOwnerUserId from admin to target. 15608 */ 15609 private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target, 15610 int profileOwnerUserId) { 15611 transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId); 15612 mOwners.transferProfileOwner(target, profileOwnerUserId); 15613 Slogf.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId); 15614 mOwners.writeProfileOwner(profileOwnerUserId); 15615 mDeviceAdminServiceController.startServiceForOwner( 15616 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner"); 15617 } 15618 15619 /** 15620 * Transfers the device owner for user with id userId from admin to target. 15621 */ 15622 private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) { 15623 transferActiveAdminUncheckedLocked(target, admin, userId); 15624 mOwners.transferDeviceOwnership(target); 15625 Slogf.i(LOG_TAG, "Device owner set: " + target + " on user " + userId); 15626 mOwners.writeDeviceOwner(); 15627 mDeviceAdminServiceController.startServiceForOwner( 15628 target.getPackageName(), userId, "transfer-device-owner"); 15629 } 15630 15631 private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) { 15632 Bundle extras = new Bundle(); 15633 if (bundle != null) { 15634 extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle); 15635 } 15636 return extras; 15637 } 15638 15639 @Override 15640 public void setStartUserSessionMessage( 15641 ComponentName admin, CharSequence startUserSessionMessage) { 15642 if (!mHasFeature) { 15643 return; 15644 } 15645 Objects.requireNonNull(admin, "ComponentName is null"); 15646 final CallerIdentity caller = getCallerIdentity(admin); 15647 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15648 15649 final String startUserSessionMessageString = 15650 startUserSessionMessage != null ? startUserSessionMessage.toString() : null; 15651 15652 synchronized (getLockObject()) { 15653 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 15654 if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) { 15655 return; 15656 } 15657 deviceOwner.startUserSessionMessage = startUserSessionMessageString; 15658 saveSettingsLocked(caller.getUserId()); 15659 } 15660 15661 mInjector.getActivityManagerInternal() 15662 .setSwitchingFromSystemUserMessage(startUserSessionMessageString); 15663 } 15664 15665 @Override 15666 public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) { 15667 if (!mHasFeature) { 15668 return; 15669 } 15670 Objects.requireNonNull(admin, "ComponentName is null"); 15671 final CallerIdentity caller = getCallerIdentity(admin); 15672 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15673 15674 final String endUserSessionMessageString = 15675 endUserSessionMessage != null ? endUserSessionMessage.toString() : null; 15676 15677 synchronized (getLockObject()) { 15678 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 15679 if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) { 15680 return; 15681 } 15682 deviceOwner.endUserSessionMessage = endUserSessionMessageString; 15683 saveSettingsLocked(caller.getUserId()); 15684 } 15685 15686 mInjector.getActivityManagerInternal() 15687 .setSwitchingToSystemUserMessage(endUserSessionMessageString); 15688 } 15689 15690 @Override 15691 public String getStartUserSessionMessage(ComponentName admin) { 15692 if (!mHasFeature) { 15693 return null; 15694 } 15695 Objects.requireNonNull(admin, "ComponentName is null"); 15696 final CallerIdentity caller = getCallerIdentity(admin); 15697 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15698 15699 synchronized (getLockObject()) { 15700 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 15701 return deviceOwner.startUserSessionMessage; 15702 } 15703 } 15704 15705 @Override 15706 public String getEndUserSessionMessage(ComponentName admin) { 15707 if (!mHasFeature) { 15708 return null; 15709 } 15710 Objects.requireNonNull(admin, "ComponentName is null"); 15711 final CallerIdentity caller = getCallerIdentity(admin); 15712 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15713 15714 synchronized (getLockObject()) { 15715 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 15716 return deviceOwner.endUserSessionMessage; 15717 } 15718 } 15719 15720 private void deleteTransferOwnershipMetadataFileLocked() { 15721 mTransferOwnershipMetadataManager.deleteMetadataFile(); 15722 } 15723 15724 @Override 15725 @Nullable 15726 public PersistableBundle getTransferOwnershipBundle() { 15727 final CallerIdentity caller = getCallerIdentity(); 15728 Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller)); 15729 15730 synchronized (getLockObject()) { 15731 final int callingUserId = caller.getUserId(); 15732 final File bundleFile = new File( 15733 mInjector.environmentGetUserSystemDirectory(callingUserId), 15734 TRANSFER_OWNERSHIP_PARAMETERS_XML); 15735 if (!bundleFile.exists()) { 15736 return null; 15737 } 15738 try (FileInputStream stream = new FileInputStream(bundleFile)) { 15739 TypedXmlPullParser parser = Xml.resolvePullParser(stream); 15740 parser.next(); 15741 return PersistableBundle.restoreFromXml(parser); 15742 } catch (IOException | XmlPullParserException | IllegalArgumentException e) { 15743 Slogf.e(LOG_TAG, "Caught exception while trying to load the " 15744 + "owner transfer parameters from file " + bundleFile, e); 15745 return null; 15746 } 15747 } 15748 } 15749 15750 @Override 15751 public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) { 15752 if (!mHasFeature || !mHasTelephonyFeature) { 15753 return -1; 15754 } 15755 Objects.requireNonNull(who, "ComponentName is null"); 15756 Objects.requireNonNull(apnSetting, "ApnSetting is null in addOverrideApn"); 15757 final CallerIdentity caller = getCallerIdentity(who); 15758 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15759 15760 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class); 15761 if (tm != null) { 15762 return mInjector.binderWithCleanCallingIdentity( 15763 () -> tm.addDevicePolicyOverrideApn(mContext, apnSetting)); 15764 } else { 15765 Slogf.w(LOG_TAG, "TelephonyManager is null when trying to add override apn"); 15766 return Telephony.Carriers.INVALID_APN_ID; 15767 } 15768 } 15769 15770 @Override 15771 public boolean updateOverrideApn(@NonNull ComponentName who, int apnId, 15772 @NonNull ApnSetting apnSetting) { 15773 if (!mHasFeature || !mHasTelephonyFeature) { 15774 return false; 15775 } 15776 Objects.requireNonNull(who, "ComponentName is null"); 15777 Objects.requireNonNull(apnSetting, "ApnSetting is null in updateOverrideApn"); 15778 final CallerIdentity caller = getCallerIdentity(who); 15779 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15780 15781 if (apnId < 0) { 15782 return false; 15783 } 15784 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class); 15785 if (tm != null) { 15786 return mInjector.binderWithCleanCallingIdentity( 15787 () -> tm.modifyDevicePolicyOverrideApn(mContext, apnId, apnSetting)); 15788 } else { 15789 Slogf.w(LOG_TAG, "TelephonyManager is null when trying to modify override apn"); 15790 return false; 15791 } 15792 } 15793 15794 @Override 15795 public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) { 15796 if (!mHasFeature || !mHasTelephonyFeature) { 15797 return false; 15798 } 15799 Objects.requireNonNull(who, "ComponentName is null"); 15800 final CallerIdentity caller = getCallerIdentity(who); 15801 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15802 return removeOverrideApnUnchecked(apnId); 15803 } 15804 15805 private boolean removeOverrideApnUnchecked(int apnId) { 15806 if(apnId < 0) { 15807 return false; 15808 } 15809 int numDeleted = mInjector.binderWithCleanCallingIdentity( 15810 () -> mContext.getContentResolver().delete( 15811 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null)); 15812 return numDeleted > 0; 15813 } 15814 15815 @Override 15816 public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) { 15817 if (!mHasFeature || !mHasTelephonyFeature) { 15818 return Collections.emptyList(); 15819 } 15820 Objects.requireNonNull(who, "ComponentName is null"); 15821 final CallerIdentity caller = getCallerIdentity(who); 15822 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15823 return getOverrideApnsUnchecked(); 15824 } 15825 15826 private List<ApnSetting> getOverrideApnsUnchecked() { 15827 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class); 15828 if (tm != null) { 15829 return mInjector.binderWithCleanCallingIdentity( 15830 () -> tm.getDevicePolicyOverrideApns(mContext)); 15831 } 15832 Slogf.w(LOG_TAG, "TelephonyManager is null when trying to get override apns"); 15833 return Collections.emptyList(); 15834 } 15835 15836 @Override 15837 public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) { 15838 if (!mHasFeature || !mHasTelephonyFeature) { 15839 return; 15840 } 15841 Objects.requireNonNull(who, "ComponentName is null"); 15842 final CallerIdentity caller = getCallerIdentity(who); 15843 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15844 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_OVERRIDE_APNS_ENABLED); 15845 15846 setOverrideApnsEnabledUnchecked(enabled); 15847 } 15848 15849 private void setOverrideApnsEnabledUnchecked(boolean enabled) { 15850 ContentValues value = new ContentValues(); 15851 value.put(ENFORCE_KEY, enabled); 15852 mInjector.binderWithCleanCallingIdentity(() -> mContext.getContentResolver().update( 15853 ENFORCE_MANAGED_URI, value, null, null)); 15854 } 15855 15856 @Override 15857 public boolean isOverrideApnEnabled(@NonNull ComponentName who) { 15858 if (!mHasFeature || !mHasTelephonyFeature) { 15859 return false; 15860 } 15861 Objects.requireNonNull(who, "ComponentName is null"); 15862 final CallerIdentity caller = getCallerIdentity(who); 15863 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15864 15865 Cursor enforceCursor = mInjector.binderWithCleanCallingIdentity( 15866 () -> mContext.getContentResolver().query( 15867 ENFORCE_MANAGED_URI, null, null, null, null)); 15868 15869 if (enforceCursor == null) { 15870 return false; 15871 } 15872 try { 15873 if (enforceCursor.moveToFirst()) { 15874 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1; 15875 } 15876 } catch (IllegalArgumentException e) { 15877 Slogf.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain " 15878 + "correct info.", e); 15879 } finally { 15880 enforceCursor.close(); 15881 } 15882 return false; 15883 } 15884 15885 @VisibleForTesting 15886 void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) { 15887 final File parametersFile = new File( 15888 mInjector.environmentGetUserSystemDirectory(userId), 15889 TRANSFER_OWNERSHIP_PARAMETERS_XML); 15890 final AtomicFile atomicFile = new AtomicFile(parametersFile); 15891 FileOutputStream stream = null; 15892 try { 15893 stream = atomicFile.startWrite(); 15894 final TypedXmlSerializer serializer = Xml.resolveSerializer(stream); 15895 serializer.startDocument(null, true); 15896 serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 15897 bundle.saveToXml(serializer); 15898 serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 15899 serializer.endDocument(); 15900 atomicFile.finishWrite(stream); 15901 } catch (IOException | XmlPullParserException e) { 15902 Slogf.e(LOG_TAG, "Caught exception while trying to save the " 15903 + "owner transfer parameters to file " + parametersFile, e); 15904 parametersFile.delete(); 15905 atomicFile.failWrite(stream); 15906 } 15907 } 15908 15909 void deleteTransferOwnershipBundleLocked(int userId) { 15910 final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId), 15911 TRANSFER_OWNERSHIP_PARAMETERS_XML); 15912 parametersFile.delete(); 15913 } 15914 15915 private void logPasswordQualitySetIfSecurityLogEnabled(ComponentName who, int userId, 15916 boolean parent, PasswordPolicy passwordPolicy) { 15917 if (SecurityLog.isLoggingEnabled()) { 15918 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 15919 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(), 15920 userId, affectedUserId, passwordPolicy.length, passwordPolicy.quality, 15921 passwordPolicy.letters, passwordPolicy.nonLetter, passwordPolicy.numeric, 15922 passwordPolicy.upperCase, passwordPolicy.lowerCase, passwordPolicy.symbols); 15923 } 15924 } 15925 15926 private static String getManagedProvisioningPackage(Context context) { 15927 return context.getResources().getString(R.string.config_managed_provisioning_package); 15928 } 15929 15930 private void putPrivateDnsSettings(int mode, @Nullable String host) { 15931 // Set Private DNS settings using system permissions, as apps cannot write 15932 // to global settings. 15933 mInjector.binderWithCleanCallingIdentity(() -> { 15934 ConnectivitySettingsManager.setPrivateDnsMode(mContext, mode); 15935 ConnectivitySettingsManager.setPrivateDnsHostname(mContext, host); 15936 }); 15937 } 15938 15939 @Override 15940 public int setGlobalPrivateDns(@NonNull ComponentName who, int mode, String privateDnsHost) { 15941 if (!mHasFeature) { 15942 return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING; 15943 } 15944 Objects.requireNonNull(who, "ComponentName is null"); 15945 final CallerIdentity caller = getCallerIdentity(who); 15946 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15947 checkAllUsersAreAffiliatedWithDevice(); 15948 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_GLOBAL_PRIVATE_DNS); 15949 15950 switch (mode) { 15951 case PRIVATE_DNS_MODE_OPPORTUNISTIC: 15952 if (!TextUtils.isEmpty(privateDnsHost)) { 15953 throw new IllegalArgumentException( 15954 "Host provided for opportunistic mode, but is not needed."); 15955 } 15956 putPrivateDnsSettings(ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC, 15957 null); 15958 return PRIVATE_DNS_SET_NO_ERROR; 15959 case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME: 15960 if (TextUtils.isEmpty(privateDnsHost) 15961 || !NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) { 15962 throw new IllegalArgumentException( 15963 String.format("Provided hostname %s is not valid", privateDnsHost)); 15964 } 15965 15966 // Connectivity check will have been performed in the DevicePolicyManager before 15967 // the call here. 15968 putPrivateDnsSettings( 15969 ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, 15970 privateDnsHost); 15971 return PRIVATE_DNS_SET_NO_ERROR; 15972 default: 15973 throw new IllegalArgumentException( 15974 String.format("Provided mode, %d, is not a valid mode.", mode)); 15975 } 15976 } 15977 15978 @Override 15979 public int getGlobalPrivateDnsMode(@NonNull ComponentName who) { 15980 if (!mHasFeature) { 15981 return PRIVATE_DNS_MODE_UNKNOWN; 15982 } 15983 Objects.requireNonNull(who, "ComponentName is null"); 15984 final CallerIdentity caller = getCallerIdentity(who); 15985 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 15986 15987 final int currentMode = ConnectivitySettingsManager.getPrivateDnsMode(mContext); 15988 switch (currentMode) { 15989 case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OFF: 15990 return PRIVATE_DNS_MODE_OFF; 15991 case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC: 15992 return PRIVATE_DNS_MODE_OPPORTUNISTIC; 15993 case ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME: 15994 return PRIVATE_DNS_MODE_PROVIDER_HOSTNAME; 15995 } 15996 15997 return PRIVATE_DNS_MODE_UNKNOWN; 15998 } 15999 16000 @Override 16001 public String getGlobalPrivateDnsHost(@NonNull ComponentName who) { 16002 if (!mHasFeature) { 16003 return null; 16004 } 16005 Objects.requireNonNull(who, "ComponentName is null"); 16006 final CallerIdentity caller = getCallerIdentity(who); 16007 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 16008 return mInjector.settingsGlobalGetString(PRIVATE_DNS_SPECIFIER); 16009 } 16010 16011 @Override 16012 public void installUpdateFromFile(ComponentName admin, 16013 ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback) { 16014 Objects.requireNonNull(admin, "ComponentName is null"); 16015 16016 final CallerIdentity caller = getCallerIdentity(admin); 16017 Preconditions.checkCallAuthorization(isDeviceOwner(caller) 16018 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 16019 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_SYSTEM_UPDATE); 16020 16021 DevicePolicyEventLogger 16022 .createEvent(DevicePolicyEnums.INSTALL_SYSTEM_UPDATE) 16023 .setAdmin(caller.getComponentName()) 16024 .setBoolean(isDeviceAB()) 16025 .write(); 16026 16027 mInjector.binderWithCleanCallingIdentity(() -> { 16028 UpdateInstaller updateInstaller; 16029 if (isDeviceAB()) { 16030 updateInstaller = new AbUpdateInstaller( 16031 mContext, updateFileDescriptor, callback, mInjector, mConstants); 16032 } else { 16033 updateInstaller = new NonAbUpdateInstaller( 16034 mContext, updateFileDescriptor, callback, mInjector, mConstants); 16035 } 16036 updateInstaller.startInstallUpdate(); 16037 }); 16038 } 16039 16040 private boolean isDeviceAB() { 16041 return "true".equalsIgnoreCase(android.os.SystemProperties 16042 .get(AB_DEVICE_KEY, "")); 16043 } 16044 16045 @Override 16046 public void setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames) { 16047 if (!mHasFeature) { 16048 return; 16049 } 16050 Objects.requireNonNull(who, "ComponentName is null"); 16051 final CallerIdentity caller = getCallerIdentity(who); 16052 16053 synchronized (getLockObject()) { 16054 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16055 admin.mCrossProfileCalendarPackages = packageNames; 16056 saveSettingsLocked(caller.getUserId()); 16057 } 16058 DevicePolicyEventLogger 16059 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALENDAR_PACKAGES) 16060 .setAdmin(who) 16061 .setStrings(packageNames == null ? null 16062 : packageNames.toArray(new String[packageNames.size()])) 16063 .write(); 16064 } 16065 16066 @Override 16067 public List<String> getCrossProfileCalendarPackages(ComponentName who) { 16068 if (!mHasFeature) { 16069 return Collections.emptyList(); 16070 } 16071 Objects.requireNonNull(who, "ComponentName is null"); 16072 final CallerIdentity caller = getCallerIdentity(who); 16073 16074 synchronized (getLockObject()) { 16075 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16076 return admin.mCrossProfileCalendarPackages; 16077 } 16078 } 16079 16080 @Override 16081 public boolean isPackageAllowedToAccessCalendarForUser(String packageName, 16082 int userHandle) { 16083 if (!mHasFeature) { 16084 return false; 16085 } 16086 Preconditions.checkStringNotEmpty(packageName, "Package name is null or empty"); 16087 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 16088 16089 final CallerIdentity caller = getCallerIdentity(); 16090 final int packageUid = mInjector.binderWithCleanCallingIdentity(() -> { 16091 try { 16092 return mInjector.getPackageManager().getPackageUidAsUser(packageName, userHandle); 16093 } catch (NameNotFoundException e) { 16094 Slogf.w(LOG_TAG, e, 16095 "Couldn't find package %s in user %d", packageName, userHandle); 16096 return -1; 16097 } 16098 }); 16099 if (caller.getUid() != packageUid) { 16100 Preconditions.checkCallAuthorization( 16101 hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS) 16102 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL)); 16103 } 16104 16105 synchronized (getLockObject()) { 16106 if (mInjector.settingsSecureGetIntForUser( 16107 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userHandle) == 0) { 16108 return false; 16109 } 16110 final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 16111 if (admin != null) { 16112 if (admin.mCrossProfileCalendarPackages == null) { 16113 return true; 16114 } 16115 return admin.mCrossProfileCalendarPackages.contains(packageName); 16116 } 16117 } 16118 return false; 16119 } 16120 16121 @Override 16122 public List<String> getCrossProfileCalendarPackagesForUser(int userHandle) { 16123 if (!mHasFeature) { 16124 return Collections.emptyList(); 16125 } 16126 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 16127 Preconditions.checkCallAuthorization( 16128 hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS) 16129 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL)); 16130 16131 synchronized (getLockObject()) { 16132 final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 16133 if (admin != null) { 16134 return admin.mCrossProfileCalendarPackages; 16135 } 16136 } 16137 return Collections.emptyList(); 16138 } 16139 16140 @Override 16141 public void setCrossProfilePackages(ComponentName who, List<String> packageNames) { 16142 if (!mHasFeature) { 16143 return; 16144 } 16145 Objects.requireNonNull(who, "ComponentName is null"); 16146 Objects.requireNonNull(packageNames, "Package names is null"); 16147 final CallerIdentity caller = getCallerIdentity(who); 16148 16149 final List<String> previousCrossProfilePackages; 16150 synchronized (getLockObject()) { 16151 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16152 previousCrossProfilePackages = admin.mCrossProfilePackages; 16153 if (packageNames.equals(previousCrossProfilePackages)) { 16154 return; 16155 } 16156 admin.mCrossProfilePackages = packageNames; 16157 saveSettingsLocked(caller.getUserId()); 16158 } 16159 logSetCrossProfilePackages(who, packageNames); 16160 final CrossProfileApps crossProfileApps = mContext.getSystemService(CrossProfileApps.class); 16161 mInjector.binderWithCleanCallingIdentity( 16162 () -> crossProfileApps.resetInteractAcrossProfilesAppOps( 16163 previousCrossProfilePackages, new HashSet<>(packageNames))); 16164 } 16165 16166 private void logSetCrossProfilePackages(ComponentName who, List<String> packageNames) { 16167 DevicePolicyEventLogger 16168 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_PACKAGES) 16169 .setAdmin(who) 16170 .setStrings(packageNames.toArray(new String[packageNames.size()])) 16171 .write(); 16172 } 16173 16174 @Override 16175 public List<String> getCrossProfilePackages(ComponentName who) { 16176 if (!mHasFeature) { 16177 return Collections.emptyList(); 16178 } 16179 Objects.requireNonNull(who, "ComponentName is null"); 16180 final CallerIdentity caller = getCallerIdentity(who); 16181 16182 synchronized (getLockObject()) { 16183 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16184 return admin.mCrossProfilePackages; 16185 } 16186 } 16187 16188 @Override 16189 public List<String> getAllCrossProfilePackages() { 16190 if (!mHasFeature) { 16191 return Collections.emptyList(); 16192 } 16193 final CallerIdentity caller = getCallerIdentity(); 16194 Preconditions.checkCallAuthorization( 16195 isSystemUid(caller) || isRootUid(caller) || hasCallingPermission( 16196 permission.INTERACT_ACROSS_USERS) || hasCallingPermission( 16197 permission.INTERACT_ACROSS_USERS_FULL) || hasPermissionForPreflight( 16198 caller, permission.INTERACT_ACROSS_PROFILES)); 16199 16200 synchronized (getLockObject()) { 16201 final List<ActiveAdmin> admins = getProfileOwnerAdminsForCurrentProfileGroup(); 16202 final List<String> packages = getCrossProfilePackagesForAdmins(admins); 16203 16204 packages.addAll(getDefaultCrossProfilePackages()); 16205 16206 return packages; 16207 } 16208 } 16209 16210 private List<String> getCrossProfilePackagesForAdmins(List<ActiveAdmin> admins) { 16211 final List<String> packages = new ArrayList<>(); 16212 for (int i = 0; i < admins.size(); i++) { 16213 packages.addAll(admins.get(i).mCrossProfilePackages); 16214 } 16215 return packages; 16216 } 16217 16218 @Override 16219 public List<String> getDefaultCrossProfilePackages() { 16220 Set<String> crossProfilePackages = new HashSet<>(); 16221 16222 Collections.addAll(crossProfilePackages, mContext.getResources() 16223 .getStringArray(R.array.cross_profile_apps)); 16224 Collections.addAll(crossProfilePackages, mContext.getResources() 16225 .getStringArray(R.array.vendor_cross_profile_apps)); 16226 16227 return new ArrayList<>(crossProfilePackages); 16228 } 16229 16230 private List<ActiveAdmin> getProfileOwnerAdminsForCurrentProfileGroup() { 16231 synchronized (getLockObject()) { 16232 final List<ActiveAdmin> admins = new ArrayList<>(); 16233 int[] users = mUserManager.getProfileIdsWithDisabled( 16234 mInjector.userHandleGetCallingUserId()); 16235 for (int i = 0; i < users.length; i++) { 16236 final ComponentName componentName = getProfileOwnerAsUser(users[i]); 16237 if (componentName != null) { 16238 ActiveAdmin admin = getActiveAdminUncheckedLocked(componentName, users[i]); 16239 if (admin != null) { 16240 admins.add(admin); 16241 } 16242 } 16243 } 16244 return admins; 16245 } 16246 } 16247 16248 @Override 16249 public boolean isManagedKiosk() { 16250 if (!mHasFeature) { 16251 return false; 16252 } 16253 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 16254 16255 long id = mInjector.binderClearCallingIdentity(); 16256 try { 16257 return isManagedKioskInternal(); 16258 } catch (RemoteException e) { 16259 throw new IllegalStateException(e); 16260 } finally { 16261 mInjector.binderRestoreCallingIdentity(id); 16262 } 16263 } 16264 16265 private boolean isUnattendedManagedKioskUnchecked() { 16266 try { 16267 return isManagedKioskInternal() 16268 && getPowerManagerInternal().wasDeviceIdleFor(UNATTENDED_MANAGED_KIOSK_MS); 16269 } catch (RemoteException e) { 16270 throw new IllegalStateException(e); 16271 } 16272 } 16273 16274 @Override 16275 public boolean isUnattendedManagedKiosk() { 16276 if (!mHasFeature) { 16277 return false; 16278 } 16279 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 16280 16281 return mInjector.binderWithCleanCallingIdentity(() -> isUnattendedManagedKioskUnchecked()); 16282 } 16283 16284 /** 16285 * Returns whether the device is currently being used as a publicly-accessible dedicated device. 16286 * Assumes that feature checks and permission checks have already been performed, and that the 16287 * calling identity has been cleared. 16288 */ 16289 private boolean isManagedKioskInternal() throws RemoteException { 16290 return mOwners.hasDeviceOwner() 16291 && mInjector.getIActivityManager().getLockTaskModeState() 16292 == ActivityManager.LOCK_TASK_MODE_LOCKED 16293 && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO) 16294 && !deviceHasKeyguard() 16295 && !inEphemeralUserSession(); 16296 } 16297 16298 private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException { 16299 //TODO(b/175285301): Explicitly get the user's identity to check. 16300 int lockTaskFeatures = 16301 getUserData(getCurrentForegroundUserId()).mLockTaskFeatures; 16302 return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature; 16303 } 16304 16305 private boolean deviceHasKeyguard() { 16306 for (UserInfo userInfo : mUserManager.getUsers()) { 16307 if (mLockPatternUtils.isSecure(userInfo.id)) { 16308 return true; 16309 } 16310 } 16311 return false; 16312 } 16313 16314 private boolean inEphemeralUserSession() { 16315 for (UserInfo userInfo : mUserManager.getUsers()) { 16316 if (mInjector.getUserManager().isUserEphemeral(userInfo.id)) { 16317 return true; 16318 } 16319 } 16320 return false; 16321 } 16322 16323 private PowerManagerInternal getPowerManagerInternal() { 16324 return mInjector.getPowerManagerInternal(); 16325 } 16326 16327 @Override 16328 public boolean startViewCalendarEventInManagedProfile(String packageName, long eventId, 16329 long start, long end, boolean allDay, int flags) { 16330 if (!mHasFeature) { 16331 return false; 16332 } 16333 Preconditions.checkStringNotEmpty(packageName, "Package name is empty"); 16334 16335 final CallerIdentity caller = getCallerIdentity(); 16336 if (!isCallingFromPackage(packageName, caller.getUid())) { 16337 throw new SecurityException("Input package name doesn't align with actual " 16338 + "calling package."); 16339 } 16340 return mInjector.binderWithCleanCallingIdentity(() -> { 16341 final int workProfileUserId = getManagedUserId(caller.getUserId()); 16342 if (workProfileUserId < 0) { 16343 return false; 16344 } 16345 if (!isPackageAllowedToAccessCalendarForUser(packageName, workProfileUserId)) { 16346 Slogf.d(LOG_TAG, "Package %s is not allowed to access cross-profile calendar APIs", 16347 packageName); 16348 return false; 16349 } 16350 final Intent intent = new Intent( 16351 CalendarContract.ACTION_VIEW_MANAGED_PROFILE_CALENDAR_EVENT); 16352 intent.setPackage(packageName); 16353 intent.putExtra(CalendarContract.EXTRA_EVENT_ID, eventId); 16354 intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start); 16355 intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end); 16356 intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay); 16357 intent.setFlags(flags); 16358 try { 16359 mContext.startActivityAsUser(intent, UserHandle.of(workProfileUserId)); 16360 } catch (ActivityNotFoundException e) { 16361 Slogf.e(LOG_TAG, "View event activity not found", e); 16362 return false; 16363 } 16364 return true; 16365 }); 16366 } 16367 16368 private boolean isCallingFromPackage(String packageName, int callingUid) { 16369 return mInjector.binderWithCleanCallingIdentity(() -> { 16370 try { 16371 final int packageUid = mInjector.getPackageManager().getPackageUidAsUser( 16372 packageName, UserHandle.getUserId(callingUid)); 16373 return packageUid == callingUid; 16374 } catch (NameNotFoundException e) { 16375 Slogf.d(LOG_TAG, "Calling package not found", e); 16376 return false; 16377 } 16378 }); 16379 } 16380 16381 private DevicePolicyConstants loadConstants() { 16382 return DevicePolicyConstants.loadFromString( 16383 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS)); 16384 } 16385 16386 @Override 16387 public void setUserControlDisabledPackages(ComponentName who, List<String> packages) { 16388 Objects.requireNonNull(who, "ComponentName is null"); 16389 Objects.requireNonNull(packages, "packages is null"); 16390 final CallerIdentity caller = getCallerIdentity(who); 16391 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 16392 checkCanExecuteOrThrowUnsafe( 16393 DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES); 16394 16395 synchronized (getLockObject()) { 16396 mOwners.setDeviceOwnerProtectedPackages(who.getPackageName(), packages); 16397 DevicePolicyEventLogger 16398 .createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES) 16399 .setAdmin(who) 16400 .setStrings(packages.toArray(new String[packages.size()])) 16401 .write(); 16402 } 16403 } 16404 16405 @Override 16406 public List<String> getUserControlDisabledPackages(ComponentName who) { 16407 Objects.requireNonNull(who, "ComponentName is null"); 16408 16409 final CallerIdentity caller = getCallerIdentity(who); 16410 Preconditions.checkCallAuthorization(isDeviceOwner(caller)); 16411 16412 synchronized (getLockObject()) { 16413 return mOwners.getDeviceOwnerProtectedPackages(who.getPackageName()); 16414 } 16415 } 16416 16417 @Override 16418 public void setCommonCriteriaModeEnabled(ComponentName who, boolean enabled) { 16419 Objects.requireNonNull(who, "Admin component name must be provided"); 16420 final CallerIdentity caller = getCallerIdentity(who); 16421 Preconditions.checkCallAuthorization( 16422 isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller), 16423 "Common Criteria mode can only be controlled by a device owner or " 16424 + "a profile owner on an organization-owned device."); 16425 synchronized (getLockObject()) { 16426 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 16427 admin.mCommonCriteriaMode = enabled; 16428 saveSettingsLocked(caller.getUserId()); 16429 } 16430 DevicePolicyEventLogger 16431 .createEvent(DevicePolicyEnums.SET_COMMON_CRITERIA_MODE) 16432 .setAdmin(who) 16433 .setBoolean(enabled) 16434 .write(); 16435 } 16436 16437 @Override 16438 public boolean isCommonCriteriaModeEnabled(ComponentName who) { 16439 if (who != null) { 16440 final CallerIdentity caller = getCallerIdentity(who); 16441 Preconditions.checkCallAuthorization( 16442 isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller), 16443 "Common Criteria mode can only be controlled by a device owner or " 16444 + "a profile owner on an organization-owned device."); 16445 16446 synchronized (getLockObject()) { 16447 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 16448 return admin.mCommonCriteriaMode; 16449 } 16450 } 16451 // Return aggregated state if caller is not admin (who == null). 16452 synchronized (getLockObject()) { 16453 // Only DO or COPE PO can turn on CC mode, so take a shortcut here and only look at 16454 // their ActiveAdmin, instead of iterating through all admins. 16455 final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 16456 UserHandle.USER_SYSTEM); 16457 return admin != null ? admin.mCommonCriteriaMode : false; 16458 } 16459 } 16460 16461 @Override 16462 public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(ComponentName who) { 16463 Objects.requireNonNull(who, "ComponentName is null"); 16464 16465 final CallerIdentity caller = getCallerIdentity(who); 16466 // DO shouldn't be able to use this method. 16467 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 16468 16469 synchronized (getLockObject()) { 16470 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16471 final long deadline = admin.mProfileOffDeadline; 16472 final int result = makeSuspensionReasons(admin.mSuspendPersonalApps, 16473 deadline != 0 && mInjector.systemCurrentTimeMillis() > deadline); 16474 Slogf.d(LOG_TAG, "getPersonalAppsSuspendedReasons user: %d; result: %d", 16475 mInjector.userHandleGetCallingUserId(), result); 16476 return result; 16477 } 16478 } 16479 16480 private @PersonalAppsSuspensionReason int makeSuspensionReasons( 16481 boolean explicit, boolean timeout) { 16482 int result = PERSONAL_APPS_NOT_SUSPENDED; 16483 if (explicit) { 16484 result |= PERSONAL_APPS_SUSPENDED_EXPLICITLY; 16485 } 16486 if (timeout) { 16487 result |= PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT; 16488 } 16489 return result; 16490 } 16491 16492 @Override 16493 public void setPersonalAppsSuspended(ComponentName who, boolean suspended) { 16494 Objects.requireNonNull(who, "ComponentName is null"); 16495 16496 final CallerIdentity caller = getCallerIdentity(who); 16497 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 16498 Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller)); 16499 16500 final int callingUserId = caller.getUserId(); 16501 synchronized (getLockObject()) { 16502 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16503 boolean shouldSaveSettings = false; 16504 if (admin.mSuspendPersonalApps != suspended) { 16505 admin.mSuspendPersonalApps = suspended; 16506 shouldSaveSettings = true; 16507 } 16508 if (admin.mProfileOffDeadline != 0) { 16509 admin.mProfileOffDeadline = 0; 16510 shouldSaveSettings = true; 16511 } 16512 if (shouldSaveSettings) { 16513 saveSettingsLocked(callingUserId); 16514 } 16515 } 16516 16517 mInjector.binderWithCleanCallingIdentity(() -> updatePersonalAppsSuspension( 16518 callingUserId, mUserManager.isUserUnlocked(callingUserId))); 16519 16520 DevicePolicyEventLogger 16521 .createEvent(DevicePolicyEnums.SET_PERSONAL_APPS_SUSPENDED) 16522 .setAdmin(caller.getComponentName()) 16523 .setBoolean(suspended) 16524 .write(); 16525 } 16526 16527 /** Starts an activity to check policy compliance or request compliance acknowledgement. */ 16528 private void triggerPolicyComplianceCheckIfNeeded(int profileUserId, boolean suspended) { 16529 synchronized (getLockObject()) { 16530 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId); 16531 if (profileOwner == null) { 16532 Slogf.wtf(LOG_TAG, "Profile owner not found for compliance check"); 16533 return; 16534 } 16535 if (suspended) { 16536 // If suspended, DPC will need to show an activity. 16537 final Intent intent = new Intent(ACTION_CHECK_POLICY_COMPLIANCE); 16538 intent.setPackage(profileOwner.info.getPackageName()); 16539 mContext.startActivityAsUser(intent, UserHandle.of(profileUserId)); 16540 } else if (profileOwner.mProfileOffDeadline > 0) { 16541 // If not suspended, but deadline set, DPC needs to acknowledge compliance so that 16542 // the deadline can be reset. 16543 sendAdminCommandLocked(profileOwner, ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED, 16544 /* adminExtras= */ null, /* receiver= */ null, /* inForeground = */ true); 16545 } 16546 } 16547 } 16548 16549 /** 16550 * Checks whether personal apps should be suspended according to the policy and applies the 16551 * change if needed. 16552 * 16553 * @param unlocked whether the profile is currently running unlocked. 16554 */ 16555 private boolean updatePersonalAppsSuspension(int profileUserId, boolean unlocked) { 16556 final boolean shouldSuspend; 16557 synchronized (getLockObject()) { 16558 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId); 16559 if (profileOwner != null) { 16560 final int notificationState = 16561 updateProfileOffDeadlineLocked(profileUserId, profileOwner, unlocked); 16562 final boolean suspendedExplicitly = profileOwner.mSuspendPersonalApps; 16563 final boolean suspendedByTimeout = profileOwner.mProfileOffDeadline == -1; 16564 Slogf.d(LOG_TAG, 16565 "Personal apps suspended explicitly: %b, by timeout: %b, notification: %d", 16566 suspendedExplicitly, suspendedByTimeout, notificationState); 16567 updateProfileOffDeadlineNotificationLocked( 16568 profileUserId, profileOwner, notificationState); 16569 shouldSuspend = suspendedExplicitly || suspendedByTimeout; 16570 } else { 16571 shouldSuspend = false; 16572 } 16573 } 16574 16575 final int parentUserId = getProfileParentId(profileUserId); 16576 suspendPersonalAppsInternal(parentUserId, shouldSuspend); 16577 return shouldSuspend; 16578 } 16579 16580 /** 16581 * Checks work profile time off policy, scheduling personal apps suspension via alarm if 16582 * necessary. 16583 * @return notification state 16584 */ 16585 private int updateProfileOffDeadlineLocked( 16586 int profileUserId, ActiveAdmin profileOwner, boolean unlocked) { 16587 final long now = mInjector.systemCurrentTimeMillis(); 16588 if (profileOwner.mProfileOffDeadline != 0 && now > profileOwner.mProfileOffDeadline) { 16589 Slogf.i(LOG_TAG, "Profile off deadline has been reached, unlocked: " + unlocked); 16590 if (profileOwner.mProfileOffDeadline != -1) { 16591 // Move the deadline far to the past so that it cannot be rolled back by TZ change. 16592 profileOwner.mProfileOffDeadline = -1; 16593 saveSettingsLocked(profileUserId); 16594 } 16595 return unlocked ? PROFILE_OFF_NOTIFICATION_NONE : PROFILE_OFF_NOTIFICATION_SUSPENDED; 16596 } 16597 boolean shouldSaveSettings = false; 16598 if (profileOwner.mSuspendPersonalApps) { 16599 // When explicit suspension is active, deadline shouldn't be set. 16600 if (profileOwner.mProfileOffDeadline != 0) { 16601 profileOwner.mProfileOffDeadline = 0; 16602 shouldSaveSettings = true; 16603 } 16604 } else if (profileOwner.mProfileOffDeadline != 0 16605 && (profileOwner.mProfileMaximumTimeOffMillis == 0)) { 16606 // There is a deadline but either there is no policy -> clear 16607 // the deadline. 16608 Slogf.i(LOG_TAG, "Profile off deadline is reset to zero"); 16609 profileOwner.mProfileOffDeadline = 0; 16610 shouldSaveSettings = true; 16611 } else if (profileOwner.mProfileOffDeadline == 0 16612 && (profileOwner.mProfileMaximumTimeOffMillis != 0 && !unlocked)) { 16613 // There profile is locked and there is a policy, but the deadline is not set -> set the 16614 // deadline. 16615 Slogf.i(LOG_TAG, "Profile off deadline is set."); 16616 profileOwner.mProfileOffDeadline = now + profileOwner.mProfileMaximumTimeOffMillis; 16617 shouldSaveSettings = true; 16618 } 16619 16620 if (shouldSaveSettings) { 16621 saveSettingsLocked(profileUserId); 16622 } 16623 16624 final long alarmTime; 16625 final int notificationState; 16626 if (unlocked || profileOwner.mProfileOffDeadline == 0) { 16627 alarmTime = 0; 16628 notificationState = PROFILE_OFF_NOTIFICATION_NONE; 16629 } else if (profileOwner.mProfileOffDeadline - now < MANAGED_PROFILE_OFF_WARNING_PERIOD) { 16630 // The deadline is close, upon the alarm personal apps should be suspended. 16631 alarmTime = profileOwner.mProfileOffDeadline; 16632 notificationState = PROFILE_OFF_NOTIFICATION_WARNING; 16633 } else { 16634 // The deadline is quite far, upon the alarm we should warn the user first, so the 16635 // alarm is scheduled earlier than the actual deadline. 16636 alarmTime = profileOwner.mProfileOffDeadline - MANAGED_PROFILE_OFF_WARNING_PERIOD; 16637 notificationState = PROFILE_OFF_NOTIFICATION_NONE; 16638 } 16639 16640 final AlarmManager am = mInjector.getAlarmManager(); 16641 final Intent intent = new Intent(ACTION_PROFILE_OFF_DEADLINE); 16642 intent.setPackage(mContext.getPackageName()); 16643 // Broadcast alarms sent by system are immutable 16644 final PendingIntent pi = mInjector.pendingIntentGetBroadcast( 16645 mContext, REQUEST_PROFILE_OFF_DEADLINE, intent, 16646 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT 16647 | PendingIntent.FLAG_IMMUTABLE); 16648 16649 if (alarmTime == 0) { 16650 Slogf.i(LOG_TAG, "Profile off deadline alarm is removed."); 16651 am.cancel(pi); 16652 } else { 16653 Slogf.i(LOG_TAG, "Profile off deadline alarm is set."); 16654 am.set(AlarmManager.RTC, alarmTime, pi); 16655 } 16656 16657 return notificationState; 16658 } 16659 16660 private void suspendPersonalAppsInternal(int userId, boolean suspended) { 16661 if (getUserData(userId).mAppsSuspended == suspended) { 16662 return; 16663 } 16664 Slogf.i(LOG_TAG, "%s personal apps for user %d", suspended ? "Suspending" : "Unsuspending", 16665 userId); 16666 16667 if (suspended) { 16668 suspendPersonalAppsInPackageManager(userId); 16669 } else { 16670 mInjector.getPackageManagerInternal().unsuspendForSuspendingPackage( 16671 PLATFORM_PACKAGE_NAME, userId); 16672 } 16673 16674 synchronized (getLockObject()) { 16675 getUserData(userId).mAppsSuspended = suspended; 16676 saveSettingsLocked(userId); 16677 } 16678 } 16679 16680 private void suspendPersonalAppsInPackageManager(int userId) { 16681 mInjector.binderWithCleanCallingIdentity(() -> { 16682 try { 16683 final String[] appsToSuspend = mInjector.getPersonalAppsForSuspension(userId); 16684 final String[] failedApps = mIPackageManager.setPackagesSuspendedAsUser( 16685 appsToSuspend, true, null, null, null, PLATFORM_PACKAGE_NAME, userId); 16686 if (!ArrayUtils.isEmpty(failedApps)) { 16687 Slogf.wtf(LOG_TAG, "Failed to suspend apps: " + String.join(",", failedApps)); 16688 } 16689 } catch (RemoteException re) { 16690 // Shouldn't happen. 16691 Slogf.e(LOG_TAG, "Failed talking to the package manager", re); 16692 } 16693 }); 16694 } 16695 16696 @GuardedBy("getLockObject()") 16697 private void updateProfileOffDeadlineNotificationLocked( 16698 int profileUserId, ActiveAdmin profileOwner, int notificationState) { 16699 if (notificationState == PROFILE_OFF_NOTIFICATION_NONE) { 16700 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED); 16701 return; 16702 } 16703 16704 final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION); 16705 intent.setPackage(mContext.getPackageName()); 16706 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 16707 16708 // Simple notification action button clicks are immutable 16709 final PendingIntent pendingIntent = mInjector.pendingIntentGetBroadcast(mContext, 16710 0 /* requestCode */, intent, 16711 PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); 16712 16713 final String buttonText = 16714 mContext.getString(R.string.personal_apps_suspended_turn_profile_on); 16715 final Notification.Action turnProfileOnButton = 16716 new Notification.Action.Builder(null /* icon */, buttonText, pendingIntent).build(); 16717 16718 final String text; 16719 final boolean ongoing; 16720 if (notificationState == PROFILE_OFF_NOTIFICATION_WARNING) { 16721 // Round to the closest integer number of days. 16722 final int maxDays = (int) 16723 ((profileOwner.mProfileMaximumTimeOffMillis + MS_PER_DAY / 2) / MS_PER_DAY); 16724 final String date = DateUtils.formatDateTime( 16725 mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_DATE); 16726 final String time = DateUtils.formatDateTime( 16727 mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_TIME); 16728 text = mContext.getString( 16729 R.string.personal_apps_suspension_soon_text, date, time, maxDays); 16730 ongoing = false; 16731 } else { 16732 text = mContext.getString(R.string.personal_apps_suspension_text); 16733 ongoing = true; 16734 } 16735 final int color = mContext.getColor(R.color.personal_apps_suspension_notification_color); 16736 final Bundle extras = new Bundle(); 16737 // TODO: Create a separate string for this. 16738 extras.putString(Notification.EXTRA_SUBSTITUTE_APP_NAME, 16739 mContext.getString(R.string.notification_work_profile_content_description)); 16740 16741 final Notification notification = 16742 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 16743 .setSmallIcon(R.drawable.ic_corp_badge_no_background) 16744 .setOngoing(ongoing) 16745 .setAutoCancel(false) 16746 .setContentTitle(mContext.getString( 16747 R.string.personal_apps_suspension_title)) 16748 .setContentText(text) 16749 .setStyle(new Notification.BigTextStyle().bigText(text)) 16750 .setColor(color) 16751 .addAction(turnProfileOnButton) 16752 .addExtras(extras) 16753 .build(); 16754 mInjector.getNotificationManager().notify( 16755 SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED, notification); 16756 } 16757 16758 @Override 16759 public void setManagedProfileMaximumTimeOff(ComponentName who, long timeoutMillis) { 16760 Objects.requireNonNull(who, "ComponentName is null"); 16761 Preconditions.checkArgumentNonnegative(timeoutMillis, "Timeout must be non-negative."); 16762 16763 final CallerIdentity caller = getCallerIdentity(who); 16764 // DO shouldn't be able to use this method. 16765 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 16766 Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller)); 16767 16768 final int userId = caller.getUserId(); 16769 synchronized (getLockObject()) { 16770 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16771 16772 // Ensure the timeout is long enough to avoid having bad user experience. 16773 if (timeoutMillis > 0 && timeoutMillis < MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD 16774 && !isAdminTestOnlyLocked(who, userId)) { 16775 timeoutMillis = MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD; 16776 } 16777 if (admin.mProfileMaximumTimeOffMillis == timeoutMillis) { 16778 return; 16779 } 16780 admin.mProfileMaximumTimeOffMillis = timeoutMillis; 16781 saveSettingsLocked(userId); 16782 } 16783 16784 mInjector.binderWithCleanCallingIdentity( 16785 () -> updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked())); 16786 16787 DevicePolicyEventLogger 16788 .createEvent(DevicePolicyEnums.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF) 16789 .setAdmin(caller.getComponentName()) 16790 .setTimePeriod(timeoutMillis) 16791 .write(); 16792 } 16793 16794 private boolean canHandleCheckPolicyComplianceIntent(CallerIdentity caller) { 16795 mInjector.binderWithCleanCallingIdentity(() -> { 16796 final Intent intent = new Intent(DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE); 16797 intent.setPackage(caller.getPackageName()); 16798 final List<ResolveInfo> handlers = 16799 mInjector.getPackageManager().queryIntentActivitiesAsUser(intent, /* flags= */ 16800 0, caller.getUserId()); 16801 return !handlers.isEmpty(); 16802 }); 16803 return true; 16804 } 16805 16806 @Override 16807 public long getManagedProfileMaximumTimeOff(ComponentName who) { 16808 Objects.requireNonNull(who, "ComponentName is null"); 16809 16810 final CallerIdentity caller = getCallerIdentity(who); 16811 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 16812 16813 synchronized (getLockObject()) { 16814 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16815 return admin.mProfileMaximumTimeOffMillis; 16816 } 16817 } 16818 16819 @Override 16820 public void acknowledgeDeviceCompliant() { 16821 final CallerIdentity caller = getCallerIdentity(); 16822 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 16823 enforceUserUnlocked(caller.getUserId()); 16824 16825 synchronized (getLockObject()) { 16826 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16827 if (admin.mProfileOffDeadline > 0) { 16828 admin.mProfileOffDeadline = 0; 16829 saveSettingsLocked(caller.getUserId()); 16830 } 16831 } 16832 } 16833 16834 @Override 16835 public boolean isComplianceAcknowledgementRequired() { 16836 final CallerIdentity caller = getCallerIdentity(); 16837 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 16838 enforceUserUnlocked(caller.getUserId()); 16839 16840 synchronized (getLockObject()) { 16841 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16842 return admin.mProfileOffDeadline != 0; 16843 } 16844 } 16845 16846 @Override 16847 public boolean canProfileOwnerResetPasswordWhenLocked(int userId) { 16848 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 16849 String.format(NOT_SYSTEM_CALLER_MSG, 16850 "call canProfileOwnerResetPasswordWhenLocked")); 16851 synchronized (getLockObject()) { 16852 final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(userId); 16853 if (poAdmin == null 16854 || getEncryptionStatus() != ENCRYPTION_STATUS_ACTIVE_PER_USER 16855 || !isResetPasswordTokenActiveForUserLocked(userId)) { 16856 return false; 16857 } 16858 final ApplicationInfo poAppInfo; 16859 try { 16860 poAppInfo = mIPackageManager.getApplicationInfo( 16861 poAdmin.info.getPackageName(), 0 /* flags */, userId); 16862 } catch (RemoteException e) { 16863 Slogf.e(LOG_TAG, "Failed to query PO app info", e); 16864 return false; 16865 } 16866 if (poAppInfo == null) { 16867 Slogf.wtf(LOG_TAG, "Cannot find AppInfo for profile owner"); 16868 return false; 16869 } 16870 if (!poAppInfo.isEncryptionAware()) { 16871 return false; 16872 } 16873 Slogf.d(LOG_TAG, "PO should be able to reset password from direct boot"); 16874 return true; 16875 } 16876 } 16877 16878 @Override 16879 public String getEnrollmentSpecificId(String callerPackage) { 16880 if (!mHasFeature) { 16881 return ""; 16882 } 16883 16884 final CallerIdentity caller = getCallerIdentity(callerPackage); 16885 Preconditions.checkCallAuthorization( 16886 isDeviceOwner(caller) || isProfileOwner(caller) 16887 || isCallerDelegate(caller, DELEGATION_CERT_INSTALL)); 16888 16889 synchronized (getLockObject()) { 16890 final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked( 16891 caller.getUserId()); 16892 final String esid = requiredAdmin.mEnrollmentSpecificId; 16893 return esid != null ? esid : ""; 16894 } 16895 } 16896 16897 @Override 16898 public void setOrganizationIdForUser( 16899 @NonNull String callerPackage, @NonNull String organizationId, int userId) { 16900 if (!mHasFeature) { 16901 return; 16902 } 16903 Objects.requireNonNull(callerPackage); 16904 16905 final CallerIdentity caller = getCallerIdentity(callerPackage); 16906 // Only the DPC can set this ID. 16907 Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller), 16908 "Only a Device Owner or Profile Owner may set the Enterprise ID."); 16909 // Empty enterprise ID must not be provided in calls to this method. 16910 Preconditions.checkArgument(!TextUtils.isEmpty(organizationId), 16911 "Enterprise ID may not be empty."); 16912 16913 Slogf.i(LOG_TAG, "Setting Enterprise ID to %s for user %d", organizationId, userId); 16914 16915 final String ownerPackage; 16916 synchronized (getLockObject()) { 16917 final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 16918 // As the caller is the system, it must specify the component name of the profile owner 16919 // as a safety check. 16920 Preconditions.checkCallAuthorization( 16921 owner != null && owner.getUserHandle().getIdentifier() == userId, 16922 String.format("The Profile Owner or Device Owner may only set the Enterprise ID" 16923 + " on its own user, called on user %d but owner user is %d", userId, 16924 owner.getUserHandle().getIdentifier())); 16925 ownerPackage = owner.info.getPackageName(); 16926 Preconditions.checkState( 16927 TextUtils.isEmpty(owner.mOrganizationId) || owner.mOrganizationId.equals( 16928 organizationId), 16929 "The organization ID has been previously set to a different value and cannot " 16930 + "be changed"); 16931 final String dpcPackage = owner.info.getPackageName(); 16932 mInjector.binderWithCleanCallingIdentity(() -> { 16933 EnterpriseSpecificIdCalculator esidCalculator = 16934 new EnterpriseSpecificIdCalculator(mContext); 16935 16936 final String esid = esidCalculator.calculateEnterpriseId(dpcPackage, 16937 organizationId); 16938 owner.mOrganizationId = organizationId; 16939 owner.mEnrollmentSpecificId = esid; 16940 saveSettingsLocked(userId); 16941 }); 16942 } 16943 16944 DevicePolicyEventLogger 16945 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_ID) 16946 .setAdmin(ownerPackage) 16947 .setBoolean(isManagedProfile(userId)) 16948 .write(); 16949 } 16950 16951 @Override 16952 public UserHandle createAndProvisionManagedProfile( 16953 @NonNull ManagedProfileProvisioningParams provisioningParams, 16954 @NonNull String callerPackage) { 16955 Objects.requireNonNull(provisioningParams, "provisioningParams is null"); 16956 Objects.requireNonNull(callerPackage, "callerPackage is null"); 16957 16958 final ComponentName admin = provisioningParams.getProfileAdminComponentName(); 16959 Objects.requireNonNull(admin, "admin is null"); 16960 16961 final CallerIdentity caller = getCallerIdentity(callerPackage); 16962 Preconditions.checkCallAuthorization( 16963 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 16964 16965 provisioningParams.logParams(callerPackage); 16966 16967 UserInfo userInfo = null; 16968 final long identity = Binder.clearCallingIdentity(); 16969 try { 16970 final int result = checkProvisioningPreConditionSkipPermission( 16971 ACTION_PROVISION_MANAGED_PROFILE, admin.getPackageName()); 16972 if (result != CODE_OK) { 16973 throw new ServiceSpecificException( 16974 PROVISIONING_RESULT_PRE_CONDITION_FAILED, 16975 "Provisioning preconditions failed with result: " + result); 16976 } 16977 16978 final long startTime = SystemClock.elapsedRealtime(); 16979 final Set<String> nonRequiredApps = provisioningParams.isLeaveAllSystemAppsEnabled() 16980 ? Collections.emptySet() 16981 : mOverlayPackagesProvider.getNonRequiredApps( 16982 admin, caller.getUserId(), ACTION_PROVISION_MANAGED_PROFILE); 16983 userInfo = mUserManager.createProfileForUserEvenWhenDisallowed( 16984 provisioningParams.getProfileName(), 16985 UserManager.USER_TYPE_PROFILE_MANAGED, 16986 UserInfo.FLAG_DISABLED, 16987 caller.getUserId(), 16988 nonRequiredApps.toArray(new String[nonRequiredApps.size()])); 16989 if (userInfo == null) { 16990 throw new ServiceSpecificException( 16991 PROVISIONING_RESULT_PROFILE_CREATION_FAILED, 16992 "Error creating profile, createProfileForUserEvenWhenDisallowed " 16993 + "returned null."); 16994 } 16995 resetInteractAcrossProfilesAppOps(); 16996 logEventDuration( 16997 DevicePolicyEnums.PLATFORM_PROVISIONING_CREATE_PROFILE_MS, 16998 startTime, 16999 callerPackage); 17000 17001 installExistingAdminPackage(userInfo.id, admin.getPackageName()); 17002 if (!enableAdminAndSetProfileOwner( 17003 userInfo.id, caller.getUserId(), admin, provisioningParams.getOwnerName())) { 17004 throw new ServiceSpecificException( 17005 PROVISIONING_RESULT_SETTING_PROFILE_OWNER_FAILED, 17006 "Error setting profile owner."); 17007 } 17008 setUserSetupComplete(userInfo.id); 17009 17010 startUser(userInfo.id, callerPackage); 17011 maybeMigrateAccount( 17012 userInfo.id, caller.getUserId(), provisioningParams.getAccountToMigrate(), 17013 provisioningParams.isKeepAccountMigrated(), callerPackage); 17014 17015 if (provisioningParams.isOrganizationOwnedProvisioning()) { 17016 synchronized (getLockObject()) { 17017 markProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(admin, userInfo.id); 17018 } 17019 } 17020 17021 return userInfo.getUserHandle(); 17022 } catch (Exception e) { 17023 DevicePolicyEventLogger 17024 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR) 17025 .setStrings(callerPackage) 17026 .write(); 17027 // In case of any errors during provisioning, remove the newly created profile. 17028 if (userInfo != null) { 17029 mUserManager.removeUserEvenWhenDisallowed(userInfo.id); 17030 } 17031 throw e; 17032 } finally { 17033 Binder.restoreCallingIdentity(identity); 17034 } 17035 } 17036 17037 private void resetInteractAcrossProfilesAppOps() { 17038 mInjector.getCrossProfileApps().clearInteractAcrossProfilesAppOps(); 17039 pregrantDefaultInteractAcrossProfilesAppOps(); 17040 } 17041 17042 private void pregrantDefaultInteractAcrossProfilesAppOps() { 17043 final String op = 17044 AppOpsManager.permissionToOp(Manifest.permission.INTERACT_ACROSS_PROFILES); 17045 for (String packageName : getConfigurableDefaultCrossProfilePackages()) { 17046 if (appOpIsChangedFromDefault(op, packageName)) { 17047 continue; 17048 } 17049 mInjector.getCrossProfileApps().setInteractAcrossProfilesAppOp( 17050 packageName, MODE_ALLOWED); 17051 } 17052 } 17053 17054 private Set<String> getConfigurableDefaultCrossProfilePackages() { 17055 List<String> defaultPackages = getDefaultCrossProfilePackages(); 17056 return defaultPackages.stream().filter( 17057 mInjector.getCrossProfileApps()::canConfigureInteractAcrossProfiles).collect( 17058 Collectors.toSet()); 17059 } 17060 17061 private boolean appOpIsChangedFromDefault(String op, String packageName) { 17062 try { 17063 final int uid = mContext.getPackageManager().getPackageUid( 17064 packageName, /* flags= */ 0); 17065 return mInjector.getAppOpsManager().unsafeCheckOpNoThrow( 17066 op, uid, packageName) 17067 != AppOpsManager.MODE_DEFAULT; 17068 } catch (NameNotFoundException e) { 17069 return false; 17070 } 17071 } 17072 17073 private void installExistingAdminPackage(int userId, String packageName) { 17074 try { 17075 final int status = mContext.getPackageManager().installExistingPackageAsUser( 17076 packageName, 17077 userId); 17078 if (status != PackageManager.INSTALL_SUCCEEDED) { 17079 throw new ServiceSpecificException( 17080 PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED, 17081 String.format("Failed to install existing package %s for user %d with " 17082 + "result code %d", 17083 packageName, userId, status)); 17084 } 17085 } catch (NameNotFoundException e) { 17086 throw new ServiceSpecificException( 17087 PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED, 17088 String.format("Failed to install existing package %s for user %d: %s", 17089 packageName, userId, e.getMessage())); 17090 } 17091 } 17092 17093 private boolean enableAdminAndSetProfileOwner( 17094 @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent, 17095 String ownerName) { 17096 enableAndSetActiveAdmin(userId, callingUserId, adminComponent); 17097 return setProfileOwner(adminComponent, ownerName, userId); 17098 } 17099 17100 private void enableAndSetActiveAdmin( 17101 @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) { 17102 final String adminPackage = adminComponent.getPackageName(); 17103 enablePackage(adminPackage, callingUserId); 17104 setActiveAdmin(adminComponent, /* refreshing= */ true, userId); 17105 } 17106 17107 private void enablePackage(String packageName, @UserIdInt int userId) { 17108 try { 17109 final int enabledSetting = mIPackageManager.getApplicationEnabledSetting( 17110 packageName, userId); 17111 if (enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17112 && enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17113 mIPackageManager.setApplicationEnabledSetting( 17114 packageName, 17115 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 17116 // Device policy app may have launched ManagedProvisioning, play nice and 17117 // don't kill it as a side-effect of this call. 17118 PackageManager.DONT_KILL_APP, 17119 userId, 17120 mContext.getOpPackageName()); 17121 } 17122 } catch (RemoteException e) { 17123 // Shouldn't happen. 17124 } 17125 } 17126 17127 private void setUserSetupComplete(@UserIdInt int userId) { 17128 Settings.Secure.putIntForUser( 17129 mContext.getContentResolver(), USER_SETUP_COMPLETE, 1, userId); 17130 } 17131 17132 private void startUser(@UserIdInt int userId, String callerPackage) 17133 throws IllegalStateException { 17134 final long startTime = SystemClock.elapsedRealtime(); 17135 final UserUnlockedBlockingReceiver unlockedReceiver = new UserUnlockedBlockingReceiver( 17136 userId); 17137 mContext.registerReceiverAsUser( 17138 unlockedReceiver, 17139 new UserHandle(userId), 17140 new IntentFilter(Intent.ACTION_USER_UNLOCKED), 17141 /* broadcastPermission = */ null, 17142 /* scheduler= */ null); 17143 try { 17144 if (!mInjector.getIActivityManager().startUserInBackground(userId)) { 17145 throw new ServiceSpecificException(PROVISIONING_RESULT_STARTING_PROFILE_FAILED, 17146 String.format("Unable to start user %d in background", userId)); 17147 } 17148 17149 if (!unlockedReceiver.waitForUserUnlocked()) { 17150 throw new ServiceSpecificException(PROVISIONING_RESULT_STARTING_PROFILE_FAILED, 17151 String.format("Timeout whilst waiting for unlock of user %d.", userId)); 17152 } 17153 logEventDuration( 17154 DevicePolicyEnums.PLATFORM_PROVISIONING_START_PROFILE_MS, 17155 startTime, 17156 callerPackage); 17157 } catch (RemoteException e) { 17158 // Shouldn't happen. 17159 } finally { 17160 mContext.unregisterReceiver(unlockedReceiver); 17161 } 17162 } 17163 17164 private void maybeMigrateAccount( 17165 @UserIdInt int targetUserId, @UserIdInt int sourceUserId, Account accountToMigrate, 17166 boolean keepAccountMigrated, String callerPackage) { 17167 final UserHandle sourceUser = UserHandle.of(sourceUserId); 17168 final UserHandle targetUser = UserHandle.of(targetUserId); 17169 if (accountToMigrate == null) { 17170 Slogf.d(LOG_TAG, "No account to migrate."); 17171 return; 17172 } 17173 if (sourceUser.equals(targetUser)) { 17174 Slogf.w(LOG_TAG, "sourceUser and targetUser are the same, won't migrate account."); 17175 return; 17176 } 17177 copyAccount(targetUser, sourceUser, accountToMigrate, callerPackage); 17178 if (!keepAccountMigrated) { 17179 removeAccount(accountToMigrate); 17180 } 17181 } 17182 17183 private void copyAccount( 17184 UserHandle targetUser, UserHandle sourceUser, Account accountToMigrate, 17185 String callerPackage) { 17186 final long startTime = SystemClock.elapsedRealtime(); 17187 try { 17188 final AccountManager accountManager = mContext.getSystemService(AccountManager.class); 17189 final boolean copySucceeded = accountManager.copyAccountToUser( 17190 accountToMigrate, 17191 sourceUser, 17192 targetUser, 17193 /* callback= */ null, /* handler= */ null) 17194 .getResult(60 * 3, TimeUnit.SECONDS); 17195 if (copySucceeded) { 17196 logCopyAccountStatus(COPY_ACCOUNT_SUCCEEDED, callerPackage); 17197 logEventDuration( 17198 DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_MS, 17199 startTime, 17200 callerPackage); 17201 } else { 17202 logCopyAccountStatus(COPY_ACCOUNT_FAILED, callerPackage); 17203 Slogf.e(LOG_TAG, "Failed to copy account to " + targetUser); 17204 } 17205 } catch (OperationCanceledException e) { 17206 // Account migration is not considered a critical operation. 17207 logCopyAccountStatus(COPY_ACCOUNT_TIMED_OUT, callerPackage); 17208 Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e); 17209 } catch (AuthenticatorException | IOException e) { 17210 logCopyAccountStatus(COPY_ACCOUNT_EXCEPTION, callerPackage); 17211 Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e); 17212 } 17213 } 17214 17215 private static void logCopyAccountStatus(@CopyAccountStatus int status, String callerPackage) { 17216 DevicePolicyEventLogger 17217 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_STATUS) 17218 .setInt(status) 17219 .setStrings(callerPackage) 17220 .write(); 17221 } 17222 17223 private void removeAccount(Account account) { 17224 final AccountManager accountManager = 17225 mContext.getSystemService(AccountManager.class); 17226 final AccountManagerFuture<Bundle> bundle = accountManager.removeAccount(account, 17227 null, null /* callback */, null /* handler */); 17228 try { 17229 final Bundle result = bundle.getResult(); 17230 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, /* default */ false)) { 17231 Slogf.i(LOG_TAG, "Account removed from the primary user."); 17232 } else { 17233 // TODO(174768447): Revisit start activity logic. 17234 final Intent removeIntent = result.getParcelable(AccountManager.KEY_INTENT); 17235 removeIntent.addFlags(FLAG_ACTIVITY_NEW_TASK); 17236 if (removeIntent != null) { 17237 Slogf.i(LOG_TAG, "Starting activity to remove account"); 17238 new Handler(Looper.getMainLooper()).post(() -> { 17239 mContext.startActivity(removeIntent); 17240 }); 17241 } else { 17242 Slogf.e(LOG_TAG, "Could not remove account from the primary user."); 17243 } 17244 } 17245 } catch (OperationCanceledException | AuthenticatorException | IOException e) { 17246 Slogf.e(LOG_TAG, "Exception removing account from the primary user.", e); 17247 } 17248 } 17249 17250 @Override 17251 public void provisionFullyManagedDevice( 17252 @NonNull FullyManagedDeviceProvisioningParams provisioningParams, 17253 @NonNull String callerPackage) { 17254 Objects.requireNonNull(provisioningParams, "provisioningParams is null."); 17255 Objects.requireNonNull(callerPackage, "callerPackage is null."); 17256 17257 ComponentName deviceAdmin = provisioningParams.getDeviceAdminComponentName(); 17258 Objects.requireNonNull(deviceAdmin, "admin is null."); 17259 Objects.requireNonNull(provisioningParams.getOwnerName(), "owner name is null."); 17260 17261 final CallerIdentity caller = getCallerIdentity(); 17262 Preconditions.checkCallAuthorization( 17263 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 17264 17265 provisioningParams.logParams(callerPackage); 17266 17267 final long identity = Binder.clearCallingIdentity(); 17268 try { 17269 int result = checkProvisioningPreConditionSkipPermission( 17270 ACTION_PROVISION_MANAGED_DEVICE, deviceAdmin.getPackageName()); 17271 if (result != CODE_OK) { 17272 throw new ServiceSpecificException( 17273 PROVISIONING_RESULT_PRE_CONDITION_FAILED, 17274 "Provisioning preconditions failed with result: " + result); 17275 } 17276 setTimeAndTimezone(provisioningParams.getTimeZone(), provisioningParams.getLocalTime()); 17277 setLocale(provisioningParams.getLocale()); 17278 17279 final int deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode() 17280 ? UserHandle.USER_SYSTEM : caller.getUserId(); 17281 if (!removeNonRequiredAppsForManagedDevice( 17282 deviceOwnerUserId, 17283 provisioningParams.isLeaveAllSystemAppsEnabled(), 17284 deviceAdmin)) { 17285 throw new ServiceSpecificException( 17286 PROVISIONING_RESULT_REMOVE_NON_REQUIRED_APPS_FAILED, 17287 "PackageManager failed to remove non required apps."); 17288 } 17289 17290 17291 if (!setActiveAdminAndDeviceOwner( 17292 deviceOwnerUserId, deviceAdmin, provisioningParams.getOwnerName())) { 17293 throw new ServiceSpecificException( 17294 PROVISIONING_RESULT_SET_DEVICE_OWNER_FAILED, 17295 "Failed to set device owner."); 17296 } 17297 17298 disallowAddUser(); 17299 setAdminCanGrantSensorsPermissionForUserUnchecked(deviceOwnerUserId, 17300 provisioningParams.canDeviceOwnerGrantSensorsPermissions()); 17301 } catch (Exception e) { 17302 DevicePolicyEventLogger 17303 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR) 17304 .setStrings(callerPackage) 17305 .write(); 17306 throw e; 17307 } finally { 17308 Binder.restoreCallingIdentity(identity); 17309 } 17310 } 17311 17312 private void setTimeAndTimezone(String timeZone, long localTime) { 17313 try { 17314 final AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class); 17315 if (timeZone != null) { 17316 alarmManager.setTimeZone(timeZone); 17317 } 17318 if (localTime > 0) { 17319 alarmManager.setTime(localTime); 17320 } 17321 } catch (Exception e) { 17322 // Do not stop provisioning and ignore this error. 17323 Slogf.e(LOG_TAG, "Alarm manager failed to set the system time/timezone.", e); 17324 } 17325 } 17326 17327 private void setLocale(Locale locale) { 17328 if (locale == null || locale.equals(Locale.getDefault())) { 17329 return; 17330 } 17331 try { 17332 // If locale is different from current locale this results in a configuration change, 17333 // which will trigger the restarting of the activity. 17334 LocalePicker.updateLocale(locale); 17335 } catch (Exception e) { 17336 // Do not stop provisioning and ignore this error. 17337 Slogf.e(LOG_TAG, "Failed to set the system locale.", e); 17338 } 17339 } 17340 17341 private boolean removeNonRequiredAppsForManagedDevice( 17342 @UserIdInt int userId, boolean leaveAllSystemAppsEnabled, ComponentName admin) { 17343 Set<String> packagesToDelete = leaveAllSystemAppsEnabled 17344 ? Collections.emptySet() 17345 : mOverlayPackagesProvider.getNonRequiredApps( 17346 admin, userId, ACTION_PROVISION_MANAGED_DEVICE); 17347 17348 removeNonInstalledPackages(packagesToDelete, userId); 17349 if (packagesToDelete.isEmpty()) { 17350 Slogf.i(LOG_TAG, "No packages to delete on user " + userId); 17351 return true; 17352 } 17353 17354 NonRequiredPackageDeleteObserver packageDeleteObserver = 17355 new NonRequiredPackageDeleteObserver(packagesToDelete.size()); 17356 for (String packageName : packagesToDelete) { 17357 Slogf.i(LOG_TAG, "Deleting package [" + packageName + "] as user " + userId); 17358 mContext.getPackageManager().deletePackageAsUser( 17359 packageName, 17360 packageDeleteObserver, 17361 PackageManager.DELETE_SYSTEM_APP, 17362 userId); 17363 } 17364 Slogf.i(LOG_TAG, "Waiting for non required apps to be deleted"); 17365 return packageDeleteObserver.awaitPackagesDeletion(); 17366 } 17367 17368 private void removeNonInstalledPackages(Set<String> packages, @UserIdInt int userId) { 17369 final Set<String> toBeRemoved = new HashSet<>(); 17370 for (String packageName : packages) { 17371 if (!isPackageInstalledForUser(packageName, userId)) { 17372 toBeRemoved.add(packageName); 17373 } 17374 } 17375 packages.removeAll(toBeRemoved); 17376 } 17377 17378 private void disallowAddUser() { 17379 if (mInjector.userManagerIsHeadlessSystemUserMode()) { 17380 Slogf.i(LOG_TAG, "Not setting DISALLOW_ADD_USER on headless system user mode."); 17381 return; 17382 } 17383 for (UserInfo userInfo : mUserManager.getUsers()) { 17384 UserHandle userHandle = userInfo.getUserHandle(); 17385 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) { 17386 mUserManager.setUserRestriction( 17387 UserManager.DISALLOW_ADD_USER, /* value= */ true, userHandle); 17388 } 17389 } 17390 } 17391 17392 private boolean setActiveAdminAndDeviceOwner( 17393 @UserIdInt int userId, ComponentName adminComponent, String name) { 17394 enableAndSetActiveAdmin(userId, userId, adminComponent); 17395 // TODO(b/178187130): Directly set DO and remove the check once silent provisioning is no 17396 // longer used. 17397 if (getDeviceOwnerComponent(/* callingUserOnly= */ true) == null) { 17398 return setDeviceOwner(adminComponent, name, userId); 17399 } 17400 return true; 17401 } 17402 17403 private static void logEventDuration(int eventId, long startTime, String callerPackage) { 17404 final long duration = SystemClock.elapsedRealtime() - startTime; 17405 DevicePolicyEventLogger 17406 .createEvent(eventId) 17407 .setTimePeriod(duration) 17408 .setStrings(callerPackage) 17409 .write(); 17410 } 17411 17412 @Override 17413 public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) { 17414 Preconditions.checkCallAuthorization( 17415 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 17416 17417 mInjector.binderWithCleanCallingIdentity(() -> { 17418 try { 17419 final List<UserInfo> profiles = mUserManager.getProfiles(userId); 17420 final int numOfProfiles = profiles.size(); 17421 if (numOfProfiles <= 1) { 17422 return; 17423 } 17424 17425 final String managedProvisioningPackageName = getManagedProvisioningPackage( 17426 mContext); 17427 // Removes cross profile intent filters from the parent to all the profiles. 17428 mIPackageManager.clearCrossProfileIntentFilters( 17429 userId, mContext.getOpPackageName()); 17430 // Setting and resetting default cross profile intent filters was previously handled 17431 // by Managed Provisioning. For backwards compatibility, clear any intent filters 17432 // that were set by ManagedProvisioning. 17433 mIPackageManager.clearCrossProfileIntentFilters( 17434 userId, managedProvisioningPackageName); 17435 17436 // For each profile reset cross profile intent filters 17437 for (int i = 0; i < numOfProfiles; i++) { 17438 UserInfo profile = profiles.get(i); 17439 mIPackageManager.clearCrossProfileIntentFilters( 17440 profile.id, mContext.getOpPackageName()); 17441 // Clear any intent filters that were set by ManagedProvisioning. 17442 mIPackageManager.clearCrossProfileIntentFilters( 17443 profile.id, managedProvisioningPackageName); 17444 17445 mUserManagerInternal.setDefaultCrossProfileIntentFilters(userId, profile.id); 17446 } 17447 } catch (RemoteException e) { 17448 // Shouldn't happen. 17449 } 17450 }); 17451 } 17452 17453 private void setAdminCanGrantSensorsPermissionForUserUnchecked(int userId, boolean canGrant) { 17454 synchronized (getLockObject()) { 17455 ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 17456 17457 Preconditions.checkState( 17458 isDeviceOwner(owner) && owner.getUserHandle().getIdentifier() == userId, 17459 "May only be set on a the user of a device owner."); 17460 17461 owner.mAdminCanGrantSensorsPermissions = canGrant; 17462 mPolicyCache.setAdminCanGrantSensorsPermissions(userId, canGrant); 17463 saveSettingsLocked(userId); 17464 } 17465 } 17466 17467 private void updateAdminCanGrantSensorsPermissionCache(int userId) { 17468 synchronized (getLockObject()) { 17469 ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 17470 final boolean canGrant = owner != null ? owner.mAdminCanGrantSensorsPermissions : false; 17471 mPolicyCache.setAdminCanGrantSensorsPermissions(userId, canGrant); 17472 } 17473 } 17474 17475 private void updateNetworkPreferenceForUser(int userId, 17476 boolean preferentialNetworkServiceEnabled) { 17477 if (!isManagedProfile(userId)) { 17478 return; 17479 } 17480 int networkPreference = preferentialNetworkServiceEnabled 17481 ? PROFILE_NETWORK_PREFERENCE_ENTERPRISE : PROFILE_NETWORK_PREFERENCE_DEFAULT; 17482 mInjector.binderWithCleanCallingIdentity(() -> 17483 mInjector.getConnectivityManager().setProfileNetworkPreference( 17484 UserHandle.of(userId), 17485 networkPreference, 17486 null /* executor */, null /* listener */)); 17487 } 17488 17489 @Override 17490 public boolean canAdminGrantSensorsPermissionsForUser(int userId) { 17491 if (!mHasFeature) { 17492 return false; 17493 } 17494 17495 return mPolicyCache.canAdminGrantSensorsPermissionsForUser(userId); 17496 } 17497 17498 @Override 17499 public void setDeviceOwnerType(@NonNull ComponentName admin, 17500 @DeviceOwnerType int deviceOwnerType) { 17501 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 17502 permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 17503 verifyDeviceOwnerTypePreconditions(admin); 17504 17505 final String packageName = admin.getPackageName(); 17506 Preconditions.checkState(!mOwners.isDeviceOwnerTypeSetForDeviceOwner(packageName), 17507 "The device owner type has already been set for " + packageName); 17508 17509 synchronized (getLockObject()) { 17510 mOwners.setDeviceOwnerType(packageName, deviceOwnerType); 17511 } 17512 } 17513 17514 @Override 17515 @DeviceOwnerType 17516 public int getDeviceOwnerType(@NonNull ComponentName admin) { 17517 verifyDeviceOwnerTypePreconditions(admin); 17518 synchronized (getLockObject()) { 17519 return mOwners.getDeviceOwnerType(admin.getPackageName()); 17520 } 17521 } 17522 17523 private void verifyDeviceOwnerTypePreconditions(@NonNull ComponentName admin) { 17524 Preconditions.checkState(mOwners.hasDeviceOwner(), "there is no device owner"); 17525 Preconditions.checkState(mOwners.getDeviceOwnerComponent().equals(admin), 17526 "admin is not the device owner"); 17527 } 17528 17529 @Override 17530 public void setUsbDataSignalingEnabled(String packageName, boolean enabled) { 17531 Objects.requireNonNull(packageName, "Admin package name must be provided"); 17532 final CallerIdentity caller = getCallerIdentity(packageName); 17533 Preconditions.checkCallAuthorization( 17534 isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller), 17535 "USB data signaling can only be controlled by a device owner or " 17536 + "a profile owner on an organization-owned device."); 17537 Preconditions.checkState(canUsbDataSignalingBeDisabled(), 17538 "USB data signaling cannot be disabled."); 17539 17540 synchronized (getLockObject()) { 17541 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 17542 if (admin.mUsbDataSignalingEnabled != enabled) { 17543 admin.mUsbDataSignalingEnabled = enabled; 17544 saveSettingsLocked(caller.getUserId()); 17545 updateUsbDataSignal(); 17546 } 17547 } 17548 DevicePolicyEventLogger 17549 .createEvent(DevicePolicyEnums.SET_USB_DATA_SIGNALING) 17550 .setAdmin(packageName) 17551 .setBoolean(enabled) 17552 .write(); 17553 } 17554 17555 private void updateUsbDataSignal() { 17556 if (!canUsbDataSignalingBeDisabled()) { 17557 return; 17558 } 17559 final boolean usbEnabled; 17560 synchronized (getLockObject()) { 17561 usbEnabled = isUsbDataSignalingEnabledInternalLocked(); 17562 } 17563 if (!mInjector.binderWithCleanCallingIdentity( 17564 () -> mInjector.getUsbManager().enableUsbDataSignal(usbEnabled))) { 17565 Slogf.w(LOG_TAG, "Failed to set usb data signaling state"); 17566 } 17567 } 17568 17569 @Override 17570 public boolean isUsbDataSignalingEnabled(String packageName) { 17571 final CallerIdentity caller = getCallerIdentity(packageName); 17572 synchronized (getLockObject()) { 17573 // If the caller is an admin, return the policy set by itself. Otherwise 17574 // return the device-wide policy. 17575 if (isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)) { 17576 return getProfileOwnerOrDeviceOwnerLocked(caller).mUsbDataSignalingEnabled; 17577 } else { 17578 return isUsbDataSignalingEnabledInternalLocked(); 17579 } 17580 } 17581 } 17582 17583 @Override 17584 public boolean isUsbDataSignalingEnabledForUser(int userId) { 17585 final CallerIdentity caller = getCallerIdentity(); 17586 Preconditions.checkCallAuthorization(isSystemUid(caller)); 17587 17588 synchronized (getLockObject()) { 17589 return isUsbDataSignalingEnabledInternalLocked(); 17590 } 17591 } 17592 17593 private boolean isUsbDataSignalingEnabledInternalLocked() { 17594 final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 17595 UserHandle.USER_SYSTEM); 17596 return admin == null || admin.mUsbDataSignalingEnabled; 17597 } 17598 17599 @Override 17600 public boolean canUsbDataSignalingBeDisabled() { 17601 return mInjector.binderWithCleanCallingIdentity(() -> 17602 mInjector.getUsbManager() != null 17603 && mInjector.getUsbManager().getUsbHalVersion() >= UsbManager.USB_HAL_V1_3 17604 ); 17605 } 17606 } 17607