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_DEVICE_POLICY_RESOURCE_UPDATED; 30 import static android.app.admin.DevicePolicyManager.ACTION_MANAGED_PROFILE_PROVISIONED; 31 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE; 32 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE; 33 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER; 34 import static android.app.admin.DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED; 35 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS; 36 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL; 37 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL; 38 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_SELECTION; 39 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP; 40 import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE; 41 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES; 42 import static android.app.admin.DevicePolicyManager.DELEGATION_NETWORK_LOGGING; 43 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS; 44 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT; 45 import static android.app.admin.DevicePolicyManager.DELEGATION_SECURITY_LOGGING; 46 import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_DEFAULT; 47 import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_FINANCED; 48 import static android.app.admin.DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 49 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE; 50 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_IDS; 51 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE; 52 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_DRAWABLE; 53 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_STRING; 54 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO; 55 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI; 56 import static android.app.admin.DevicePolicyManager.ID_TYPE_INDIVIDUAL_ATTESTATION; 57 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID; 58 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL; 59 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED; 60 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS; 61 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME; 62 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_KEYGUARD; 63 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS; 64 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW; 65 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO; 66 import static android.app.admin.DevicePolicyManager.NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 67 import static android.app.admin.DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 68 import static android.app.admin.DevicePolicyManager.OPERATION_SAFETY_REASON_NONE; 69 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH; 70 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_LOW; 71 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM; 72 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE; 73 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC; 74 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC; 75 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK; 76 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 77 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED; 78 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC; 79 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX; 80 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; 81 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 82 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED; 83 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_EXPLICITLY; 84 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT; 85 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OFF; 86 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OPPORTUNISTIC; 87 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME; 88 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_UNKNOWN; 89 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_ERROR_FAILURE_SETTING; 90 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR; 91 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 92 import static android.app.admin.DevicePolicyManager.STATE_USER_SETUP_FINALIZED; 93 import static android.app.admin.DevicePolicyManager.STATE_USER_UNMANAGED; 94 import static android.app.admin.DevicePolicyManager.STATUS_ACCOUNTS_NOT_EMPTY; 95 import static android.app.admin.DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE; 96 import static android.app.admin.DevicePolicyManager.STATUS_DEVICE_ADMIN_NOT_SUPPORTED; 97 import static android.app.admin.DevicePolicyManager.STATUS_HAS_DEVICE_OWNER; 98 import static android.app.admin.DevicePolicyManager.STATUS_HAS_PAIRED; 99 import static android.app.admin.DevicePolicyManager.STATUS_MANAGED_USERS_NOT_SUPPORTED; 100 import static android.app.admin.DevicePolicyManager.STATUS_NONSYSTEM_USER_EXISTS; 101 import static android.app.admin.DevicePolicyManager.STATUS_NOT_SYSTEM_USER; 102 import static android.app.admin.DevicePolicyManager.STATUS_OK; 103 import static android.app.admin.DevicePolicyManager.STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS; 104 import static android.app.admin.DevicePolicyManager.STATUS_SYSTEM_USER; 105 import static android.app.admin.DevicePolicyManager.STATUS_USER_HAS_PROFILE_OWNER; 106 import static android.app.admin.DevicePolicyManager.STATUS_USER_NOT_RUNNING; 107 import static android.app.admin.DevicePolicyManager.STATUS_USER_SETUP_COMPLETED; 108 import static android.app.admin.DevicePolicyManager.WIPE_EUICC; 109 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE; 110 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA; 111 import static android.app.admin.DevicePolicyManager.WIPE_SILENTLY; 112 import static android.app.admin.DevicePolicyResources.Strings.Core.LOCATION_CHANGED_MESSAGE; 113 import static android.app.admin.DevicePolicyResources.Strings.Core.LOCATION_CHANGED_TITLE; 114 import static android.app.admin.DevicePolicyResources.Strings.Core.NETWORK_LOGGING_MESSAGE; 115 import static android.app.admin.DevicePolicyResources.Strings.Core.NETWORK_LOGGING_TITLE; 116 import static android.app.admin.DevicePolicyResources.Strings.Core.NOTIFICATION_WORK_PROFILE_CONTENT_DESCRIPTION; 117 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_MESSAGE; 118 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_SOON_MESSAGE; 119 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_TITLE; 120 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_TURN_ON_PROFILE; 121 import static android.app.admin.DevicePolicyResources.Strings.Core.PRINTING_DISABLED_NAMED_ADMIN; 122 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_FAILED_PASSWORD_ATTEMPTS_MESSAGE; 123 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_GENERIC_MESSAGE; 124 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_ORG_OWNED_MESSAGE; 125 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_TITLE; 126 import static android.app.admin.ProvisioningException.ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED; 127 import static android.app.admin.ProvisioningException.ERROR_PRE_CONDITION_FAILED; 128 import static android.app.admin.ProvisioningException.ERROR_PROFILE_CREATION_FAILED; 129 import static android.app.admin.ProvisioningException.ERROR_REMOVE_NON_REQUIRED_APPS_FAILED; 130 import static android.app.admin.ProvisioningException.ERROR_SETTING_PROFILE_OWNER_FAILED; 131 import static android.app.admin.ProvisioningException.ERROR_SET_DEVICE_OWNER_FAILED; 132 import static android.app.admin.ProvisioningException.ERROR_STARTING_PROFILE_FAILED; 133 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; 134 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 135 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 136 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 137 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT; 138 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE; 139 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK; 140 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK; 141 import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER; 142 import static android.provider.Settings.Secure.MANAGED_PROVISIONING_DPC_DOWNLOADED; 143 import static android.provider.Settings.Secure.USER_SETUP_COMPLETE; 144 import static android.provider.Telephony.Carriers.DPC_URI; 145 import static android.provider.Telephony.Carriers.ENFORCE_KEY; 146 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI; 147 import static android.provider.Telephony.Carriers.INVALID_APN_ID; 148 import static android.security.keystore.AttestationUtils.USE_INDIVIDUAL_ATTESTATION; 149 150 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB; 151 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE; 152 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW; 153 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS; 154 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER; 155 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER; 156 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 157 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_DEVICE_OWNER; 158 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER; 159 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE; 160 161 import android.Manifest; 162 import android.Manifest.permission; 163 import android.accessibilityservice.AccessibilityServiceInfo; 164 import android.accounts.Account; 165 import android.accounts.AccountManager; 166 import android.accounts.AccountManagerFuture; 167 import android.accounts.AuthenticatorException; 168 import android.accounts.OperationCanceledException; 169 import android.annotation.IntDef; 170 import android.annotation.NonNull; 171 import android.annotation.Nullable; 172 import android.annotation.UserIdInt; 173 import android.app.Activity; 174 import android.app.ActivityManager; 175 import android.app.ActivityManagerInternal; 176 import android.app.ActivityTaskManager; 177 import android.app.AlarmManager; 178 import android.app.AppGlobals; 179 import android.app.AppOpsManager; 180 import android.app.AppOpsManager.Mode; 181 import android.app.BroadcastOptions; 182 import android.app.IActivityManager; 183 import android.app.IActivityTaskManager; 184 import android.app.IApplicationThread; 185 import android.app.IServiceConnection; 186 import android.app.Notification; 187 import android.app.NotificationManager; 188 import android.app.PendingIntent; 189 import android.app.StatusBarManager; 190 import android.app.admin.DeviceAdminInfo; 191 import android.app.admin.DeviceAdminReceiver; 192 import android.app.admin.DevicePolicyCache; 193 import android.app.admin.DevicePolicyDrawableResource; 194 import android.app.admin.DevicePolicyEventLogger; 195 import android.app.admin.DevicePolicyManager; 196 import android.app.admin.DevicePolicyManager.DeviceOwnerType; 197 import android.app.admin.DevicePolicyManager.DevicePolicyOperation; 198 import android.app.admin.DevicePolicyManager.OperationSafetyReason; 199 import android.app.admin.DevicePolicyManager.PasswordComplexity; 200 import android.app.admin.DevicePolicyManager.PersonalAppsSuspensionReason; 201 import android.app.admin.DevicePolicyManagerInternal; 202 import android.app.admin.DevicePolicyManagerLiteInternal; 203 import android.app.admin.DevicePolicySafetyChecker; 204 import android.app.admin.DevicePolicyStringResource; 205 import android.app.admin.DeviceStateCache; 206 import android.app.admin.FactoryResetProtectionPolicy; 207 import android.app.admin.FullyManagedDeviceProvisioningParams; 208 import android.app.admin.ManagedProfileProvisioningParams; 209 import android.app.admin.NetworkEvent; 210 import android.app.admin.ParcelableGranteeMap; 211 import android.app.admin.ParcelableResource; 212 import android.app.admin.PasswordMetrics; 213 import android.app.admin.PasswordPolicy; 214 import android.app.admin.PreferentialNetworkServiceConfig; 215 import android.app.admin.SecurityLog; 216 import android.app.admin.SecurityLog.SecurityEvent; 217 import android.app.admin.StartInstallingUpdateCallback; 218 import android.app.admin.SystemUpdateInfo; 219 import android.app.admin.SystemUpdatePolicy; 220 import android.app.admin.UnsafeStateException; 221 import android.app.admin.WifiSsidPolicy; 222 import android.app.backup.IBackupManager; 223 import android.app.compat.CompatChanges; 224 import android.app.role.OnRoleHoldersChangedListener; 225 import android.app.role.RoleManager; 226 import android.app.trust.TrustManager; 227 import android.app.usage.UsageStatsManagerInternal; 228 import android.compat.annotation.ChangeId; 229 import android.compat.annotation.EnabledAfter; 230 import android.compat.annotation.EnabledSince; 231 import android.content.ActivityNotFoundException; 232 import android.content.BroadcastReceiver; 233 import android.content.ComponentName; 234 import android.content.ContentResolver; 235 import android.content.ContentValues; 236 import android.content.Context; 237 import android.content.IIntentReceiver; 238 import android.content.IIntentSender; 239 import android.content.Intent; 240 import android.content.IntentFilter; 241 import android.content.IntentSender; 242 import android.content.PermissionChecker; 243 import android.content.pm.ActivityInfo; 244 import android.content.pm.ApplicationInfo; 245 import android.content.pm.CrossProfileApps; 246 import android.content.pm.CrossProfileAppsInternal; 247 import android.content.pm.IPackageDataObserver; 248 import android.content.pm.IPackageManager; 249 import android.content.pm.PackageInfo; 250 import android.content.pm.PackageInstaller; 251 import android.content.pm.PackageManager; 252 import android.content.pm.PackageManager.NameNotFoundException; 253 import android.content.pm.PackageManagerInternal; 254 import android.content.pm.ParceledListSlice; 255 import android.content.pm.PermissionInfo; 256 import android.content.pm.ResolveInfo; 257 import android.content.pm.ServiceInfo; 258 import android.content.pm.Signature; 259 import android.content.pm.StringParceledListSlice; 260 import android.content.pm.UserInfo; 261 import android.content.res.Resources; 262 import android.database.ContentObserver; 263 import android.database.Cursor; 264 import android.graphics.Bitmap; 265 import android.hardware.usb.UsbManager; 266 import android.location.Location; 267 import android.location.LocationManager; 268 import android.media.AudioManager; 269 import android.media.IAudioService; 270 import android.net.ConnectivityManager; 271 import android.net.ConnectivitySettingsManager; 272 import android.net.IIpConnectivityMetrics; 273 import android.net.ProfileNetworkPreference; 274 import android.net.ProxyInfo; 275 import android.net.Uri; 276 import android.net.VpnManager; 277 import android.net.metrics.IpConnectivityLog; 278 import android.net.wifi.WifiManager; 279 import android.os.Binder; 280 import android.os.Build; 281 import android.os.Bundle; 282 import android.os.Handler; 283 import android.os.IBinder; 284 import android.os.Looper; 285 import android.os.ParcelFileDescriptor; 286 import android.os.PersistableBundle; 287 import android.os.PowerManager; 288 import android.os.PowerManagerInternal; 289 import android.os.Process; 290 import android.os.RemoteCallback; 291 import android.os.RemoteException; 292 import android.os.ResultReceiver; 293 import android.os.ServiceManager; 294 import android.os.ServiceSpecificException; 295 import android.os.ShellCallback; 296 import android.os.SystemClock; 297 import android.os.SystemProperties; 298 import android.os.UserHandle; 299 import android.os.UserManager; 300 import android.os.UserManager.UserRestrictionSource; 301 import android.os.storage.StorageManager; 302 import android.permission.AdminPermissionControlParams; 303 import android.permission.IPermissionManager; 304 import android.permission.PermissionControllerManager; 305 import android.provider.CalendarContract; 306 import android.provider.ContactsContract.QuickContact; 307 import android.provider.ContactsInternal; 308 import android.provider.Settings; 309 import android.provider.Settings.Global; 310 import android.provider.Telephony; 311 import android.security.AppUriAuthenticationPolicy; 312 import android.security.IKeyChainAliasCallback; 313 import android.security.IKeyChainService; 314 import android.security.KeyChain; 315 import android.security.KeyChain.KeyChainConnection; 316 import android.security.KeyStore; 317 import android.security.keymaster.KeymasterCertificateChain; 318 import android.security.keystore.AttestationUtils; 319 import android.security.keystore.KeyGenParameterSpec; 320 import android.security.keystore.ParcelableKeyGenParameterSpec; 321 import android.stats.devicepolicy.DevicePolicyEnums; 322 import android.telephony.TelephonyManager; 323 import android.telephony.data.ApnSetting; 324 import android.text.TextUtils; 325 import android.text.format.DateUtils; 326 import android.util.ArrayMap; 327 import android.util.ArraySet; 328 import android.util.AtomicFile; 329 import android.util.DebugUtils; 330 import android.util.IndentingPrintWriter; 331 import android.util.Log; 332 import android.util.Pair; 333 import android.util.SparseArray; 334 import android.util.TypedXmlPullParser; 335 import android.util.TypedXmlSerializer; 336 import android.util.Xml; 337 import android.view.IWindowManager; 338 import android.view.accessibility.AccessibilityManager; 339 import android.view.accessibility.IAccessibilityManager; 340 import android.view.inputmethod.InputMethodInfo; 341 342 import com.android.internal.R; 343 import com.android.internal.annotations.GuardedBy; 344 import com.android.internal.annotations.VisibleForTesting; 345 import com.android.internal.app.LocalePicker; 346 import com.android.internal.infra.AndroidFuture; 347 import com.android.internal.logging.MetricsLogger; 348 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 349 import com.android.internal.net.NetworkUtilsInternal; 350 import com.android.internal.notification.SystemNotificationChannels; 351 import com.android.internal.os.BackgroundThread; 352 import com.android.internal.statusbar.IStatusBarService; 353 import com.android.internal.telephony.SmsApplication; 354 import com.android.internal.util.ArrayUtils; 355 import com.android.internal.util.DumpUtils; 356 import com.android.internal.util.FunctionalUtils.ThrowingRunnable; 357 import com.android.internal.util.FunctionalUtils.ThrowingSupplier; 358 import com.android.internal.util.JournaledFile; 359 import com.android.internal.util.Preconditions; 360 import com.android.internal.util.StatLogger; 361 import com.android.internal.widget.LockPatternUtils; 362 import com.android.internal.widget.LockSettingsInternal; 363 import com.android.internal.widget.LockscreenCredential; 364 import com.android.internal.widget.PasswordValidationError; 365 import com.android.net.module.util.ProxyUtils; 366 import com.android.server.LocalServices; 367 import com.android.server.LockGuard; 368 import com.android.server.PersistentDataBlockManagerInternal; 369 import com.android.server.SystemServerInitThreadPool; 370 import com.android.server.SystemService; 371 import com.android.server.devicepolicy.ActiveAdmin.TrustAgentInfo; 372 import com.android.server.inputmethod.InputMethodManagerInternal; 373 import com.android.server.net.NetworkPolicyManagerInternal; 374 import com.android.server.pm.RestrictionsSet; 375 import com.android.server.pm.UserManagerInternal; 376 import com.android.server.pm.UserManagerInternal.UserRestrictionsListener; 377 import com.android.server.pm.UserRestrictionsUtils; 378 import com.android.server.pm.parsing.pkg.AndroidPackage; 379 import com.android.server.storage.DeviceStorageMonitorInternal; 380 import com.android.server.uri.NeededUriGrants; 381 import com.android.server.uri.UriGrantsManagerInternal; 382 import com.android.server.utils.Slogf; 383 import com.android.server.wm.ActivityTaskManagerInternal; 384 385 import org.xmlpull.v1.XmlPullParserException; 386 387 import java.io.ByteArrayInputStream; 388 import java.io.File; 389 import java.io.FileDescriptor; 390 import java.io.FileInputStream; 391 import java.io.FileOutputStream; 392 import java.io.IOException; 393 import java.io.PrintWriter; 394 import java.lang.reflect.Constructor; 395 import java.security.cert.CertificateException; 396 import java.security.cert.CertificateFactory; 397 import java.security.cert.X509Certificate; 398 import java.text.DateFormat; 399 import java.time.LocalDate; 400 import java.util.ArrayDeque; 401 import java.util.ArrayList; 402 import java.util.Arrays; 403 import java.util.Collection; 404 import java.util.Collections; 405 import java.util.Date; 406 import java.util.HashMap; 407 import java.util.HashSet; 408 import java.util.List; 409 import java.util.Locale; 410 import java.util.Map; 411 import java.util.Objects; 412 import java.util.Queue; 413 import java.util.Set; 414 import java.util.concurrent.Executor; 415 import java.util.concurrent.TimeUnit; 416 import java.util.function.Function; 417 import java.util.function.Predicate; 418 import java.util.stream.Collectors; 419 420 /** 421 * Implementation of the device policy APIs. 422 */ 423 public class DevicePolicyManagerService extends BaseIDevicePolicyManager { 424 425 protected static final String LOG_TAG = "DevicePolicyManager"; 426 427 private static final String ATTRIBUTION_TAG = "DevicePolicyManagerService"; 428 429 static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE 430 431 static final String DEVICE_POLICIES_XML = "device_policies.xml"; 432 433 static final String POLICIES_VERSION_XML = "device_policies_version"; 434 435 private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML = 436 "transfer-ownership-parameters.xml"; 437 438 private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle"; 439 440 private static final int REQUEST_EXPIRE_PASSWORD = 5571; 441 442 private static final int REQUEST_PROFILE_OFF_DEADLINE = 5572; 443 444 // Binary XML serializer doesn't support longer strings 445 private static final int MAX_POLICY_STRING_LENGTH = 65535; 446 // FrameworkParsingPackageUtils#MAX_FILE_NAME_SIZE, Android packages are used in dir names. 447 private static final int MAX_PACKAGE_NAME_LENGTH = 223; 448 449 private static final int MAX_PROFILE_NAME_LENGTH = 200; 450 private static final int MAX_LONG_SUPPORT_MESSAGE_LENGTH = 20000; 451 private static final int MAX_SHORT_SUPPORT_MESSAGE_LENGTH = 200; 452 private static final int MAX_ORG_NAME_LENGTH = 200; 453 454 private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1); 455 456 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms 457 private static final long MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD = 3 * MS_PER_DAY; 458 /** When to warn the user about the approaching work profile off deadline: 1 day before */ 459 private static final long MANAGED_PROFILE_OFF_WARNING_PERIOD = 1 * MS_PER_DAY; 460 461 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION = 462 "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION"; 463 464 /** Broadcast action invoked when the user taps a notification to turn the profile on. */ 465 @VisibleForTesting 466 static final String ACTION_TURN_PROFILE_ON_NOTIFICATION = 467 "com.android.server.ACTION_TURN_PROFILE_ON_NOTIFICATION"; 468 469 /** Broadcast action for tracking managed profile maximum time off. */ 470 @VisibleForTesting 471 static final String ACTION_PROFILE_OFF_DEADLINE = 472 "com.android.server.ACTION_PROFILE_OFF_DEADLINE"; 473 474 private static final String CALLED_FROM_PARENT = "calledFromParent"; 475 private static final String NOT_CALLED_FROM_PARENT = "notCalledFromParent"; 476 477 private static final String CREDENTIAL_MANAGEMENT_APP = "credentialManagementApp"; 478 private static final String NOT_CREDENTIAL_MANAGEMENT_APP = "notCredentialManagementApp"; 479 480 private static final String NULL_STRING_ARRAY = "nullStringArray"; 481 482 private static final String ALLOW_USER_PROVISIONING_KEY = "ro.config.allowuserprovisioning"; 483 484 // Comprehensive list of delegations. 485 private static final String DELEGATIONS[] = { 486 DELEGATION_CERT_INSTALL, 487 DELEGATION_APP_RESTRICTIONS, 488 DELEGATION_BLOCK_UNINSTALL, 489 DELEGATION_ENABLE_SYSTEM_APP, 490 DELEGATION_KEEP_UNINSTALLED_PACKAGES, 491 DELEGATION_PACKAGE_ACCESS, 492 DELEGATION_PERMISSION_GRANT, 493 DELEGATION_INSTALL_EXISTING_PACKAGE, 494 DELEGATION_KEEP_UNINSTALLED_PACKAGES, 495 DELEGATION_NETWORK_LOGGING, 496 DELEGATION_SECURITY_LOGGING, 497 DELEGATION_CERT_SELECTION, 498 }; 499 500 // Subset of delegations that can only be delegated by Device Owner or Profile Owner of a 501 // managed profile. 502 private static final List<String> DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS = 503 Arrays.asList(new String[]{ 504 DELEGATION_NETWORK_LOGGING, 505 }); 506 507 // Subset of delegations that can only be delegated by Device Owner or Profile Owner of an 508 // organization-owned and managed profile. 509 private static final List<String> 510 DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS = 511 Arrays.asList(new String[]{ 512 DELEGATION_SECURITY_LOGGING, 513 }); 514 515 // Subset of delegations that only one single package within a given user can hold 516 private static final List<String> EXCLUSIVE_DELEGATIONS = Arrays.asList(new String[] { 517 DELEGATION_NETWORK_LOGGING, 518 DELEGATION_SECURITY_LOGGING, 519 DELEGATION_CERT_SELECTION, 520 }); 521 522 /** 523 * System property whose value indicates whether the device is fully owned by an organization: 524 * it can be either a device owner device, or a device with an organization-owned managed 525 * profile. 526 * 527 * <p>The state is stored as a Boolean string. 528 */ 529 private static final String PROPERTY_ORGANIZATION_OWNED = "ro.organization_owned"; 530 531 private static final int STATUS_BAR_DISABLE_MASK = 532 StatusBarManager.DISABLE_EXPAND | 533 StatusBarManager.DISABLE_NOTIFICATION_ICONS | 534 StatusBarManager.DISABLE_NOTIFICATION_ALERTS | 535 StatusBarManager.DISABLE_SEARCH; 536 537 private static final int STATUS_BAR_DISABLE2_MASK = 538 StatusBarManager.DISABLE2_QUICK_SETTINGS; 539 540 private static final Set<String> SECURE_SETTINGS_ALLOWLIST; 541 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST; 542 private static final Set<String> GLOBAL_SETTINGS_ALLOWLIST; 543 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED; 544 private static final Set<String> SYSTEM_SETTINGS_ALLOWLIST; 545 private static final Set<Integer> DA_DISALLOWED_POLICIES; 546 private static final String AB_DEVICE_KEY = "ro.build.ab_update"; 547 // The version of the current DevicePolicyManagerService data. This version is used 548 // to decide whether an existing policy in the {@link #DEVICE_POLICIES_XML} needs to 549 // be upgraded. See {@link PolicyVersionUpgrader} on instructions how to add an upgrade 550 // step. 551 static final int DPMS_VERSION = 3; 552 553 static { 554 SECURE_SETTINGS_ALLOWLIST = new ArraySet<>(); 555 SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.DEFAULT_INPUT_METHOD); 556 SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS); 557 SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS); 558 559 SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST = new ArraySet<>(); 560 SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.addAll(SECURE_SETTINGS_ALLOWLIST); 561 SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.add(Settings.Secure.LOCATION_MODE); 562 563 GLOBAL_SETTINGS_ALLOWLIST = new ArraySet<>(); 564 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_ENABLED); 565 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_WIFI_ENABLED); 566 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME); 567 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME_ZONE); 568 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.DATA_ROAMING); 569 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED); 570 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_SLEEP_POLICY); 571 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN); 572 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN); 573 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_MODE); 574 GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER); 575 576 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>(); 577 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON); 578 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); 579 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER); 580 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE); 581 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON); 582 583 SYSTEM_SETTINGS_ALLOWLIST = new ArraySet<>(); 584 SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS); 585 SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_FLOAT); 586 SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE); 587 SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_OFF_TIMEOUT); 588 589 DA_DISALLOWED_POLICIES = new ArraySet<>(); 590 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 591 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES); 592 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD); 593 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 594 } 595 596 /** 597 * Keyguard features that when set on a profile affect the profile content or challenge only. 598 * These cannot be set on the managed profile's parent DPM instance 599 */ 600 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY = 601 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS; 602 603 /** Keyguard features that are allowed to be set on a managed profile */ 604 private static final int PROFILE_KEYGUARD_FEATURES = 605 NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER 606 | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY; 607 608 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000; 609 610 /** 611 * Minimum timeout in milliseconds after which unlocking with weak auth times out, 612 * i.e. the user has to use a strong authentication method like password, PIN or pattern. 613 */ 614 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1); 615 616 /** 617 * The amount of ms that a managed kiosk must go without user interaction to be considered 618 * unattended. 619 */ 620 private static final int UNATTENDED_MANAGED_KIOSK_MS = 30000; 621 622 /** 623 * Strings logged with {@link 624 * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}, 625 * {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB}, 626 * {@link DevicePolicyEnums#SET_NETWORK_LOGGING_ENABLED} and 627 * {@link DevicePolicyEnums#RETRIEVE_NETWORK_LOGS}. 628 */ 629 private static final String LOG_TAG_PROFILE_OWNER = "profile-owner"; 630 private static final String LOG_TAG_DEVICE_OWNER = "device-owner"; 631 632 /** 633 * For admin apps targeting R+, throw when the app sets password requirement 634 * that is not taken into account at given quality. For example when quality is set 635 * to {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, it doesn't 636 * make sense to require certain password length. If the intent is to require a password of 637 * certain length having at least NUMERIC quality, the admin should first call 638 * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} and only then call 639 * {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLength}. 640 * 641 * <p>Conversely when an admin app targeting R+ lowers password quality, those 642 * requirements that stop making sense are reset to default values. 643 */ 644 @ChangeId 645 @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q) 646 private static final long ADMIN_APP_PASSWORD_COMPLEXITY = 123562444L; 647 648 /** 649 * Admin apps targeting Android R+ may not use 650 * {@link android.app.admin.DevicePolicyManager#setSecureSetting} to change the deprecated 651 * {@link android.provider.Settings.Secure#LOCATION_MODE} setting. Instead they should use 652 * {@link android.app.admin.DevicePolicyManager#setLocationEnabled}. 653 */ 654 @ChangeId 655 @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q) 656 private static final long USE_SET_LOCATION_ENABLED = 117835097L; 657 658 // Only add to the end of the list. Do not change or rearrange these values, that will break 659 // historical data. Do not use negative numbers or zero, logger only handles positive 660 // integers. 661 private static final int COPY_ACCOUNT_SUCCEEDED = 1; 662 private static final int COPY_ACCOUNT_FAILED = 2; 663 private static final int COPY_ACCOUNT_TIMED_OUT = 3; 664 private static final int COPY_ACCOUNT_EXCEPTION = 4; 665 666 @IntDef({ 667 COPY_ACCOUNT_SUCCEEDED, 668 COPY_ACCOUNT_FAILED, 669 COPY_ACCOUNT_TIMED_OUT, 670 COPY_ACCOUNT_EXCEPTION}) 671 private @interface CopyAccountStatus {} 672 673 /** 674 * Admin apps targeting Android S+ may not use 675 * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} to set password quality 676 * on the {@code DevicePolicyManager} instance obtained by calling 677 * {@link android.app.admin.DevicePolicyManager#getParentProfileInstance}. 678 * Instead, they should use 679 * {@link android.app.admin.DevicePolicyManager#setRequiredPasswordComplexity} to set 680 * coarse-grained password requirements device-wide. 681 */ 682 @ChangeId 683 @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S) 684 private static final long PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT = 165573442L; 685 686 private static final String CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG = 687 "The alias provided must be contained in the aliases specified in the credential " 688 + "management app's authentication policy"; 689 private static final String NOT_SYSTEM_CALLER_MSG = "Only the system can %s"; 690 691 final Context mContext; 692 final Injector mInjector; 693 final PolicyPathProvider mPathProvider; 694 final IPackageManager mIPackageManager; 695 final IPermissionManager mIPermissionManager; 696 final UserManager mUserManager; 697 final UserManagerInternal mUserManagerInternal; 698 final UsageStatsManagerInternal mUsageStatsManagerInternal; 699 final TelephonyManager mTelephonyManager; 700 private final LockPatternUtils mLockPatternUtils; 701 private final LockSettingsInternal mLockSettingsInternal; 702 private final DeviceAdminServiceController mDeviceAdminServiceController; 703 private final OverlayPackagesProvider mOverlayPackagesProvider; 704 705 private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl(); 706 private final DeviceStateCacheImpl mStateCache = new DeviceStateCacheImpl(); 707 private final Object mESIDInitilizationLock = new Object(); 708 private EnterpriseSpecificIdCalculator mEsidCalculator; 709 710 /** 711 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p 712 * is requested for user u. 713 */ 714 private final Set<Pair<String, Integer>> mPackagesToRemove = 715 new ArraySet<Pair<String, Integer>>(); 716 717 final LocalService mLocalService; 718 719 // Stores and loads state on device and profile owners. 720 @VisibleForTesting 721 final Owners mOwners; 722 723 private final Binder mToken = new Binder(); 724 725 /** 726 * Whether or not device admin feature is supported. If it isn't return defaults for all 727 * public methods, unless the caller has the appropriate permission for a particular method. 728 */ 729 final boolean mHasFeature; 730 731 /** 732 * Whether or not this device is a watch. 733 */ 734 final boolean mIsWatch; 735 736 /** 737 * Whether or not this device is an automotive. 738 */ 739 private final boolean mIsAutomotive; 740 741 /** 742 * Whether this device has the telephony feature. 743 */ 744 final boolean mHasTelephonyFeature; 745 746 private final CertificateMonitor mCertificateMonitor; 747 private final SecurityLogMonitor mSecurityLogMonitor; 748 private final RemoteBugreportManager mBugreportCollectionManager; 749 750 @GuardedBy("getLockObject()") 751 private NetworkLogger mNetworkLogger; 752 753 private final SetupContentObserver mSetupContentObserver; 754 private final DevicePolicyConstantsObserver mConstantsObserver; 755 756 private DevicePolicyConstants mConstants; 757 758 /** 759 * User to be switched to on {@code logoutUser()}. 760 * 761 * <p>Only used on devices with headless system user mode 762 */ 763 @GuardedBy("getLockObject()") 764 private @UserIdInt int mLogoutUserId = UserHandle.USER_NULL; 765 766 /** 767 * User the network logging notification was sent to. 768 */ 769 // Guarded by mHandler 770 private @UserIdInt int mNetworkLoggingNotificationUserId = UserHandle.USER_NULL; 771 772 private final DeviceManagementResourcesProvider mDeviceManagementResourcesProvider; 773 private final DevicePolicyManagementRoleObserver mDevicePolicyManagementRoleObserver; 774 775 private static final boolean ENABLE_LOCK_GUARD = true; 776 777 /** 778 * Profile off deadline is not set or more than MANAGED_PROFILE_OFF_WARNING_PERIOD away, or the 779 * user is running unlocked, no need for notification. 780 */ 781 private static final int PROFILE_OFF_NOTIFICATION_NONE = 0; 782 /** 783 * Profile off deadline is closer than MANAGED_PROFILE_OFF_WARNING_PERIOD. 784 */ 785 private static final int PROFILE_OFF_NOTIFICATION_WARNING = 1; 786 /** 787 * Profile off deadline reached, notify the user that personal apps blocked. 788 */ 789 private static final int PROFILE_OFF_NOTIFICATION_SUSPENDED = 2; 790 791 interface Stats { 792 int LOCK_GUARD_GUARD = 0; 793 794 int COUNT = LOCK_GUARD_GUARD + 1; 795 } 796 797 private final StatLogger mStatLogger = new StatLogger(new String[] { 798 "LockGuard.guard()", 799 }); 800 801 private final Object mLockDoNoUseDirectly = LockGuard.installNewLock( 802 LockGuard.INDEX_DPMS, /* doWtf=*/ true); 803 getLockObject()804 final Object getLockObject() { 805 if (ENABLE_LOCK_GUARD) { 806 final long start = mStatLogger.getTime(); 807 LockGuard.guard(LockGuard.INDEX_DPMS); 808 mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start); 809 } 810 return mLockDoNoUseDirectly; 811 } 812 813 /** 814 * Check if the current thread holds the DPMS lock, and if not, do a WTF. 815 * 816 * (Doing this check too much may be costly, so don't call it in a hot path.) 817 */ ensureLocked()818 final void ensureLocked() { 819 if (Thread.holdsLock(mLockDoNoUseDirectly)) { 820 return; 821 } 822 Slogf.wtfStack(LOG_TAG, "Not holding DPMS lock."); 823 } 824 825 /** 826 * Calls wtfStack() if called with the DPMS lock held. 827 */ wtfIfInLock()828 private void wtfIfInLock() { 829 if (Thread.holdsLock(mLockDoNoUseDirectly)) { 830 Slogf.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held"); 831 } 832 } 833 834 @VisibleForTesting 835 final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager; 836 837 @Nullable 838 private DevicePolicySafetyChecker mSafetyChecker; 839 840 @GuardedBy("getLockObject()") 841 private final ArrayList<Object> mPendingUserCreatedCallbackTokens = new ArrayList<>(); 842 843 public static final class Lifecycle extends SystemService { 844 private BaseIDevicePolicyManager mService; 845 Lifecycle(Context context)846 public Lifecycle(Context context) { 847 super(context); 848 String dpmsClassName = context.getResources() 849 .getString(R.string.config_deviceSpecificDevicePolicyManagerService); 850 if (TextUtils.isEmpty(dpmsClassName)) { 851 dpmsClassName = DevicePolicyManagerService.class.getName(); 852 } 853 try { 854 Class<?> serviceClass = Class.forName(dpmsClassName); 855 Constructor<?> constructor = serviceClass.getConstructor(Context.class); 856 mService = (BaseIDevicePolicyManager) constructor.newInstance(context); 857 } catch (Exception e) { 858 throw new IllegalStateException( 859 "Failed to instantiate DevicePolicyManagerService with class name: " 860 + dpmsClassName, e); 861 } 862 } 863 864 /** Sets the {@link DevicePolicySafetyChecker}. */ setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)865 public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) { 866 mService.setDevicePolicySafetyChecker(safetyChecker); 867 } 868 869 @Override onStart()870 public void onStart() { 871 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService); 872 } 873 874 @Override onBootPhase(int phase)875 public void onBootPhase(int phase) { 876 mService.systemReady(phase); 877 } 878 879 @Override onUserStarting(@onNull TargetUser user)880 public void onUserStarting(@NonNull TargetUser user) { 881 if (user.isPreCreated()) return; 882 mService.handleStartUser(user.getUserIdentifier()); 883 } 884 885 @Override onUserUnlocking(@onNull TargetUser user)886 public void onUserUnlocking(@NonNull TargetUser user) { 887 if (user.isPreCreated()) return; 888 mService.handleUnlockUser(user.getUserIdentifier()); 889 } 890 891 @Override onUserStopping(@onNull TargetUser user)892 public void onUserStopping(@NonNull TargetUser user) { 893 if (user.isPreCreated()) return; 894 mService.handleStopUser(user.getUserIdentifier()); 895 } 896 897 @Override onUserUnlocked(@onNull TargetUser user)898 public void onUserUnlocked(@NonNull TargetUser user) { 899 if (user.isPreCreated()) return; 900 mService.handleOnUserUnlocked(user.getUserIdentifier()); 901 } 902 } 903 904 @GuardedBy("getLockObject()") 905 final SparseArray<DevicePolicyData> mUserData; 906 907 @GuardedBy("getLockObject()") 908 909 final Handler mHandler; 910 final Handler mBackgroundHandler; 911 912 /** Listens only if mHasFeature == true. */ 913 final BroadcastReceiver mReceiver = new BroadcastReceiver() { 914 @Override 915 public void onReceive(Context context, Intent intent) { 916 final String action = intent.getAction(); 917 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 918 getSendingUserId()); 919 920 /* 921 * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(), 922 * however it's too early in the boot process to register with IIpConnectivityMetrics 923 * to listen for events. 924 */ 925 if (Intent.ACTION_USER_STARTED.equals(action) && userHandle == UserHandle.USER_SYSTEM) { 926 synchronized (getLockObject()) { 927 if (isNetworkLoggingEnabledInternalLocked()) { 928 setNetworkLoggingActiveInternal(true); 929 } 930 } 931 } 932 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 933 && userHandle == mOwners.getDeviceOwnerUserId()) { 934 mBugreportCollectionManager.checkForPendingBugreportAfterBoot(); 935 936 } 937 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 938 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) { 939 if (VERBOSE_LOG) { 940 Slogf.v(LOG_TAG, "Sending password expiration notifications for action " 941 + action + " for user " + userHandle); 942 } 943 mHandler.post(new Runnable() { 944 @Override 945 public void run() { 946 handlePasswordExpirationNotification(userHandle); 947 } 948 }); 949 } 950 951 if (Intent.ACTION_USER_ADDED.equals(action)) { 952 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle); 953 synchronized (getLockObject()) { 954 // It might take a while for the user to become affiliated. Make security 955 // and network logging unavailable in the meantime. 956 maybePauseDeviceWideLoggingLocked(); 957 } 958 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 959 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle); 960 synchronized (getLockObject()) { 961 // Check whether the user is affiliated, *before* removing its data. 962 boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle); 963 removeUserData(userHandle); 964 if (!isRemovedUserAffiliated) { 965 // We discard the logs when unaffiliated users are deleted (so that the 966 // device owner cannot retrieve data about that user after it's gone). 967 discardDeviceWideLogsLocked(); 968 // Resume logging if all remaining users are affiliated. 969 maybeResumeDeviceWideLoggingLocked(); 970 } 971 } 972 } else if (Intent.ACTION_USER_STARTED.equals(action)) { 973 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle); 974 synchronized (getLockObject()) { 975 maybeSendAdminEnabledBroadcastLocked(userHandle); 976 // Reset the policy data 977 mUserData.remove(userHandle); 978 } 979 handlePackagesChanged(null /* check all admins */, userHandle); 980 updatePersonalAppsSuspensionOnUserStart(userHandle); 981 } else if (Intent.ACTION_USER_STOPPED.equals(action)) { 982 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle); 983 if (isManagedProfile(userHandle)) { 984 Slogf.d(LOG_TAG, "Managed profile was stopped"); 985 updatePersonalAppsSuspension(userHandle, false /* unlocked */); 986 } 987 } else if (Intent.ACTION_USER_SWITCHED.equals(action)) { 988 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle); 989 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) { 990 synchronized (getLockObject()) { 991 maybeSendAdminEnabledBroadcastLocked(userHandle); 992 } 993 if (isManagedProfile(userHandle)) { 994 Slogf.d(LOG_TAG, "Managed profile became unlocked"); 995 final boolean suspended = 996 updatePersonalAppsSuspension(userHandle, true /* unlocked */); 997 triggerPolicyComplianceCheckIfNeeded(userHandle, suspended); 998 } 999 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { 1000 handlePackagesChanged(null /* check all admins */, userHandle); 1001 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { 1002 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 1003 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { 1004 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 1005 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 1006 } else { 1007 handleNewPackageInstalled(intent.getData().getSchemeSpecificPart(), userHandle); 1008 } 1009 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action) 1010 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 1011 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 1012 removeCredentialManagementApp(intent.getData().getSchemeSpecificPart()); 1013 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) { 1014 clearWipeProfileNotification(); 1015 } else if (Intent.ACTION_DATE_CHANGED.equals(action) 1016 || Intent.ACTION_TIME_CHANGED.equals(action)) { 1017 // Update freeze period record when clock naturally progresses to the next day 1018 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made 1019 // (ACTION_TIME_CHANGED) 1020 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true); 1021 final int userId = getManagedUserId(UserHandle.USER_SYSTEM); 1022 if (userId >= 0) { 1023 updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked(userId)); 1024 } 1025 } else if (ACTION_PROFILE_OFF_DEADLINE.equals(action)) { 1026 Slogf.i(LOG_TAG, "Profile off deadline alarm was triggered"); 1027 final int userId = getManagedUserId(UserHandle.USER_SYSTEM); 1028 if (userId >= 0) { 1029 updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked(userId)); 1030 } else { 1031 Slogf.wtf(LOG_TAG, "Got deadline alarm for nonexistent profile"); 1032 } 1033 } else if (ACTION_TURN_PROFILE_ON_NOTIFICATION.equals(action)) { 1034 Slogf.i(LOG_TAG, "requesting to turn on the profile: " + userHandle); 1035 mUserManager.requestQuietModeEnabled(false, UserHandle.of(userHandle)); 1036 } 1037 } 1038 1039 private void sendDeviceOwnerUserCommand(String action, int userHandle) { 1040 synchronized (getLockObject()) { 1041 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 1042 if (deviceOwner != null) { 1043 Bundle extras = new Bundle(); 1044 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 1045 sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null, 1046 /* inForeground */ true); 1047 } 1048 } 1049 } 1050 }; 1051 1052 protected static class RestrictionsListener implements UserRestrictionsListener { 1053 private final Context mContext; 1054 private final UserManagerInternal mUserManagerInternal; 1055 private final DevicePolicyManagerService mDpms; 1056 RestrictionsListener( Context context, UserManagerInternal userManagerInternal, DevicePolicyManagerService dpms)1057 public RestrictionsListener( 1058 Context context, 1059 UserManagerInternal userManagerInternal, 1060 DevicePolicyManagerService dpms) { 1061 mContext = context; 1062 mUserManagerInternal = userManagerInternal; 1063 mDpms = dpms; 1064 } 1065 1066 @Override onUserRestrictionsChanged(int userId, Bundle newRestrictions, Bundle prevRestrictions)1067 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions, 1068 Bundle prevRestrictions) { 1069 resetCrossProfileIntentFiltersIfNeeded(userId, newRestrictions, prevRestrictions); 1070 resetUserVpnIfNeeded(userId, newRestrictions, prevRestrictions); 1071 } 1072 resetUserVpnIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1073 private void resetUserVpnIfNeeded( 1074 int userId, Bundle newRestrictions, Bundle prevRestrictions) { 1075 final boolean newlyEnforced = 1076 !prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN) 1077 && newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN); 1078 if (newlyEnforced) { 1079 mDpms.clearUserConfiguredVpns(userId); 1080 } 1081 } 1082 resetCrossProfileIntentFiltersIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1083 private void resetCrossProfileIntentFiltersIfNeeded( 1084 int userId, Bundle newRestrictions, Bundle prevRestrictions) { 1085 if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions, 1086 UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE)) { 1087 final int parentId = mUserManagerInternal.getProfileParentId(userId); 1088 if (parentId == userId) { 1089 return; 1090 } 1091 1092 // Always reset filters on the parent user, which handles cross profile intent 1093 // filters between the parent and its profiles. 1094 Slogf.i(LOG_TAG, "Resetting cross-profile intent filters on restriction " 1095 + "change"); 1096 mDpms.resetDefaultCrossProfileIntentFilters(parentId); 1097 mContext.sendBroadcastAsUser( 1098 new Intent(DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_APPLIED), 1099 UserHandle.of(userId)); 1100 } 1101 } 1102 } 1103 clearUserConfiguredVpns(int userId)1104 private void clearUserConfiguredVpns(int userId) { 1105 final String adminConfiguredVpnPkg; 1106 synchronized (getLockObject()) { 1107 final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 1108 if (owner == null) { 1109 Slogf.wtf(LOG_TAG, "Admin not found"); 1110 return; 1111 } 1112 adminConfiguredVpnPkg = owner.mAlwaysOnVpnPackage; 1113 } 1114 1115 // Clear always-on configuration if it wasn't set by the admin. 1116 if (adminConfiguredVpnPkg == null) { 1117 mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(userId, null, false, null); 1118 } 1119 1120 // Clear app authorizations to establish VPNs. When DISALLOW_CONFIG_VPN is enforced apps 1121 // won't be able to get those authorizations unless it is configured by an admin. 1122 final List<AppOpsManager.PackageOps> allVpnOps = mInjector.getAppOpsManager() 1123 .getPackagesForOps(new int[] {AppOpsManager.OP_ACTIVATE_VPN}); 1124 if (allVpnOps == null) { 1125 return; 1126 } 1127 for (AppOpsManager.PackageOps pkgOps : allVpnOps) { 1128 if (UserHandle.getUserId(pkgOps.getUid()) != userId 1129 || pkgOps.getPackageName().equals(adminConfiguredVpnPkg)) { 1130 continue; 1131 } 1132 if (pkgOps.getOps().size() != 1) { 1133 Slogf.wtf(LOG_TAG, "Unexpected number of ops returned"); 1134 continue; 1135 } 1136 final @Mode int mode = pkgOps.getOps().get(0).getMode(); 1137 if (mode == MODE_ALLOWED) { 1138 Slogf.i(LOG_TAG, String.format("Revoking VPN authorization for package %s uid %d", 1139 pkgOps.getPackageName(), pkgOps.getUid())); 1140 mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN, pkgOps.getUid(), 1141 pkgOps.getPackageName(), MODE_DEFAULT); 1142 } 1143 } 1144 } 1145 1146 private final class UserLifecycleListener implements UserManagerInternal.UserLifecycleListener { 1147 1148 @Override onUserCreated(UserInfo user, Object token)1149 public void onUserCreated(UserInfo user, Object token) { 1150 mHandler.post(() -> handleNewUserCreated(user, token)); 1151 } 1152 } 1153 handlePackagesChanged(@ullable String packageName, int userHandle)1154 private void handlePackagesChanged(@Nullable String packageName, int userHandle) { 1155 boolean removedAdmin = false; 1156 if (VERBOSE_LOG) { 1157 Slogf.d(LOG_TAG, "Handling package changes package " + packageName 1158 + " for user " + userHandle); 1159 } 1160 DevicePolicyData policy = getUserData(userHandle); 1161 synchronized (getLockObject()) { 1162 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 1163 ActiveAdmin aa = policy.mAdminList.get(i); 1164 try { 1165 // If we're checking all packages or if the specific one we're checking matches, 1166 // then check if the package and receiver still exist. 1167 final String adminPackage = aa.info.getPackageName(); 1168 if (packageName == null || packageName.equals(adminPackage)) { 1169 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null 1170 || mIPackageManager.getReceiverInfo(aa.info.getComponent(), 1171 PackageManager.MATCH_DIRECT_BOOT_AWARE 1172 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 1173 userHandle) == null) { 1174 removedAdmin = true; 1175 policy.mAdminList.remove(i); 1176 policy.mAdminMap.remove(aa.info.getComponent()); 1177 pushActiveAdminPackagesLocked(userHandle); 1178 pushMeteredDisabledPackages(userHandle); 1179 } 1180 } 1181 } catch (RemoteException re) { 1182 // Shouldn't happen. 1183 } 1184 } 1185 if (removedAdmin) { 1186 policy.validatePasswordOwner(); 1187 } 1188 1189 boolean removedDelegate = false; 1190 1191 // Check if a delegate was removed. 1192 for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) { 1193 final String delegatePackage = policy.mDelegationMap.keyAt(i); 1194 if (isRemovedPackage(packageName, delegatePackage, userHandle)) { 1195 policy.mDelegationMap.removeAt(i); 1196 removedDelegate = true; 1197 } 1198 } 1199 1200 // If it's an owner package, we may need to refresh the bound connection. 1201 final ComponentName owner = getOwnerComponent(userHandle); 1202 if ((packageName != null) && (owner != null) 1203 && (owner.getPackageName().equals(packageName))) { 1204 startOwnerService(userHandle, "package-broadcast"); 1205 } 1206 1207 // Persist updates if the removed package was an admin or delegate. 1208 if (removedAdmin || removedDelegate) { 1209 saveSettingsLocked(policy.mUserId); 1210 } 1211 } 1212 if (removedAdmin) { 1213 // The removed admin might have disabled camera, so update user restrictions. 1214 pushUserRestrictions(userHandle); 1215 } 1216 } 1217 removeCredentialManagementApp(String packageName)1218 private void removeCredentialManagementApp(String packageName) { 1219 mBackgroundHandler.post(() -> { 1220 try (KeyChainConnection connection = mInjector.keyChainBind()) { 1221 IKeyChainService service = connection.getService(); 1222 if (service.hasCredentialManagementApp() 1223 && packageName.equals(service.getCredentialManagementAppPackageName())) { 1224 service.removeCredentialManagementApp(); 1225 } 1226 } catch (RemoteException | InterruptedException | IllegalStateException 1227 | AssertionError e) { 1228 Slogf.e(LOG_TAG, "Unable to remove the credential management app", e); 1229 } 1230 }); 1231 } 1232 isRemovedPackage(String changedPackage, String targetPackage, int userHandle)1233 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) { 1234 try { 1235 return targetPackage != null 1236 && (changedPackage == null || changedPackage.equals(targetPackage)) 1237 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null; 1238 } catch (RemoteException e) { 1239 // Shouldn't happen 1240 } 1241 1242 return false; 1243 } 1244 handleNewPackageInstalled(String packageName, int userHandle)1245 private void handleNewPackageInstalled(String packageName, int userHandle) { 1246 // If personal apps were suspended by the admin, suspend the newly installed one. 1247 if (!getUserData(userHandle).mAppsSuspended) { 1248 return; 1249 } 1250 final String[] packagesToSuspend = { packageName }; 1251 // Check if package is considered not suspendable? 1252 if (mInjector.getPackageManager(userHandle) 1253 .getUnsuspendablePackages(packagesToSuspend).length != 0) { 1254 Slogf.i(LOG_TAG, "Newly installed package is unsuspendable: " + packageName); 1255 return; 1256 } 1257 try { 1258 mIPackageManager.setPackagesSuspendedAsUser(packagesToSuspend, true /*suspend*/, 1259 null, null, null, PLATFORM_PACKAGE_NAME, userHandle); 1260 } catch (RemoteException ignored) { 1261 // shouldn't happen. 1262 } 1263 } 1264 1265 @Override setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1266 public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) { 1267 CallerIdentity callerIdentity = getCallerIdentity(); 1268 Preconditions.checkCallAuthorization(mIsAutomotive || isAdb(callerIdentity), "can only set " 1269 + "DevicePolicySafetyChecker on automotive builds or from ADB (but caller is %s)", 1270 callerIdentity); 1271 setDevicePolicySafetyCheckerUnchecked(safetyChecker); 1272 } 1273 1274 /** 1275 * Used by {@code setDevicePolicySafetyChecker()} above and {@link OneTimeSafetyChecker}. 1276 */ setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker)1277 void setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker) { 1278 Slogf.i(LOG_TAG, "Setting DevicePolicySafetyChecker as %s", safetyChecker); 1279 mSafetyChecker = safetyChecker; 1280 mInjector.setDevicePolicySafetyChecker(safetyChecker); 1281 } 1282 1283 /** 1284 * Used by {@link OneTimeSafetyChecker} only. 1285 */ getDevicePolicySafetyChecker()1286 DevicePolicySafetyChecker getDevicePolicySafetyChecker() { 1287 return mSafetyChecker; 1288 } 1289 1290 /** 1291 * Checks if it's safe to execute the given {@code operation}. 1292 * 1293 * @throws UnsafeStateException if it's not safe to execute the operation. 1294 */ checkCanExecuteOrThrowUnsafe(@evicePolicyOperation int operation)1295 private void checkCanExecuteOrThrowUnsafe(@DevicePolicyOperation int operation) { 1296 int reason = getUnsafeOperationReason(operation); 1297 if (reason == OPERATION_SAFETY_REASON_NONE) return; 1298 1299 if (mSafetyChecker == null) { 1300 // Happens on CTS after it's set just once (by OneTimeSafetyChecker) 1301 throw new UnsafeStateException(operation, reason); 1302 } 1303 // Let mSafetyChecker customize it (for example, by explaining how to retry) 1304 throw mSafetyChecker.newUnsafeStateException(operation, reason); 1305 } 1306 1307 /** 1308 * Returns whether it's safe to execute the given {@code operation}, and why. 1309 */ 1310 @OperationSafetyReason getUnsafeOperationReason(@evicePolicyOperation int operation)1311 int getUnsafeOperationReason(@DevicePolicyOperation int operation) { 1312 return mSafetyChecker == null ? OPERATION_SAFETY_REASON_NONE 1313 : mSafetyChecker.getUnsafeOperationReason(operation); 1314 } 1315 1316 @Override setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)1317 public void setNextOperationSafety(@DevicePolicyOperation int operation, 1318 @OperationSafetyReason int reason) { 1319 Preconditions.checkCallAuthorization( 1320 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 1321 Slogf.i(LOG_TAG, "setNextOperationSafety(%s, %s)", 1322 DevicePolicyManager.operationToString(operation), 1323 DevicePolicyManager.operationSafetyReasonToString(reason)); 1324 mSafetyChecker = new OneTimeSafetyChecker(this, operation, reason); 1325 } 1326 1327 @Override isSafeOperation(@perationSafetyReason int reason)1328 public boolean isSafeOperation(@OperationSafetyReason int reason) { 1329 if (VERBOSE_LOG) { 1330 Slogf.v(LOG_TAG, "checking isSafeOperation(%s) using mSafetyChecker %s", 1331 DevicePolicyManager.operationSafetyReasonToString(reason), mSafetyChecker); 1332 } 1333 return mSafetyChecker == null ? true : mSafetyChecker.isSafeOperation(reason); 1334 } 1335 1336 // Used by DevicePolicyManagerServiceShellCommand listAllOwners()1337 List<OwnerShellData> listAllOwners() { 1338 Preconditions.checkCallAuthorization( 1339 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 1340 return mInjector.binderWithCleanCallingIdentity(() -> { 1341 SparseArray<DevicePolicyData> userData; 1342 1343 // Gets the owners of "full users" first (device owner and profile owners) 1344 List<OwnerShellData> owners = mOwners.listAllOwners(); 1345 synchronized (getLockObject()) { 1346 for (int i = 0; i < owners.size(); i++) { 1347 OwnerShellData owner = owners.get(i); 1348 owner.isAffiliated = isUserAffiliatedWithDeviceLocked(owner.userId); 1349 } 1350 userData = mUserData; 1351 } 1352 1353 // Then the owners of profile users (managed profiles) 1354 for (int i = 0; i < userData.size(); i++) { 1355 DevicePolicyData policyData = mUserData.valueAt(i); 1356 int userId = userData.keyAt(i); 1357 int parentUserId = mUserManagerInternal.getProfileParentId(userId); 1358 boolean isProfile = parentUserId != userId; 1359 if (!isProfile) continue; 1360 for (int j = 0; j < policyData.mAdminList.size(); j++) { 1361 ActiveAdmin admin = policyData.mAdminList.get(j); 1362 OwnerShellData owner = OwnerShellData.forManagedProfileOwner(userId, 1363 parentUserId, admin.info.getComponent()); 1364 owners.add(owner); 1365 } 1366 } 1367 1368 return owners; 1369 }); 1370 } 1371 1372 /** 1373 * Unit test will subclass it to inject mocks. 1374 */ 1375 @VisibleForTesting 1376 static class Injector { 1377 1378 public final Context mContext; 1379 1380 @Nullable private DevicePolicySafetyChecker mSafetyChecker; 1381 Injector(Context context)1382 Injector(Context context) { 1383 mContext = context; 1384 } 1385 hasFeature()1386 public boolean hasFeature() { 1387 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN); 1388 } 1389 createContextAsUser(UserHandle user)1390 Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException { 1391 final String packageName = mContext.getPackageName(); 1392 return mContext.createPackageContextAsUser(packageName, 0, user); 1393 } 1394 getResources()1395 Resources getResources() { 1396 return mContext.getResources(); 1397 } 1398 getUserManager()1399 UserManager getUserManager() { 1400 return UserManager.get(mContext); 1401 } 1402 getUserManagerInternal()1403 UserManagerInternal getUserManagerInternal() { 1404 return LocalServices.getService(UserManagerInternal.class); 1405 } 1406 getPackageManagerInternal()1407 PackageManagerInternal getPackageManagerInternal() { 1408 return LocalServices.getService(PackageManagerInternal.class); 1409 } 1410 getActivityTaskManagerInternal()1411 ActivityTaskManagerInternal getActivityTaskManagerInternal() { 1412 return LocalServices.getService(ActivityTaskManagerInternal.class); 1413 } 1414 getPermissionControllerManager( @onNull UserHandle user)1415 @NonNull PermissionControllerManager getPermissionControllerManager( 1416 @NonNull UserHandle user) { 1417 if (user.equals(mContext.getUser())) { 1418 return mContext.getSystemService(PermissionControllerManager.class); 1419 } else { 1420 try { 1421 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, 1422 user).getSystemService(PermissionControllerManager.class); 1423 } catch (NameNotFoundException notPossible) { 1424 // not possible 1425 throw new IllegalStateException(notPossible); 1426 } 1427 } 1428 } 1429 getUsageStatsManagerInternal()1430 UsageStatsManagerInternal getUsageStatsManagerInternal() { 1431 return LocalServices.getService(UsageStatsManagerInternal.class); 1432 } 1433 getNetworkPolicyManagerInternal()1434 NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() { 1435 return LocalServices.getService(NetworkPolicyManagerInternal.class); 1436 } 1437 getNotificationManager()1438 NotificationManager getNotificationManager() { 1439 return mContext.getSystemService(NotificationManager.class); 1440 } 1441 getIIpConnectivityMetrics()1442 IIpConnectivityMetrics getIIpConnectivityMetrics() { 1443 return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface( 1444 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME)); 1445 } 1446 getPackageManager()1447 PackageManager getPackageManager() { 1448 return mContext.getPackageManager(); 1449 } 1450 getPackageManager(int userId)1451 PackageManager getPackageManager(int userId) { 1452 return mContext 1453 .createContextAsUser(UserHandle.of(userId), 0 /* flags */).getPackageManager(); 1454 } 1455 getPowerManagerInternal()1456 PowerManagerInternal getPowerManagerInternal() { 1457 return LocalServices.getService(PowerManagerInternal.class); 1458 } 1459 getTelephonyManager()1460 TelephonyManager getTelephonyManager() { 1461 return mContext.getSystemService(TelephonyManager.class); 1462 } 1463 getTrustManager()1464 TrustManager getTrustManager() { 1465 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE); 1466 } 1467 getAlarmManager()1468 AlarmManager getAlarmManager() { 1469 return mContext.getSystemService(AlarmManager.class); 1470 } 1471 getConnectivityManager()1472 ConnectivityManager getConnectivityManager() { 1473 return mContext.getSystemService(ConnectivityManager.class); 1474 } 1475 getVpnManager()1476 VpnManager getVpnManager() { 1477 return mContext.getSystemService(VpnManager.class); 1478 } 1479 getLocationManager()1480 LocationManager getLocationManager() { 1481 return mContext.getSystemService(LocationManager.class); 1482 } 1483 getIWindowManager()1484 IWindowManager getIWindowManager() { 1485 return IWindowManager.Stub 1486 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)); 1487 } 1488 getIActivityManager()1489 IActivityManager getIActivityManager() { 1490 return ActivityManager.getService(); 1491 } 1492 getIActivityTaskManager()1493 IActivityTaskManager getIActivityTaskManager() { 1494 return ActivityTaskManager.getService(); 1495 } 1496 getActivityManagerInternal()1497 ActivityManagerInternal getActivityManagerInternal() { 1498 return LocalServices.getService(ActivityManagerInternal.class); 1499 } 1500 getIPackageManager()1501 IPackageManager getIPackageManager() { 1502 return AppGlobals.getPackageManager(); 1503 } 1504 getIPermissionManager()1505 IPermissionManager getIPermissionManager() { 1506 return AppGlobals.getPermissionManager(); 1507 } 1508 getIBackupManager()1509 IBackupManager getIBackupManager() { 1510 return IBackupManager.Stub.asInterface( 1511 ServiceManager.getService(Context.BACKUP_SERVICE)); 1512 } 1513 getIAudioService()1514 IAudioService getIAudioService() { 1515 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE)); 1516 } 1517 getPersistentDataBlockManagerInternal()1518 PersistentDataBlockManagerInternal getPersistentDataBlockManagerInternal() { 1519 return LocalServices.getService(PersistentDataBlockManagerInternal.class); 1520 } 1521 getAppOpsManager()1522 AppOpsManager getAppOpsManager() { 1523 return mContext.getSystemService(AppOpsManager.class); 1524 } 1525 getLockSettingsInternal()1526 LockSettingsInternal getLockSettingsInternal() { 1527 return LocalServices.getService(LockSettingsInternal.class); 1528 } 1529 getCrossProfileApps()1530 CrossProfileApps getCrossProfileApps() { 1531 return mContext.getSystemService(CrossProfileApps.class); 1532 } 1533 hasUserSetupCompleted(DevicePolicyData userData)1534 boolean hasUserSetupCompleted(DevicePolicyData userData) { 1535 return userData.mUserSetupComplete; 1536 } 1537 isBuildDebuggable()1538 boolean isBuildDebuggable() { 1539 return Build.IS_DEBUGGABLE; 1540 } 1541 newLockPatternUtils()1542 LockPatternUtils newLockPatternUtils() { 1543 return new LockPatternUtils(mContext); 1544 } 1545 newEnterpriseSpecificIdCalculator()1546 EnterpriseSpecificIdCalculator newEnterpriseSpecificIdCalculator() { 1547 return new EnterpriseSpecificIdCalculator(mContext); 1548 } 1549 storageManagerIsFileBasedEncryptionEnabled()1550 boolean storageManagerIsFileBasedEncryptionEnabled() { 1551 return StorageManager.isFileEncryptedNativeOnly(); 1552 } 1553 getMyLooper()1554 Looper getMyLooper() { 1555 return Looper.myLooper(); 1556 } 1557 getWifiManager()1558 WifiManager getWifiManager() { 1559 return mContext.getSystemService(WifiManager.class); 1560 } 1561 getUsbManager()1562 UsbManager getUsbManager() { 1563 return mContext.getSystemService(UsbManager.class); 1564 } 1565 1566 @SuppressWarnings("AndroidFrameworkBinderIdentity") binderClearCallingIdentity()1567 long binderClearCallingIdentity() { 1568 return Binder.clearCallingIdentity(); 1569 } 1570 1571 @SuppressWarnings("AndroidFrameworkBinderIdentity") binderRestoreCallingIdentity(long token)1572 void binderRestoreCallingIdentity(long token) { 1573 Binder.restoreCallingIdentity(token); 1574 } 1575 binderGetCallingUid()1576 int binderGetCallingUid() { 1577 return Binder.getCallingUid(); 1578 } 1579 binderGetCallingPid()1580 int binderGetCallingPid() { 1581 return Binder.getCallingPid(); 1582 } 1583 binderGetCallingUserHandle()1584 UserHandle binderGetCallingUserHandle() { 1585 return Binder.getCallingUserHandle(); 1586 } 1587 binderIsCallingUidMyUid()1588 boolean binderIsCallingUidMyUid() { 1589 return getCallingUid() == Process.myUid(); 1590 } 1591 binderWithCleanCallingIdentity(@onNull ThrowingRunnable action)1592 void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) { 1593 Binder.withCleanCallingIdentity(action); 1594 } 1595 binderWithCleanCallingIdentity(@onNull ThrowingSupplier<T> action)1596 final <T> T binderWithCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) { 1597 return Binder.withCleanCallingIdentity(action); 1598 } 1599 userHandleGetCallingUserId()1600 final int userHandleGetCallingUserId() { 1601 return UserHandle.getUserId(binderGetCallingUid()); 1602 } 1603 powerManagerGoToSleep(long time, int reason, int flags)1604 void powerManagerGoToSleep(long time, int reason, int flags) { 1605 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags); 1606 } 1607 powerManagerReboot(String reason)1608 void powerManagerReboot(String reason) { 1609 mContext.getSystemService(PowerManager.class).reboot(reason); 1610 } 1611 recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)1612 boolean recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, 1613 boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData) 1614 throws IOException { 1615 return FactoryResetter.newBuilder(mContext).setSafetyChecker(mSafetyChecker) 1616 .setReason(reason).setShutdown(shutdown).setForce(force).setWipeEuicc(wipeEuicc) 1617 .setWipeAdoptableStorage(wipeExtRequested) 1618 .setWipeFactoryResetProtection(wipeResetProtectionData) 1619 .build().factoryReset(); 1620 } 1621 systemPropertiesGetBoolean(String key, boolean def)1622 boolean systemPropertiesGetBoolean(String key, boolean def) { 1623 return SystemProperties.getBoolean(key, def); 1624 } 1625 systemPropertiesGetLong(String key, long def)1626 long systemPropertiesGetLong(String key, long def) { 1627 return SystemProperties.getLong(key, def); 1628 } 1629 systemPropertiesGet(String key, String def)1630 String systemPropertiesGet(String key, String def) { 1631 return SystemProperties.get(key, def); 1632 } 1633 systemPropertiesGet(String key)1634 String systemPropertiesGet(String key) { 1635 return SystemProperties.get(key); 1636 } 1637 systemPropertiesSet(String key, String value)1638 void systemPropertiesSet(String key, String value) { 1639 SystemProperties.set(key, value); 1640 } 1641 userManagerIsHeadlessSystemUserMode()1642 boolean userManagerIsHeadlessSystemUserMode() { 1643 return UserManager.isHeadlessSystemUserMode(); 1644 } 1645 1646 @SuppressWarnings("AndroidFrameworkPendingIntentMutability") pendingIntentGetActivityAsUser(Context context, int requestCode, @NonNull Intent intent, int flags, Bundle options, UserHandle user)1647 PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode, 1648 @NonNull Intent intent, int flags, Bundle options, UserHandle user) { 1649 return PendingIntent.getActivityAsUser( 1650 context, requestCode, intent, flags, options, user); 1651 } 1652 1653 @SuppressWarnings("AndroidFrameworkPendingIntentMutability") pendingIntentGetBroadcast( Context context, int requestCode, Intent intent, int flags)1654 PendingIntent pendingIntentGetBroadcast( 1655 Context context, int requestCode, Intent intent, int flags) { 1656 return PendingIntent.getBroadcast(context, requestCode, intent, flags); 1657 } 1658 registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer, int userHandle)1659 void registerContentObserver(Uri uri, boolean notifyForDescendents, 1660 ContentObserver observer, int userHandle) { 1661 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents, 1662 observer, userHandle); 1663 } 1664 settingsSecureGetIntForUser(String name, int def, int userHandle)1665 int settingsSecureGetIntForUser(String name, int def, int userHandle) { 1666 return Settings.Secure.getIntForUser(mContext.getContentResolver(), 1667 name, def, userHandle); 1668 } 1669 settingsSecureGetStringForUser(String name, int userHandle)1670 String settingsSecureGetStringForUser(String name, int userHandle) { 1671 return Settings.Secure.getStringForUser(mContext.getContentResolver(), name, 1672 userHandle); 1673 } 1674 settingsSecurePutIntForUser(String name, int value, int userHandle)1675 void settingsSecurePutIntForUser(String name, int value, int userHandle) { 1676 Settings.Secure.putIntForUser(mContext.getContentResolver(), 1677 name, value, userHandle); 1678 } 1679 settingsSecurePutStringForUser(String name, String value, int userHandle)1680 void settingsSecurePutStringForUser(String name, String value, int userHandle) { 1681 Settings.Secure.putStringForUser(mContext.getContentResolver(), 1682 name, value, userHandle); 1683 } 1684 settingsGlobalPutStringForUser(String name, String value, int userHandle)1685 void settingsGlobalPutStringForUser(String name, String value, int userHandle) { 1686 Settings.Global.putStringForUser(mContext.getContentResolver(), 1687 name, value, userHandle); 1688 } 1689 settingsSecurePutInt(String name, int value)1690 void settingsSecurePutInt(String name, int value) { 1691 Settings.Secure.putInt(mContext.getContentResolver(), name, value); 1692 } 1693 settingsGlobalGetInt(String name, int def)1694 int settingsGlobalGetInt(String name, int def) { 1695 return Settings.Global.getInt(mContext.getContentResolver(), name, def); 1696 } 1697 1698 @Nullable settingsGlobalGetString(String name)1699 String settingsGlobalGetString(String name) { 1700 return Settings.Global.getString(mContext.getContentResolver(), name); 1701 } 1702 settingsGlobalPutInt(String name, int value)1703 void settingsGlobalPutInt(String name, int value) { 1704 Settings.Global.putInt(mContext.getContentResolver(), name, value); 1705 } 1706 settingsSecurePutString(String name, String value)1707 void settingsSecurePutString(String name, String value) { 1708 Settings.Secure.putString(mContext.getContentResolver(), name, value); 1709 } 1710 settingsGlobalPutString(String name, String value)1711 void settingsGlobalPutString(String name, String value) { 1712 Settings.Global.putString(mContext.getContentResolver(), name, value); 1713 } 1714 settingsSystemPutStringForUser(String name, String value, int userId)1715 void settingsSystemPutStringForUser(String name, String value, int userId) { 1716 Settings.System.putStringForUser( 1717 mContext.getContentResolver(), name, value, userId); 1718 } 1719 securityLogSetLoggingEnabledProperty(boolean enabled)1720 void securityLogSetLoggingEnabledProperty(boolean enabled) { 1721 SecurityLog.setLoggingEnabledProperty(enabled); 1722 } 1723 securityLogGetLoggingEnabledProperty()1724 boolean securityLogGetLoggingEnabledProperty() { 1725 return SecurityLog.getLoggingEnabledProperty(); 1726 } 1727 securityLogIsLoggingEnabled()1728 boolean securityLogIsLoggingEnabled() { 1729 return SecurityLog.isLoggingEnabled(); 1730 } 1731 keyChainBind()1732 KeyChainConnection keyChainBind() throws InterruptedException { 1733 return KeyChain.bind(mContext); 1734 } 1735 keyChainBindAsUser(UserHandle user)1736 KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException { 1737 return KeyChain.bindAsUser(mContext, user); 1738 } 1739 postOnSystemServerInitThreadPool(Runnable runnable)1740 void postOnSystemServerInitThreadPool(Runnable runnable) { 1741 SystemServerInitThreadPool.submit(runnable, LOG_TAG); 1742 } 1743 newTransferOwnershipMetadataManager()1744 public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() { 1745 return new TransferOwnershipMetadataManager(); 1746 } 1747 runCryptoSelfTest()1748 public void runCryptoSelfTest() { 1749 CryptoTestHelper.runAndLogSelfTest(); 1750 } 1751 getPersonalAppsForSuspension(@serIdInt int userId)1752 public String[] getPersonalAppsForSuspension(@UserIdInt int userId) { 1753 return PersonalAppsSuspensionHelper.forUser(mContext, userId) 1754 .getPersonalAppsForSuspension(); 1755 } 1756 systemCurrentTimeMillis()1757 public long systemCurrentTimeMillis() { 1758 return System.currentTimeMillis(); 1759 } 1760 isChangeEnabled(long changeId, String packageName, int userId)1761 public boolean isChangeEnabled(long changeId, String packageName, int userId) { 1762 return CompatChanges.isChangeEnabled(changeId, packageName, UserHandle.of(userId)); 1763 } 1764 setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1765 void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) { 1766 mSafetyChecker = safetyChecker; 1767 } 1768 getDeviceManagementResourcesProvider()1769 DeviceManagementResourcesProvider getDeviceManagementResourcesProvider() { 1770 return new DeviceManagementResourcesProvider(); 1771 } 1772 } 1773 1774 /** 1775 * Instantiates the service. 1776 */ DevicePolicyManagerService(Context context)1777 public DevicePolicyManagerService(Context context) { 1778 this(new Injector( 1779 context.createAttributionContext(ATTRIBUTION_TAG)), new PolicyPathProvider() {}); 1780 } 1781 1782 @VisibleForTesting DevicePolicyManagerService(Injector injector, PolicyPathProvider pathProvider)1783 DevicePolicyManagerService(Injector injector, PolicyPathProvider pathProvider) { 1784 DevicePolicyManager.disableLocalCaches(); 1785 1786 mInjector = injector; 1787 mPathProvider = pathProvider; 1788 mContext = Objects.requireNonNull(injector.mContext); 1789 mHandler = new Handler(Objects.requireNonNull(injector.getMyLooper())); 1790 1791 mConstantsObserver = new DevicePolicyConstantsObserver(mHandler); 1792 mConstantsObserver.register(); 1793 mConstants = loadConstants(); 1794 1795 mUserManager = Objects.requireNonNull(injector.getUserManager()); 1796 mUserManagerInternal = Objects.requireNonNull(injector.getUserManagerInternal()); 1797 mUsageStatsManagerInternal = Objects.requireNonNull( 1798 injector.getUsageStatsManagerInternal()); 1799 mIPackageManager = Objects.requireNonNull(injector.getIPackageManager()); 1800 mIPermissionManager = Objects.requireNonNull(injector.getIPermissionManager()); 1801 mTelephonyManager = Objects.requireNonNull(injector.getTelephonyManager()); 1802 1803 mLocalService = new LocalService(); 1804 mLockPatternUtils = injector.newLockPatternUtils(); 1805 mLockSettingsInternal = injector.getLockSettingsInternal(); 1806 // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false? 1807 mSecurityLogMonitor = new SecurityLogMonitor(this); 1808 1809 mHasFeature = mInjector.hasFeature(); 1810 mIsWatch = mInjector.getPackageManager() 1811 .hasSystemFeature(PackageManager.FEATURE_WATCH); 1812 mHasTelephonyFeature = mInjector.getPackageManager() 1813 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY); 1814 mIsAutomotive = mInjector.getPackageManager() 1815 .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE); 1816 mBackgroundHandler = BackgroundThread.getHandler(); 1817 1818 // Needed when mHasFeature == false, because it controls the certificate warning text. 1819 mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler); 1820 1821 mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants); 1822 mOverlayPackagesProvider = new OverlayPackagesProvider(mContext); 1823 mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager(); 1824 mBugreportCollectionManager = new RemoteBugreportManager(this, mInjector); 1825 1826 mDeviceManagementResourcesProvider = mInjector.getDeviceManagementResourcesProvider(); 1827 mDevicePolicyManagementRoleObserver = new DevicePolicyManagementRoleObserver(mContext); 1828 mDevicePolicyManagementRoleObserver.register(); 1829 1830 // "Lite" interface is available even when the device doesn't have the feature 1831 LocalServices.addService(DevicePolicyManagerLiteInternal.class, mLocalService); 1832 1833 // Policy version upgrade must not depend on either mOwners or mUserData, so they are 1834 // initialized only after performing the upgrade. 1835 if (mHasFeature) { 1836 performPolicyVersionUpgrade(); 1837 } 1838 mUserData = new SparseArray<>(); 1839 mOwners = makeOwners(injector, pathProvider); 1840 1841 if (!mHasFeature) { 1842 // Skip the rest of the initialization 1843 mSetupContentObserver = null; 1844 return; 1845 } 1846 1847 loadOwners(); 1848 1849 IntentFilter filter = new IntentFilter(); 1850 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 1851 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION); 1852 filter.addAction(ACTION_TURN_PROFILE_ON_NOTIFICATION); 1853 filter.addAction(ACTION_PROFILE_OFF_DEADLINE); 1854 filter.addAction(Intent.ACTION_USER_ADDED); 1855 filter.addAction(Intent.ACTION_USER_REMOVED); 1856 filter.addAction(Intent.ACTION_USER_STARTED); 1857 filter.addAction(Intent.ACTION_USER_STOPPED); 1858 filter.addAction(Intent.ACTION_USER_SWITCHED); 1859 filter.addAction(Intent.ACTION_USER_UNLOCKED); 1860 filter.addAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE); 1861 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 1862 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1863 filter = new IntentFilter(); 1864 filter.addAction(Intent.ACTION_PACKAGE_CHANGED); 1865 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 1866 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 1867 filter.addAction(Intent.ACTION_PACKAGE_ADDED); 1868 filter.addDataScheme("package"); 1869 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1870 filter = new IntentFilter(); 1871 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED); 1872 filter.addAction(Intent.ACTION_TIME_CHANGED); 1873 filter.addAction(Intent.ACTION_DATE_CHANGED); 1874 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1875 1876 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService); 1877 1878 mSetupContentObserver = new SetupContentObserver(mHandler); 1879 1880 mUserManagerInternal.addUserRestrictionsListener( 1881 new RestrictionsListener(mContext, mUserManagerInternal, this)); 1882 mUserManagerInternal.addUserLifecycleListener(new UserLifecycleListener()); 1883 1884 mDeviceManagementResourcesProvider.load(); 1885 1886 // The binder caches are not enabled until the first invalidation. 1887 invalidateBinderCaches(); 1888 } 1889 makeOwners(Injector injector, PolicyPathProvider pathProvider)1890 private Owners makeOwners(Injector injector, PolicyPathProvider pathProvider) { 1891 return new Owners(injector.getUserManager(), injector.getUserManagerInternal(), 1892 injector.getPackageManagerInternal(), 1893 injector.getActivityTaskManagerInternal(), 1894 injector.getActivityManagerInternal(), pathProvider); 1895 } 1896 1897 /** 1898 * Invalidate the binder API caches. The invalidation itself does not require any 1899 * locking, but this specific call should be protected by getLockObject() to ensure 1900 * that the invalidation is synchronous with cached queries, for those queries that 1901 * are served under getLockObject(). 1902 */ invalidateBinderCaches()1903 static void invalidateBinderCaches() { 1904 DevicePolicyManager.invalidateBinderCaches(); 1905 } 1906 1907 /** 1908 * Creates and loads the policy data from xml. 1909 * @param userHandle the user for whom to load the policy data 1910 * @return 1911 */ 1912 @NonNull getUserData(int userHandle)1913 DevicePolicyData getUserData(int userHandle) { 1914 synchronized (getLockObject()) { 1915 DevicePolicyData policy = mUserData.get(userHandle); 1916 if (policy == null) { 1917 policy = new DevicePolicyData(userHandle); 1918 mUserData.append(userHandle, policy); 1919 loadSettingsLocked(policy, userHandle); 1920 if (userHandle == UserHandle.USER_SYSTEM) { 1921 mStateCache.setDeviceProvisioned(policy.mUserSetupComplete); 1922 } 1923 } 1924 return policy; 1925 } 1926 } 1927 1928 /** 1929 * Creates and loads the policy data from xml for data that is shared between 1930 * various profiles of a user. In contrast to {@link #getUserData(int)} 1931 * it allows access to data of users other than the calling user. 1932 * 1933 * This function should only be used for shared data, e.g. everything regarding 1934 * passwords and should be removed once multiple screen locks are present. 1935 * @param userHandle the user for whom to load the policy data 1936 * @return 1937 */ getUserDataUnchecked(int userHandle)1938 DevicePolicyData getUserDataUnchecked(int userHandle) { 1939 return mInjector.binderWithCleanCallingIdentity(() -> getUserData(userHandle)); 1940 } 1941 removeUserData(int userHandle)1942 void removeUserData(int userHandle) { 1943 final boolean isOrgOwned; 1944 synchronized (getLockObject()) { 1945 if (userHandle == UserHandle.USER_SYSTEM) { 1946 Slogf.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring."); 1947 return; 1948 } 1949 updatePasswordQualityCacheForUserGroup(userHandle); 1950 mPolicyCache.onUserRemoved(userHandle); 1951 1952 if (isManagedProfile(userHandle)) { 1953 clearManagedProfileApnUnchecked(); 1954 } 1955 isOrgOwned = mOwners.isProfileOwnerOfOrganizationOwnedDevice(userHandle); 1956 1957 mOwners.removeProfileOwner(userHandle); 1958 mOwners.writeProfileOwner(userHandle); 1959 pushScreenCapturePolicy(userHandle); 1960 1961 DevicePolicyData policy = mUserData.get(userHandle); 1962 if (policy != null) { 1963 mUserData.remove(userHandle); 1964 } 1965 1966 File policyFile = 1967 new File(mPathProvider.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML); 1968 policyFile.delete(); 1969 Slogf.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath()); 1970 } 1971 if (isOrgOwned) { 1972 final UserInfo primaryUser = mUserManager.getPrimaryUser(); 1973 if (primaryUser != null) { 1974 clearOrgOwnedProfileOwnerDeviceWidePolicies(primaryUser.id); 1975 } else { 1976 Slogf.wtf(LOG_TAG, "Was unable to get primary user."); 1977 } 1978 } 1979 } 1980 1981 /** 1982 * Load information about device and profile owners of the device, populating mOwners and 1983 * pushing owner info to other system services. This is called at a fairly early stage of 1984 * system server initialiation (via DevicePolicyManagerService's ctor), so care should to 1985 * be taken to not interact with system services that are initialiated after DPMS. 1986 * onLockSettingsReady() is a safer place to do initialization work not critical during 1987 * the first boot stage. 1988 * Note this only loads the list of owners, and not their actual policy (DevicePolicyData). 1989 * The policy is normally loaded lazily when it's first accessed. In several occasions 1990 * the list of owners is necessary for providing callers with aggregated policies across 1991 * multiple owners, hence the owner list is loaded as part of DPMS's construction here. 1992 */ loadOwners()1993 void loadOwners() { 1994 synchronized (getLockObject()) { 1995 mOwners.load(); 1996 setDeviceOwnershipSystemPropertyLocked(); 1997 if (mOwners.hasDeviceOwner()) { 1998 setGlobalSettingDeviceOwnerType( 1999 mOwners.getDeviceOwnerType(mOwners.getDeviceOwnerPackageName())); 2000 } 2001 } 2002 } 2003 2004 /** 2005 * Creates a new {@link CallerIdentity} object to represent the caller's identity. 2006 */ getCallerIdentity()2007 private CallerIdentity getCallerIdentity() { 2008 return getCallerIdentity(null, null); 2009 } 2010 2011 /** 2012 * Creates a new {@link CallerIdentity} object to represent the caller's identity. 2013 */ getCallerIdentity(@ullable String callerPackage)2014 private CallerIdentity getCallerIdentity(@Nullable String callerPackage) { 2015 2016 return getCallerIdentity(null, callerPackage); 2017 } 2018 2019 /** 2020 * Creates a new {@link CallerIdentity} object to represent the caller's identity. 2021 * The component name should be an active admin for the calling user. 2022 */ 2023 @VisibleForTesting getCallerIdentity(@ullable ComponentName adminComponent)2024 CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent) { 2025 return getCallerIdentity(adminComponent, null); 2026 } 2027 2028 /** 2029 * Creates a new {@link CallerIdentity} object to represent the caller's identity. 2030 * If {@code adminComponent} is provided, it's validated against the list of known 2031 * active admins and caller uid. If {@code callerPackage} is provided, it's validated 2032 * against the caller uid. If a valid {@code adminComponent} is provided but not 2033 * {@code callerPackage}, the package name of the {@code adminComponent} is used instead. 2034 */ 2035 @VisibleForTesting getCallerIdentity(@ullable ComponentName adminComponent, @Nullable String callerPackage)2036 CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent, 2037 @Nullable String callerPackage) { 2038 final int callerUid = mInjector.binderGetCallingUid(); 2039 2040 if (callerPackage != null) { 2041 if (!isCallingFromPackage(callerPackage, callerUid)) { 2042 throw new SecurityException( 2043 String.format("Caller with uid %d is not %s", callerUid, callerPackage)); 2044 } 2045 } 2046 2047 if (adminComponent != null) { 2048 final DevicePolicyData policy = getUserData(UserHandle.getUserId(callerUid)); 2049 ActiveAdmin admin = policy.mAdminMap.get(adminComponent); 2050 2051 // Throwing combined exception message for both the cases here, because from different 2052 // security exceptions it could be deduced if particular package is admin package. 2053 if (admin == null || admin.getUid() != callerUid) { 2054 throw new SecurityException(String.format( 2055 "Admin %s does not exist or is not owned by uid %d", adminComponent, 2056 callerUid)); 2057 } 2058 if (callerPackage != null) { 2059 Preconditions.checkArgument(callerPackage.equals(adminComponent.getPackageName())); 2060 } else { 2061 callerPackage = adminComponent.getPackageName(); 2062 } 2063 } 2064 2065 return new CallerIdentity(callerUid, callerPackage, adminComponent); 2066 } 2067 2068 /** 2069 * Checks if the device is in COMP mode, and if so migrates it to managed profile on a 2070 * corporate owned device. 2071 */ 2072 @GuardedBy("getLockObject()") migrateToProfileOnOrganizationOwnedDeviceIfCompLocked()2073 private void migrateToProfileOnOrganizationOwnedDeviceIfCompLocked() { 2074 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Checking whether we need to migrate COMP "); 2075 final int doUserId = mOwners.getDeviceOwnerUserId(); 2076 if (doUserId == UserHandle.USER_NULL) { 2077 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping migration."); 2078 return; 2079 } 2080 2081 final List<UserInfo> profiles = mUserManager.getProfiles(doUserId); 2082 if (profiles.size() != 2) { 2083 if (profiles.size() == 1) { 2084 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Profile not found, skipping migration."); 2085 } else { 2086 Slogf.wtf(LOG_TAG, "Found " + profiles.size() + " profiles, skipping migration"); 2087 } 2088 return; 2089 } 2090 2091 final int poUserId = getManagedUserId(doUserId); 2092 if (poUserId < 0) { 2093 Slogf.wtf(LOG_TAG, "Found DO and a profile, but it is not managed, skipping migration"); 2094 return; 2095 } 2096 2097 final ActiveAdmin doAdmin = getDeviceOwnerAdminLocked(); 2098 final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(poUserId); 2099 if (doAdmin == null || poAdmin == null) { 2100 Slogf.wtf(LOG_TAG, "Failed to get either PO or DO admin, aborting migration."); 2101 return; 2102 } 2103 2104 final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent(); 2105 final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(poUserId); 2106 if (doAdminComponent == null || poAdminComponent == null) { 2107 Slogf.wtf(LOG_TAG, "Cannot find PO or DO component name, aborting migration."); 2108 return; 2109 } 2110 if (!doAdminComponent.getPackageName().equals(poAdminComponent.getPackageName())) { 2111 Slogf.e(LOG_TAG, "DO and PO are different packages, aborting migration."); 2112 return; 2113 } 2114 2115 Slogf.i(LOG_TAG, "Migrating COMP to PO on a corp owned device; primary user: %d; " 2116 + "profile: %d", doUserId, poUserId); 2117 2118 Slogf.i(LOG_TAG, "Giving the PO additional power..."); 2119 setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(poAdminComponent, poUserId, true); 2120 Slogf.i(LOG_TAG, "Migrating DO policies to PO..."); 2121 moveDoPoliciesToProfileParentAdminLocked(doAdmin, poAdmin.getParentActiveAdmin()); 2122 migratePersonalAppSuspensionLocked(doUserId, poUserId, poAdmin); 2123 saveSettingsLocked(poUserId); 2124 Slogf.i(LOG_TAG, "Clearing the DO..."); 2125 final ComponentName doAdminReceiver = doAdmin.info.getComponent(); 2126 clearDeviceOwnerLocked(doAdmin, doUserId); 2127 Slogf.i(LOG_TAG, "Removing admin artifacts..."); 2128 removeAdminArtifacts(doAdminReceiver, doUserId); 2129 Slogf.i(LOG_TAG, "Uninstalling the DO..."); 2130 uninstallOrDisablePackage(doAdminComponent.getPackageName(), doUserId); 2131 Slogf.i(LOG_TAG, "Migration complete."); 2132 2133 // Note: KeyChain keys are not removed and will remain accessible for the apps that have 2134 // been given grants to use them. 2135 2136 DevicePolicyEventLogger 2137 .createEvent(DevicePolicyEnums.COMP_TO_ORG_OWNED_PO_MIGRATED) 2138 .setAdmin(poAdminComponent) 2139 .write(); 2140 } 2141 2142 @GuardedBy("getLockObject()") migratePersonalAppSuspensionLocked( int doUserId, int poUserId, ActiveAdmin poAdmin)2143 private void migratePersonalAppSuspensionLocked( 2144 int doUserId, int poUserId, ActiveAdmin poAdmin) { 2145 final PackageManagerInternal pmi = mInjector.getPackageManagerInternal(); 2146 if (!pmi.isSuspendingAnyPackages(PLATFORM_PACKAGE_NAME, doUserId)) { 2147 Slogf.i(LOG_TAG, "DO is not suspending any apps."); 2148 return; 2149 } 2150 2151 if (getTargetSdk(poAdmin.info.getPackageName(), poUserId) >= Build.VERSION_CODES.R) { 2152 Slogf.i(LOG_TAG, "PO is targeting R+, keeping personal apps suspended."); 2153 getUserData(doUserId).mAppsSuspended = true; 2154 poAdmin.mSuspendPersonalApps = true; 2155 } else { 2156 Slogf.i(LOG_TAG, "PO isn't targeting R+, unsuspending personal apps."); 2157 pmi.unsuspendForSuspendingPackage(PLATFORM_PACKAGE_NAME, doUserId); 2158 } 2159 } 2160 uninstallOrDisablePackage(String packageName, @UserIdInt int userId)2161 private void uninstallOrDisablePackage(String packageName, @UserIdInt int userId) { 2162 final ApplicationInfo appInfo; 2163 try { 2164 appInfo = mIPackageManager.getApplicationInfo( 2165 packageName, MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId); 2166 } catch (RemoteException e) { 2167 // Shouldn't happen. 2168 return; 2169 } 2170 if (appInfo == null) { 2171 Slogf.wtf(LOG_TAG, "Failed to get package info for " + packageName); 2172 return; 2173 } 2174 if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 2175 Slogf.i(LOG_TAG, "Package %s is pre-installed, marking disabled until used", 2176 packageName); 2177 mContext.getPackageManager().setApplicationEnabledSetting(packageName, 2178 PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, /* flags= */ 0); 2179 return; 2180 } 2181 2182 final IIntentSender.Stub mLocalSender = new IIntentSender.Stub() { 2183 @Override 2184 public void send(int code, Intent intent, String resolvedType, IBinder allowlistToken, 2185 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { 2186 final int status = intent.getIntExtra( 2187 PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE); 2188 if (status == PackageInstaller.STATUS_SUCCESS) { 2189 Slogf.i(LOG_TAG, "Package %s uninstalled for user %d", packageName, userId); 2190 } else { 2191 Slogf.e(LOG_TAG, "Failed to uninstall %s; status: %d", packageName, status); 2192 } 2193 } 2194 }; 2195 2196 final PackageInstaller pi = mInjector.getPackageManager(userId).getPackageInstaller(); 2197 pi.uninstall(packageName, /* flags= */ 0, new IntentSender((IIntentSender) mLocalSender)); 2198 } 2199 2200 @GuardedBy("getLockObject()") moveDoPoliciesToProfileParentAdminLocked( ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2201 private void moveDoPoliciesToProfileParentAdminLocked( 2202 ActiveAdmin doAdmin, ActiveAdmin parentAdmin) { 2203 // The following policies can be already controlled via parent instance, skip if so. 2204 if (parentAdmin.mPasswordPolicy.quality == PASSWORD_QUALITY_UNSPECIFIED) { 2205 parentAdmin.mPasswordPolicy = doAdmin.mPasswordPolicy; 2206 } 2207 if (parentAdmin.passwordHistoryLength == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) { 2208 parentAdmin.passwordHistoryLength = doAdmin.passwordHistoryLength; 2209 } 2210 if (parentAdmin.passwordExpirationTimeout == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) { 2211 parentAdmin.passwordExpirationTimeout = doAdmin.passwordExpirationTimeout; 2212 } 2213 if (parentAdmin.maximumFailedPasswordsForWipe 2214 == ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 2215 parentAdmin.maximumFailedPasswordsForWipe = doAdmin.maximumFailedPasswordsForWipe; 2216 } 2217 if (parentAdmin.maximumTimeToUnlock == ActiveAdmin.DEF_MAXIMUM_TIME_TO_UNLOCK) { 2218 parentAdmin.maximumTimeToUnlock = doAdmin.maximumTimeToUnlock; 2219 } 2220 if (parentAdmin.strongAuthUnlockTimeout 2221 == DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 2222 parentAdmin.strongAuthUnlockTimeout = doAdmin.strongAuthUnlockTimeout; 2223 } 2224 parentAdmin.disabledKeyguardFeatures |= 2225 doAdmin.disabledKeyguardFeatures & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 2226 2227 parentAdmin.trustAgentInfos.putAll(doAdmin.trustAgentInfos); 2228 2229 // The following policies weren't available to PO, but will be available after migration. 2230 parentAdmin.disableCamera = doAdmin.disableCamera; 2231 parentAdmin.disableScreenCapture = doAdmin.disableScreenCapture; 2232 parentAdmin.accountTypesWithManagementDisabled.addAll( 2233 doAdmin.accountTypesWithManagementDisabled); 2234 2235 moveDoUserRestrictionsToCopeParent(doAdmin, parentAdmin); 2236 2237 // From Android 11, {@link setAutoTimeRequired} is no longer used. The user restriction 2238 // {@link UserManager#DISALLOW_CONFIG_DATE_TIME} should be used to enforce auto time 2239 // settings instead. 2240 if (doAdmin.requireAutoTime) { 2241 parentAdmin.ensureUserRestrictions().putBoolean( 2242 UserManager.DISALLOW_CONFIG_DATE_TIME, true); 2243 } 2244 } 2245 moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2246 private void moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin) { 2247 if (doAdmin.userRestrictions == null) { 2248 return; 2249 } 2250 for (final String restriction : doAdmin.userRestrictions.keySet()) { 2251 if (UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(restriction)) { 2252 parentAdmin.ensureUserRestrictions().putBoolean( 2253 restriction, doAdmin.userRestrictions.getBoolean(restriction)); 2254 } 2255 } 2256 } 2257 2258 /** 2259 * If the device is in Device Owner mode, apply the restriction on adding 2260 * a managed profile. 2261 */ 2262 @GuardedBy("getLockObject()") applyProfileRestrictionsIfDeviceOwnerLocked()2263 private void applyProfileRestrictionsIfDeviceOwnerLocked() { 2264 final int doUserId = mOwners.getDeviceOwnerUserId(); 2265 if (doUserId == UserHandle.USER_NULL) { 2266 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping application of restriction."); 2267 return; 2268 } 2269 2270 final UserHandle doUserHandle = UserHandle.of(doUserId); 2271 2272 // Based on CDD : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support, 2273 // creation of clone profile is not allowed in case device owner is set. 2274 // Enforcing this restriction on setting up of device owner. 2275 if (!mUserManager.hasUserRestriction( 2276 UserManager.DISALLOW_ADD_CLONE_PROFILE, doUserHandle)) { 2277 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, true, 2278 doUserHandle); 2279 } 2280 // Creation of managed profile is restricted in case device owner is set, enforcing this 2281 // restriction by setting user level restriction at time of device owner setup. 2282 if (!mUserManager.hasUserRestriction( 2283 UserManager.DISALLOW_ADD_MANAGED_PROFILE, doUserHandle)) { 2284 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true, 2285 doUserHandle); 2286 } 2287 } 2288 2289 /** Apply default restrictions that haven't been applied to profile owners yet. */ maybeSetDefaultProfileOwnerUserRestrictions()2290 private void maybeSetDefaultProfileOwnerUserRestrictions() { 2291 synchronized (getLockObject()) { 2292 for (final int userId : mOwners.getProfileOwnerKeys()) { 2293 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 2294 // The following restrictions used to be applied to managed profiles by different 2295 // means (via Settings or by disabling components). Now they are proper user 2296 // restrictions so we apply them to managed profile owners. Non-managed secondary 2297 // users didn't have those restrictions so we skip them to keep existing behavior. 2298 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) { 2299 continue; 2300 } 2301 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner, 2302 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 2303 ensureUnknownSourcesRestrictionForProfileOwnerLocked( 2304 userId, profileOwner, false /* newOwner */); 2305 } 2306 } 2307 } 2308 2309 /** 2310 * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the 2311 * set of restrictions for this profile owner. 2312 */ ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, ActiveAdmin profileOwner, boolean newOwner)2313 private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, 2314 ActiveAdmin profileOwner, boolean newOwner) { 2315 if (newOwner || mInjector.settingsSecureGetIntForUser( 2316 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) { 2317 profileOwner.ensureUserRestrictions().putBoolean( 2318 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true); 2319 saveUserRestrictionsLocked(userId); 2320 mInjector.settingsSecurePutIntForUser( 2321 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId); 2322 } 2323 } 2324 2325 /** 2326 * Apply default restrictions that haven't been applied to a given admin yet. 2327 */ maybeSetDefaultRestrictionsForAdminLocked( int userId, ActiveAdmin admin, Set<String> defaultRestrictions)2328 private void maybeSetDefaultRestrictionsForAdminLocked( 2329 int userId, ActiveAdmin admin, Set<String> defaultRestrictions) { 2330 if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) { 2331 return; // The same set of default restrictions has been already applied. 2332 } 2333 Slogf.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId); 2334 2335 if (VERBOSE_LOG) { 2336 Slogf.d(LOG_TAG, "Default enabled restrictions: " 2337 + defaultRestrictions 2338 + ". Restrictions already enabled: " 2339 + admin.defaultEnabledRestrictionsAlreadySet); 2340 } 2341 2342 final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions); 2343 restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet); 2344 if (!restrictionsToSet.isEmpty()) { 2345 for (final String restriction : restrictionsToSet) { 2346 admin.ensureUserRestrictions().putBoolean(restriction, true); 2347 } 2348 admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet); 2349 Slogf.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet); 2350 saveUserRestrictionsLocked(userId); 2351 } 2352 } 2353 setDeviceOwnershipSystemPropertyLocked()2354 private void setDeviceOwnershipSystemPropertyLocked() { 2355 final boolean deviceProvisioned = 2356 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0; 2357 final boolean hasDeviceOwner = mOwners.hasDeviceOwner(); 2358 final boolean hasOrgOwnedProfile = isOrganizationOwnedDeviceWithManagedProfile(); 2359 // If the device is not provisioned and there is currently no management, do not set the 2360 // read-only system property yet, since device owner / org-owned profile may still be 2361 // provisioned. 2362 if (!hasDeviceOwner && !hasOrgOwnedProfile && !deviceProvisioned) { 2363 return; 2364 } 2365 final String value = Boolean.toString(hasDeviceOwner || hasOrgOwnedProfile); 2366 final String currentVal = mInjector.systemPropertiesGet(PROPERTY_ORGANIZATION_OWNED, null); 2367 if (TextUtils.isEmpty(currentVal)) { 2368 Slogf.i(LOG_TAG, "Set ro.organization_owned property to " + value); 2369 mInjector.systemPropertiesSet(PROPERTY_ORGANIZATION_OWNED, value); 2370 } else if (!value.equals(currentVal)) { 2371 Slogf.w(LOG_TAG, "Cannot change existing ro.organization_owned to " + value); 2372 } 2373 } 2374 maybeStartSecurityLogMonitorOnActivityManagerReady()2375 private void maybeStartSecurityLogMonitorOnActivityManagerReady() { 2376 synchronized (getLockObject()) { 2377 if (mInjector.securityLogIsLoggingEnabled()) { 2378 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser()); 2379 mInjector.runCryptoSelfTest(); 2380 maybePauseDeviceWideLoggingLocked(); 2381 } 2382 } 2383 } 2384 2385 /** 2386 * Fix left-over restrictions and auto-time policy during COMP -> COPE migration. 2387 * 2388 * When a COMP device with requireAutoTime policy set was migrated to an 2389 * organization-owned profile, a DISALLOW_CONFIG_DATE_TIME restriction is set 2390 * on user 0 from the DO user, which becomes unremovable by the organization-owned 2391 * profile owner. Fix this by force removing that restriction. Also revert the 2392 * parentAdmin.requireAutoTime bit (since the COPE PO cannot unset this bit) 2393 * and replace it with DISALLOW_CONFIG_DATE_TIME on the correct 2394 * admin, in line with the deprecation recommendation of setAutoTimeRequired(). 2395 */ fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration()2396 private void fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration() { 2397 for (UserInfo ui : mUserManager.getUsers()) { 2398 final int userId = ui.id; 2399 if (isProfileOwnerOfOrganizationOwnedDevice(userId)) { 2400 final ActiveAdmin parent = getProfileOwnerAdminLocked(userId).parentAdmin; 2401 if (parent != null && parent.requireAutoTime) { 2402 // Remove deprecated requireAutoTime 2403 parent.requireAutoTime = false; 2404 saveSettingsLocked(userId); 2405 2406 // Remove user restrictions set by the device owner before the upgrade to 2407 // Android 11. 2408 mUserManagerInternal.setDevicePolicyUserRestrictions(UserHandle.USER_SYSTEM, 2409 new Bundle(), new RestrictionsSet(), /* isDeviceOwner */ false); 2410 2411 // Apply user restriction to parent active admin instead 2412 parent.ensureUserRestrictions().putBoolean( 2413 UserManager.DISALLOW_CONFIG_DATE_TIME, true); 2414 pushUserRestrictions(userId); 2415 } 2416 } 2417 } 2418 } 2419 2420 /** 2421 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration 2422 * reminders. Clears alarm if no expirations are configured. 2423 */ setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent)2424 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) { 2425 final long expiration = getPasswordExpirationLocked(null, userHandle, parent); 2426 final long now = System.currentTimeMillis(); 2427 final long timeToExpire = expiration - now; 2428 final long alarmTime; 2429 if (expiration == 0) { 2430 // No expirations are currently configured: Cancel alarm. 2431 alarmTime = 0; 2432 } else if (timeToExpire <= 0) { 2433 // The password has already expired: Repeat every 24 hours. 2434 alarmTime = now + MS_PER_DAY; 2435 } else { 2436 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before 2437 // the expiration time. 2438 long alarmInterval = timeToExpire % MS_PER_DAY; 2439 if (alarmInterval == 0) { 2440 alarmInterval = MS_PER_DAY; 2441 } 2442 alarmTime = now + alarmInterval; 2443 } 2444 2445 mInjector.binderWithCleanCallingIdentity(() -> { 2446 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle; 2447 AlarmManager am = mInjector.getAlarmManager(); 2448 // Broadcast alarms sent by system are immutable 2449 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD, 2450 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION), 2451 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT 2452 | PendingIntent.FLAG_IMMUTABLE, 2453 UserHandle.of(affectedUserHandle)); 2454 am.cancel(pi); 2455 if (alarmTime != 0) { 2456 am.set(AlarmManager.RTC, alarmTime, pi); 2457 } 2458 }); 2459 } 2460 getActiveAdminUncheckedLocked(ComponentName who, int userHandle)2461 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) { 2462 ensureLocked(); 2463 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who); 2464 if (admin != null 2465 && who.getPackageName().equals(admin.info.getActivityInfo().packageName) 2466 && who.getClassName().equals(admin.info.getActivityInfo().name)) { 2467 return admin; 2468 } 2469 return null; 2470 } 2471 getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent)2472 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) { 2473 ensureLocked(); 2474 if (parent) { 2475 Preconditions.checkCallAuthorization(isManagedProfile(userHandle), 2476 "You can not call APIs on the parent profile outside a managed profile, " 2477 + "userId = %d", userHandle); 2478 } 2479 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2480 if (admin != null && parent) { 2481 admin = admin.getParentActiveAdmin(); 2482 } 2483 return admin; 2484 } 2485 getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)2486 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy) 2487 throws SecurityException { 2488 return getActiveAdminOrCheckPermissionForCallerLocked(who, 2489 reqPolicy, /* permission= */ null); 2490 } 2491 getDeviceOwnerLocked(final CallerIdentity caller)2492 @NonNull ActiveAdmin getDeviceOwnerLocked(final CallerIdentity caller) { 2493 ensureLocked(); 2494 ComponentName doComponent = mOwners.getDeviceOwnerComponent(); 2495 Preconditions.checkState(doComponent != null, 2496 "No device owner for user %d", caller.getUid()); 2497 2498 // Use the user ID of the caller instead of mOwners.getDeviceOwnerUserId() because 2499 // secondary, affiliated users will have their own admin. 2500 ActiveAdmin doAdmin = getUserData(caller.getUserId()).mAdminMap.get(doComponent); 2501 Preconditions.checkState(doAdmin != null, 2502 "Device owner %s for user %d not found", doComponent, 2503 caller.getUid()); 2504 2505 Preconditions.checkCallAuthorization(doAdmin.getUid() == caller.getUid(), 2506 "Admin %s is not owned by uid %d, but uid %d", doComponent, 2507 caller.getUid(), doAdmin.getUid()); 2508 2509 Preconditions.checkCallAuthorization( 2510 !caller.hasAdminComponent() 2511 || doAdmin.info.getComponent().equals(caller.getComponentName()), 2512 "Caller component %s is not device owner", 2513 caller.getComponentName()); 2514 2515 return doAdmin; 2516 } 2517 getProfileOwnerLocked(final CallerIdentity caller)2518 @NonNull ActiveAdmin getProfileOwnerLocked(final CallerIdentity caller) { 2519 ensureLocked(); 2520 final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(caller.getUserId()); 2521 2522 Preconditions.checkState(poAdminComponent != null, 2523 "No profile owner for user %d", caller.getUid()); 2524 2525 ActiveAdmin poAdmin = getUserData(caller.getUserId()).mAdminMap.get(poAdminComponent); 2526 Preconditions.checkState(poAdmin != null, 2527 "No device profile owner for caller %d", caller.getUid()); 2528 2529 Preconditions.checkCallAuthorization(poAdmin.getUid() == caller.getUid(), 2530 "Admin %s is not owned by uid %d", poAdminComponent, 2531 caller.getUid()); 2532 2533 Preconditions.checkCallAuthorization( 2534 !caller.hasAdminComponent() 2535 || poAdmin.info.getComponent().equals(caller.getComponentName()), 2536 "Caller component %s is not profile owner", 2537 caller.getComponentName()); 2538 2539 return poAdmin; 2540 } 2541 getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller)2542 @NonNull ActiveAdmin getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller) { 2543 final ActiveAdmin profileOwner = getProfileOwnerLocked(caller); 2544 2545 Preconditions.checkCallAuthorization( 2546 mOwners.isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()), 2547 "Admin %s is not of an org-owned device", 2548 profileOwner.info.getComponent()); 2549 2550 return profileOwner; 2551 } 2552 getProfileOwnerOrDeviceOwnerLocked(final CallerIdentity caller)2553 @NonNull ActiveAdmin getProfileOwnerOrDeviceOwnerLocked(final CallerIdentity caller) { 2554 ensureLocked(); 2555 // Try to find an admin which can use reqPolicy 2556 final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(caller.getUserId()); 2557 final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent(); 2558 2559 if (poAdminComponent == null && doAdminComponent == null) { 2560 throw new IllegalStateException( 2561 String.format("No profile or device owner for user %d", caller.getUid())); 2562 } 2563 2564 if (poAdminComponent != null) { 2565 return getProfileOwnerLocked(caller); 2566 } 2567 2568 return getDeviceOwnerLocked(caller); 2569 } 2570 getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent)2571 @NonNull ActiveAdmin getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent) { 2572 Objects.requireNonNull(admin); 2573 return parent ? admin.getParentActiveAdmin() : admin; 2574 } 2575 2576 /** 2577 * Finds an active admin for the caller then checks {@code permission} if admin check failed. 2578 * 2579 * @return an active admin or {@code null} if there is no active admin but 2580 * {@code permission} is granted 2581 * @throws SecurityException if caller neither has an active admin nor {@code permission} 2582 */ 2583 @Nullable getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, @Nullable String permission)2584 ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked( 2585 ComponentName who, 2586 int reqPolicy, 2587 @Nullable String permission) throws SecurityException { 2588 ensureLocked(); 2589 final CallerIdentity caller = getCallerIdentity(); 2590 2591 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, caller.getUid()); 2592 if (result != null) { 2593 return result; 2594 } else if (permission != null && hasCallingPermission(permission)) { 2595 return null; 2596 } 2597 2598 // Code for handling failure from getActiveAdminWithPolicyForUidLocked to find an admin 2599 // that satisfies the required policy. 2600 // Throws a security exception with the right error message. 2601 if (who != null) { 2602 final DevicePolicyData policy = getUserData(caller.getUserId()); 2603 ActiveAdmin admin = policy.mAdminMap.get(who); 2604 final boolean isDeviceOwner = isDeviceOwner(admin.info.getComponent(), 2605 caller.getUserId()); 2606 final boolean isProfileOwner = isProfileOwner(admin.info.getComponent(), 2607 caller.getUserId()); 2608 2609 if (DA_DISALLOWED_POLICIES.contains(reqPolicy) && !isDeviceOwner && !isProfileOwner) { 2610 throw new SecurityException("Admin " + admin.info.getComponent() 2611 + " is not a device owner or profile owner, so may not use policy: " 2612 + admin.info.getTagForPolicy(reqPolicy)); 2613 } 2614 throw new SecurityException("Admin " + admin.info.getComponent() 2615 + " did not specify uses-policy for: " 2616 + admin.info.getTagForPolicy(reqPolicy)); 2617 } else { 2618 throw new SecurityException("No active admin owned by uid " 2619 + caller.getUid() + " for policy #" + reqPolicy + (permission == null ? "" 2620 : ", which doesn't have " + permission)); 2621 } 2622 } 2623 getActiveAdminForCallerLocked(@ullable ComponentName who, int reqPolicy, boolean parent)2624 ActiveAdmin getActiveAdminForCallerLocked(@Nullable ComponentName who, int reqPolicy, 2625 boolean parent) throws SecurityException { 2626 return getActiveAdminOrCheckPermissionForCallerLocked( 2627 who, reqPolicy, parent, /* permission= */ null); 2628 } 2629 2630 /** 2631 * Finds an active admin for the caller then checks {@code permission} if admin check failed. 2632 * 2633 * @return an active admin or {@code null} if there is no active admin but 2634 * {@code permission} is granted 2635 * @throws SecurityException if caller neither has an active admin nor {@code permission} 2636 */ 2637 @Nullable getActiveAdminOrCheckPermissionForCallerLocked( @ullable ComponentName who, int reqPolicy, boolean parent, @Nullable String permission)2638 ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked( 2639 @Nullable ComponentName who, 2640 int reqPolicy, 2641 boolean parent, 2642 @Nullable String permission) throws SecurityException { 2643 ensureLocked(); 2644 if (parent) { 2645 Preconditions.checkCallingUser(isManagedProfile(getCallerIdentity().getUserId())); 2646 } 2647 ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked( 2648 who, reqPolicy, permission); 2649 return parent ? admin.getParentActiveAdmin() : admin; 2650 } 2651 2652 /** 2653 * Find the admin for the component and userId bit of the uid, then check 2654 * the admin's uid matches the uid. 2655 */ getActiveAdminForUidLocked(ComponentName who, int uid)2656 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) { 2657 ensureLocked(); 2658 final int userId = UserHandle.getUserId(uid); 2659 final DevicePolicyData policy = getUserData(userId); 2660 ActiveAdmin admin = policy.mAdminMap.get(who); 2661 if (admin == null) { 2662 throw new SecurityException("No active admin " + who + " for UID " + uid); 2663 } 2664 if (admin.getUid() != uid) { 2665 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2666 } 2667 return admin; 2668 } 2669 2670 /** 2671 * Returns the active admin for the user of the caller as denoted by uid, which implements 2672 * the {@code reqPolicy}. 2673 * 2674 * The {@code who} parameter is used as a hint: 2675 * If provided, it must be the component name of the active admin for that user and the caller 2676 * uid must match the uid of the admin. 2677 * If not provided, iterate over all of the active admins in the DevicePolicyData for that user 2678 * and return the one with the uid specified as parameter, and has the policy specified. 2679 */ 2680 @Nullable getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, int uid)2681 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, 2682 int uid) { 2683 ensureLocked(); 2684 // Try to find an admin which can use reqPolicy 2685 final int userId = UserHandle.getUserId(uid); 2686 final DevicePolicyData policy = getUserData(userId); 2687 if (who != null) { 2688 ActiveAdmin admin = policy.mAdminMap.get(who); 2689 if (admin == null) { 2690 throw new SecurityException("No active admin " + who); 2691 } 2692 if (admin.getUid() != uid) { 2693 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2694 } 2695 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) { 2696 return admin; 2697 } 2698 } else { 2699 for (ActiveAdmin admin : policy.mAdminList) { 2700 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, 2701 userId)) { 2702 return admin; 2703 } 2704 } 2705 } 2706 2707 return null; 2708 } 2709 2710 @VisibleForTesting isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, int userId)2711 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, 2712 int userId) { 2713 ensureLocked(); 2714 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId); 2715 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId); 2716 2717 boolean allowedToUsePolicy = ownsDevice || ownsProfile 2718 || !DA_DISALLOWED_POLICIES.contains(reqPolicy) 2719 || getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.Q; 2720 return allowedToUsePolicy && admin.info.usesPolicy(reqPolicy); 2721 } 2722 2723 void sendAdminCommandLocked(ActiveAdmin admin, String action) { 2724 sendAdminCommandLocked(admin, action, null); 2725 } 2726 2727 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) { 2728 sendAdminCommandLocked(admin, action, null, result); 2729 } 2730 2731 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2732 BroadcastReceiver result) { 2733 sendAdminCommandLocked(admin, action, adminExtras, result, false); 2734 } 2735 2736 /** 2737 * Send an update to one specific admin, get notified when that admin returns a result. 2738 * 2739 * @return whether the broadcast was successfully sent 2740 */ 2741 boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2742 BroadcastReceiver result, boolean inForeground) { 2743 Intent intent = new Intent(action); 2744 intent.setComponent(admin.info.getComponent()); 2745 if (UserManager.isDeviceInDemoMode(mContext)) { 2746 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2747 } 2748 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) { 2749 intent.putExtra("expiration", admin.passwordExpirationDate); 2750 } 2751 if (inForeground) { 2752 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2753 } 2754 if (adminExtras != null) { 2755 intent.putExtras(adminExtras); 2756 } 2757 if (mInjector.getPackageManager().queryBroadcastReceiversAsUser( 2758 intent, 2759 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, 2760 admin.getUserHandle()).isEmpty()) { 2761 return false; 2762 } 2763 2764 final BroadcastOptions options = BroadcastOptions.makeBasic(); 2765 options.setBackgroundActivityStartsAllowed(true); 2766 2767 if (result != null) { 2768 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(), 2769 null, AppOpsManager.OP_NONE, options.toBundle(), 2770 result, mHandler, Activity.RESULT_OK, null, null); 2771 } else { 2772 mContext.sendBroadcastAsUser(intent, admin.getUserHandle(), null, options.toBundle()); 2773 } 2774 2775 return true; 2776 } 2777 2778 /** 2779 * Send an update to all admins of a user that enforce a specified policy. 2780 */ 2781 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) { 2782 final DevicePolicyData policy = getUserData(userHandle); 2783 final int count = policy.mAdminList.size(); 2784 for (int i = 0; i < count; i++) { 2785 final ActiveAdmin admin = policy.mAdminList.get(i); 2786 if (admin.info.usesPolicy(reqPolicy)) { 2787 sendAdminCommandLocked(admin, action, adminExtras, null); 2788 } 2789 } 2790 } 2791 2792 /** 2793 * Send an update intent to all admins of a user and its profiles. Only send to admins that 2794 * enforce a specified policy. 2795 */ 2796 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy, 2797 int userHandle, Bundle adminExtras) { 2798 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle); 2799 for (int profileId : profileIds) { 2800 sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras); 2801 } 2802 } 2803 2804 /** 2805 * Sends a broadcast to each profile that share the password unlock with the given user id. 2806 */ 2807 private void sendAdminCommandForLockscreenPoliciesLocked( 2808 String action, int reqPolicy, int userHandle) { 2809 final Bundle extras = new Bundle(); 2810 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 2811 if (isSeparateProfileChallengeEnabled(userHandle)) { 2812 sendAdminCommandLocked(action, reqPolicy, userHandle, extras); 2813 } else { 2814 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras); 2815 } 2816 } 2817 2818 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) { 2819 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 2820 DevicePolicyData policy = getUserData(userHandle); 2821 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) { 2822 policy.mRemovingAdmins.add(adminReceiver); 2823 sendAdminCommandLocked(admin, 2824 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED, 2825 new BroadcastReceiver() { 2826 @Override 2827 public void onReceive(Context context, Intent intent) { 2828 removeAdminArtifacts(adminReceiver, userHandle); 2829 removePackageIfRequired(adminReceiver.getPackageName(), userHandle); 2830 } 2831 }); 2832 } 2833 } 2834 2835 private DeviceAdminInfo findAdmin(final ComponentName adminName, final int userHandle, 2836 boolean throwForMissingPermission) { 2837 final ActivityInfo ai = mInjector.binderWithCleanCallingIdentity(() -> { 2838 try { 2839 return mIPackageManager.getReceiverInfo(adminName, 2840 PackageManager.GET_META_DATA 2841 | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS 2842 | PackageManager.MATCH_DIRECT_BOOT_AWARE 2843 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle); 2844 } catch (RemoteException e) { 2845 // shouldn't happen. 2846 return null; 2847 } 2848 }); 2849 if (ai == null) { 2850 throw new IllegalArgumentException("Unknown admin: " + adminName); 2851 } 2852 2853 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) { 2854 final String message = "DeviceAdminReceiver " + adminName + " must be protected with " 2855 + permission.BIND_DEVICE_ADMIN; 2856 Slogf.w(LOG_TAG, message); 2857 if (throwForMissingPermission && 2858 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) { 2859 throw new IllegalArgumentException(message); 2860 } 2861 } 2862 2863 try { 2864 return new DeviceAdminInfo(mContext, ai); 2865 } catch (XmlPullParserException | IOException e) { 2866 Slogf.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName, 2867 e); 2868 return null; 2869 } 2870 } 2871 2872 private File getPolicyFileDirectory(@UserIdInt int userId) { 2873 return userId == UserHandle.USER_SYSTEM 2874 ? mPathProvider.getDataSystemDirectory() 2875 : mPathProvider.getUserSystemDirectory(userId); 2876 } 2877 2878 private JournaledFile makeJournaledFile(@UserIdInt int userId, String fileName) { 2879 final String base = new File(getPolicyFileDirectory(userId), fileName) 2880 .getAbsolutePath(); 2881 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Opening %s", base); 2882 return new JournaledFile(new File(base), new File(base + ".tmp")); 2883 } 2884 2885 private JournaledFile makeJournaledFile(@UserIdInt int userId) { 2886 return makeJournaledFile(userId, DEVICE_POLICIES_XML); 2887 } 2888 2889 /** 2890 * Persist modified values to disk by calling {@link #saveSettingsLocked} for each 2891 * affected user ID. 2892 */ 2893 @GuardedBy("getLockObject()") 2894 private void saveSettingsForUsersLocked(Set<Integer> affectedUserIds) { 2895 for (int userId : affectedUserIds) { 2896 saveSettingsLocked(userId); 2897 } 2898 } 2899 2900 private void saveSettingsLocked(int userHandle) { 2901 if (DevicePolicyData.store( 2902 getUserData(userHandle), 2903 makeJournaledFile(userHandle), 2904 !mInjector.storageManagerIsFileBasedEncryptionEnabled())) { 2905 sendChangedNotification(userHandle); 2906 } 2907 invalidateBinderCaches(); 2908 } 2909 2910 private void sendChangedNotification(int userHandle) { 2911 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 2912 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 2913 mInjector.binderWithCleanCallingIdentity(() -> 2914 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle))); 2915 } 2916 2917 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) { 2918 DevicePolicyData.load(policy, 2919 !mInjector.storageManagerIsFileBasedEncryptionEnabled(), 2920 makeJournaledFile(userHandle), 2921 component -> findAdmin( 2922 component, userHandle, /* throwForMissingPermission= */ false), 2923 getOwnerComponent(userHandle)); 2924 2925 policy.validatePasswordOwner(); 2926 updateMaximumTimeToLockLocked(userHandle); 2927 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle); 2928 updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle); 2929 if (policy.mStatusBarDisabled) { 2930 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle); 2931 } 2932 } 2933 2934 private void updateLockTaskPackagesLocked(List<String> packages, int userId) { 2935 String[] packagesArray = null; 2936 2937 if (!packages.isEmpty()) { 2938 // When adding packages, we need to include the exempt apps so they can still be 2939 // launched (ideally we should use a different AM API as these apps don't need to use 2940 // lock-task mode). 2941 // They're not added when the packages is empty though, as in that case we're disabling 2942 // lock-task mode. 2943 List<String> exemptApps = listPolicyExemptAppsUnchecked(); 2944 if (!exemptApps.isEmpty()) { 2945 // TODO(b/175377361): add unit test to verify it (cannot be CTS because the policy- 2946 // -exempt apps are provided by OEM and the test would have no control over it) once 2947 // tests are migrated to the new infra-structure 2948 HashSet<String> updatedPackages = new HashSet<>(packages); 2949 updatedPackages.addAll(exemptApps); 2950 if (VERBOSE_LOG) { 2951 Slogf.v(LOG_TAG, "added %d policy-exempt apps to %d lock task packages. Final " 2952 + "list: %s", exemptApps.size(), packages.size(), updatedPackages); 2953 } 2954 packagesArray = updatedPackages.toArray(new String[updatedPackages.size()]); 2955 } 2956 } 2957 2958 if (packagesArray == null) { 2959 packagesArray = packages.toArray(new String[packages.size()]); 2960 } 2961 2962 long ident = mInjector.binderClearCallingIdentity(); 2963 try { 2964 mInjector.getIActivityManager().updateLockTaskPackages(userId, packagesArray); 2965 } catch (RemoteException e) { 2966 // Not gonna happen. 2967 } finally { 2968 mInjector.binderRestoreCallingIdentity(ident); 2969 } 2970 } 2971 2972 private void updateLockTaskFeaturesLocked(int flags, int userId) { 2973 long ident = mInjector.binderClearCallingIdentity(); 2974 try { 2975 mInjector.getIActivityTaskManager().updateLockTaskFeatures(userId, flags); 2976 } catch (RemoteException e) { 2977 // Not gonna happen. 2978 } finally { 2979 mInjector.binderRestoreCallingIdentity(ident); 2980 } 2981 } 2982 2983 static void validateQualityConstant(int quality) { 2984 switch (quality) { 2985 case PASSWORD_QUALITY_UNSPECIFIED: 2986 case PASSWORD_QUALITY_BIOMETRIC_WEAK: 2987 case PASSWORD_QUALITY_SOMETHING: 2988 case PASSWORD_QUALITY_NUMERIC: 2989 case PASSWORD_QUALITY_NUMERIC_COMPLEX: 2990 case PASSWORD_QUALITY_ALPHABETIC: 2991 case PASSWORD_QUALITY_ALPHANUMERIC: 2992 case PASSWORD_QUALITY_COMPLEX: 2993 case PASSWORD_QUALITY_MANAGED: 2994 return; 2995 } 2996 throw new IllegalArgumentException("Invalid quality constant: 0x" 2997 + Integer.toHexString(quality)); 2998 } 2999 3000 @VisibleForTesting 3001 @Override 3002 void systemReady(int phase) { 3003 if (!mHasFeature) { 3004 return; 3005 } 3006 switch (phase) { 3007 case SystemService.PHASE_LOCK_SETTINGS_READY: 3008 onLockSettingsReady(); 3009 loadAdminDataAsync(); 3010 mOwners.systemReady(); 3011 break; 3012 case SystemService.PHASE_ACTIVITY_MANAGER_READY: 3013 synchronized (getLockObject()) { 3014 migrateToProfileOnOrganizationOwnedDeviceIfCompLocked(); 3015 applyProfileRestrictionsIfDeviceOwnerLocked(); 3016 } 3017 maybeStartSecurityLogMonitorOnActivityManagerReady(); 3018 break; 3019 case SystemService.PHASE_BOOT_COMPLETED: 3020 // Ideally it should be done earlier, but currently it relies on RecoverySystem, 3021 // which would hang on earlier phases 3022 factoryResetIfDelayedEarlier(); 3023 3024 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this. 3025 break; 3026 } 3027 } 3028 3029 private void updatePersonalAppsSuspensionOnUserStart(int userHandle) { 3030 final int profileUserHandle = getManagedUserId(userHandle); 3031 if (profileUserHandle >= 0) { 3032 // Given that the parent user has just started, profile should be locked. 3033 updatePersonalAppsSuspension(profileUserHandle, false /* unlocked */); 3034 } else { 3035 suspendPersonalAppsInternal(userHandle, false); 3036 } 3037 } 3038 3039 private void onLockSettingsReady() { 3040 synchronized (getLockObject()) { 3041 fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration(); 3042 } 3043 getUserData(UserHandle.USER_SYSTEM); 3044 cleanUpOldUsers(); 3045 maybeSetDefaultProfileOwnerUserRestrictions(); 3046 handleStartUser(UserHandle.USER_SYSTEM); 3047 maybeLogStart(); 3048 3049 // Register an observer for watching for user setup complete and settings changes. 3050 mSetupContentObserver.register(); 3051 // Initialize the user setup state, to handle the upgrade case. 3052 updateUserSetupCompleteAndPaired(); 3053 3054 List<String> packageList; 3055 synchronized (getLockObject()) { 3056 packageList = getKeepUninstalledPackagesLocked(); 3057 } 3058 if (packageList != null) { 3059 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 3060 } 3061 3062 synchronized (getLockObject()) { 3063 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 3064 if (deviceOwner != null) { 3065 // Push the force-ephemeral-users policy to the user manager. 3066 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers); 3067 3068 // Update user switcher message to activity manager. 3069 ActivityManagerInternal activityManagerInternal = 3070 mInjector.getActivityManagerInternal(); 3071 activityManagerInternal.setSwitchingFromSystemUserMessage( 3072 deviceOwner.startUserSessionMessage); 3073 activityManagerInternal.setSwitchingToSystemUserMessage( 3074 deviceOwner.endUserSessionMessage); 3075 } 3076 3077 revertTransferOwnershipIfNecessaryLocked(); 3078 } 3079 updateUsbDataSignal(); 3080 } 3081 3082 // TODO(b/230841522) Make it static. 3083 private class DpmsUpgradeDataProvider implements PolicyUpgraderDataProvider { 3084 @Override 3085 public boolean storageManagerIsFileBasedEncryptionEnabled() { 3086 return mInjector.storageManagerIsFileBasedEncryptionEnabled(); 3087 } 3088 3089 @Override 3090 public JournaledFile makeDevicePoliciesJournaledFile(int userId) { 3091 return DevicePolicyManagerService.this.makeJournaledFile(userId, DEVICE_POLICIES_XML); 3092 } 3093 3094 @Override 3095 public JournaledFile makePoliciesVersionJournaledFile(int userId) { 3096 return DevicePolicyManagerService.this.makeJournaledFile(userId, POLICIES_VERSION_XML); 3097 } 3098 3099 @Override 3100 public Function<ComponentName, DeviceAdminInfo> getAdminInfoSupplier(int userId) { 3101 return component -> 3102 findAdmin(component, userId, /* throwForMissingPermission= */ false); 3103 } 3104 3105 @Override 3106 public int[] getUsersForUpgrade() { 3107 List<UserInfo> allUsers = mUserManager.getUsers(); 3108 return allUsers.stream().mapToInt(u -> u.id).toArray(); 3109 } 3110 } 3111 3112 private void performPolicyVersionUpgrade() { 3113 PolicyVersionUpgrader upgrader = new PolicyVersionUpgrader( 3114 new DpmsUpgradeDataProvider(), mPathProvider); 3115 upgrader.upgradePolicy(DPMS_VERSION); 3116 } 3117 3118 private void revertTransferOwnershipIfNecessaryLocked() { 3119 if (!mTransferOwnershipMetadataManager.metadataFileExists()) { 3120 return; 3121 } 3122 Slogf.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer."); 3123 final TransferOwnershipMetadataManager.Metadata metadata = 3124 mTransferOwnershipMetadataManager.loadMetadataFile(); 3125 // Revert transfer 3126 if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) { 3127 transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent, 3128 metadata.userId); 3129 deleteTransferOwnershipMetadataFileLocked(); 3130 deleteTransferOwnershipBundleLocked(metadata.userId); 3131 } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) { 3132 transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent, 3133 metadata.userId); 3134 deleteTransferOwnershipMetadataFileLocked(); 3135 deleteTransferOwnershipBundleLocked(metadata.userId); 3136 } 3137 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true); 3138 pushUserControlDisabledPackagesLocked(metadata.userId); 3139 } 3140 3141 private void maybeLogStart() { 3142 if (!SecurityLog.isLoggingEnabled()) { 3143 return; 3144 } 3145 final String verifiedBootState = 3146 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate"); 3147 final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode"); 3148 SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode); 3149 } 3150 3151 private void ensureDeviceOwnerUserStarted() { 3152 final int userId; 3153 synchronized (getLockObject()) { 3154 if (!mOwners.hasDeviceOwner()) { 3155 return; 3156 } 3157 userId = mOwners.getDeviceOwnerUserId(); 3158 } 3159 if (VERBOSE_LOG) { 3160 Log.v(LOG_TAG, "Starting non-system DO user: " + userId); 3161 } 3162 if (userId != UserHandle.USER_SYSTEM) { 3163 try { 3164 mInjector.getIActivityManager().startUserInBackground(userId); 3165 3166 // STOPSHIP Prevent the DO user from being killed. 3167 3168 } catch (RemoteException e) { 3169 Slogf.w(LOG_TAG, "Exception starting user", e); 3170 } 3171 } 3172 } 3173 3174 @Override 3175 void handleStartUser(int userId) { 3176 synchronized (getLockObject()) { 3177 pushScreenCapturePolicy(userId); 3178 pushUserControlDisabledPackagesLocked(userId); 3179 } 3180 pushUserRestrictions(userId); 3181 // When system user is started (device boot), load cache for all users. 3182 // This is to mitigate the potential race between loading the cache and keyguard 3183 // reading the value during user switch, due to onStartUser() being asynchronous. 3184 updatePasswordQualityCacheForUserGroup( 3185 userId == UserHandle.USER_SYSTEM ? UserHandle.USER_ALL : userId); 3186 updatePermissionPolicyCache(userId); 3187 updateAdminCanGrantSensorsPermissionCache(userId); 3188 3189 final List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs; 3190 synchronized (getLockObject()) { 3191 ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 3192 preferentialNetworkServiceConfigs = owner != null 3193 ? owner.mPreferentialNetworkServiceConfigs 3194 : List.of(PreferentialNetworkServiceConfig.DEFAULT); 3195 } 3196 updateNetworkPreferenceForUser(userId, preferentialNetworkServiceConfigs); 3197 3198 startOwnerService(userId, "start-user"); 3199 } 3200 3201 void pushUserControlDisabledPackagesLocked(int userId) { 3202 final int targetUserId; 3203 final ActiveAdmin owner; 3204 if (getDeviceOwnerUserIdUncheckedLocked() == userId) { 3205 owner = getDeviceOwnerAdminLocked(); 3206 targetUserId = UserHandle.USER_ALL; 3207 } else { 3208 owner = getProfileOwnerAdminLocked(userId); 3209 targetUserId = userId; 3210 } 3211 3212 List<String> protectedPackages = (owner == null || owner.protectedPackages == null) 3213 ? Collections.emptyList() : owner.protectedPackages; 3214 mInjector.binderWithCleanCallingIdentity(() -> 3215 mInjector.getPackageManagerInternal().setOwnerProtectedPackages( 3216 targetUserId, protectedPackages)); 3217 mUsageStatsManagerInternal.setAdminProtectedPackages(new ArraySet(protectedPackages), 3218 targetUserId); 3219 } 3220 3221 @Override 3222 void handleUnlockUser(int userId) { 3223 startOwnerService(userId, "unlock-user"); 3224 } 3225 3226 @Override 3227 void handleOnUserUnlocked(int userId) { 3228 showNewUserDisclaimerIfNecessary(userId); 3229 } 3230 3231 @Override 3232 void handleStopUser(int userId) { 3233 updateNetworkPreferenceForUser(userId, List.of(PreferentialNetworkServiceConfig.DEFAULT)); 3234 stopOwnerService(userId, "stop-user"); 3235 } 3236 3237 private void startOwnerService(int userId, String actionForLog) { 3238 final ComponentName owner = getOwnerComponent(userId); 3239 if (owner != null) { 3240 mDeviceAdminServiceController.startServiceForOwner( 3241 owner.getPackageName(), userId, actionForLog); 3242 invalidateBinderCaches(); 3243 } 3244 } 3245 3246 private void stopOwnerService(int userId, String actionForLog) { 3247 mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog); 3248 } 3249 3250 private void cleanUpOldUsers() { 3251 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled 3252 // before reboot 3253 Set<Integer> usersWithProfileOwners; 3254 Set<Integer> usersWithData; 3255 synchronized (getLockObject()) { 3256 usersWithProfileOwners = mOwners.getProfileOwnerKeys(); 3257 usersWithData = new ArraySet<>(); 3258 for (int i = 0; i < mUserData.size(); i++) { 3259 usersWithData.add(mUserData.keyAt(i)); 3260 } 3261 } 3262 List<UserInfo> allUsers = mUserManager.getUsers(); 3263 3264 Set<Integer> deletedUsers = new ArraySet<>(); 3265 deletedUsers.addAll(usersWithProfileOwners); 3266 deletedUsers.addAll(usersWithData); 3267 for (UserInfo userInfo : allUsers) { 3268 deletedUsers.remove(userInfo.id); 3269 } 3270 for (Integer userId : deletedUsers) { 3271 removeUserData(userId); 3272 } 3273 } 3274 3275 private void handlePasswordExpirationNotification(int userHandle) { 3276 final Bundle adminExtras = new Bundle(); 3277 adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 3278 3279 synchronized (getLockObject()) { 3280 final long now = System.currentTimeMillis(); 3281 3282 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle); 3283 final int N = admins.size(); 3284 for (int i = 0; i < N; i++) { 3285 ActiveAdmin admin = admins.get(i); 3286 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD) 3287 && admin.passwordExpirationTimeout > 0L 3288 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS 3289 && admin.passwordExpirationDate > 0L) { 3290 sendAdminCommandLocked(admin, 3291 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null); 3292 } 3293 } 3294 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false); 3295 } 3296 } 3297 3298 /** 3299 * Clean up internal state when the set of installed trusted CA certificates changes. 3300 * 3301 * @param userHandle user to check for. This must be a real user and not, for example, 3302 * {@link UserHandle#ALL}. 3303 * @param installedCertificates the full set of certificate authorities currently installed for 3304 * {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will 3305 * correspond to some subset of this. 3306 */ 3307 protected void onInstalledCertificatesChanged(final UserHandle userHandle, 3308 final @NonNull Collection<String> installedCertificates) { 3309 if (!mHasFeature) { 3310 return; 3311 } 3312 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 3313 3314 synchronized (getLockObject()) { 3315 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3316 3317 boolean changed = false; 3318 changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates); 3319 changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates); 3320 if (changed) { 3321 saveSettingsLocked(userHandle.getIdentifier()); 3322 } 3323 } 3324 } 3325 3326 /** 3327 * Internal method used by {@link CertificateMonitor}. 3328 */ 3329 protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) { 3330 if (!mHasFeature) { 3331 return Collections.<String> emptySet(); 3332 } 3333 synchronized (getLockObject()) { 3334 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3335 return policy.mAcceptedCaCertificates; 3336 } 3337 } 3338 3339 /** 3340 * @param adminReceiver The admin to add 3341 * @param refreshing true = update an active admin, no error 3342 */ 3343 @Override 3344 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) { 3345 if (!mHasFeature) { 3346 return; 3347 } 3348 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3349 3350 final CallerIdentity caller = getCallerIdentity(); 3351 Preconditions.checkCallAuthorization( 3352 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 3353 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3354 3355 DevicePolicyData policy = getUserData(userHandle); 3356 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle, 3357 /* throwForMissingPermission= */ true); 3358 synchronized (getLockObject()) { 3359 checkActiveAdminPrecondition(adminReceiver, info, policy); 3360 mInjector.binderWithCleanCallingIdentity(() -> { 3361 final ActiveAdmin existingAdmin 3362 = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3363 if (!refreshing && existingAdmin != null) { 3364 throw new IllegalArgumentException("Admin is already added"); 3365 } 3366 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false); 3367 newAdmin.testOnlyAdmin = 3368 (existingAdmin != null) ? existingAdmin.testOnlyAdmin 3369 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle); 3370 policy.mAdminMap.put(adminReceiver, newAdmin); 3371 int replaceIndex = -1; 3372 final int N = policy.mAdminList.size(); 3373 for (int i=0; i < N; i++) { 3374 ActiveAdmin oldAdmin = policy.mAdminList.get(i); 3375 if (oldAdmin.info.getComponent().equals(adminReceiver)) { 3376 replaceIndex = i; 3377 break; 3378 } 3379 } 3380 if (replaceIndex == -1) { 3381 policy.mAdminList.add(newAdmin); 3382 enableIfNecessary(info.getPackageName(), userHandle); 3383 mUsageStatsManagerInternal.onActiveAdminAdded( 3384 adminReceiver.getPackageName(), userHandle); 3385 } else { 3386 policy.mAdminList.set(replaceIndex, newAdmin); 3387 } 3388 saveSettingsLocked(userHandle); 3389 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3390 /* adminExtras= */ null, /* result= */ null); 3391 }); 3392 } 3393 } 3394 3395 private void loadAdminDataAsync() { 3396 mInjector.postOnSystemServerInitThreadPool(() -> { 3397 pushActiveAdminPackages(); 3398 mUsageStatsManagerInternal.onAdminDataAvailable(); 3399 pushAllMeteredRestrictedPackages(); 3400 mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable(); 3401 }); 3402 } 3403 3404 private void pushActiveAdminPackages() { 3405 synchronized (getLockObject()) { 3406 final List<UserInfo> users = mUserManager.getUsers(); 3407 for (int i = users.size() - 1; i >= 0; --i) { 3408 final int userId = users.get(i).id; 3409 mUsageStatsManagerInternal.setActiveAdminApps( 3410 getActiveAdminPackagesLocked(userId), userId); 3411 } 3412 } 3413 } 3414 3415 private void pushAllMeteredRestrictedPackages() { 3416 synchronized (getLockObject()) { 3417 final List<UserInfo> users = mUserManager.getUsers(); 3418 for (int i = users.size() - 1; i >= 0; --i) { 3419 final int userId = users.get(i).id; 3420 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync( 3421 getMeteredDisabledPackages(userId), userId); 3422 } 3423 } 3424 } 3425 3426 private void pushActiveAdminPackagesLocked(int userId) { 3427 mUsageStatsManagerInternal.setActiveAdminApps( 3428 getActiveAdminPackagesLocked(userId), userId); 3429 } 3430 3431 private Set<String> getActiveAdminPackagesLocked(int userId) { 3432 final DevicePolicyData policy = getUserData(userId); 3433 Set<String> adminPkgs = null; 3434 for (int i = policy.mAdminList.size() - 1; i >= 0; --i) { 3435 final String pkgName = policy.mAdminList.get(i).info.getPackageName(); 3436 if (adminPkgs == null) { 3437 adminPkgs = new ArraySet<>(); 3438 } 3439 adminPkgs.add(pkgName); 3440 } 3441 return adminPkgs; 3442 } 3443 3444 private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver, 3445 ComponentName outgoingReceiver, int userHandle) { 3446 final DevicePolicyData policy = getUserData(userHandle); 3447 if (!policy.mAdminMap.containsKey(outgoingReceiver) 3448 && policy.mAdminMap.containsKey(incomingReceiver)) { 3449 // Nothing to transfer - the incoming receiver is already the active admin. 3450 return; 3451 } 3452 final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle, 3453 /* throwForMissingPermission= */ true); 3454 final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver); 3455 final int oldAdminUid = adminToTransfer.getUid(); 3456 3457 adminToTransfer.transfer(incomingDeviceInfo); 3458 policy.mAdminMap.remove(outgoingReceiver); 3459 policy.mAdminMap.put(incomingReceiver, adminToTransfer); 3460 if (policy.mPasswordOwner == oldAdminUid) { 3461 policy.mPasswordOwner = adminToTransfer.getUid(); 3462 } 3463 3464 saveSettingsLocked(userHandle); 3465 sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3466 null, null); 3467 } 3468 3469 private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info, 3470 DevicePolicyData policy) { 3471 if (info == null) { 3472 throw new IllegalArgumentException("Bad admin: " + adminReceiver); 3473 } 3474 if (!info.getActivityInfo().applicationInfo.isInternal()) { 3475 throw new IllegalArgumentException("Only apps in internal storage can be active admin: " 3476 + adminReceiver); 3477 } 3478 if (info.getActivityInfo().applicationInfo.isInstantApp()) { 3479 throw new IllegalArgumentException("Instant apps cannot be device admins: " 3480 + adminReceiver); 3481 } 3482 if (policy.mRemovingAdmins.contains(adminReceiver)) { 3483 throw new IllegalArgumentException( 3484 "Trying to set an admin which is being removed"); 3485 } 3486 } 3487 3488 private void checkAllUsersAreAffiliatedWithDevice() { 3489 Preconditions.checkCallAuthorization(areAllUsersAffiliatedWithDeviceLocked(), 3490 "operation not allowed when device has unaffiliated users"); 3491 } 3492 3493 @Override 3494 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) { 3495 if (!mHasFeature) { 3496 return false; 3497 } 3498 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3499 3500 final CallerIdentity caller = getCallerIdentity(); 3501 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3502 3503 synchronized (getLockObject()) { 3504 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null; 3505 } 3506 } 3507 3508 @Override 3509 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) { 3510 if (!mHasFeature) { 3511 return false; 3512 } 3513 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3514 3515 final CallerIdentity caller = getCallerIdentity(); 3516 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3517 3518 synchronized (getLockObject()) { 3519 DevicePolicyData policyData = getUserData(userHandle); 3520 return policyData.mRemovingAdmins.contains(adminReceiver); 3521 } 3522 } 3523 3524 @Override 3525 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) { 3526 if (!mHasFeature) { 3527 return false; 3528 } 3529 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3530 3531 final CallerIdentity caller = getCallerIdentity(); 3532 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3533 Preconditions.checkCallAuthorization( 3534 isCallingFromPackage(adminReceiver.getPackageName(), caller.getUid()) 3535 || isSystemUid(caller)); 3536 3537 synchronized (getLockObject()) { 3538 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3539 if (administrator == null) { 3540 throw new SecurityException("No active admin " + adminReceiver); 3541 } 3542 return administrator.info.usesPolicy(policyId); 3543 } 3544 } 3545 3546 @Override 3547 @SuppressWarnings("unchecked") 3548 public List<ComponentName> getActiveAdmins(int userHandle) { 3549 if (!mHasFeature) { 3550 return Collections.EMPTY_LIST; 3551 } 3552 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3553 3554 final CallerIdentity caller = getCallerIdentity(); 3555 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3556 3557 synchronized (getLockObject()) { 3558 DevicePolicyData policy = getUserData(userHandle); 3559 final int N = policy.mAdminList.size(); 3560 if (N <= 0) { 3561 return null; 3562 } 3563 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N); 3564 for (int i=0; i<N; i++) { 3565 res.add(policy.mAdminList.get(i).info.getComponent()); 3566 } 3567 return res; 3568 } 3569 } 3570 3571 @Override 3572 public boolean packageHasActiveAdmins(String packageName, int userHandle) { 3573 if (!mHasFeature) { 3574 return false; 3575 } 3576 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3577 3578 final CallerIdentity caller = getCallerIdentity(); 3579 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3580 3581 synchronized (getLockObject()) { 3582 DevicePolicyData policy = getUserData(userHandle); 3583 final int N = policy.mAdminList.size(); 3584 for (int i=0; i<N; i++) { 3585 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) { 3586 return true; 3587 } 3588 } 3589 return false; 3590 } 3591 } 3592 3593 @Override 3594 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) { 3595 if (!mHasFeature) { 3596 return; 3597 } 3598 Objects.requireNonNull(adminReceiver, "ComponentName is null"); 3599 Preconditions.checkCallAuthorization(isAdb(getCallerIdentity()) 3600 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS), 3601 "Caller must be shell or hold MANAGE_PROFILE_AND_DEVICE_OWNERS to call " 3602 + "forceRemoveActiveAdmin"); 3603 mInjector.binderWithCleanCallingIdentity(() -> { 3604 boolean isOrgOwnedProfile = false; 3605 synchronized (getLockObject()) { 3606 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) { 3607 throw new SecurityException("Attempt to remove non-test admin " 3608 + adminReceiver + " " + userHandle); 3609 } 3610 3611 // If admin is a device or profile owner tidy that up first. 3612 if (isDeviceOwner(adminReceiver, userHandle)) { 3613 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle); 3614 } 3615 if (isProfileOwner(adminReceiver, userHandle)) { 3616 isOrgOwnedProfile = isProfileOwnerOfOrganizationOwnedDevice(userHandle); 3617 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, 3618 userHandle, /* parent */ false); 3619 clearProfileOwnerLocked(admin, userHandle); 3620 } 3621 } 3622 // Remove the admin skipping sending the broadcast. 3623 removeAdminArtifacts(adminReceiver, userHandle); 3624 3625 // In case of PO on org owned device, clean device-wide policies and restrictions. 3626 if (isOrgOwnedProfile) { 3627 final UserHandle parentUser = UserHandle.of(getProfileParentId(userHandle)); 3628 clearOrgOwnedProfileOwnerUserRestrictions(parentUser); 3629 clearOrgOwnedProfileOwnerDeviceWidePolicies(parentUser.getIdentifier()); 3630 } 3631 3632 Slogf.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle); 3633 }); 3634 } 3635 3636 private void clearOrgOwnedProfileOwnerUserRestrictions(UserHandle parentUserHandle) { 3637 mUserManager.setUserRestriction( 3638 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, false, parentUserHandle); 3639 mUserManager.setUserRestriction( 3640 UserManager.DISALLOW_ADD_USER, false, parentUserHandle); 3641 } 3642 3643 private void clearDeviceOwnerUserRestriction(UserHandle userHandle) { 3644 // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state 3645 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) { 3646 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle); 3647 } 3648 // When a device owner is set, the system automatically restricts adding a managed profile. 3649 // Remove this restriction when the device owner is cleared. 3650 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, userHandle)) { 3651 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false, 3652 userHandle); 3653 } 3654 // When a device owner is set, the system automatically restricts adding a clone profile. 3655 // Remove this restriction when the device owner is cleared. 3656 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, userHandle)) { 3657 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, false, 3658 userHandle); 3659 } 3660 } 3661 3662 /** 3663 * Return if a given package has testOnly="true", in which case we'll relax certain rules 3664 * for CTS. 3665 * 3666 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked} 3667 * to check wehter an active admin is test-only or not. 3668 * 3669 * The system allows this flag to be changed when an app is updated, which is not good 3670 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed, 3671 * and used the persisted version in actual checks. (See b/31382361 and b/28928996) 3672 */ 3673 private boolean isPackageTestOnly(String packageName, int userHandle) { 3674 final ApplicationInfo ai; 3675 try { 3676 ai = mInjector.getIPackageManager().getApplicationInfo(packageName, 3677 (PackageManager.MATCH_DIRECT_BOOT_AWARE 3678 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle); 3679 } catch (RemoteException e) { 3680 throw new IllegalStateException(e); 3681 } 3682 if (ai == null) { 3683 throw new IllegalStateException("Couldn't find package: " 3684 + packageName + " on user " + userHandle); 3685 } 3686 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0; 3687 } 3688 3689 /** 3690 * See {@link #isPackageTestOnly}. 3691 */ 3692 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) { 3693 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3694 return (admin != null) && admin.testOnlyAdmin; 3695 } 3696 3697 @Override 3698 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) { 3699 if (!mHasFeature) { 3700 return; 3701 } 3702 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3703 3704 final CallerIdentity caller = hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS) 3705 ? getCallerIdentity() : getCallerIdentity(adminReceiver); 3706 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3707 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_ACTIVE_ADMIN); 3708 enforceUserUnlocked(userHandle); 3709 3710 synchronized (getLockObject()) { 3711 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3712 if (admin == null) { 3713 return; 3714 } 3715 // Active device/profile owners must remain active admins. 3716 if (isDeviceOwner(adminReceiver, userHandle) 3717 || isProfileOwner(adminReceiver, userHandle)) { 3718 Slogf.e(LOG_TAG, "Device/profile owner cannot be removed: component=" 3719 + adminReceiver); 3720 return; 3721 } 3722 3723 mInjector.binderWithCleanCallingIdentity(() -> 3724 removeActiveAdminLocked(adminReceiver, userHandle)); 3725 } 3726 } 3727 3728 private boolean canSetPasswordQualityOnParent(String packageName, final CallerIdentity caller) { 3729 return !mInjector.isChangeEnabled( 3730 PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT, packageName, caller.getUserId()) 3731 || isProfileOwnerOfOrganizationOwnedDevice(caller); 3732 } 3733 3734 private boolean isPasswordLimitingAdminTargetingP(CallerIdentity caller) { 3735 if (!caller.hasAdminComponent()) { 3736 return false; 3737 } 3738 3739 synchronized (getLockObject()) { 3740 return getActiveAdminWithPolicyForUidLocked( 3741 caller.getComponentName(), DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, 3742 caller.getUid()) != null; 3743 } 3744 } 3745 3746 private boolean notSupportedOnAutomotive(String method) { 3747 if (mIsAutomotive) { 3748 Slogf.i(LOG_TAG, "%s is not supported on automotive builds", method); 3749 return true; 3750 } 3751 return false; 3752 } 3753 3754 @Override 3755 public void setPasswordQuality(ComponentName who, int quality, boolean parent) { 3756 if (!mHasFeature || notSupportedOnAutomotive("setPasswordQuality")) { 3757 return; 3758 } 3759 Objects.requireNonNull(who, "ComponentName is null"); 3760 validateQualityConstant(quality); 3761 3762 final CallerIdentity caller = getCallerIdentity(who); 3763 Preconditions.checkCallAuthorization( 3764 isProfileOwner(caller) || isDefaultDeviceOwner(caller) 3765 || isSystemUid(caller) || isPasswordLimitingAdminTargetingP(caller)); 3766 3767 if (parent) { 3768 Preconditions.checkCallAuthorization( 3769 canSetPasswordQualityOnParent(who.getPackageName(), caller), 3770 "Profile Owner may not apply password quality requirements device-wide"); 3771 } 3772 3773 final int userId = caller.getUserId(); 3774 synchronized (getLockObject()) { 3775 ActiveAdmin ap = getActiveAdminForCallerLocked( 3776 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3777 3778 // If setPasswordQuality is called on the parent, ensure that 3779 // the primary admin does not have password complexity state (this is an 3780 // unsupported state). 3781 if (parent) { 3782 final ActiveAdmin primaryAdmin = getActiveAdminForCallerLocked( 3783 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, false); 3784 final boolean hasComplexitySet = 3785 primaryAdmin.mPasswordComplexity != PASSWORD_COMPLEXITY_NONE; 3786 Preconditions.checkState(!hasComplexitySet, 3787 "Cannot set password quality when complexity is set on the primary admin." 3788 + " Set the primary admin's complexity to NONE first."); 3789 } 3790 mInjector.binderWithCleanCallingIdentity(() -> { 3791 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 3792 if (passwordPolicy.quality != quality) { 3793 passwordPolicy.quality = quality; 3794 ap.mPasswordComplexity = PASSWORD_COMPLEXITY_NONE; 3795 resetInactivePasswordRequirementsIfRPlus(userId, ap); 3796 updatePasswordValidityCheckpointLocked(userId, parent); 3797 updatePasswordQualityCacheForUserGroup(userId); 3798 saveSettingsLocked(userId); 3799 } 3800 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 3801 }); 3802 } 3803 DevicePolicyEventLogger 3804 .createEvent(DevicePolicyEnums.SET_PASSWORD_QUALITY) 3805 .setAdmin(who) 3806 .setInt(quality) 3807 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 3808 .write(); 3809 } 3810 3811 private boolean passwordQualityInvocationOrderCheckEnabled(String packageName, int userId) { 3812 return mInjector.isChangeEnabled(ADMIN_APP_PASSWORD_COMPLEXITY, packageName, userId); 3813 } 3814 3815 /** 3816 * For admins targeting R+ reset various password constraints to default values when quality is 3817 * set to a value that makes those constraints that have no effect. 3818 */ 3819 private void resetInactivePasswordRequirementsIfRPlus(int userId, ActiveAdmin admin) { 3820 if (passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(), userId)) { 3821 final PasswordPolicy policy = admin.mPasswordPolicy; 3822 if (policy.quality < PASSWORD_QUALITY_NUMERIC) { 3823 policy.length = PasswordPolicy.DEF_MINIMUM_LENGTH; 3824 } 3825 if (policy.quality < PASSWORD_QUALITY_COMPLEX) { 3826 policy.letters = PasswordPolicy.DEF_MINIMUM_LETTERS; 3827 policy.upperCase = PasswordPolicy.DEF_MINIMUM_UPPER_CASE; 3828 policy.lowerCase = PasswordPolicy.DEF_MINIMUM_LOWER_CASE; 3829 policy.numeric = PasswordPolicy.DEF_MINIMUM_NUMERIC; 3830 policy.symbols = PasswordPolicy.DEF_MINIMUM_SYMBOLS; 3831 policy.nonLetter = PasswordPolicy.DEF_MINIMUM_NON_LETTER; 3832 } 3833 } 3834 } 3835 3836 /** 3837 * Updates a flag that tells us whether the user's password currently satisfies the 3838 * requirements set by all of the user's active admins. 3839 * This should be called whenever the password or the admin policies have changed. The caller 3840 * is responsible for calling {@link #saveSettingsLocked} to persist the change. 3841 * 3842 * @return the set of user IDs that have been affected 3843 */ 3844 @GuardedBy("getLockObject()") 3845 private Set<Integer> updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) { 3846 final ArraySet<Integer> affectedUserIds = new ArraySet<>(); 3847 final int credentialOwner = getCredentialOwner(userHandle, parent); 3848 DevicePolicyData policy = getUserData(credentialOwner); 3849 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner); 3850 // Update the checkpoint only if the user's password metrics is known 3851 if (metrics != null) { 3852 final int userToCheck = getProfileParentUserIfRequested(userHandle, parent); 3853 final boolean newCheckpoint = isPasswordSufficientForUserWithoutCheckpointLocked( 3854 metrics, userToCheck); 3855 if (newCheckpoint != policy.mPasswordValidAtLastCheckpoint) { 3856 policy.mPasswordValidAtLastCheckpoint = newCheckpoint; 3857 affectedUserIds.add(credentialOwner); 3858 } 3859 } 3860 return affectedUserIds; 3861 } 3862 3863 /** 3864 * Update password quality values in policy cache for all users in the same user group as 3865 * the given user. The cached password quality for user X is the aggregated quality among all 3866 * admins who have influence of user X's screenlock, i.e. it's equivalent to the return value of 3867 * getPasswordQuality(null, user X, false). 3868 * 3869 * Caches for all users in the same user group often need to be updated alltogether because a 3870 * user's admin policy can affect another's aggregated password quality in some situation. 3871 * For example a managed profile's policy will affect the parent user if the profile has unified 3872 * challenge. A profile can also explicitly set a parent password quality which will affect the 3873 * aggregated password quality of the parent user. 3874 */ 3875 private void updatePasswordQualityCacheForUserGroup(@UserIdInt int userId) { 3876 final List<UserInfo> users; 3877 if (userId == UserHandle.USER_ALL) { 3878 users = mUserManager.getUsers(); 3879 } else { 3880 users = mUserManager.getProfiles(userId); 3881 } 3882 for (UserInfo userInfo : users) { 3883 final int currentUserId = userInfo.id; 3884 mPolicyCache.setPasswordQuality(currentUserId, 3885 getPasswordQuality(null, currentUserId, false)); 3886 } 3887 } 3888 3889 @Override 3890 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) { 3891 if (!mHasFeature) { 3892 return PASSWORD_QUALITY_UNSPECIFIED; 3893 } 3894 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 3895 3896 final CallerIdentity caller = getCallerIdentity(); 3897 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 3898 // System caller can query policy for a particular admin. 3899 Preconditions.checkCallAuthorization( 3900 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid()) 3901 || canQueryAdminPolicy(caller)); 3902 3903 synchronized (getLockObject()) { 3904 int mode = PASSWORD_QUALITY_UNSPECIFIED; 3905 3906 if (who != null) { 3907 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3908 return admin != null ? admin.mPasswordPolicy.quality : mode; 3909 } 3910 3911 // Return the strictest policy across all participating admins. 3912 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 3913 getProfileParentUserIfRequested(userHandle, parent)); 3914 final int N = admins.size(); 3915 for (int i = 0; i < N; i++) { 3916 ActiveAdmin admin = admins.get(i); 3917 if (mode < admin.mPasswordPolicy.quality) { 3918 mode = admin.mPasswordPolicy.quality; 3919 } 3920 } 3921 return mode; 3922 } 3923 } 3924 3925 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(int userHandle) { 3926 if (isSeparateProfileChallengeEnabled(userHandle)) { 3927 // If this user has a separate challenge, only return its restrictions. 3928 return getUserDataUnchecked(userHandle).mAdminList; 3929 } 3930 // If isSeparateProfileChallengeEnabled is false and userHandle points to a managed profile 3931 // we need to query the parent user who owns the credential. 3932 return getActiveAdminsForUserAndItsManagedProfilesLocked(getProfileParentId(userHandle), 3933 (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id)); 3934 } 3935 3936 /** 3937 * Get the list of active admins for an affected user: 3938 * <ul> 3939 * <li>The active admins associated with the userHandle itself</li> 3940 * <li>The parent active admins for each managed profile associated with the userHandle</li> 3941 * </ul> 3942 * 3943 * @param userHandle the affected user for whom to get the active admins 3944 * @return the list of active admins for the affected user 3945 */ 3946 @GuardedBy("getLockObject()") 3947 private List<ActiveAdmin> getActiveAdminsForAffectedUserLocked(int userHandle) { 3948 if (isManagedProfile(userHandle)) { 3949 return getUserDataUnchecked(userHandle).mAdminList; 3950 } 3951 return getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle, 3952 /* shouldIncludeProfileAdmins */ (user) -> false); 3953 } 3954 3955 /** 3956 * Returns the list of admins on the given user, as well as parent admins for each managed 3957 * profile associated with the given user. Optionally also include the admin of each managed 3958 * profile. 3959 * <p> Should not be called on a profile user. 3960 */ 3961 @GuardedBy("getLockObject()") 3962 private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesLocked(int userHandle, 3963 Predicate<UserInfo> shouldIncludeProfileAdmins) { 3964 ArrayList<ActiveAdmin> admins = new ArrayList<>(); 3965 mInjector.binderWithCleanCallingIdentity(() -> { 3966 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 3967 DevicePolicyData policy = getUserDataUnchecked(userInfo.id); 3968 if (userInfo.id == userHandle) { 3969 admins.addAll(policy.mAdminList); 3970 } else if (userInfo.isManagedProfile()) { 3971 for (int i = 0; i < policy.mAdminList.size(); i++) { 3972 ActiveAdmin admin = policy.mAdminList.get(i); 3973 if (admin.hasParentActiveAdmin()) { 3974 admins.add(admin.getParentActiveAdmin()); 3975 } 3976 if (shouldIncludeProfileAdmins.test(userInfo)) { 3977 admins.add(admin); 3978 } 3979 } 3980 } else { 3981 Slogf.w(LOG_TAG, "Unknown user type: " + userInfo); 3982 } 3983 } 3984 }); 3985 return admins; 3986 } 3987 3988 private boolean isSeparateProfileChallengeEnabled(int userHandle) { 3989 return mInjector.binderWithCleanCallingIdentity(() -> 3990 mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle)); 3991 } 3992 3993 @Override 3994 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) { 3995 if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLength")) { 3996 return; 3997 } 3998 Objects.requireNonNull(who, "ComponentName is null"); 3999 final int userId = mInjector.userHandleGetCallingUserId(); 4000 synchronized (getLockObject()) { 4001 ActiveAdmin ap = getActiveAdminForCallerLocked( 4002 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4003 ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_NUMERIC, "setPasswordMinimumLength"); 4004 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4005 if (passwordPolicy.length != length) { 4006 passwordPolicy.length = length; 4007 updatePasswordValidityCheckpointLocked(userId, parent); 4008 saveSettingsLocked(userId); 4009 } 4010 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4011 } 4012 DevicePolicyEventLogger 4013 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LENGTH) 4014 .setAdmin(who) 4015 .setInt(length) 4016 .write(); 4017 } 4018 4019 private void ensureMinimumQuality( 4020 int userId, ActiveAdmin admin, int minimumQuality, String operation) { 4021 mInjector.binderWithCleanCallingIdentity(() -> { 4022 // This check will also take care of the case where the password requirements 4023 // are specified as complexity rather than quality: When a password complexity 4024 // is set, the quality is reset to "unspecified" which will be below any value 4025 // of minimumQuality. 4026 if (admin.mPasswordPolicy.quality < minimumQuality 4027 && passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(), 4028 userId)) { 4029 throw new IllegalStateException(String.format( 4030 "password quality should be at least %d for %s", 4031 minimumQuality, operation)); 4032 } 4033 }); 4034 } 4035 4036 @Override 4037 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) { 4038 return getStrictestPasswordRequirement(who, userHandle, parent, 4039 admin -> admin.mPasswordPolicy.length, PASSWORD_QUALITY_NUMERIC); 4040 } 4041 4042 @Override 4043 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) { 4044 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4045 return; 4046 } 4047 Objects.requireNonNull(who, "ComponentName is null"); 4048 final int userId = mInjector.userHandleGetCallingUserId(); 4049 synchronized (getLockObject()) { 4050 ActiveAdmin ap = getActiveAdminForCallerLocked( 4051 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4052 if (ap.passwordHistoryLength != length) { 4053 ap.passwordHistoryLength = length; 4054 updatePasswordValidityCheckpointLocked(userId, parent); 4055 saveSettingsLocked(userId); 4056 } 4057 } 4058 if (SecurityLog.isLoggingEnabled()) { 4059 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4060 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET, 4061 who.getPackageName(), userId, affectedUserId, length); 4062 } 4063 } 4064 4065 @Override 4066 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) { 4067 if (!mLockPatternUtils.hasSecureLockScreen()) { 4068 return 0; 4069 } 4070 return getStrictestPasswordRequirement(who, userHandle, parent, 4071 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED); 4072 } 4073 4074 @Override 4075 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) { 4076 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4077 return; 4078 } 4079 Objects.requireNonNull(who, "ComponentName is null"); 4080 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms"); 4081 final int userHandle = mInjector.userHandleGetCallingUserId(); 4082 synchronized (getLockObject()) { 4083 ActiveAdmin ap = getActiveAdminForCallerLocked( 4084 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent); 4085 // Calling this API automatically bumps the expiration date 4086 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 4087 ap.passwordExpirationDate = expiration; 4088 ap.passwordExpirationTimeout = timeout; 4089 if (timeout > 0L) { 4090 Slogf.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 4091 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 4092 .format(new Date(expiration))); 4093 } 4094 saveSettingsLocked(userHandle); 4095 4096 // in case this is the first one, set the alarm on the appropriate user. 4097 setExpirationAlarmCheckLocked(mContext, userHandle, parent); 4098 } 4099 if (SecurityLog.isLoggingEnabled()) { 4100 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 4101 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(), 4102 userHandle, affectedUserId, timeout); 4103 } 4104 } 4105 4106 /** 4107 * Return a single admin's expiration cycle time, or the min of all cycle times. 4108 * Returns 0 if not configured. 4109 */ 4110 @Override 4111 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) { 4112 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4113 return 0L; 4114 } 4115 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4116 4117 final CallerIdentity caller = getCallerIdentity(who); 4118 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4119 4120 synchronized (getLockObject()) { 4121 long timeout = 0L; 4122 4123 if (who != null) { 4124 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4125 return admin != null ? admin.passwordExpirationTimeout : timeout; 4126 } 4127 4128 // Return the strictest policy across all participating admins. 4129 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4130 getProfileParentUserIfRequested(userHandle, parent)); 4131 final int N = admins.size(); 4132 for (int i = 0; i < N; i++) { 4133 ActiveAdmin admin = admins.get(i); 4134 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 4135 && timeout > admin.passwordExpirationTimeout)) { 4136 timeout = admin.passwordExpirationTimeout; 4137 } 4138 } 4139 return timeout; 4140 } 4141 } 4142 4143 @Override 4144 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4145 Objects.requireNonNull(admin, "ComponentName is null"); 4146 4147 final CallerIdentity caller = getCallerIdentity(admin); 4148 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 4149 List<String> changedProviders = null; 4150 4151 synchronized (getLockObject()) { 4152 ActiveAdmin activeAdmin = getProfileOwnerLocked(caller); 4153 if (activeAdmin.crossProfileWidgetProviders == null) { 4154 activeAdmin.crossProfileWidgetProviders = new ArrayList<>(); 4155 } 4156 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4157 if (!providers.contains(packageName)) { 4158 providers.add(packageName); 4159 changedProviders = new ArrayList<>(providers); 4160 saveSettingsLocked(caller.getUserId()); 4161 } 4162 } 4163 4164 DevicePolicyEventLogger 4165 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_WIDGET_PROVIDER) 4166 .setAdmin(admin) 4167 .write(); 4168 4169 if (changedProviders != null) { 4170 mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(), 4171 changedProviders); 4172 return true; 4173 } 4174 4175 return false; 4176 } 4177 4178 @Override 4179 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4180 Objects.requireNonNull(admin, "ComponentName is null"); 4181 4182 final CallerIdentity caller = getCallerIdentity(admin); 4183 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 4184 List<String> changedProviders = null; 4185 4186 synchronized (getLockObject()) { 4187 ActiveAdmin activeAdmin = getProfileOwnerLocked(caller); 4188 if (activeAdmin.crossProfileWidgetProviders == null 4189 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4190 return false; 4191 } 4192 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4193 if (providers.remove(packageName)) { 4194 changedProviders = new ArrayList<>(providers); 4195 saveSettingsLocked(caller.getUserId()); 4196 } 4197 } 4198 4199 DevicePolicyEventLogger 4200 .createEvent(DevicePolicyEnums.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER) 4201 .setAdmin(admin) 4202 .write(); 4203 4204 if (changedProviders != null) { 4205 mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(), 4206 changedProviders); 4207 return true; 4208 } 4209 4210 return false; 4211 } 4212 4213 @Override 4214 public List<String> getCrossProfileWidgetProviders(ComponentName admin) { 4215 Objects.requireNonNull(admin, "ComponentName is null"); 4216 4217 final CallerIdentity caller = getCallerIdentity(admin); 4218 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 4219 4220 synchronized (getLockObject()) { 4221 ActiveAdmin activeAdmin = getProfileOwnerLocked(caller); 4222 if (activeAdmin.crossProfileWidgetProviders == null 4223 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4224 return null; 4225 } 4226 if (mInjector.binderIsCallingUidMyUid()) { 4227 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders); 4228 } else { 4229 return activeAdmin.crossProfileWidgetProviders; 4230 } 4231 } 4232 } 4233 4234 /** 4235 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 4236 * Returns 0 if not configured. 4237 */ 4238 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) { 4239 long timeout = 0L; 4240 4241 if (who != null) { 4242 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4243 return admin != null ? admin.passwordExpirationDate : timeout; 4244 } 4245 4246 // Return the strictest policy across all participating admins. 4247 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4248 getProfileParentUserIfRequested(userHandle, parent)); 4249 final int N = admins.size(); 4250 for (int i = 0; i < N; i++) { 4251 ActiveAdmin admin = admins.get(i); 4252 if (timeout == 0L || (admin.passwordExpirationDate != 0 4253 && timeout > admin.passwordExpirationDate)) { 4254 timeout = admin.passwordExpirationDate; 4255 } 4256 } 4257 return timeout; 4258 } 4259 4260 @Override 4261 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) { 4262 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4263 return 0L; 4264 } 4265 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4266 4267 final CallerIdentity caller = getCallerIdentity(who); 4268 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4269 4270 synchronized (getLockObject()) { 4271 return getPasswordExpirationLocked(who, userHandle, parent); 4272 } 4273 } 4274 4275 @Override 4276 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) { 4277 if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumUpperCase")) { 4278 return; 4279 } 4280 Objects.requireNonNull(who, "ComponentName is null"); 4281 final int userId = mInjector.userHandleGetCallingUserId(); 4282 synchronized (getLockObject()) { 4283 final ActiveAdmin ap = getActiveAdminForCallerLocked( 4284 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4285 ensureMinimumQuality( 4286 userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumUpperCase"); 4287 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4288 if (passwordPolicy.upperCase != length) { 4289 passwordPolicy.upperCase = length; 4290 updatePasswordValidityCheckpointLocked(userId, parent); 4291 saveSettingsLocked(userId); 4292 } 4293 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4294 } 4295 DevicePolicyEventLogger 4296 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_UPPER_CASE) 4297 .setAdmin(who) 4298 .setInt(length) 4299 .write(); 4300 } 4301 4302 @Override 4303 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) { 4304 return getStrictestPasswordRequirement(who, userHandle, parent, 4305 admin -> admin.mPasswordPolicy.upperCase, PASSWORD_QUALITY_COMPLEX); 4306 } 4307 4308 @Override 4309 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) { 4310 if (notSupportedOnAutomotive("setPasswordMinimumLowerCase")) { 4311 return; 4312 } 4313 Objects.requireNonNull(who, "ComponentName is null"); 4314 final int userId = mInjector.userHandleGetCallingUserId(); 4315 synchronized (getLockObject()) { 4316 ActiveAdmin ap = getActiveAdminForCallerLocked( 4317 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4318 ensureMinimumQuality( 4319 userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLowerCase"); 4320 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4321 if (passwordPolicy.lowerCase != length) { 4322 passwordPolicy.lowerCase = length; 4323 updatePasswordValidityCheckpointLocked(userId, parent); 4324 saveSettingsLocked(userId); 4325 } 4326 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4327 } 4328 DevicePolicyEventLogger 4329 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LOWER_CASE) 4330 .setAdmin(who) 4331 .setInt(length) 4332 .write(); 4333 } 4334 4335 @Override 4336 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) { 4337 return getStrictestPasswordRequirement(who, userHandle, parent, 4338 admin -> admin.mPasswordPolicy.lowerCase, PASSWORD_QUALITY_COMPLEX); 4339 } 4340 4341 @Override 4342 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) { 4343 if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLetters")) { 4344 return; 4345 } 4346 Objects.requireNonNull(who, "ComponentName is null"); 4347 final int userId = mInjector.userHandleGetCallingUserId(); 4348 synchronized (getLockObject()) { 4349 ActiveAdmin ap = getActiveAdminForCallerLocked( 4350 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4351 ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLetters"); 4352 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4353 if (passwordPolicy.letters != length) { 4354 passwordPolicy.letters = length; 4355 updatePasswordValidityCheckpointLocked(userId, parent); 4356 saveSettingsLocked(userId); 4357 } 4358 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4359 } 4360 DevicePolicyEventLogger 4361 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LETTERS) 4362 .setAdmin(who) 4363 .setInt(length) 4364 .write(); 4365 } 4366 4367 @Override 4368 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) { 4369 return getStrictestPasswordRequirement(who, userHandle, parent, 4370 admin -> admin.mPasswordPolicy.letters, PASSWORD_QUALITY_COMPLEX); 4371 } 4372 4373 @Override 4374 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) { 4375 if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNumeric")) { 4376 return; 4377 } 4378 Objects.requireNonNull(who, "ComponentName is null"); 4379 final int userId = mInjector.userHandleGetCallingUserId(); 4380 synchronized (getLockObject()) { 4381 ActiveAdmin ap = getActiveAdminForCallerLocked( 4382 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4383 ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNumeric"); 4384 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4385 if (passwordPolicy.numeric != length) { 4386 passwordPolicy.numeric = length; 4387 updatePasswordValidityCheckpointLocked(userId, parent); 4388 saveSettingsLocked(userId); 4389 } 4390 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4391 } 4392 DevicePolicyEventLogger 4393 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NUMERIC) 4394 .setAdmin(who) 4395 .setInt(length) 4396 .write(); 4397 } 4398 4399 @Override 4400 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) { 4401 return getStrictestPasswordRequirement(who, userHandle, parent, 4402 admin -> admin.mPasswordPolicy.numeric, PASSWORD_QUALITY_COMPLEX); 4403 } 4404 4405 @Override 4406 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) { 4407 if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumSymbols")) { 4408 return; 4409 } 4410 Objects.requireNonNull(who, "ComponentName is null"); 4411 final int userId = mInjector.userHandleGetCallingUserId(); 4412 synchronized (getLockObject()) { 4413 ActiveAdmin ap = getActiveAdminForCallerLocked( 4414 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4415 ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumSymbols"); 4416 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4417 if (passwordPolicy.symbols != length) { 4418 ap.mPasswordPolicy.symbols = length; 4419 updatePasswordValidityCheckpointLocked(userId, parent); 4420 saveSettingsLocked(userId); 4421 } 4422 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4423 } 4424 DevicePolicyEventLogger 4425 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_SYMBOLS) 4426 .setAdmin(who) 4427 .setInt(length) 4428 .write(); 4429 } 4430 4431 @Override 4432 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) { 4433 return getStrictestPasswordRequirement(who, userHandle, parent, 4434 admin -> admin.mPasswordPolicy.symbols, PASSWORD_QUALITY_COMPLEX); 4435 } 4436 4437 @Override 4438 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) { 4439 if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNonLetter")) { 4440 return; 4441 } 4442 Objects.requireNonNull(who, "ComponentName is null"); 4443 final int userId = mInjector.userHandleGetCallingUserId(); 4444 synchronized (getLockObject()) { 4445 ActiveAdmin ap = getActiveAdminForCallerLocked( 4446 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4447 ensureMinimumQuality( 4448 userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNonLetter"); 4449 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy; 4450 if (passwordPolicy.nonLetter != length) { 4451 ap.mPasswordPolicy.nonLetter = length; 4452 updatePasswordValidityCheckpointLocked(userId, parent); 4453 saveSettingsLocked(userId); 4454 } 4455 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy); 4456 } 4457 DevicePolicyEventLogger 4458 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NON_LETTER) 4459 .setAdmin(who) 4460 .setInt(length) 4461 .write(); 4462 } 4463 4464 @Override 4465 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) { 4466 return getStrictestPasswordRequirement(who, userHandle, parent, 4467 admin -> admin.mPasswordPolicy.nonLetter, PASSWORD_QUALITY_COMPLEX); 4468 } 4469 4470 /** 4471 * Calculates strictest (maximum) value for a given password property enforced by admin[s]. 4472 */ 4473 private int getStrictestPasswordRequirement(ComponentName who, int userHandle, 4474 boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) { 4475 if (!mHasFeature) { 4476 return 0; 4477 } 4478 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4479 4480 final CallerIdentity caller = getCallerIdentity(who); 4481 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4482 4483 synchronized (getLockObject()) { 4484 if (who != null) { 4485 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4486 return admin != null ? getter.apply(admin) : 0; 4487 } 4488 4489 int maxValue = 0; 4490 final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4491 getProfileParentUserIfRequested(userHandle, parent)); 4492 final int N = admins.size(); 4493 for (int i = 0; i < N; i++) { 4494 final ActiveAdmin admin = admins.get(i); 4495 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) { 4496 continue; 4497 } 4498 final Integer adminValue = getter.apply(admin); 4499 if (adminValue > maxValue) { 4500 maxValue = adminValue; 4501 } 4502 } 4503 return maxValue; 4504 } 4505 } 4506 4507 /** 4508 * Calculates strictest (maximum) value for a given password property enforced by admin[s]. 4509 */ 4510 @Override 4511 public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle, 4512 boolean deviceWideOnly) { 4513 final CallerIdentity caller = getCallerIdentity(); 4514 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle) 4515 && (isSystemUid(caller) || hasCallingOrSelfPermission( 4516 permission.SET_INITIAL_LOCK))); 4517 return getPasswordMinimumMetricsUnchecked(userHandle, deviceWideOnly); 4518 } 4519 4520 private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId) { 4521 return getPasswordMinimumMetricsUnchecked(userId, false); 4522 } 4523 4524 private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId, 4525 boolean deviceWideOnly) { 4526 if (!mHasFeature) { 4527 new PasswordMetrics(CREDENTIAL_TYPE_NONE); 4528 } 4529 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 4530 if (deviceWideOnly) { 4531 Preconditions.checkArgument(!isManagedProfile(userId)); 4532 } 4533 4534 ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>(); 4535 final List<ActiveAdmin> admins; 4536 synchronized (getLockObject()) { 4537 if (deviceWideOnly) { 4538 admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userId, 4539 /* shouldIncludeProfileAdmins */ (user) -> false); 4540 } else { 4541 admins = getActiveAdminsForLockscreenPoliciesLocked(userId); 4542 } 4543 for (ActiveAdmin admin : admins) { 4544 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics()); 4545 } 4546 } 4547 return PasswordMetrics.merge(adminMetrics); 4548 } 4549 4550 @Override 4551 public boolean isActivePasswordSufficient(int userHandle, boolean parent) { 4552 if (!mHasFeature) { 4553 return true; 4554 } 4555 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4556 4557 final CallerIdentity caller = getCallerIdentity(); 4558 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4559 enforceUserUnlocked(userHandle, parent); 4560 4561 synchronized (getLockObject()) { 4562 // This API can only be called by an active device admin, 4563 // so try to retrieve it to check that the caller is one. 4564 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4565 int credentialOwner = getCredentialOwner(userHandle, parent); 4566 DevicePolicyData policy = getUserDataUnchecked(credentialOwner); 4567 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner); 4568 final int userToCheck = getProfileParentUserIfRequested(userHandle, parent); 4569 boolean activePasswordSufficientForUserLocked = isActivePasswordSufficientForUserLocked( 4570 policy.mPasswordValidAtLastCheckpoint, metrics, userToCheck); 4571 return activePasswordSufficientForUserLocked; 4572 } 4573 } 4574 4575 @Override 4576 public boolean isActivePasswordSufficientForDeviceRequirement() { 4577 if (!mHasFeature) { 4578 return true; 4579 } 4580 final CallerIdentity caller = getCallerIdentity(); 4581 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 4582 4583 final int profileUserId = caller.getUserId(); 4584 Preconditions.checkCallingUser(isManagedProfile(profileUserId)); 4585 4586 // This method is always called on the parent DPM instance to check if its password (i.e. 4587 // the device password) is sufficient for all explicit password requirement set on it 4588 // So retrieve the parent user Id to which the device password belongs. 4589 final int parentUser = getProfileParentId(profileUserId); 4590 enforceUserUnlocked(parentUser); 4591 4592 final boolean isSufficient; 4593 synchronized (getLockObject()) { 4594 4595 int complexity = getAggregatedPasswordComplexityLocked(parentUser, true); 4596 PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(parentUser, true); 4597 4598 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(parentUser); 4599 final List<PasswordValidationError> passwordValidationErrors = 4600 PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics); 4601 isSufficient = passwordValidationErrors.isEmpty(); 4602 } 4603 DevicePolicyEventLogger 4604 .createEvent(DevicePolicyEnums.IS_ACTIVE_PASSWORD_SUFFICIENT_FOR_DEVICE) 4605 .setStrings(mOwners.getProfileOwnerComponent(caller.getUserId()).getPackageName()) 4606 .write(); 4607 return isSufficient; 4608 } 4609 4610 @Override 4611 public boolean isUsingUnifiedPassword(ComponentName admin) { 4612 if (!mHasFeature) { 4613 return true; 4614 } 4615 Objects.requireNonNull(admin, "ComponentName is null"); 4616 4617 final CallerIdentity caller = getCallerIdentity(admin); 4618 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 4619 || isProfileOwner(caller)); 4620 Preconditions.checkCallingUser(isManagedProfile(caller.getUserId())); 4621 4622 return !isSeparateProfileChallengeEnabled(caller.getUserId()); 4623 } 4624 4625 @Override 4626 public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) { 4627 if (!mHasFeature) { 4628 return true; 4629 } 4630 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4631 4632 final CallerIdentity caller = getCallerIdentity(); 4633 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4634 Preconditions.checkCallAuthorization(!isManagedProfile(userHandle), 4635 "You can not check password sufficiency for a managed profile, userId = %d", 4636 userHandle); 4637 enforceUserUnlocked(userHandle); 4638 4639 synchronized (getLockObject()) { 4640 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(userHandle); 4641 4642 // Combine password policies across the user and its profiles. Profile admins are 4643 // included if the profile is to be unified or currently has unified challenge 4644 List<ActiveAdmin> admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle, 4645 /* shouldIncludeProfileAdmins */ (user) -> user.id == profileUser 4646 || !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id)); 4647 ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>(admins.size()); 4648 int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE; 4649 for (ActiveAdmin admin : admins) { 4650 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics()); 4651 maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity); 4652 } 4653 return PasswordMetrics.validatePasswordMetrics(PasswordMetrics.merge(adminMetrics), 4654 maxRequiredComplexity, metrics).isEmpty(); 4655 } 4656 } 4657 4658 private boolean isActivePasswordSufficientForUserLocked( 4659 boolean passwordValidAtLastCheckpoint, @Nullable PasswordMetrics metrics, 4660 int userHandle) { 4661 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) { 4662 // Before user enters their password for the first time after a reboot, return the 4663 // value of this flag, which tells us whether the password was valid the last time 4664 // settings were saved. If DPC changes password requirements on boot so that the 4665 // current password no longer meets the requirements, this value will be stale until 4666 // the next time the password is entered. 4667 return passwordValidAtLastCheckpoint; 4668 } 4669 4670 if (metrics == null) { 4671 // Called on a FBE device when the user password exists but its metrics is unknown. 4672 // This shouldn't happen since we enforce the user to be unlocked (which would result 4673 // in the metrics known to the framework on a FBE device) at all call sites. 4674 throw new IllegalStateException("isActivePasswordSufficient called on FBE-locked user"); 4675 } 4676 4677 return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle); 4678 } 4679 4680 /** 4681 * Returns {@code true} if the password represented by the {@code metrics} argument 4682 * sufficiently fulfills the password requirements for the user corresponding to 4683 * {@code userId}. 4684 */ 4685 private boolean isPasswordSufficientForUserWithoutCheckpointLocked( 4686 @NonNull PasswordMetrics metrics, @UserIdInt int userId) { 4687 final int complexity = getAggregatedPasswordComplexityLocked(userId); 4688 PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userId); 4689 final List<PasswordValidationError> passwordValidationErrors = 4690 PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics); 4691 return passwordValidationErrors.isEmpty(); 4692 } 4693 4694 @Override 4695 @PasswordComplexity 4696 public int getPasswordComplexity(boolean parent) { 4697 final CallerIdentity caller = getCallerIdentity(); 4698 DevicePolicyEventLogger 4699 .createEvent(DevicePolicyEnums.GET_USER_PASSWORD_COMPLEXITY_LEVEL) 4700 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT, 4701 mInjector.getPackageManager().getPackagesForUid(caller.getUid())) 4702 .write(); 4703 4704 enforceUserUnlocked(caller.getUserId()); 4705 if (parent) { 4706 Preconditions.checkCallAuthorization( 4707 isDefaultDeviceOwner(caller) || isProfileOwner(caller) || isSystemUid(caller), 4708 "Only profile owner, device owner and system may call this method on parent."); 4709 } else { 4710 Preconditions.checkCallAuthorization( 4711 hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY) 4712 || isDefaultDeviceOwner(caller) || isProfileOwner(caller), 4713 "Must have " + REQUEST_PASSWORD_COMPLEXITY 4714 + " permission, or be a profile owner or device owner."); 4715 } 4716 4717 synchronized (getLockObject()) { 4718 final int credentialOwner = getCredentialOwner(caller.getUserId(), parent); 4719 PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner); 4720 return metrics == null ? PASSWORD_COMPLEXITY_NONE : metrics.determineComplexity(); 4721 } 4722 } 4723 4724 @Override 4725 public void setRequiredPasswordComplexity(int passwordComplexity, boolean calledOnParent) { 4726 if (!mHasFeature) { 4727 return; 4728 } 4729 final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW, 4730 PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH); 4731 Preconditions.checkArgument(allowedModes.contains(passwordComplexity), 4732 "Provided complexity is not one of the allowed values."); 4733 4734 final CallerIdentity caller = getCallerIdentity(); 4735 Preconditions.checkCallAuthorization( 4736 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 4737 Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller)); 4738 4739 synchronized (getLockObject()) { 4740 final ActiveAdmin admin = getParentOfAdminIfRequired( 4741 getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParent); 4742 if (admin.mPasswordComplexity != passwordComplexity) { 4743 // We require the caller to explicitly clear any password quality requirements set 4744 // on the parent DPM instance, to avoid the case where password requirements are 4745 // specified in the form of quality on the parent but complexity on the profile 4746 // itself. 4747 if (!calledOnParent) { 4748 final boolean hasQualityRequirementsOnParent = admin.hasParentActiveAdmin() 4749 && admin.getParentActiveAdmin().mPasswordPolicy.quality 4750 != PASSWORD_QUALITY_UNSPECIFIED; 4751 Preconditions.checkState(!hasQualityRequirementsOnParent, 4752 "Password quality is set on the parent when attempting to set password" 4753 + "complexity. Clear the quality by setting the password quality " 4754 + "on the parent to PASSWORD_QUALITY_UNSPECIFIED first"); 4755 } 4756 4757 mInjector.binderWithCleanCallingIdentity(() -> { 4758 admin.mPasswordComplexity = passwordComplexity; 4759 // Reset the password policy. 4760 admin.mPasswordPolicy = new PasswordPolicy(); 4761 updatePasswordValidityCheckpointLocked(caller.getUserId(), calledOnParent); 4762 updatePasswordQualityCacheForUserGroup(caller.getUserId()); 4763 saveSettingsLocked(caller.getUserId()); 4764 }); 4765 4766 DevicePolicyEventLogger 4767 .createEvent(DevicePolicyEnums.SET_PASSWORD_COMPLEXITY) 4768 .setAdmin(admin.info.getPackageName()) 4769 .setInt(passwordComplexity) 4770 .setBoolean(calledOnParent) 4771 .write(); 4772 } 4773 logPasswordComplexityRequiredIfSecurityLogEnabled(admin.info.getComponent(), 4774 caller.getUserId(), calledOnParent, passwordComplexity); 4775 } 4776 } 4777 4778 private void logPasswordComplexityRequiredIfSecurityLogEnabled(ComponentName who, int userId, 4779 boolean parent, int complexity) { 4780 if (SecurityLog.isLoggingEnabled()) { 4781 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4782 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_REQUIRED, 4783 who.getPackageName(), userId, affectedUserId, complexity); 4784 } 4785 } 4786 4787 private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle) { 4788 return getAggregatedPasswordComplexityLocked(userHandle, false); 4789 } 4790 4791 private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle, 4792 boolean deviceWideOnly) { 4793 ensureLocked(); 4794 final List<ActiveAdmin> admins; 4795 if (deviceWideOnly) { 4796 admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle, 4797 /* shouldIncludeProfileAdmins */ (user) -> false); 4798 } else { 4799 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle); 4800 } 4801 int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE; 4802 for (ActiveAdmin admin : admins) { 4803 maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity); 4804 } 4805 return maxRequiredComplexity; 4806 } 4807 4808 @Override 4809 public int getRequiredPasswordComplexity(boolean calledOnParent) { 4810 if (!mHasFeature) { 4811 return PASSWORD_COMPLEXITY_NONE; 4812 } 4813 4814 final CallerIdentity caller = getCallerIdentity(); 4815 Preconditions.checkCallAuthorization( 4816 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 4817 4818 Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller)); 4819 4820 synchronized (getLockObject()) { 4821 final ActiveAdmin requiredAdmin = getParentOfAdminIfRequired( 4822 getDeviceOrProfileOwnerAdminLocked(caller.getUserId()), calledOnParent); 4823 return requiredAdmin.mPasswordComplexity; 4824 } 4825 } 4826 4827 @Override 4828 public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) { 4829 if (!mHasFeature) { 4830 return PASSWORD_COMPLEXITY_NONE; 4831 } 4832 4833 final CallerIdentity caller = getCallerIdentity(); 4834 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 4835 4836 synchronized (getLockObject()) { 4837 return getAggregatedPasswordComplexityLocked(userId, deviceWideOnly); 4838 } 4839 } 4840 4841 4842 @Override 4843 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) { 4844 if (!mLockPatternUtils.hasSecureLockScreen()) { 4845 return 0; 4846 } 4847 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4848 4849 final CallerIdentity caller = getCallerIdentity(); 4850 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4851 4852 synchronized (getLockObject()) { 4853 if (!isSystemUid(caller)) { 4854 // This API can be called by an active device admin or by keyguard code. 4855 if (!hasCallingPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)) { 4856 getActiveAdminForCallerLocked( 4857 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4858 } 4859 } 4860 4861 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4862 4863 return policy.mFailedPasswordAttempts; 4864 } 4865 } 4866 4867 @Override 4868 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) { 4869 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4870 return; 4871 } 4872 Objects.requireNonNull(who, "ComponentName is null"); 4873 final int userId = mInjector.userHandleGetCallingUserId(); 4874 synchronized (getLockObject()) { 4875 // This API can only be called by an active device admin, 4876 // so try to retrieve it to check that the caller is one. 4877 getActiveAdminForCallerLocked( 4878 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent); 4879 ActiveAdmin ap = getActiveAdminForCallerLocked( 4880 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4881 if (ap.maximumFailedPasswordsForWipe != num) { 4882 ap.maximumFailedPasswordsForWipe = num; 4883 saveSettingsLocked(userId); 4884 } 4885 } 4886 if (SecurityLog.isLoggingEnabled()) { 4887 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4888 SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(), 4889 userId, affectedUserId, num); 4890 } 4891 } 4892 4893 @Override 4894 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) { 4895 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4896 return 0; 4897 } 4898 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4899 4900 final CallerIdentity caller = getCallerIdentity(); 4901 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4902 // System caller can query policy for a particular admin. 4903 Preconditions.checkCallAuthorization( 4904 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid()) 4905 || canQueryAdminPolicy(caller)); 4906 4907 synchronized (getLockObject()) { 4908 ActiveAdmin admin = (who != null) 4909 ? getActiveAdminUncheckedLocked(who, userHandle, parent) 4910 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent); 4911 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 4912 } 4913 } 4914 4915 @Override 4916 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) { 4917 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4918 return UserHandle.USER_NULL; 4919 } 4920 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 4921 4922 final CallerIdentity caller = getCallerIdentity(); 4923 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 4924 4925 synchronized (getLockObject()) { 4926 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked( 4927 userHandle, parent); 4928 return admin != null ? getUserIdToWipeForFailedPasswords(admin) : UserHandle.USER_NULL; 4929 } 4930 } 4931 4932 /** 4933 * Returns the admin with the strictest policy on maximum failed passwords for: 4934 * <ul> 4935 * <li>this user if it has a separate profile challenge, or 4936 * <li>this user and all profiles that don't have their own challenge otherwise. 4937 * </ul> 4938 * <p>If the policy for the primary and any other profile are equal, it returns the admin for 4939 * the primary profile. Policy of a PO on an organization-owned device applies to the primary 4940 * profile. 4941 * Returns {@code null} if no participating admin has that policy set. 4942 */ 4943 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked( 4944 int userHandle, boolean parent) { 4945 int count = 0; 4946 ActiveAdmin strictestAdmin = null; 4947 4948 // Return the strictest policy across all participating admins. 4949 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4950 getProfileParentUserIfRequested(userHandle, parent)); 4951 final int N = admins.size(); 4952 for (int i = 0; i < N; i++) { 4953 ActiveAdmin admin = admins.get(i); 4954 if (admin.maximumFailedPasswordsForWipe == 4955 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 4956 continue; // No max number of failed passwords policy set for this profile. 4957 } 4958 4959 // We always favor the primary profile if several profiles have the same value set. 4960 final int userId = getUserIdToWipeForFailedPasswords(admin); 4961 if (count == 0 || 4962 count > admin.maximumFailedPasswordsForWipe || 4963 (count == admin.maximumFailedPasswordsForWipe && 4964 getUserInfo(userId).isPrimary())) { 4965 count = admin.maximumFailedPasswordsForWipe; 4966 strictestAdmin = admin; 4967 } 4968 } 4969 return strictestAdmin; 4970 } 4971 4972 private UserInfo getUserInfo(@UserIdInt int userId) { 4973 return mInjector.binderWithCleanCallingIdentity(() -> mUserManager.getUserInfo(userId)); 4974 } 4975 4976 private boolean setPasswordPrivileged(@NonNull String password, int flags, 4977 CallerIdentity caller) { 4978 // Only allow setting password on an unsecured user 4979 if (isLockScreenSecureUnchecked(caller.getUserId())) { 4980 throw new SecurityException("Cannot change current password"); 4981 } 4982 return resetPasswordInternal(password, 0, null, flags, caller); 4983 } 4984 4985 @Override 4986 public boolean resetPassword(@Nullable String password, int flags) throws RemoteException { 4987 if (!mLockPatternUtils.hasSecureLockScreen()) { 4988 Slogf.w(LOG_TAG, "Cannot reset password when the device has no lock screen"); 4989 return false; 4990 } 4991 if (password == null) password = ""; 4992 final CallerIdentity caller = getCallerIdentity(); 4993 final int userHandle = caller.getUserId(); 4994 4995 // As of R, only privileged caller holding RESET_PASSWORD can call resetPassword() to 4996 // set password to an unsecured user. 4997 if (hasCallingPermission(permission.RESET_PASSWORD)) { 4998 final boolean result = setPasswordPrivileged(password, flags, caller); 4999 if (result) { 5000 DevicePolicyEventLogger 5001 .createEvent(DevicePolicyEnums.RESET_PASSWORD) 5002 .write(); 5003 } 5004 return result; 5005 } 5006 5007 // If caller has PO (or DO) throw or fail silently depending on its target SDK level. 5008 if (isDefaultDeviceOwner(caller) || isProfileOwner(caller)) { 5009 synchronized (getLockObject()) { 5010 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 5011 if (getTargetSdk(admin.info.getPackageName(), userHandle) < Build.VERSION_CODES.O) { 5012 Slogf.e(LOG_TAG, "DPC can no longer call resetPassword()"); 5013 return false; 5014 } 5015 throw new SecurityException("Device admin can no longer call resetPassword()"); 5016 } 5017 } 5018 5019 // Caller is not DO or PO, could either be unauthorized or Device Admin. 5020 synchronized (getLockObject()) { 5021 // Legacy device admin cannot call resetPassword either 5022 ActiveAdmin admin = getActiveAdminForCallerLocked( 5023 null, DeviceAdminInfo.USES_POLICY_RESET_PASSWORD, false); 5024 Preconditions.checkCallAuthorization(admin != null, 5025 "Unauthorized caller cannot call resetPassword."); 5026 if (getTargetSdk(admin.info.getPackageName(), 5027 userHandle) <= android.os.Build.VERSION_CODES.M) { 5028 Slogf.e(LOG_TAG, "Device admin can no longer call resetPassword()"); 5029 return false; 5030 } 5031 throw new SecurityException("Device admin can no longer call resetPassword()"); 5032 } 5033 } 5034 5035 private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token, 5036 int flags, CallerIdentity caller) { 5037 final int callingUid = caller.getUid(); 5038 final int userHandle = UserHandle.getUserId(callingUid); 5039 final boolean isPin = PasswordMetrics.isNumericOnly(password); 5040 synchronized (getLockObject()) { 5041 final PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userHandle); 5042 final List<PasswordValidationError> validationErrors; 5043 final int complexity = getAggregatedPasswordComplexityLocked(userHandle); 5044 // TODO: Consider changing validation API to take LockscreenCredential. 5045 if (password.isEmpty()) { 5046 validationErrors = PasswordMetrics.validatePasswordMetrics( 5047 minMetrics, complexity, new PasswordMetrics(CREDENTIAL_TYPE_NONE)); 5048 } else { 5049 // TODO(b/120484642): remove getBytes() below 5050 validationErrors = PasswordMetrics.validatePassword( 5051 minMetrics, complexity, isPin, password.getBytes()); 5052 } 5053 5054 if (!validationErrors.isEmpty()) { 5055 Slogf.w(LOG_TAG, "Failed to reset password due to constraint violation: %s", 5056 validationErrors.get(0)); 5057 return false; 5058 } 5059 } 5060 5061 DevicePolicyData policy = getUserData(userHandle); 5062 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 5063 Slogf.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 5064 return false; 5065 } 5066 5067 boolean callerIsDeviceOwnerAdmin = isDefaultDeviceOwner(caller); 5068 boolean doNotAskCredentialsOnBoot = 5069 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 5070 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 5071 setDoNotAskCredentialsOnBoot(); 5072 } 5073 5074 // Don't do this with the lock held, because it is going to call 5075 // back in to the service. 5076 final long ident = mInjector.binderClearCallingIdentity(); 5077 final LockscreenCredential newCredential; 5078 if (isPin) { 5079 newCredential = LockscreenCredential.createPin(password); 5080 } else { 5081 newCredential = LockscreenCredential.createPasswordOrNone(password); 5082 } 5083 try { 5084 if (tokenHandle == 0 || token == null) { 5085 if (!mLockPatternUtils.setLockCredential(newCredential, 5086 LockscreenCredential.createNone(), userHandle)) { 5087 return false; 5088 } 5089 } else { 5090 if (!mLockPatternUtils.setLockCredentialWithToken(newCredential, tokenHandle, 5091 token, userHandle)) { 5092 return false; 5093 } 5094 } 5095 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 5096 if (requireEntry) { 5097 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, 5098 UserHandle.USER_ALL); 5099 } 5100 synchronized (getLockObject()) { 5101 int newOwner = requireEntry ? callingUid : -1; 5102 if (policy.mPasswordOwner != newOwner) { 5103 policy.mPasswordOwner = newOwner; 5104 saveSettingsLocked(userHandle); 5105 } 5106 } 5107 } finally { 5108 mInjector.binderRestoreCallingIdentity(ident); 5109 } 5110 return true; 5111 } 5112 5113 private boolean isLockScreenSecureUnchecked(int userId) { 5114 return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.isSecure(userId)); 5115 } 5116 5117 private void setDoNotAskCredentialsOnBoot() { 5118 synchronized (getLockObject()) { 5119 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 5120 if (!policyData.mDoNotAskCredentialsOnBoot) { 5121 policyData.mDoNotAskCredentialsOnBoot = true; 5122 saveSettingsLocked(UserHandle.USER_SYSTEM); 5123 } 5124 } 5125 } 5126 5127 @Override 5128 public boolean getDoNotAskCredentialsOnBoot() { 5129 Preconditions.checkCallAuthorization( 5130 hasCallingOrSelfPermission(permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT)); 5131 synchronized (getLockObject()) { 5132 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 5133 return policyData.mDoNotAskCredentialsOnBoot; 5134 } 5135 } 5136 5137 @Override 5138 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) { 5139 if (!mHasFeature) { 5140 return; 5141 } 5142 Objects.requireNonNull(who, "ComponentName is null"); 5143 final int userHandle = mInjector.userHandleGetCallingUserId(); 5144 synchronized (getLockObject()) { 5145 final ActiveAdmin ap = getActiveAdminForCallerLocked( 5146 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 5147 if (ap.maximumTimeToUnlock != timeMs) { 5148 ap.maximumTimeToUnlock = timeMs; 5149 saveSettingsLocked(userHandle); 5150 updateMaximumTimeToLockLocked(userHandle); 5151 } 5152 } 5153 if (SecurityLog.isLoggingEnabled()) { 5154 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 5155 SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET, 5156 who.getPackageName(), userHandle, affectedUserId, timeMs); 5157 } 5158 } 5159 5160 private void updateMaximumTimeToLockLocked(@UserIdInt int userId) { 5161 // Update the profile's timeout 5162 if (isManagedProfile(userId)) { 5163 updateProfileLockTimeoutLocked(userId); 5164 } 5165 5166 mInjector.binderWithCleanCallingIdentity(() -> { 5167 // Update the device timeout 5168 final int parentId = getProfileParentId(userId); 5169 final long timeMs = getMaximumTimeToLockPolicyFromAdmins( 5170 getActiveAdminsForLockscreenPoliciesLocked(parentId)); 5171 5172 final DevicePolicyData policy = getUserDataUnchecked(parentId); 5173 if (policy.mLastMaximumTimeToLock == timeMs) { 5174 return; 5175 } 5176 policy.mLastMaximumTimeToLock = timeMs; 5177 5178 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) { 5179 // Make sure KEEP_SCREEN_ON is disabled, since that 5180 // would allow bypassing of the maximum time to lock. 5181 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 5182 } 5183 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5184 UserHandle.USER_SYSTEM, timeMs); 5185 }); 5186 } 5187 5188 private void updateProfileLockTimeoutLocked(@UserIdInt int userId) { 5189 final long timeMs; 5190 if (isSeparateProfileChallengeEnabled(userId)) { 5191 timeMs = getMaximumTimeToLockPolicyFromAdmins( 5192 getActiveAdminsForLockscreenPoliciesLocked(userId)); 5193 } else { 5194 timeMs = Long.MAX_VALUE; 5195 } 5196 5197 final DevicePolicyData policy = getUserDataUnchecked(userId); 5198 if (policy.mLastMaximumTimeToLock == timeMs) { 5199 return; 5200 } 5201 policy.mLastMaximumTimeToLock = timeMs; 5202 5203 mInjector.binderWithCleanCallingIdentity(() -> 5204 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5205 userId, policy.mLastMaximumTimeToLock)); 5206 } 5207 5208 @Override 5209 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) { 5210 if (!mHasFeature) { 5211 return 0; 5212 } 5213 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 5214 5215 final CallerIdentity caller = getCallerIdentity(); 5216 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 5217 // System caller can query policy for a particular admin. 5218 Preconditions.checkCallAuthorization( 5219 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid()) 5220 || canQueryAdminPolicy(caller)); 5221 5222 synchronized (getLockObject()) { 5223 if (who != null) { 5224 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 5225 return admin != null ? admin.maximumTimeToUnlock : 0; 5226 } 5227 // Return the strictest policy across all participating admins. 5228 final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5229 getProfileParentUserIfRequested(userHandle, parent)); 5230 final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins); 5231 return timeMs == Long.MAX_VALUE ? 0 : timeMs; 5232 } 5233 } 5234 5235 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) { 5236 long time = Long.MAX_VALUE; 5237 for (final ActiveAdmin admin : admins) { 5238 if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) { 5239 time = admin.maximumTimeToUnlock; 5240 } 5241 } 5242 return time; 5243 } 5244 5245 @Override 5246 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, 5247 boolean parent) { 5248 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 5249 return; 5250 } 5251 Objects.requireNonNull(who, "ComponentName is null"); 5252 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number."); 5253 final CallerIdentity caller = getCallerIdentity(who); 5254 Preconditions.checkCallAuthorization( 5255 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 5256 // timeoutMs with value 0 means that the admin doesn't participate 5257 // timeoutMs is clamped to the interval in case the internal constants change in the future 5258 final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs(); 5259 if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) { 5260 timeoutMs = minimumStrongAuthTimeout; 5261 } 5262 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 5263 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5264 } 5265 5266 final int userHandle = caller.getUserId(); 5267 boolean changed = false; 5268 synchronized (getLockObject()) { 5269 ActiveAdmin ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller), 5270 parent); 5271 if (ap.strongAuthUnlockTimeout != timeoutMs) { 5272 ap.strongAuthUnlockTimeout = timeoutMs; 5273 saveSettingsLocked(userHandle); 5274 changed = true; 5275 } 5276 } 5277 if (changed) { 5278 mLockSettingsInternal.refreshStrongAuthTimeout(userHandle); 5279 // Refreshes the parent if profile has unified challenge, since the timeout would 5280 // also affect the parent user in this case. 5281 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 5282 mLockSettingsInternal.refreshStrongAuthTimeout(getProfileParentId(userHandle)); 5283 } 5284 } 5285 } 5286 5287 /** 5288 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all 5289 * admins if who is null. 5290 * Returns 0 if not configured for the provided admin. 5291 */ 5292 @Override 5293 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) { 5294 if (!mHasFeature) { 5295 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5296 } 5297 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 5298 5299 final CallerIdentity caller = getCallerIdentity(who); 5300 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 5301 5302 if (!mLockPatternUtils.hasSecureLockScreen()) { 5303 // No strong auth timeout on devices not supporting the 5304 // {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature 5305 return 0; 5306 } 5307 synchronized (getLockObject()) { 5308 if (who != null) { 5309 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent); 5310 return admin != null ? admin.strongAuthUnlockTimeout : 0; 5311 } 5312 5313 // Return the strictest policy across all participating admins. 5314 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5315 getProfileParentUserIfRequested(userId, parent)); 5316 5317 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5318 for (int i = 0; i < admins.size(); i++) { 5319 final long timeout = admins.get(i).strongAuthUnlockTimeout; 5320 if (timeout != 0) { // take only participating admins into account 5321 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout); 5322 } 5323 } 5324 return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs()); 5325 } 5326 } 5327 5328 private long getMinimumStrongAuthTimeoutMs() { 5329 if (!mInjector.isBuildDebuggable()) { 5330 return MINIMUM_STRONG_AUTH_TIMEOUT_MS; 5331 } 5332 // ideally the property was named persist.sys.min_strong_auth_timeout, but system property 5333 // name cannot be longer than 31 characters 5334 return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo", 5335 MINIMUM_STRONG_AUTH_TIMEOUT_MS), 5336 MINIMUM_STRONG_AUTH_TIMEOUT_MS); 5337 } 5338 5339 @Override 5340 public void lockNow(int flags, boolean parent) { 5341 final CallerIdentity caller = getCallerIdentity(); 5342 5343 final int callingUserId = caller.getUserId(); 5344 ComponentName adminComponent = null; 5345 synchronized (getLockObject()) { 5346 // Make sure the caller has any active admin with the right policy or 5347 // the required permission. 5348 final ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked( 5349 null, 5350 DeviceAdminInfo.USES_POLICY_FORCE_LOCK, 5351 parent, 5352 android.Manifest.permission.LOCK_DEVICE); 5353 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOCK_NOW); 5354 final long ident = mInjector.binderClearCallingIdentity(); 5355 try { 5356 adminComponent = admin == null ? null : admin.info.getComponent(); 5357 if (adminComponent != null) { 5358 // For Profile Owners only, callers with only permission not allowed. 5359 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) { 5360 // Evict key 5361 Preconditions.checkCallingUser(isManagedProfile(callingUserId)); 5362 Preconditions.checkArgument(!parent, 5363 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent"); 5364 if (!isProfileOwner(adminComponent, callingUserId)) { 5365 throw new SecurityException("Only profile owner admins can set " 5366 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 5367 } 5368 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5369 throw new UnsupportedOperationException( 5370 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices"); 5371 } 5372 mUserManager.evictCredentialEncryptionKey(callingUserId); 5373 } 5374 } 5375 5376 // Lock all users unless this is a managed profile with a separate challenge 5377 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId) 5378 ? UserHandle.USER_ALL : callingUserId); 5379 mLockPatternUtils.requireStrongAuth( 5380 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock); 5381 5382 // Require authentication for the device or profile 5383 if (userToLock == UserHandle.USER_ALL) { 5384 if (mIsAutomotive) { 5385 if (VERBOSE_LOG) { 5386 Slogf.v(LOG_TAG, "lockNow(): not powering off display on automotive" 5387 + " build"); 5388 } 5389 } else { 5390 // Power off the display 5391 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(), 5392 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 5393 } 5394 mInjector.getIWindowManager().lockNow(null); 5395 } else { 5396 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true); 5397 } 5398 5399 if (SecurityLog.isLoggingEnabled() && adminComponent != null) { 5400 final int affectedUserId = 5401 parent ? getProfileParentId(callingUserId) : callingUserId; 5402 SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK, 5403 adminComponent.getPackageName(), callingUserId, affectedUserId); 5404 } 5405 } catch (RemoteException e) { 5406 } finally { 5407 mInjector.binderRestoreCallingIdentity(ident); 5408 } 5409 } 5410 DevicePolicyEventLogger 5411 .createEvent(DevicePolicyEnums.LOCK_NOW) 5412 .setAdmin(adminComponent) 5413 .setInt(flags) 5414 .write(); 5415 } 5416 5417 @Override 5418 public void enforceCanManageCaCerts(ComponentName who, String callerPackage) { 5419 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5420 Preconditions.checkCallAuthorization(canManageCaCerts(caller)); 5421 } 5422 5423 private boolean canManageCaCerts(CallerIdentity caller) { 5424 return (caller.hasAdminComponent() && (isDefaultDeviceOwner(caller) 5425 || isProfileOwner(caller))) 5426 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_INSTALL)) 5427 || hasCallingOrSelfPermission(MANAGE_CA_CERTIFICATES); 5428 } 5429 5430 @Override 5431 public boolean approveCaCert(String alias, int userId, boolean approval) { 5432 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 5433 5434 synchronized (getLockObject()) { 5435 Set<String> certs = getUserData(userId).mAcceptedCaCertificates; 5436 boolean changed = (approval ? certs.add(alias) : certs.remove(alias)); 5437 if (!changed) { 5438 return false; 5439 } 5440 saveSettingsLocked(userId); 5441 } 5442 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5443 return true; 5444 } 5445 5446 @Override 5447 public boolean isCaCertApproved(String alias, int userId) { 5448 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 5449 5450 synchronized (getLockObject()) { 5451 return getUserData(userId).mAcceptedCaCertificates.contains(alias); 5452 } 5453 } 5454 5455 private Set<Integer> removeCaApprovalsIfNeeded(int userId) { 5456 final ArraySet<Integer> affectedUserIds = new ArraySet<>(); 5457 for (UserInfo userInfo : mUserManager.getProfiles(userId)) { 5458 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id); 5459 if (userInfo.isManagedProfile()){ 5460 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id)); 5461 } 5462 if (!isSecure) { 5463 synchronized (getLockObject()) { 5464 getUserData(userInfo.id).mAcceptedCaCertificates.clear(); 5465 affectedUserIds.add(userInfo.id); 5466 } 5467 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5468 } 5469 } 5470 return affectedUserIds; 5471 } 5472 5473 @Override 5474 public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) { 5475 if (!mHasFeature) { 5476 return false; 5477 } 5478 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 5479 Preconditions.checkCallAuthorization(canManageCaCerts(caller)); 5480 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_CA_CERT); 5481 5482 final String alias = mInjector.binderWithCleanCallingIdentity(() -> { 5483 String installedAlias = mCertificateMonitor.installCaCert( 5484 caller.getUserHandle(), certBuffer); 5485 DevicePolicyEventLogger 5486 .createEvent(DevicePolicyEnums.INSTALL_CA_CERT) 5487 .setAdmin(caller.getPackageName()) 5488 .setBoolean(/* isDelegate */ admin == null) 5489 .write(); 5490 return installedAlias; 5491 }); 5492 5493 if (alias == null) { 5494 Slogf.w(LOG_TAG, "Problem installing cert"); 5495 return false; 5496 } 5497 5498 synchronized (getLockObject()) { 5499 getUserData(caller.getUserId()).mOwnerInstalledCaCerts.add(alias); 5500 saveSettingsLocked(caller.getUserId()); 5501 } 5502 return true; 5503 } 5504 5505 @Override 5506 public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) { 5507 if (!mHasFeature) { 5508 return; 5509 } 5510 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 5511 Preconditions.checkCallAuthorization(canManageCaCerts(caller)); 5512 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_UNINSTALL_CA_CERT); 5513 5514 mInjector.binderWithCleanCallingIdentity(() -> { 5515 mCertificateMonitor.uninstallCaCerts(caller.getUserHandle(), aliases); 5516 DevicePolicyEventLogger 5517 .createEvent(DevicePolicyEnums.UNINSTALL_CA_CERTS) 5518 .setAdmin(caller.getPackageName()) 5519 .setBoolean(/* isDelegate */ admin == null) 5520 .write(); 5521 }); 5522 5523 synchronized (getLockObject()) { 5524 if (getUserData(caller.getUserId()).mOwnerInstalledCaCerts.removeAll( 5525 Arrays.asList(aliases))) { 5526 saveSettingsLocked(caller.getUserId()); 5527 } 5528 } 5529 } 5530 5531 @Override 5532 public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey, 5533 byte[] cert, byte[] chain, String alias, boolean requestAccess, 5534 boolean isUserSelectable) { 5535 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5536 final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 5537 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 5538 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 5539 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 5540 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp))); 5541 if (isCredentialManagementApp) { 5542 Preconditions.checkCallAuthorization(!isUserSelectable, "The credential " 5543 + "management app is not allowed to install a user selectable key pair"); 5544 Preconditions.checkCallAuthorization( 5545 isAliasInCredentialManagementAppPolicy(caller, alias), 5546 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 5547 } 5548 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_KEY_PAIR); 5549 5550 final long id = mInjector.binderClearCallingIdentity(); 5551 try { 5552 final KeyChainConnection keyChainConnection = 5553 KeyChain.bindAsUser(mContext, caller.getUserHandle()); 5554 try { 5555 IKeyChainService keyChain = keyChainConnection.getService(); 5556 if (!keyChain.installKeyPair(privKey, cert, chain, alias, KeyStore.UID_SELF)) { 5557 logInstallKeyPairFailure(caller, isCredentialManagementApp); 5558 return false; 5559 } 5560 if (requestAccess) { 5561 keyChain.setGrant(caller.getUid(), alias, true); 5562 } 5563 keyChain.setUserSelectable(alias, isUserSelectable); 5564 DevicePolicyEventLogger 5565 .createEvent(DevicePolicyEnums.INSTALL_KEY_PAIR) 5566 .setAdmin(caller.getPackageName()) 5567 .setBoolean(/* isDelegate */ isCallerDelegate) 5568 .setStrings(isCredentialManagementApp 5569 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP) 5570 .write(); 5571 return true; 5572 } catch (RemoteException e) { 5573 Slogf.e(LOG_TAG, "Installing certificate", e); 5574 } finally { 5575 keyChainConnection.close(); 5576 } 5577 } catch (InterruptedException e) { 5578 Slogf.w(LOG_TAG, "Interrupted while installing certificate", e); 5579 Thread.currentThread().interrupt(); 5580 } finally { 5581 mInjector.binderRestoreCallingIdentity(id); 5582 } 5583 logInstallKeyPairFailure(caller, isCredentialManagementApp); 5584 return false; 5585 } 5586 5587 private void logInstallKeyPairFailure(CallerIdentity caller, 5588 boolean isCredentialManagementApp) { 5589 if (!isCredentialManagementApp) { 5590 return; 5591 } 5592 DevicePolicyEventLogger 5593 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_INSTALL_KEY_PAIR_FAILED) 5594 .setStrings(caller.getPackageName()) 5595 .write(); 5596 } 5597 5598 @Override 5599 public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) { 5600 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5601 final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 5602 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 5603 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 5604 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 5605 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp))); 5606 if (isCredentialManagementApp) { 5607 Preconditions.checkCallAuthorization( 5608 isAliasInCredentialManagementAppPolicy(caller, alias), 5609 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 5610 } 5611 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_KEY_PAIR); 5612 5613 final long id = Binder.clearCallingIdentity(); 5614 try { 5615 final KeyChainConnection keyChainConnection = 5616 KeyChain.bindAsUser(mContext, caller.getUserHandle()); 5617 try { 5618 IKeyChainService keyChain = keyChainConnection.getService(); 5619 DevicePolicyEventLogger 5620 .createEvent(DevicePolicyEnums.REMOVE_KEY_PAIR) 5621 .setAdmin(caller.getPackageName()) 5622 .setBoolean(/* isDelegate */ isCallerDelegate) 5623 .setStrings(isCredentialManagementApp 5624 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP) 5625 .write(); 5626 return keyChain.removeKeyPair(alias); 5627 } catch (RemoteException e) { 5628 Slogf.e(LOG_TAG, "Removing keypair", e); 5629 } finally { 5630 keyChainConnection.close(); 5631 } 5632 } catch (InterruptedException e) { 5633 Slogf.w(LOG_TAG, "Interrupted while removing keypair", e); 5634 Thread.currentThread().interrupt(); 5635 } finally { 5636 Binder.restoreCallingIdentity(id); 5637 } 5638 return false; 5639 } 5640 5641 @Override 5642 public boolean hasKeyPair(String callerPackage, String alias) { 5643 final CallerIdentity caller = getCallerIdentity(callerPackage); 5644 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 5645 Preconditions.checkCallAuthorization(canInstallCertificates(caller) 5646 || isCredentialManagementApp); 5647 if (isCredentialManagementApp) { 5648 Preconditions.checkCallAuthorization( 5649 isAliasInCredentialManagementAppPolicy(caller, alias), 5650 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 5651 } 5652 5653 return mInjector.binderWithCleanCallingIdentity(() -> { 5654 try (KeyChainConnection keyChainConnection = 5655 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 5656 return keyChainConnection.getService().containsKeyPair(alias); 5657 } catch (RemoteException e) { 5658 Slogf.e(LOG_TAG, "Querying keypair", e); 5659 } catch (InterruptedException e) { 5660 Slogf.w(LOG_TAG, "Interrupted while querying keypair", e); 5661 Thread.currentThread().interrupt(); 5662 } 5663 return false; 5664 }); 5665 } 5666 5667 private boolean canInstallCertificates(CallerIdentity caller) { 5668 return isProfileOwner(caller) || isDefaultDeviceOwner(caller) 5669 || isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 5670 } 5671 5672 private boolean canChooseCertificates(CallerIdentity caller) { 5673 return isProfileOwner(caller) || isDefaultDeviceOwner(caller) 5674 || isCallerDelegate(caller, DELEGATION_CERT_SELECTION); 5675 } 5676 5677 @Override 5678 public boolean setKeyGrantToWifiAuth(String callerPackage, String alias, boolean hasGrant) { 5679 Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty"); 5680 5681 final CallerIdentity caller = getCallerIdentity(callerPackage); 5682 Preconditions.checkCallAuthorization(canChooseCertificates(caller)); 5683 5684 return setKeyChainGrantInternal(alias, hasGrant, Process.WIFI_UID, caller.getUserHandle()); 5685 } 5686 5687 @Override 5688 public boolean isKeyPairGrantedToWifiAuth(String callerPackage, String alias) { 5689 Preconditions.checkStringNotEmpty(alias, "Alias to check cannot be empty"); 5690 5691 final CallerIdentity caller = getCallerIdentity(callerPackage); 5692 Preconditions.checkCallAuthorization(canChooseCertificates(caller)); 5693 5694 return mInjector.binderWithCleanCallingIdentity(() -> { 5695 try (KeyChainConnection keyChainConnection = 5696 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 5697 final List<String> result = new ArrayList<>(); 5698 final int[] granteeUids = keyChainConnection.getService().getGrants(alias); 5699 5700 for (final int uid : granteeUids) { 5701 if (uid == Process.WIFI_UID) { 5702 return true; 5703 } 5704 } 5705 return false; 5706 } catch (RemoteException e) { 5707 Slogf.e(LOG_TAG, "Querying grant to wifi auth.", e); 5708 return false; 5709 } 5710 }); 5711 } 5712 5713 @Override 5714 public boolean setKeyGrantForApp(ComponentName who, String callerPackage, String alias, 5715 String packageName, boolean hasGrant) { 5716 Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty"); 5717 Preconditions.checkStringNotEmpty(packageName, "Package to grant to cannot be empty"); 5718 5719 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5720 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 5721 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 5722 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_SELECTION))); 5723 5724 final int granteeUid; 5725 try { 5726 ApplicationInfo ai = mInjector.getIPackageManager().getApplicationInfo( 5727 packageName, 0, caller.getUserId()); 5728 Preconditions.checkArgument(ai != null, 5729 "Provided package %s is not installed", packageName); 5730 granteeUid = ai.uid; 5731 } catch (RemoteException e) { 5732 throw new IllegalStateException("Failure getting grantee uid", e); 5733 } 5734 5735 return setKeyChainGrantInternal(alias, hasGrant, granteeUid, caller.getUserHandle()); 5736 } 5737 5738 private boolean setKeyChainGrantInternal(String alias, boolean hasGrant, int granteeUid, 5739 UserHandle userHandle) { 5740 final long id = mInjector.binderClearCallingIdentity(); 5741 try { 5742 try (KeyChainConnection keyChainConnection = 5743 KeyChain.bindAsUser(mContext, userHandle)) { 5744 IKeyChainService keyChain = keyChainConnection.getService(); 5745 return keyChain.setGrant(granteeUid, alias, hasGrant); 5746 } catch (RemoteException e) { 5747 Slogf.e(LOG_TAG, "Setting grant for package.", e); 5748 return false; 5749 } 5750 } catch (InterruptedException e) { 5751 Slogf.w(LOG_TAG, "Interrupted while setting key grant", e); 5752 Thread.currentThread().interrupt(); 5753 } finally { 5754 mInjector.binderRestoreCallingIdentity(id); 5755 } 5756 return false; 5757 } 5758 5759 @Override 5760 public ParcelableGranteeMap getKeyPairGrants(String callerPackage, String alias) { 5761 final CallerIdentity caller = getCallerIdentity(callerPackage); 5762 Preconditions.checkCallAuthorization(canChooseCertificates(caller)); 5763 5764 final ArrayMap<Integer, Set<String>> result = new ArrayMap<>(); 5765 mInjector.binderWithCleanCallingIdentity(() -> { 5766 try (KeyChainConnection keyChainConnection = 5767 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 5768 final int[] granteeUids = keyChainConnection.getService().getGrants(alias); 5769 final PackageManager pm = mInjector.getPackageManager(caller.getUserId()); 5770 5771 for (final int uid : granteeUids) { 5772 final String[] packages = pm.getPackagesForUid(uid); 5773 if (packages == null) { 5774 Slogf.wtf(LOG_TAG, "No packages found for uid " + uid); 5775 continue; 5776 } 5777 result.put(uid, new ArraySet<String>(packages)); 5778 } 5779 } catch (RemoteException e) { 5780 Slogf.e(LOG_TAG, "Querying keypair grants", e); 5781 } catch (InterruptedException e) { 5782 Slogf.w(LOG_TAG, "Interrupted while querying keypair grants", e); 5783 Thread.currentThread().interrupt(); 5784 } 5785 }); 5786 return new ParcelableGranteeMap(result); 5787 } 5788 5789 /** 5790 * Enforce one the following conditions are met: 5791 * (1) The device has a Device Owner, and one of the following holds: 5792 * (1.1) The caller is the Device Owner 5793 * (1.2) The caller is another app in the same user as the device owner, AND 5794 * The caller is the delegated certificate installer. 5795 * (1.3) The caller is a Profile Owner and the calling user is affiliated. 5796 * (2) The user has a profile owner, AND: 5797 * (2.1) The profile owner has been granted access to Device IDs and one of the following 5798 * holds: 5799 * (2.1.1) The caller is the profile owner. 5800 * (2.1.2) The caller is from another app in the same user as the profile owner, AND 5801 * (2.1.2.1) The caller is the delegated cert installer. 5802 * 5803 * For the device owner case, simply check that the caller is the device owner or the 5804 * delegated certificate installer. 5805 * 5806 * For the profile owner case, first check that the caller is the profile owner or can 5807 * manage the DELEGATION_CERT_INSTALL scope. 5808 * If that check succeeds, ensure the profile owner was granted access to device 5809 * identifiers. The grant is transitive: The delegated cert installer is implicitly allowed 5810 * access to device identifiers in this case as part of the delegation. 5811 */ 5812 @VisibleForTesting 5813 public void enforceCallerCanRequestDeviceIdAttestation(CallerIdentity caller) 5814 throws SecurityException { 5815 /** 5816 * First check if there's a profile owner because the device could be in COMP mode (where 5817 * there's a device owner and profile owner on the same device). 5818 * If the caller is from the work profile, then it must be the PO or the delegate, and 5819 * it must have the right permission to access device identifiers. 5820 */ 5821 int callerUserId = caller.getUserId(); 5822 if (hasProfileOwner(callerUserId)) { 5823 // Make sure that the caller is the profile owner or delegate. 5824 Preconditions.checkCallAuthorization(canInstallCertificates(caller)); 5825 // Verify that the managed profile is on an organization-owned device (or is affiliated 5826 // with the device owner user) and as such the profile owner can access Device IDs. 5827 if (isProfileOwnerOfOrganizationOwnedDevice(callerUserId) 5828 || isUserAffiliatedWithDevice(callerUserId)) { 5829 return; 5830 } 5831 throw new SecurityException( 5832 "Profile Owner is not allowed to access Device IDs."); 5833 } 5834 5835 // If not, fall back to the device owner check. 5836 Preconditions.checkCallAuthorization( 5837 isDefaultDeviceOwner(caller) || isCallerDelegate(caller, DELEGATION_CERT_INSTALL)); 5838 } 5839 5840 @VisibleForTesting 5841 public static int[] translateIdAttestationFlags( 5842 int idAttestationFlags) { 5843 Map<Integer, Integer> idTypeToAttestationFlag = new HashMap(); 5844 idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL); 5845 idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI); 5846 idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID); 5847 idTypeToAttestationFlag.put( 5848 ID_TYPE_INDIVIDUAL_ATTESTATION, USE_INDIVIDUAL_ATTESTATION); 5849 5850 int numFlagsSet = Integer.bitCount(idAttestationFlags); 5851 // No flags are set - return null to indicate no device ID attestation information should 5852 // be included in the attestation record. 5853 if (numFlagsSet == 0) { 5854 return null; 5855 } 5856 5857 // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if 5858 // no other flag is set. That will lead to inclusion of general device make data in the 5859 // attestation record, but no specific device identifiers. 5860 if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) { 5861 numFlagsSet -= 1; 5862 idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO); 5863 } 5864 5865 int[] attestationUtilsFlags = new int[numFlagsSet]; 5866 int i = 0; 5867 for (Integer idType: idTypeToAttestationFlag.keySet()) { 5868 if ((idType & idAttestationFlags) != 0) { 5869 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType); 5870 } 5871 } 5872 5873 return attestationUtilsFlags; 5874 } 5875 5876 @Override 5877 public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm, 5878 ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags, 5879 KeymasterCertificateChain attestationChain) { 5880 // Get attestation flags, if any. 5881 final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags); 5882 final boolean deviceIdAttestationRequired = attestationUtilsFlags != null; 5883 KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec(); 5884 final String alias = keySpec.getKeystoreAlias(); 5885 5886 Preconditions.checkStringNotEmpty(alias, "Empty alias provided"); 5887 Preconditions.checkArgument( 5888 !deviceIdAttestationRequired || keySpec.getAttestationChallenge() != null, 5889 "Requested Device ID attestation but challenge is empty"); 5890 5891 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 5892 final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 5893 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 5894 if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) { 5895 // TODO: replace enforce methods 5896 enforceCallerCanRequestDeviceIdAttestation(caller); 5897 enforceIndividualAttestationSupportedIfRequested(attestationUtilsFlags); 5898 } else { 5899 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 5900 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 5901 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp))); 5902 if (isCredentialManagementApp) { 5903 Preconditions.checkCallAuthorization( 5904 isAliasInCredentialManagementAppPolicy(caller, alias), 5905 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 5906 } 5907 } 5908 5909 if (TextUtils.isEmpty(alias)) { 5910 throw new IllegalArgumentException("Empty alias provided."); 5911 } 5912 // As the caller will be granted access to the key, ensure no UID was specified, as 5913 // it will not have the desired effect. 5914 if (keySpec.getUid() != KeyStore.UID_SELF) { 5915 Slogf.e(LOG_TAG, "Only the caller can be granted access to the generated keypair."); 5916 logGenerateKeyPairFailure(caller, isCredentialManagementApp); 5917 return false; 5918 } 5919 5920 if (deviceIdAttestationRequired) { 5921 if (keySpec.getAttestationChallenge() == null) { 5922 throw new IllegalArgumentException( 5923 "Requested Device ID attestation but challenge is empty."); 5924 } 5925 KeyGenParameterSpec.Builder specBuilder = new KeyGenParameterSpec.Builder(keySpec); 5926 specBuilder.setAttestationIds(attestationUtilsFlags); 5927 specBuilder.setDevicePropertiesAttestationIncluded(true); 5928 keySpec = specBuilder.build(); 5929 } 5930 5931 final long id = mInjector.binderClearCallingIdentity(); 5932 try { 5933 try (KeyChainConnection keyChainConnection = 5934 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 5935 IKeyChainService keyChain = keyChainConnection.getService(); 5936 5937 final int generationResult = keyChain.generateKeyPair(algorithm, 5938 new ParcelableKeyGenParameterSpec(keySpec)); 5939 if (generationResult != KeyChain.KEY_GEN_SUCCESS) { 5940 Slogf.e(LOG_TAG, "KeyChain failed to generate a keypair, error %d.", 5941 generationResult); 5942 logGenerateKeyPairFailure(caller, isCredentialManagementApp); 5943 switch (generationResult) { 5944 case KeyChain.KEY_GEN_STRONGBOX_UNAVAILABLE: 5945 throw new ServiceSpecificException( 5946 DevicePolicyManager.KEY_GEN_STRONGBOX_UNAVAILABLE, 5947 String.format("KeyChain error: %d", generationResult)); 5948 case KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS: 5949 throw new UnsupportedOperationException( 5950 "Device does not support Device ID attestation."); 5951 default: 5952 return false; 5953 } 5954 } 5955 5956 // Set a grant for the caller here so that when the client calls 5957 // requestPrivateKey, it will be able to get the key from Keystore. 5958 // Note the use of the calling UID, since the request for the private 5959 // key will come from the client's process, so the grant has to be for 5960 // that UID. 5961 keyChain.setGrant(caller.getUid(), alias, true); 5962 5963 try { 5964 final List<byte[]> encodedCerts = new ArrayList(); 5965 final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 5966 final byte[] certChainBytes = keyChain.getCaCertificates(alias); 5967 encodedCerts.add(keyChain.getCertificate(alias)); 5968 if (certChainBytes != null) { 5969 final Collection<X509Certificate> certs = 5970 (Collection<X509Certificate>) certFactory.generateCertificates( 5971 new ByteArrayInputStream(certChainBytes)); 5972 for (X509Certificate cert : certs) { 5973 encodedCerts.add(cert.getEncoded()); 5974 } 5975 } 5976 5977 attestationChain.shallowCopyFrom(new KeymasterCertificateChain(encodedCerts)); 5978 } catch (CertificateException e) { 5979 logGenerateKeyPairFailure(caller, isCredentialManagementApp); 5980 Slogf.e(LOG_TAG, "While retrieving certificate chain.", e); 5981 return false; 5982 } 5983 5984 DevicePolicyEventLogger 5985 .createEvent(DevicePolicyEnums.GENERATE_KEY_PAIR) 5986 .setAdmin(caller.getPackageName()) 5987 .setBoolean(/* isDelegate */ isCallerDelegate) 5988 .setInt(idAttestationFlags) 5989 .setStrings(algorithm, isCredentialManagementApp 5990 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP) 5991 .write(); 5992 return true; 5993 } 5994 } catch (RemoteException e) { 5995 Slogf.e(LOG_TAG, "KeyChain error while generating a keypair", e); 5996 } catch (InterruptedException e) { 5997 Slogf.w(LOG_TAG, "Interrupted while generating keypair", e); 5998 Thread.currentThread().interrupt(); 5999 } finally { 6000 mInjector.binderRestoreCallingIdentity(id); 6001 } 6002 logGenerateKeyPairFailure(caller, isCredentialManagementApp); 6003 return false; 6004 } 6005 6006 private void logGenerateKeyPairFailure(CallerIdentity caller, 6007 boolean isCredentialManagementApp) { 6008 if (!isCredentialManagementApp) { 6009 return; 6010 } 6011 DevicePolicyEventLogger 6012 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_GENERATE_KEY_PAIR_FAILED) 6013 .setStrings(caller.getPackageName()) 6014 .write(); 6015 } 6016 6017 private void enforceIndividualAttestationSupportedIfRequested(int[] attestationUtilsFlags) { 6018 for (int attestationFlag : attestationUtilsFlags) { 6019 if (attestationFlag == USE_INDIVIDUAL_ATTESTATION 6020 && !mInjector.getPackageManager().hasSystemFeature( 6021 PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION)) { 6022 throw new UnsupportedOperationException("Device Individual attestation is not " 6023 + "supported on this device."); 6024 } 6025 } 6026 } 6027 6028 @Override 6029 public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias, 6030 byte[] cert, byte[] chain, boolean isUserSelectable) { 6031 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 6032 final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL); 6033 final boolean isCredentialManagementApp = isCredentialManagementApp(caller); 6034 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 6035 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 6036 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp))); 6037 if (isCredentialManagementApp) { 6038 Preconditions.checkCallAuthorization( 6039 isAliasInCredentialManagementAppPolicy(caller, alias), 6040 CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG); 6041 } 6042 6043 final long id = mInjector.binderClearCallingIdentity(); 6044 try (final KeyChainConnection keyChainConnection = 6045 KeyChain.bindAsUser(mContext, caller.getUserHandle())) { 6046 IKeyChainService keyChain = keyChainConnection.getService(); 6047 if (!keyChain.setKeyPairCertificate(alias, cert, chain)) { 6048 return false; 6049 } 6050 keyChain.setUserSelectable(alias, isUserSelectable); 6051 DevicePolicyEventLogger 6052 .createEvent(DevicePolicyEnums.SET_KEY_PAIR_CERTIFICATE) 6053 .setAdmin(caller.getPackageName()) 6054 .setBoolean(/* isDelegate */ isCallerDelegate) 6055 .setStrings(isCredentialManagementApp 6056 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP) 6057 .write(); 6058 return true; 6059 } catch (InterruptedException e) { 6060 Slogf.w(LOG_TAG, "Interrupted while setting keypair certificate", e); 6061 Thread.currentThread().interrupt(); 6062 } catch (RemoteException e) { 6063 Slogf.e(LOG_TAG, "Failed setting keypair certificate", e); 6064 } finally { 6065 mInjector.binderRestoreCallingIdentity(id); 6066 } 6067 return false; 6068 } 6069 6070 @Override 6071 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, 6072 final IBinder response) { 6073 final CallerIdentity caller = getCallerIdentity(); 6074 Preconditions.checkCallAuthorization(isSystemUid(caller), 6075 String.format(NOT_SYSTEM_CALLER_MSG, "choose private key alias")); 6076 6077 // If there is a profile owner, redirect to that; otherwise query the device owner. 6078 ComponentName aliasChooser = getProfileOwnerAsUser(caller.getUserId()); 6079 if (aliasChooser == null && caller.getUserHandle().isSystem()) { 6080 synchronized (getLockObject()) { 6081 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 6082 if (deviceOwnerAdmin != null) { 6083 aliasChooser = deviceOwnerAdmin.info.getComponent(); 6084 } 6085 } 6086 } 6087 if (aliasChooser == null) { 6088 sendPrivateKeyAliasResponse(null, response); 6089 return; 6090 } 6091 6092 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 6093 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 6094 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri); 6095 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 6096 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 6097 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 6098 6099 final ComponentName delegateReceiver; 6100 delegateReceiver = resolveDelegateReceiver(DELEGATION_CERT_SELECTION, 6101 DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS, caller.getUserId()); 6102 6103 final boolean isDelegate; 6104 if (delegateReceiver != null) { 6105 intent.setComponent(delegateReceiver); 6106 isDelegate = true; 6107 } else { 6108 intent.setComponent(aliasChooser); 6109 isDelegate = false; 6110 } 6111 6112 mInjector.binderWithCleanCallingIdentity(() -> { 6113 mContext.sendOrderedBroadcastAsUser(intent, caller.getUserHandle(), null, 6114 new BroadcastReceiver() { 6115 @Override 6116 public void onReceive(Context context, Intent intent) { 6117 final String chosenAlias = getResultData(); 6118 sendPrivateKeyAliasResponse(chosenAlias, response); 6119 } 6120 }, null, Activity.RESULT_OK, null, null); 6121 DevicePolicyEventLogger 6122 .createEvent(DevicePolicyEnums.CHOOSE_PRIVATE_KEY_ALIAS) 6123 .setAdmin(intent.getComponent()) 6124 .setBoolean(isDelegate) 6125 .write(); 6126 }); 6127 } 6128 6129 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 6130 final IKeyChainAliasCallback keyChainAliasResponse = 6131 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 6132 // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback 6133 // is oneway, which means it won't block if the recipient lives in another process. 6134 try { 6135 keyChainAliasResponse.alias(alias); 6136 } catch (Exception e) { 6137 // Caller could throw RuntimeException or RemoteException back across processes. Catch 6138 // everything just to be sure. 6139 Slogf.e(LOG_TAG, "error while responding to callback", e); 6140 } 6141 } 6142 6143 /** 6144 * Determine whether DPMS should check if a delegate package is already installed before 6145 * granting it new delegations via {@link #setDelegatedScopes}. 6146 */ 6147 private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, 6148 int targetSdk, List<String> scopes) { 6149 // 1) Never skip is installed check from N. 6150 if (targetSdk >= Build.VERSION_CODES.N) { 6151 return true; 6152 } 6153 // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given. 6154 if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) { 6155 return false; 6156 } 6157 // 3) Skip if all previously granted scopes are being cleared. 6158 if (scopes.isEmpty()) { 6159 return false; 6160 } 6161 // Otherwise it should check that delegatePackage is installed. 6162 return true; 6163 } 6164 6165 /** 6166 * Set the scopes of a device owner or profile owner delegate. 6167 * 6168 * @param who the device owner or profile owner. 6169 * @param delegatePackage the name of the delegate package. 6170 * @param scopeList the list of delegation scopes to be given to the delegate package. 6171 */ 6172 @Override 6173 public void setDelegatedScopes(ComponentName who, String delegatePackage, 6174 List<String> scopeList) throws SecurityException { 6175 Objects.requireNonNull(who, "ComponentName is null"); 6176 Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty"); 6177 Preconditions.checkCollectionElementsNotNull(scopeList, "Scopes"); 6178 final CallerIdentity caller = getCallerIdentity(who); 6179 6180 // Remove possible duplicates. 6181 final ArrayList<String> scopes = new ArrayList(new ArraySet(scopeList)); 6182 // Ensure given scopes are valid. 6183 if (scopes.retainAll(Arrays.asList(DELEGATIONS))) { 6184 throw new IllegalArgumentException("Unexpected delegation scopes"); 6185 } 6186 // Retrieve the user ID of the calling process. 6187 final int userId = caller.getUserId(); 6188 // Ensure calling process is device/profile owner. 6189 if (!Collections.disjoint(scopes, DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS)) { 6190 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 6191 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))); 6192 } else if (!Collections.disjoint( 6193 scopes, DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS)) { 6194 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 6195 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 6196 } else { 6197 Preconditions.checkCallAuthorization( 6198 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 6199 } 6200 6201 synchronized (getLockObject()) { 6202 // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N). 6203 if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage, 6204 getTargetSdk(who.getPackageName(), userId), scopes)) { 6205 // Throw when the delegate package is not installed. 6206 if (!isPackageInstalledForUser(delegatePackage, userId)) { 6207 throw new IllegalArgumentException("Package " + delegatePackage 6208 + " is not installed on the current user"); 6209 } 6210 } 6211 6212 // Set the new delegate in user policies. 6213 final DevicePolicyData policy = getUserData(userId); 6214 List<String> exclusiveScopes = null; 6215 if (!scopes.isEmpty()) { 6216 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes)); 6217 exclusiveScopes = new ArrayList<>(scopes); 6218 exclusiveScopes.retainAll(EXCLUSIVE_DELEGATIONS); 6219 } else { 6220 // Remove any delegation info if the given scopes list is empty. 6221 policy.mDelegationMap.remove(delegatePackage); 6222 } 6223 sendDelegationChangedBroadcast(delegatePackage, scopes, userId); 6224 6225 // If set, remove exclusive scopes from all other delegates 6226 if (exclusiveScopes != null && !exclusiveScopes.isEmpty()) { 6227 for (int i = policy.mDelegationMap.size() - 1; i >= 0; --i) { 6228 final String currentPackage = policy.mDelegationMap.keyAt(i); 6229 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 6230 6231 if (!currentPackage.equals(delegatePackage)) { 6232 // Iterate through all other delegates 6233 if (currentScopes.removeAll(exclusiveScopes)) { 6234 // And if this delegate had some exclusive scopes which are now moved 6235 // to the new delegate, notify about its delegation changes. 6236 if (currentScopes.isEmpty()) { 6237 policy.mDelegationMap.removeAt(i); 6238 } 6239 sendDelegationChangedBroadcast(currentPackage, 6240 new ArrayList<>(currentScopes), userId); 6241 } 6242 } 6243 } 6244 } 6245 // Persist updates. 6246 saveSettingsLocked(userId); 6247 } 6248 } 6249 6250 private void sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes, 6251 int userId) { 6252 // Notify delegate package of updates. 6253 final Intent intent = new Intent( 6254 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED); 6255 // Only call receivers registered with Context#registerReceiver (don’t wake delegate). 6256 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 6257 // Limit components this intent resolves to to the delegate package. 6258 intent.setPackage(delegatePackage); 6259 // Include the list of delegated scopes as an extra. 6260 intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes); 6261 // Send the broadcast. 6262 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 6263 } 6264 6265 /** 6266 * Get the delegation scopes given to a delegate package by a device owner or profile owner. 6267 * 6268 * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by 6269 * passing in {@code null} as the {@code who} parameter and its own name as the 6270 * {@code delegatepackage}. 6271 * 6272 * @param who the device owner or profile owner, or {@code null} if the caller is 6273 * {@code delegatePackage}. 6274 * @param delegatePackage the name of the delegate package whose scopes are to be retrieved. 6275 * @return a list of the delegation scopes currently given to {@code delegatePackage}. 6276 */ 6277 @Override 6278 @NonNull 6279 public List<String> getDelegatedScopes(ComponentName who, 6280 String delegatePackage) throws SecurityException { 6281 Objects.requireNonNull(delegatePackage, "Delegate package is null"); 6282 final CallerIdentity caller = getCallerIdentity(who); 6283 6284 // Ensure the caller may call this method: 6285 // * Either it's a profile owner / device owner, if componentName is provided 6286 // * Or it's an app querying its own delegation scopes 6287 if (caller.hasAdminComponent()) { 6288 Preconditions.checkCallAuthorization( 6289 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 6290 } else { 6291 Preconditions.checkCallAuthorization(isPackage(caller, delegatePackage), 6292 String.format("Caller with uid %d is not %s", caller.getUid(), 6293 delegatePackage)); 6294 } 6295 synchronized (getLockObject()) { 6296 final DevicePolicyData policy = getUserData(caller.getUserId()); 6297 // Retrieve the scopes assigned to delegatePackage, or null if no scope was given. 6298 final List<String> scopes = policy.mDelegationMap.get(delegatePackage); 6299 return scopes == null ? Collections.EMPTY_LIST : scopes; 6300 } 6301 } 6302 6303 /** 6304 * Get a list of packages that were given a specific delegation scopes by a device owner or 6305 * profile owner. 6306 * 6307 * @param who the device owner or profile owner. 6308 * @param scope the scope whose delegates are to be retrieved. 6309 * @return a list of the delegate packages currently given the {@code scope} delegation. 6310 */ 6311 @NonNull 6312 public List<String> getDelegatePackages(ComponentName who, String scope) 6313 throws SecurityException { 6314 Objects.requireNonNull(who, "ComponentName is null"); 6315 Objects.requireNonNull(scope, "Scope is null"); 6316 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 6317 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 6318 } 6319 6320 // Retrieve the user ID of the calling process. 6321 final CallerIdentity caller = getCallerIdentity(who); 6322 Preconditions.checkCallAuthorization( 6323 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 6324 synchronized (getLockObject()) { 6325 return getDelegatePackagesInternalLocked(scope, caller.getUserId()); 6326 } 6327 } 6328 6329 private List<String> getDelegatePackagesInternalLocked(String scope, int userId) { 6330 final DevicePolicyData policy = getUserData(userId); 6331 6332 // Create a list to hold the resulting delegate packages. 6333 final List<String> delegatePackagesWithScope = new ArrayList<>(); 6334 // Add all delegations containing scope to the result list. 6335 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 6336 if (policy.mDelegationMap.valueAt(i).contains(scope)) { 6337 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i)); 6338 } 6339 } 6340 return delegatePackagesWithScope; 6341 } 6342 6343 /** 6344 * Return the ComponentName of the receiver that handles the given broadcast action, from 6345 * the app that holds the given delegation capability. If the app defines multiple receivers 6346 * with the same intent action filter, will return any one of them nondeterministically. 6347 * 6348 * @return ComponentName of the receiver or {@null} if none exists. 6349 */ 6350 private ComponentName resolveDelegateReceiver(String scope, String action, int userId) { 6351 6352 final List<String> delegates; 6353 synchronized (getLockObject()) { 6354 delegates = getDelegatePackagesInternalLocked(scope, userId); 6355 } 6356 if (delegates.size() == 0) { 6357 return null; 6358 } else if (delegates.size() > 1) { 6359 Slogf.wtf(LOG_TAG, "More than one delegate holds " + scope); 6360 return null; 6361 } 6362 final String pkg = delegates.get(0); 6363 Intent intent = new Intent(action); 6364 intent.setPackage(pkg); 6365 final List<ResolveInfo> receivers; 6366 try { 6367 receivers = mIPackageManager.queryIntentReceivers( 6368 intent, null, 0, userId).getList(); 6369 } catch (RemoteException e) { 6370 return null; 6371 } 6372 final int count = receivers.size(); 6373 if (count >= 1) { 6374 if (count > 1) { 6375 Slogf.w(LOG_TAG, pkg + " defines more than one delegate receiver for " + action); 6376 } 6377 return receivers.get(0).activityInfo.getComponentName(); 6378 } else { 6379 return null; 6380 } 6381 } 6382 6383 /** 6384 * Check whether a caller application has been delegated a given scope via 6385 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 6386 * device owner. 6387 * <p> 6388 * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and 6389 * then comparing the calling UID with the UID of {@code callerPackage} as reported by 6390 * {@link PackageManager#getPackageUidAsUser}. 6391 * 6392 * @param callerPackage the name of the package that is trying to invoke a function in the DPMS. 6393 * @param scope the delegation scope to be checked. 6394 * @return {@code true} if the calling process is a delegate of {@code scope}. 6395 */ 6396 private boolean isCallerDelegate(String callerPackage, int callerUid, String scope) { 6397 Objects.requireNonNull(callerPackage, "callerPackage is null"); 6398 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 6399 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 6400 } 6401 6402 // Retrieve the UID and user ID of the calling process. 6403 final int userId = UserHandle.getUserId(callerUid); 6404 synchronized (getLockObject()) { 6405 // Retrieve user policy data. 6406 final DevicePolicyData policy = getUserData(userId); 6407 // Retrieve the list of delegation scopes granted to callerPackage. 6408 final List<String> scopes = policy.mDelegationMap.get(callerPackage); 6409 // Check callingUid only if callerPackage has the required scope delegation. 6410 if (scopes != null && scopes.contains(scope)) { 6411 // Return true if the caller is actually callerPackage. 6412 return isCallingFromPackage(callerPackage, callerUid); 6413 } 6414 return false; 6415 } 6416 } 6417 6418 /** 6419 * Check whether a caller application has been delegated a given scope via 6420 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 6421 * device owner. 6422 * <p> 6423 * This is done by checking that the calling package was granted {@code scope} delegation and 6424 * then comparing the calling UID with the UID of the calling package as reported by 6425 * {@link PackageManager#getPackageUidAsUser}. 6426 * 6427 * @param caller the calling identity 6428 * @param scope the delegation scope to be checked. 6429 * @return {@code true} if the calling process is a delegate of {@code scope}. 6430 */ 6431 private boolean isCallerDelegate(CallerIdentity caller, String scope) { 6432 Objects.requireNonNull(caller.getPackageName(), "callerPackage is null"); 6433 Preconditions.checkArgument(Arrays.asList(DELEGATIONS).contains(scope), 6434 "Unexpected delegation scope: %s", scope); 6435 6436 synchronized (getLockObject()) { 6437 // Retrieve user policy data. 6438 final DevicePolicyData policy = getUserData(caller.getUserId()); 6439 // Retrieve the list of delegation scopes granted to callerPackage. 6440 final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName()); 6441 // Check callingUid only if callerPackage has the required scope delegation. 6442 return scopes != null && scopes.contains(scope); 6443 } 6444 } 6445 6446 /** 6447 * Helper function to preserve delegation behavior pre-O when using the deprecated functions 6448 * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}. 6449 */ 6450 private void setDelegatedScopePreO(ComponentName who, 6451 String delegatePackage, String scope) { 6452 Objects.requireNonNull(who, "ComponentName is null"); 6453 6454 final CallerIdentity caller = getCallerIdentity(who); 6455 // Ensure calling process is device/profile owner. 6456 Preconditions.checkCallAuthorization( 6457 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 6458 6459 synchronized (getLockObject()) { 6460 final DevicePolicyData policy = getUserData(caller.getUserId()); 6461 6462 if (delegatePackage != null) { 6463 // Set package as a delegate for scope if it is not already one. 6464 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 6465 if (scopes == null) { 6466 scopes = new ArrayList<>(); 6467 } 6468 if (!scopes.contains(scope)) { 6469 scopes.add(scope); 6470 setDelegatedScopes(who, delegatePackage, scopes); 6471 } 6472 } 6473 6474 // Clear any existing scope delegates. 6475 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 6476 final String currentPackage = policy.mDelegationMap.keyAt(i); 6477 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 6478 6479 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) { 6480 final List<String> newScopes = new ArrayList(currentScopes); 6481 newScopes.remove(scope); 6482 setDelegatedScopes(who, currentPackage, newScopes); 6483 } 6484 } 6485 } 6486 } 6487 6488 /** 6489 * Check whether a caller application is the credential management app, which can access 6490 * privileged APIs. 6491 * <p> 6492 * This is done by checking that the calling package is authorized to perform the app operation 6493 * {@link android.app.AppOpsManager#OP_MANAGE_CREDENTIALS}. 6494 * 6495 * @param caller the calling identity 6496 * @return {@code true} if the calling process is the credential management app. 6497 */ 6498 private boolean isCredentialManagementApp(CallerIdentity caller) { 6499 return mInjector.binderWithCleanCallingIdentity(() -> { 6500 AppOpsManager appOpsManager = mInjector.getAppOpsManager(); 6501 if (appOpsManager == null) return false; 6502 return appOpsManager.noteOpNoThrow(AppOpsManager.OP_MANAGE_CREDENTIALS, caller.getUid(), 6503 caller.getPackageName(), null, null) == AppOpsManager.MODE_ALLOWED; 6504 }); 6505 } 6506 6507 /** 6508 * If the caller is the credential management app, the alias provided must be contained 6509 * in the aliases specified in the credential management app's authentication policy. 6510 */ 6511 private boolean isAliasInCredentialManagementAppPolicy(CallerIdentity caller, String alias) { 6512 return mInjector.binderWithCleanCallingIdentity(() -> { 6513 try (KeyChainConnection connection = KeyChain.bindAsUser(mContext, 6514 caller.getUserHandle())) { 6515 // The policy will be null if there is no credential management app 6516 AppUriAuthenticationPolicy policy = 6517 connection.getService().getCredentialManagementAppPolicy(); 6518 return policy != null && !policy.getAppAndUriMappings().isEmpty() 6519 && containsAlias(policy, alias); 6520 } catch (RemoteException | InterruptedException e) { 6521 return false; 6522 } 6523 }); 6524 } 6525 6526 private static boolean containsAlias(AppUriAuthenticationPolicy policy, String alias) { 6527 for (Map.Entry<String, Map<Uri, String>> appsToUris : 6528 policy.getAppAndUriMappings().entrySet()) { 6529 for (Map.Entry<Uri, String> urisToAliases : appsToUris.getValue().entrySet()) { 6530 if (urisToAliases.getValue().equals(alias)) { 6531 return true; 6532 } 6533 } 6534 } 6535 return false; 6536 } 6537 6538 @Override 6539 public void setCertInstallerPackage(ComponentName who, String installerPackage) 6540 throws SecurityException { 6541 setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL); 6542 DevicePolicyEventLogger 6543 .createEvent(DevicePolicyEnums.SET_CERT_INSTALLER_PACKAGE) 6544 .setAdmin(who) 6545 .setStrings(installerPackage) 6546 .write(); 6547 } 6548 6549 @Override 6550 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 6551 final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL); 6552 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 6553 } 6554 6555 /** 6556 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is 6557 * not installed and therefore not available. 6558 * 6559 * @throws SecurityException if the caller is not a profile or device owner. 6560 * @throws UnsupportedOperationException if the package does not support being set as always-on. 6561 */ 6562 @Override 6563 public boolean setAlwaysOnVpnPackage(ComponentName who, String vpnPackage, boolean lockdown, 6564 List<String> lockdownAllowlist) 6565 throws SecurityException { 6566 Objects.requireNonNull(who, "ComponentName is null"); 6567 6568 final CallerIdentity caller = getCallerIdentity(who); 6569 Preconditions.checkCallAuthorization( 6570 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 6571 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_ALWAYS_ON_VPN_PACKAGE); 6572 6573 if (vpnPackage == null) { 6574 final String prevVpnPackage; 6575 synchronized (getLockObject()) { 6576 prevVpnPackage = getProfileOwnerOrDeviceOwnerLocked(caller).mAlwaysOnVpnPackage; 6577 // If the admin is clearing VPN package but hasn't configure any VPN previously, 6578 // ignore it so that it doesn't interfere with user-configured VPNs. 6579 if (TextUtils.isEmpty(prevVpnPackage)) { 6580 return true; 6581 } 6582 } 6583 revokeVpnAuthorizationForPackage(prevVpnPackage, caller.getUserId()); 6584 } 6585 6586 final int userId = caller.getUserId(); 6587 mInjector.binderWithCleanCallingIdentity(() -> { 6588 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) { 6589 Slogf.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage); 6590 throw new ServiceSpecificException( 6591 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage); 6592 } 6593 6594 if (vpnPackage != null && lockdown && lockdownAllowlist != null) { 6595 for (String packageName : lockdownAllowlist) { 6596 if (!isPackageInstalledForUser(packageName, userId)) { 6597 Slogf.w(LOG_TAG, "Non-existent package in VPN allowlist: " + packageName); 6598 throw new ServiceSpecificException( 6599 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName); 6600 } 6601 } 6602 } 6603 // If some package is uninstalled after the check above, it will be ignored by CM. 6604 if (!mInjector.getVpnManager().setAlwaysOnVpnPackageForUser( 6605 userId, vpnPackage, lockdown, lockdownAllowlist)) { 6606 throw new UnsupportedOperationException(); 6607 } 6608 }); 6609 DevicePolicyEventLogger 6610 .createEvent(DevicePolicyEnums.SET_ALWAYS_ON_VPN_PACKAGE) 6611 .setAdmin(caller.getComponentName()) 6612 .setStrings(vpnPackage) 6613 .setBoolean(lockdown) 6614 .setInt(lockdownAllowlist != null ? lockdownAllowlist.size() : 0) 6615 .write(); 6616 synchronized (getLockObject()) { 6617 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 6618 if (!TextUtils.equals(vpnPackage, admin.mAlwaysOnVpnPackage) 6619 || lockdown != admin.mAlwaysOnVpnLockdown) { 6620 admin.mAlwaysOnVpnPackage = vpnPackage; 6621 admin.mAlwaysOnVpnLockdown = lockdown; 6622 saveSettingsLocked(userId); 6623 } 6624 } 6625 return true; 6626 } 6627 6628 private void revokeVpnAuthorizationForPackage(String vpnPackage, int userId) { 6629 mInjector.binderWithCleanCallingIdentity(() -> { 6630 try { 6631 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 6632 vpnPackage, /* flags= */ 0, userId); 6633 if (ai == null) { 6634 Slogf.w(LOG_TAG, "Non-existent VPN package: " + vpnPackage); 6635 } else { 6636 mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN, 6637 ai.uid, vpnPackage, MODE_DEFAULT); 6638 } 6639 } catch (RemoteException e) { 6640 Slogf.e(LOG_TAG, "Can't talk to package managed", e); 6641 } 6642 }); 6643 } 6644 6645 @Override 6646 public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException { 6647 Objects.requireNonNull(admin, "ComponentName is null"); 6648 6649 final CallerIdentity caller = getCallerIdentity(admin); 6650 Preconditions.checkCallAuthorization( 6651 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 6652 6653 return mInjector.binderWithCleanCallingIdentity( 6654 () -> mInjector.getVpnManager().getAlwaysOnVpnPackageForUser(caller.getUserId())); 6655 } 6656 6657 @Override 6658 public String getAlwaysOnVpnPackageForUser(int userHandle) { 6659 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 6660 String.format(NOT_SYSTEM_CALLER_MSG, "call getAlwaysOnVpnPackageForUser")); 6661 synchronized (getLockObject()) { 6662 ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle); 6663 return admin != null ? admin.mAlwaysOnVpnPackage : null; 6664 } 6665 } 6666 6667 @Override 6668 public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException { 6669 final CallerIdentity caller; 6670 if (hasCallingPermission(PERMISSION_MAINLINE_NETWORK_STACK)) { 6671 // TODO: CaptivePortalLoginActivity erroneously calls this method with a non-admin 6672 // ComponentName, so we have to use a separate code path for it: 6673 // getCallerIdentity(admin) will throw if the admin is not in the known admin list. 6674 caller = getCallerIdentity(); 6675 } else { 6676 caller = getCallerIdentity(admin); 6677 Preconditions.checkCallAuthorization( 6678 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 6679 } 6680 6681 return mInjector.binderWithCleanCallingIdentity( 6682 () -> mInjector.getVpnManager().isVpnLockdownEnabled(caller.getUserId())); 6683 } 6684 6685 @Override 6686 public boolean isAlwaysOnVpnLockdownEnabledForUser(int userHandle) { 6687 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 6688 String.format(NOT_SYSTEM_CALLER_MSG, "call isAlwaysOnVpnLockdownEnabledForUser")); 6689 synchronized (getLockObject()) { 6690 ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle); 6691 return admin != null && admin.mAlwaysOnVpnLockdown; 6692 } 6693 } 6694 6695 @Override 6696 public List<String> getAlwaysOnVpnLockdownAllowlist(ComponentName admin) 6697 throws SecurityException { 6698 Objects.requireNonNull(admin, "ComponentName is null"); 6699 6700 final CallerIdentity caller = getCallerIdentity(admin); 6701 Preconditions.checkCallAuthorization( 6702 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 6703 6704 return mInjector.binderWithCleanCallingIdentity( 6705 () -> mInjector.getVpnManager().getVpnLockdownAllowlist(caller.getUserId())); 6706 } 6707 6708 private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc, 6709 boolean wipeResetProtectionData) { 6710 wtfIfInLock(); 6711 boolean success = false; 6712 6713 try { 6714 boolean delayed = !mInjector.recoverySystemRebootWipeUserData( 6715 /* shutdown= */ false, reason, /* force= */ true, /* wipeEuicc= */ wipeEuicc, 6716 wipeExtRequested, wipeResetProtectionData); 6717 if (delayed) { 6718 // Persist the request so the device is automatically factory-reset on next start if 6719 // the system crashes or reboots before the {@code DevicePolicySafetyChecker} calls 6720 // its callback. 6721 Slogf.i(LOG_TAG, "Persisting factory reset request as it could be delayed by %s", 6722 mSafetyChecker); 6723 synchronized (getLockObject()) { 6724 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6725 policy.setDelayedFactoryReset(reason, wipeExtRequested, wipeEuicc, 6726 wipeResetProtectionData); 6727 saveSettingsLocked(UserHandle.USER_SYSTEM); 6728 } 6729 } 6730 success = true; 6731 } catch (IOException | SecurityException e) { 6732 Slogf.w(LOG_TAG, "Failed requesting data wipe", e); 6733 } finally { 6734 if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE); 6735 } 6736 } 6737 6738 private void factoryResetIfDelayedEarlier() { 6739 synchronized (getLockObject()) { 6740 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6741 6742 if (policy.mFactoryResetFlags == 0) return; 6743 6744 if (policy.mFactoryResetReason == null) { 6745 // Shouldn't happen. 6746 Slogf.e(LOG_TAG, "no persisted reason for factory resetting"); 6747 policy.mFactoryResetReason = "requested before boot"; 6748 } 6749 FactoryResetter factoryResetter = FactoryResetter.newBuilder(mContext) 6750 .setReason(policy.mFactoryResetReason).setForce(true) 6751 .setWipeEuicc((policy.mFactoryResetFlags & DevicePolicyData 6752 .FACTORY_RESET_FLAG_WIPE_EUICC) != 0) 6753 .setWipeAdoptableStorage((policy.mFactoryResetFlags & DevicePolicyData 6754 .FACTORY_RESET_FLAG_WIPE_EXTERNAL_STORAGE) != 0) 6755 .setWipeFactoryResetProtection((policy.mFactoryResetFlags & DevicePolicyData 6756 .FACTORY_RESET_FLAG_WIPE_FACTORY_RESET_PROTECTION) != 0) 6757 .build(); 6758 Slogf.i(LOG_TAG, "Factory resetting on boot using " + factoryResetter); 6759 try { 6760 if (!factoryResetter.factoryReset()) { 6761 // Shouldn't happen because FactoryResetter was created without a 6762 // DevicePolicySafetyChecker. 6763 Slogf.wtf(LOG_TAG, "Factory reset using " + factoryResetter + " failed."); 6764 } 6765 } catch (IOException e) { 6766 // Shouldn't happen. 6767 Slogf.wtf(LOG_TAG, "Could not factory reset using " + factoryResetter, e); 6768 } 6769 } 6770 } 6771 6772 private void forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently) { 6773 boolean success = false; 6774 try { 6775 if (getCurrentForegroundUserId() == userId) { 6776 mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM); 6777 } 6778 6779 success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId); 6780 if (!success) { 6781 Slogf.w(LOG_TAG, "Couldn't remove user " + userId); 6782 } else if (isManagedProfile(userId) && !wipeSilently) { 6783 sendWipeProfileNotification(wipeReasonForUser); 6784 } 6785 } catch (RemoteException re) { 6786 // Shouldn't happen 6787 } finally { 6788 if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE); 6789 } 6790 } 6791 6792 @Override 6793 public void wipeDataWithReason(int flags, String wipeReasonForUser, 6794 boolean calledOnParentInstance) { 6795 if (!mHasFeature && !hasCallingOrSelfPermission(permission.MASTER_CLEAR)) { 6796 return; 6797 } 6798 final CallerIdentity caller = getCallerIdentity(); 6799 boolean calledByProfileOwnerOnOrgOwnedDevice = 6800 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()); 6801 if (calledOnParentInstance) { 6802 Preconditions.checkCallAuthorization(calledByProfileOwnerOnOrgOwnedDevice, 6803 "Wiping the entire device can only be done by a profile owner on " 6804 + "organization-owned device."); 6805 } 6806 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 6807 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 6808 || calledByProfileOwnerOnOrgOwnedDevice 6809 || isFinancedDeviceOwner(caller), 6810 "Only device owners or profile owners of organization-owned device can set " 6811 + "WIPE_RESET_PROTECTION_DATA"); 6812 } 6813 6814 final ActiveAdmin admin; 6815 synchronized (getLockObject()) { 6816 admin = getActiveAdminWithPolicyForUidLocked(/* who= */ null, 6817 DeviceAdminInfo.USES_POLICY_WIPE_DATA, caller.getUid()); 6818 } 6819 6820 Preconditions.checkCallAuthorization( 6821 (admin != null) || hasCallingOrSelfPermission(permission.MASTER_CLEAR), 6822 "No active admin for user %d and caller %d does not hold MASTER_CLEAR permission", 6823 caller.getUserId(), caller.getUid()); 6824 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_WIPE_DATA); 6825 6826 if (TextUtils.isEmpty(wipeReasonForUser)) { 6827 wipeReasonForUser = getGenericWipeReason( 6828 calledByProfileOwnerOnOrgOwnedDevice, calledOnParentInstance); 6829 } 6830 6831 int userId = admin != null ? admin.getUserHandle().getIdentifier() 6832 : caller.getUserId(); 6833 Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser, admin, 6834 userId); 6835 if (calledByProfileOwnerOnOrgOwnedDevice) { 6836 // When wipeData is called on the parent instance, it implies wiping the entire device. 6837 if (calledOnParentInstance) { 6838 userId = UserHandle.USER_SYSTEM; 6839 } else { 6840 // when wipeData is _not_ called on the parent instance, it implies relinquishing 6841 // control over the device, wiping only the work profile. So the user restriction 6842 // on profile removal needs to be removed first. 6843 final UserHandle parentUser = UserHandle.of(getProfileParentId(userId)); 6844 mInjector.binderWithCleanCallingIdentity( 6845 () -> clearOrgOwnedProfileOwnerUserRestrictions(parentUser)); 6846 } 6847 } 6848 DevicePolicyEventLogger event = DevicePolicyEventLogger 6849 .createEvent(DevicePolicyEnums.WIPE_DATA_WITH_REASON) 6850 .setInt(flags) 6851 .setStrings(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT); 6852 6853 final String adminName; 6854 final ComponentName adminComp; 6855 if (admin != null) { 6856 adminComp = admin.info.getComponent(); 6857 adminName = adminComp.flattenToShortString(); 6858 event.setAdmin(adminComp); 6859 } else { 6860 adminComp = null; 6861 adminName = mInjector.getPackageManager().getPackagesForUid(caller.getUid())[0]; 6862 Slogf.i(LOG_TAG, "Logging wipeData() event admin as " + adminName); 6863 event.setAdmin(adminName); 6864 if (mInjector.userManagerIsHeadlessSystemUserMode()) { 6865 // On headless system user mode, the call is meant to factory reset the whole 6866 // device, otherwise the caller could simply remove the current user. 6867 userId = UserHandle.USER_SYSTEM; 6868 } 6869 } 6870 event.write(); 6871 6872 String internalReason = String.format( 6873 "DevicePolicyManager.wipeDataWithReason() from %s, organization-owned? %s", 6874 adminName, calledByProfileOwnerOnOrgOwnedDevice); 6875 6876 wipeDataNoLock(adminComp, flags, internalReason, wipeReasonForUser, userId); 6877 } 6878 6879 private String getGenericWipeReason( 6880 boolean calledByProfileOwnerOnOrgOwnedDevice, boolean calledOnParentInstance) { 6881 return calledByProfileOwnerOnOrgOwnedDevice && !calledOnParentInstance 6882 ? getUpdatableString( 6883 WORK_PROFILE_DELETED_ORG_OWNED_MESSAGE, 6884 R.string.device_ownership_relinquished) 6885 : getUpdatableString( 6886 WORK_PROFILE_DELETED_GENERIC_MESSAGE, 6887 R.string.work_profile_deleted_description_dpm_wipe); 6888 } 6889 6890 /** 6891 * Clears device wide policies enforced by COPE PO when relinquishing the device. This method 6892 * should be invoked once the admin is gone, so that all methods that rely on calculating 6893 * aggregate policy (e.g. strong auth timeout) from all admins aren't affected by its policies. 6894 * This method assumes that there is no other device or profile owners left on the device. 6895 * Shouldn't be called from binder thread without clearing identity. 6896 */ 6897 private void clearOrgOwnedProfileOwnerDeviceWidePolicies(@UserIdInt int parentId) { 6898 Slogf.i(LOG_TAG, "Cleaning up device-wide policies left over from org-owned profile..."); 6899 // Lockscreen message 6900 mLockPatternUtils.setDeviceOwnerInfo(null); 6901 // Wifi config lockdown 6902 mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0); 6903 // Security logging 6904 if (mInjector.securityLogGetLoggingEnabledProperty()) { 6905 mSecurityLogMonitor.stop(); 6906 mInjector.securityLogSetLoggingEnabledProperty(false); 6907 } 6908 // Network logging 6909 setNetworkLoggingActiveInternal(false); 6910 6911 // System update policy. 6912 final boolean hasSystemUpdatePolicy; 6913 synchronized (getLockObject()) { 6914 hasSystemUpdatePolicy = mOwners.getSystemUpdatePolicy() != null; 6915 if (hasSystemUpdatePolicy) { 6916 mOwners.clearSystemUpdatePolicy(); 6917 mOwners.writeDeviceOwner(); 6918 } 6919 } 6920 if (hasSystemUpdatePolicy) { 6921 mContext.sendBroadcastAsUser( 6922 new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM); 6923 } 6924 6925 // Unsuspend personal apps if needed. 6926 suspendPersonalAppsInternal(parentId, false); 6927 6928 // Notify FRP agent, LSS and WindowManager to ensure they don't hold on to stale policies. 6929 final int frpAgentUid = getFrpManagementAgentUid(); 6930 if (frpAgentUid > 0) { 6931 notifyResetProtectionPolicyChanged(frpAgentUid); 6932 } 6933 mLockSettingsInternal.refreshStrongAuthTimeout(parentId); 6934 6935 Slogf.i(LOG_TAG, "Cleaning up device-wide policies done."); 6936 } 6937 6938 private void wipeDataNoLock(ComponentName admin, int flags, String internalReason, 6939 String wipeReasonForUser, int userId) { 6940 wtfIfInLock(); 6941 6942 mInjector.binderWithCleanCallingIdentity(() -> { 6943 // First check whether the admin is allowed to wipe the device/user/profile. 6944 final String restriction; 6945 if (userId == UserHandle.USER_SYSTEM) { 6946 restriction = UserManager.DISALLOW_FACTORY_RESET; 6947 } else if (isManagedProfile(userId)) { 6948 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 6949 } else { 6950 restriction = UserManager.DISALLOW_REMOVE_USER; 6951 } 6952 if (isAdminAffectedByRestriction(admin, restriction, userId)) { 6953 throw new SecurityException("Cannot wipe data. " + restriction 6954 + " restriction is set for user " + userId); 6955 } 6956 6957 if (userId == UserHandle.USER_SYSTEM) { 6958 forceWipeDeviceNoLock( 6959 (flags & WIPE_EXTERNAL_STORAGE) != 0, 6960 internalReason, 6961 (flags & WIPE_EUICC) != 0, 6962 (flags & WIPE_RESET_PROTECTION_DATA) != 0); 6963 } else { 6964 forceWipeUser(userId, wipeReasonForUser, (flags & WIPE_SILENTLY) != 0); 6965 } 6966 }); 6967 } 6968 6969 private void sendWipeProfileNotification(String wipeReasonForUser) { 6970 Notification notification = 6971 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 6972 .setSmallIcon(android.R.drawable.stat_sys_warning) 6973 .setContentTitle(getWorkProfileDeletedTitle()) 6974 .setContentText(wipeReasonForUser) 6975 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 6976 .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser)) 6977 .build(); 6978 mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification); 6979 } 6980 6981 private String getWorkProfileDeletedTitle() { 6982 return getUpdatableString(WORK_PROFILE_DELETED_TITLE, R.string.work_profile_deleted); 6983 } 6984 6985 private void clearWipeProfileNotification() { 6986 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED); 6987 } 6988 6989 @Override 6990 public void setFactoryResetProtectionPolicy(ComponentName who, 6991 @Nullable FactoryResetProtectionPolicy policy) { 6992 if (!mHasFeature) { 6993 return; 6994 } 6995 Preconditions.checkNotNull(who, "ComponentName is null"); 6996 CallerIdentity caller = getCallerIdentity(who); 6997 Preconditions.checkCallAuthorization( 6998 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 6999 checkCanExecuteOrThrowUnsafe(DevicePolicyManager 7000 .OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY); 7001 7002 final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow(); 7003 synchronized (getLockObject()) { 7004 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7005 admin.mFactoryResetProtectionPolicy = policy; 7006 saveSettingsLocked(caller.getUserId()); 7007 } 7008 7009 mInjector.binderWithCleanCallingIdentity( 7010 () -> notifyResetProtectionPolicyChanged(frpManagementAgentUid)); 7011 7012 DevicePolicyEventLogger 7013 .createEvent(DevicePolicyEnums.SET_FACTORY_RESET_PROTECTION) 7014 .setAdmin(who) 7015 .write(); 7016 } 7017 7018 // Shouldn't be called from binder thread without clearing identity. 7019 private void notifyResetProtectionPolicyChanged(int frpManagementAgentUid) { 7020 final Intent intent = new Intent( 7021 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED).addFlags( 7022 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND | Intent.FLAG_RECEIVER_FOREGROUND); 7023 mContext.sendBroadcastAsUser(intent, 7024 UserHandle.getUserHandleForUid(frpManagementAgentUid), 7025 permission.MANAGE_FACTORY_RESET_PROTECTION); 7026 } 7027 7028 @Override 7029 public FactoryResetProtectionPolicy getFactoryResetProtectionPolicy( 7030 @Nullable ComponentName who) { 7031 if (!mHasFeature) { 7032 return null; 7033 } 7034 7035 final CallerIdentity caller = getCallerIdentity(who); 7036 final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow(); 7037 final ActiveAdmin admin; 7038 synchronized (getLockObject()) { 7039 if (who == null) { 7040 Preconditions.checkCallAuthorization(frpManagementAgentUid == caller.getUid() 7041 || hasCallingPermission(permission.MASTER_CLEAR), 7042 "Must be called by the FRP management agent on device"); 7043 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 7044 UserHandle.getUserId(frpManagementAgentUid)); 7045 } else { 7046 Preconditions.checkCallAuthorization( 7047 isDefaultDeviceOwner(caller) 7048 || isProfileOwnerOfOrganizationOwnedDevice(caller)); 7049 admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7050 } 7051 } 7052 7053 return admin != null ? admin.mFactoryResetProtectionPolicy : null; 7054 } 7055 7056 private int getFrpManagementAgentUid() { 7057 PersistentDataBlockManagerInternal pdb = mInjector.getPersistentDataBlockManagerInternal(); 7058 return pdb != null ? pdb.getAllowedUid() : -1; 7059 } 7060 7061 private int getFrpManagementAgentUidOrThrow() { 7062 int uid = getFrpManagementAgentUid(); 7063 if (uid == -1) { 7064 throw new UnsupportedOperationException( 7065 "The persistent data block service is not supported on this device"); 7066 } 7067 return uid; 7068 } 7069 7070 @Override 7071 public boolean isFactoryResetProtectionPolicySupported() { 7072 return getFrpManagementAgentUid() != -1; 7073 } 7074 7075 @Override 7076 public void sendLostModeLocationUpdate(AndroidFuture<Boolean> future) { 7077 if (!mHasFeature) { 7078 future.complete(false); 7079 return; 7080 } 7081 Preconditions.checkCallAuthorization( 7082 hasCallingOrSelfPermission(permission.TRIGGER_LOST_MODE)); 7083 7084 synchronized (getLockObject()) { 7085 final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 7086 UserHandle.USER_SYSTEM); 7087 Preconditions.checkState(admin != null, 7088 "Lost mode location updates can only be sent on an organization-owned device."); 7089 mInjector.binderWithCleanCallingIdentity(() -> { 7090 String[] providers = {LocationManager.FUSED_PROVIDER, 7091 LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER}; 7092 tryRetrieveAndSendLocationUpdate(admin, future, providers, /* index= */ 0); 7093 }); 7094 } 7095 } 7096 7097 /** Send lost mode location updates recursively, in order of the list of location providers. */ 7098 private void tryRetrieveAndSendLocationUpdate(ActiveAdmin admin, 7099 AndroidFuture<Boolean> future, String[] providers, int index) { 7100 // None of the providers were able to get location, return false 7101 if (index == providers.length) { 7102 future.complete(false); 7103 return; 7104 } 7105 if (mInjector.getLocationManager().isProviderEnabled(providers[index])) { 7106 mInjector.getLocationManager().getCurrentLocation(providers[index], 7107 /* cancellationSignal= */ null, mContext.getMainExecutor(), location -> { 7108 if (location != null) { 7109 mContext.sendBroadcastAsUser( 7110 newLostModeLocationUpdateIntent(admin, location), 7111 admin.getUserHandle()); 7112 future.complete(true); 7113 } else { 7114 tryRetrieveAndSendLocationUpdate(admin, future, providers, index + 1); 7115 } 7116 } 7117 ); 7118 } else { 7119 tryRetrieveAndSendLocationUpdate(admin, future, providers, index + 1); 7120 } 7121 } 7122 7123 private Intent newLostModeLocationUpdateIntent(ActiveAdmin admin, Location location) { 7124 final Intent intent = new Intent( 7125 DevicePolicyManager.ACTION_LOST_MODE_LOCATION_UPDATE); 7126 intent.putExtra(DevicePolicyManager.EXTRA_LOST_MODE_LOCATION, location); 7127 intent.setPackage(admin.info.getPackageName()); 7128 return intent; 7129 } 7130 7131 /** 7132 * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve 7133 * the remove warning for the given device admin. 7134 */ 7135 @Override 7136 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 7137 if (!mHasFeature) { 7138 return; 7139 } 7140 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7141 7142 final CallerIdentity caller = getCallerIdentity(); 7143 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7144 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7145 7146 synchronized (getLockObject()) { 7147 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 7148 if (admin == null) { 7149 result.sendResult(null); 7150 return; 7151 } 7152 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 7153 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 7154 intent.setComponent(admin.info.getComponent()); 7155 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 7156 null, new BroadcastReceiver() { 7157 @Override 7158 public void onReceive(Context context, Intent intent) { 7159 result.sendResult(getResultExtras(false)); 7160 } 7161 }, null, Activity.RESULT_OK, null, null); 7162 } 7163 } 7164 7165 @Override 7166 public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) { 7167 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 7168 return; 7169 } 7170 7171 final CallerIdentity caller = getCallerIdentity(); 7172 Preconditions.checkCallAuthorization(isSystemUid(caller)); 7173 // Managed Profile password can only be changed when it has a separate challenge. 7174 if (!isSeparateProfileChallengeEnabled(userId)) { 7175 Preconditions.checkCallAuthorization(!isManagedProfile(userId), "You can " 7176 + "not set the active password for a managed profile, userId = %d", userId); 7177 } 7178 7179 DevicePolicyData policy = getUserData(userId); 7180 final ArraySet<Integer> affectedUserIds = new ArraySet<>(); 7181 7182 synchronized (getLockObject()) { 7183 policy.mFailedPasswordAttempts = 0; 7184 affectedUserIds.add(userId); 7185 affectedUserIds.addAll(updatePasswordValidityCheckpointLocked( 7186 userId, /* parent */ false)); 7187 affectedUserIds.addAll(updatePasswordExpirationsLocked(userId)); 7188 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 7189 7190 // Send a broadcast to each profile using this password as its primary unlock. 7191 sendAdminCommandForLockscreenPoliciesLocked( 7192 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 7193 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 7194 7195 affectedUserIds.addAll(removeCaApprovalsIfNeeded(userId)); 7196 saveSettingsForUsersLocked(affectedUserIds); 7197 } 7198 if (mInjector.securityLogIsLoggingEnabled()) { 7199 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_CHANGED, 7200 /* complexity */ metrics.determineComplexity(), /*user*/ userId); 7201 } 7202 } 7203 7204 /** 7205 * Called any time the device password is updated. Resets all password expiration clocks. 7206 * 7207 * @return the set of user IDs that have been affected 7208 */ 7209 private Set<Integer> updatePasswordExpirationsLocked(int userHandle) { 7210 final ArraySet<Integer> affectedUserIds = new ArraySet<>(); 7211 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle); 7212 for (int i = 0; i < admins.size(); i++) { 7213 ActiveAdmin admin = admins.get(i); 7214 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 7215 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 7216 long timeout = admin.passwordExpirationTimeout; 7217 admin.passwordExpirationDate = 7218 timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 7219 } 7220 } 7221 return affectedUserIds; 7222 } 7223 7224 @Override 7225 public void reportFailedPasswordAttempt(int userHandle) { 7226 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7227 7228 final CallerIdentity caller = getCallerIdentity(); 7229 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7230 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7231 if (!isSeparateProfileChallengeEnabled(userHandle)) { 7232 Preconditions.checkCallAuthorization(!isManagedProfile(userHandle), 7233 "You can not report failed password attempt if separate profile challenge is " 7234 + "not in place for a managed profile, userId = %d", userHandle); 7235 } 7236 7237 boolean wipeData = false; 7238 ActiveAdmin strictestAdmin = null; 7239 final long ident = mInjector.binderClearCallingIdentity(); 7240 try { 7241 synchronized (getLockObject()) { 7242 DevicePolicyData policy = getUserData(userHandle); 7243 policy.mFailedPasswordAttempts++; 7244 saveSettingsLocked(userHandle); 7245 if (mHasFeature) { 7246 strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 7247 userHandle, /* parent */ false); 7248 int max = strictestAdmin != null 7249 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 7250 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 7251 wipeData = true; 7252 } 7253 7254 sendAdminCommandForLockscreenPoliciesLocked( 7255 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 7256 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 7257 } 7258 } 7259 } finally { 7260 mInjector.binderRestoreCallingIdentity(ident); 7261 } 7262 7263 if (wipeData && strictestAdmin != null) { 7264 final int userId = getUserIdToWipeForFailedPasswords(strictestAdmin); 7265 Slogf.i(LOG_TAG, "Max failed password attempts policy reached for admin: " 7266 + strictestAdmin.info.getComponent().flattenToShortString() 7267 + ". Calling wipeData for user " + userId); 7268 7269 // Attempt to wipe the device/user/profile associated with the admin, as if the 7270 // admin had called wipeData(). That way we can check whether the admin is actually 7271 // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the 7272 // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be 7273 // able to do so). 7274 // IMPORTANT: Call without holding the lock to prevent deadlock. 7275 try { 7276 wipeDataNoLock(strictestAdmin.info.getComponent(), 7277 /*flags=*/ 0, 7278 /*reason=*/ "reportFailedPasswordAttempt()", 7279 getFailedPasswordAttemptWipeMessage(), 7280 userId); 7281 } catch (SecurityException e) { 7282 Slogf.w(LOG_TAG, "Failed to wipe user " + userId 7283 + " after max failed password attempts reached.", e); 7284 } 7285 } 7286 7287 if (mInjector.securityLogIsLoggingEnabled()) { 7288 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, 7289 /*result*/ 0, /*method strength*/ 1); 7290 } 7291 } 7292 7293 private String getFailedPasswordAttemptWipeMessage() { 7294 return getUpdatableString( 7295 WORK_PROFILE_DELETED_FAILED_PASSWORD_ATTEMPTS_MESSAGE, 7296 R.string.work_profile_deleted_reason_maximum_password_failure); 7297 } 7298 7299 /** 7300 * Returns which user should be wiped if this admin's maximum filed password attempts policy is 7301 * violated. 7302 */ 7303 private int getUserIdToWipeForFailedPasswords(ActiveAdmin admin) { 7304 final int userId = admin.getUserHandle().getIdentifier(); 7305 final ComponentName component = admin.info.getComponent(); 7306 return isProfileOwnerOfOrganizationOwnedDevice(component, userId) 7307 ? getProfileParentId(userId) : userId; 7308 } 7309 7310 @Override 7311 public void reportSuccessfulPasswordAttempt(int userHandle) { 7312 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7313 7314 final CallerIdentity caller = getCallerIdentity(); 7315 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7316 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7317 7318 synchronized (getLockObject()) { 7319 DevicePolicyData policy = getUserData(userHandle); 7320 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 7321 mInjector.binderWithCleanCallingIdentity(() -> { 7322 policy.mFailedPasswordAttempts = 0; 7323 policy.mPasswordOwner = -1; 7324 saveSettingsLocked(userHandle); 7325 if (mHasFeature) { 7326 sendAdminCommandForLockscreenPoliciesLocked( 7327 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 7328 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 7329 } 7330 }); 7331 } 7332 } 7333 7334 if (mInjector.securityLogIsLoggingEnabled()) { 7335 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 7336 /*method strength*/ 1); 7337 } 7338 } 7339 7340 @Override 7341 public void reportFailedBiometricAttempt(int userHandle) { 7342 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7343 7344 final CallerIdentity caller = getCallerIdentity(); 7345 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7346 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7347 7348 if (mInjector.securityLogIsLoggingEnabled()) { 7349 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 7350 /*method strength*/ 0); 7351 } 7352 } 7353 7354 @Override 7355 public void reportSuccessfulBiometricAttempt(int userHandle) { 7356 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7357 7358 final CallerIdentity caller = getCallerIdentity(); 7359 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7360 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7361 7362 if (mInjector.securityLogIsLoggingEnabled()) { 7363 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 7364 /*method strength*/ 0); 7365 } 7366 } 7367 7368 @Override 7369 public void reportKeyguardDismissed(int userHandle) { 7370 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7371 7372 final CallerIdentity caller = getCallerIdentity(); 7373 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7374 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7375 7376 if (mInjector.securityLogIsLoggingEnabled()) { 7377 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 7378 } 7379 } 7380 7381 @Override 7382 public void reportKeyguardSecured(int userHandle) { 7383 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7384 7385 final CallerIdentity caller = getCallerIdentity(); 7386 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7387 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN)); 7388 7389 if (mInjector.securityLogIsLoggingEnabled()) { 7390 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 7391 } 7392 } 7393 7394 @Override 7395 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 7396 String exclusionList) { 7397 if (!mHasFeature) { 7398 return null; 7399 } 7400 synchronized (getLockObject()) { 7401 Objects.requireNonNull(who, "ComponentName is null"); 7402 7403 // Only check if system user has set global proxy. We don't allow other users to set it. 7404 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 7405 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7406 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 7407 7408 // Scan through active admins and find if anyone has already 7409 // set the global proxy. 7410 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 7411 for (ComponentName component : compSet) { 7412 ActiveAdmin ap = policy.mAdminMap.get(component); 7413 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 7414 // Another admin already sets the global proxy 7415 // Return it to the caller. 7416 return component; 7417 } 7418 } 7419 7420 // If the user is not system, don't set the global proxy. Fail silently. 7421 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 7422 Slogf.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 7423 + UserHandle.getCallingUserId() + " is not permitted."); 7424 return null; 7425 } 7426 if (proxySpec == null) { 7427 admin.specifiesGlobalProxy = false; 7428 admin.globalProxySpec = null; 7429 admin.globalProxyExclusionList = null; 7430 } else { 7431 7432 admin.specifiesGlobalProxy = true; 7433 admin.globalProxySpec = proxySpec; 7434 admin.globalProxyExclusionList = exclusionList; 7435 } 7436 7437 // Reset the global proxy accordingly 7438 // Do this using system permissions, as apps cannot write to secure settings 7439 mInjector.binderWithCleanCallingIdentity(() -> resetGlobalProxyLocked(policy)); 7440 return null; 7441 } 7442 } 7443 7444 @Override 7445 public ComponentName getGlobalProxyAdmin(int userHandle) { 7446 if (!mHasFeature) { 7447 return null; 7448 } 7449 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7450 7451 final CallerIdentity caller = getCallerIdentity(); 7452 Preconditions.checkCallAuthorization( 7453 hasFullCrossUsersPermission(caller, userHandle) && canQueryAdminPolicy(caller)); 7454 7455 synchronized (getLockObject()) { 7456 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 7457 // Scan through active admins and find if anyone has already 7458 // set the global proxy. 7459 final int N = policy.mAdminList.size(); 7460 for (int i = 0; i < N; i++) { 7461 ActiveAdmin ap = policy.mAdminList.get(i); 7462 if (ap.specifiesGlobalProxy) { 7463 // Device admin sets the global proxy 7464 // Return it to the caller. 7465 return ap.info.getComponent(); 7466 } 7467 } 7468 } 7469 // No device admin sets the global proxy. 7470 return null; 7471 } 7472 7473 @Override 7474 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 7475 Objects.requireNonNull(who, "ComponentName is null"); 7476 final CallerIdentity caller = getCallerIdentity(who); 7477 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 7478 checkAllUsersAreAffiliatedWithDevice(); 7479 mInjector.binderWithCleanCallingIdentity( 7480 () -> mInjector.getConnectivityManager().setGlobalProxy(proxyInfo)); 7481 } 7482 7483 private void resetGlobalProxyLocked(DevicePolicyData policy) { 7484 final int N = policy.mAdminList.size(); 7485 for (int i = 0; i < N; i++) { 7486 ActiveAdmin ap = policy.mAdminList.get(i); 7487 if (ap.specifiesGlobalProxy) { 7488 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 7489 return; 7490 } 7491 } 7492 // No device admins defining global proxies - reset global proxy settings to none 7493 saveGlobalProxyLocked(null, null); 7494 } 7495 7496 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 7497 if (exclusionList == null) { 7498 exclusionList = ""; 7499 } 7500 if (proxySpec == null) { 7501 proxySpec = ""; 7502 } 7503 // Remove white spaces 7504 proxySpec = proxySpec.trim(); 7505 String data[] = proxySpec.split(":"); 7506 int proxyPort = 8080; 7507 if (data.length > 1) { 7508 try { 7509 proxyPort = Integer.parseInt(data[1]); 7510 } catch (NumberFormatException e) {} 7511 } 7512 exclusionList = exclusionList.trim(); 7513 7514 ProxyInfo proxyProperties = ProxyInfo.buildDirectProxy(data[0], proxyPort, 7515 ProxyUtils.exclusionStringAsList(exclusionList)); 7516 if (!proxyProperties.isValid()) { 7517 Slogf.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 7518 return; 7519 } 7520 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 7521 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 7522 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 7523 exclusionList); 7524 } 7525 7526 /** 7527 * Called by an application that is administering the device to request that the storage system 7528 * be encrypted. Does nothing if the caller is on a secondary user or a managed profile. 7529 * 7530 * @return the new total request status (for all admins), or {@link 7531 * DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user 7532 */ 7533 @Override 7534 public int setStorageEncryption(ComponentName who, boolean encrypt) { 7535 if (!mHasFeature) { 7536 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7537 } 7538 Objects.requireNonNull(who, "ComponentName is null"); 7539 final int userHandle = UserHandle.getCallingUserId(); 7540 synchronized (getLockObject()) { 7541 // Check for permissions 7542 // Only system user can set storage encryption 7543 if (userHandle != UserHandle.USER_SYSTEM) { 7544 Slogf.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. " 7545 + "User " + UserHandle.getCallingUserId() + " is not permitted."); 7546 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7547 } 7548 7549 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 7550 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 7551 7552 // Quick exit: If the filesystem does not support encryption, we can exit early. 7553 if (!isEncryptionSupported()) { 7554 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7555 } 7556 7557 // (1) Record the value for the admin so it's sticky 7558 if (ap.encryptionRequested != encrypt) { 7559 ap.encryptionRequested = encrypt; 7560 saveSettingsLocked(userHandle); 7561 } 7562 7563 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 7564 // (2) Compute "max" for all admins 7565 boolean newRequested = false; 7566 final int N = policy.mAdminList.size(); 7567 for (int i = 0; i < N; i++) { 7568 newRequested |= policy.mAdminList.get(i).encryptionRequested; 7569 } 7570 7571 // Notify OS of new request 7572 setEncryptionRequested(newRequested); 7573 7574 // Return the new global request status 7575 return newRequested 7576 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 7577 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 7578 } 7579 } 7580 7581 /** 7582 * Get the current storage encryption request status for a given admin, or aggregate of all 7583 * active admins. 7584 */ 7585 @Override 7586 public boolean getStorageEncryption(@Nullable ComponentName who, int userHandle) { 7587 if (!mHasFeature) { 7588 return false; 7589 } 7590 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7591 7592 final CallerIdentity caller = getCallerIdentity(who); 7593 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7594 7595 synchronized (getLockObject()) { 7596 // Check for permissions if a particular caller is specified 7597 if (caller.hasAdminComponent()) { 7598 // When checking for a single caller, status is based on caller's request 7599 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 7600 return ap != null ? ap.encryptionRequested : false; 7601 } 7602 7603 // If no particular caller is specified, return the aggregate set of requests. 7604 // This is short circuited by returning true on the first hit. 7605 DevicePolicyData policy = getUserData(userHandle); 7606 final int N = policy.mAdminList.size(); 7607 for (int i = 0; i < N; i++) { 7608 if (policy.mAdminList.get(i).encryptionRequested) { 7609 return true; 7610 } 7611 } 7612 return false; 7613 } 7614 } 7615 7616 /** 7617 * Get the current encryption status of the device. 7618 */ 7619 @Override 7620 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 7621 if (!mHasFeature) { 7622 // Ok to return current status. 7623 } 7624 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 7625 7626 final CallerIdentity caller = getCallerIdentity(callerPackage); 7627 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7628 7629 7630 final ApplicationInfo ai; 7631 try { 7632 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 7633 } catch (RemoteException e) { 7634 throw new SecurityException(e); 7635 } 7636 7637 boolean legacyApp = false; 7638 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 7639 legacyApp = true; 7640 } 7641 7642 final int rawStatus = getEncryptionStatus(); 7643 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 7644 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 7645 } 7646 return rawStatus; 7647 } 7648 7649 /** 7650 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 7651 */ 7652 private boolean isEncryptionSupported() { 7653 // Note, this can be implemented as 7654 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7655 // But is provided as a separate internal method if there's a faster way to do a 7656 // simple check for supported-or-not. 7657 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7658 } 7659 7660 /** 7661 * Hook to low-levels: Reporting the current status of encryption. 7662 * @return Either {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} 7663 * or {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}. 7664 */ 7665 private int getEncryptionStatus() { 7666 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 7667 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 7668 } else { 7669 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7670 } 7671 } 7672 7673 /** 7674 * Hook to low-levels: If needed, record the new admin setting for encryption. 7675 */ 7676 private void setEncryptionRequested(boolean encrypt) { 7677 } 7678 7679 /** 7680 * Set whether the screen capture is disabled for the user managed by the specified admin. 7681 */ 7682 @Override 7683 public void setScreenCaptureDisabled(ComponentName who, boolean disabled, boolean parent) { 7684 if (!mHasFeature) { 7685 return; 7686 } 7687 Objects.requireNonNull(who, "ComponentName is null"); 7688 7689 final CallerIdentity caller = getCallerIdentity(who); 7690 if (parent) { 7691 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 7692 } 7693 7694 synchronized (getLockObject()) { 7695 ActiveAdmin ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller), 7696 parent); 7697 if (ap.disableScreenCapture != disabled) { 7698 ap.disableScreenCapture = disabled; 7699 saveSettingsLocked(caller.getUserId()); 7700 pushScreenCapturePolicy(caller.getUserId()); 7701 } 7702 } 7703 DevicePolicyEventLogger 7704 .createEvent(DevicePolicyEnums.SET_SCREEN_CAPTURE_DISABLED) 7705 .setAdmin(caller.getComponentName()) 7706 .setBoolean(disabled) 7707 .write(); 7708 } 7709 7710 // Push the screen capture policy for a given userId. If screen capture is disabled by the 7711 // DO or COPE PO on the parent profile, then this takes precedence as screen capture will 7712 // be disabled device-wide. 7713 private void pushScreenCapturePolicy(int adminUserId) { 7714 // Update screen capture device-wide if disabled by the DO or COPE PO on the parent profile. 7715 ActiveAdmin admin = 7716 getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceParentLocked( 7717 UserHandle.USER_SYSTEM); 7718 if (admin != null && admin.disableScreenCapture) { 7719 setScreenCaptureDisabled(UserHandle.USER_ALL); 7720 } else { 7721 // Otherwise, update screen capture only for the calling user. 7722 admin = getProfileOwnerAdminLocked(adminUserId); 7723 if (admin != null && admin.disableScreenCapture) { 7724 setScreenCaptureDisabled(adminUserId); 7725 } else { 7726 setScreenCaptureDisabled(UserHandle.USER_NULL); 7727 } 7728 } 7729 } 7730 7731 // Set the latest screen capture policy, overriding any existing ones. 7732 // userHandle can be one of USER_ALL, USER_NULL or a concrete userId. 7733 private void setScreenCaptureDisabled(int userHandle) { 7734 int current = mPolicyCache.getScreenCaptureDisallowedUser(); 7735 if (userHandle == current) { 7736 return; 7737 } 7738 mPolicyCache.setScreenCaptureDisallowedUser(userHandle); 7739 updateScreenCaptureDisabled(); 7740 } 7741 7742 /** 7743 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 7744 * active admin (if given admin is null). 7745 */ 7746 @Override 7747 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle, boolean parent) { 7748 if (!mHasFeature) { 7749 return false; 7750 } 7751 final CallerIdentity caller = getCallerIdentity(who); 7752 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 7753 7754 if (parent) { 7755 Preconditions.checkCallAuthorization( 7756 isProfileOwnerOfOrganizationOwnedDevice(getCallerIdentity().getUserId())); 7757 } 7758 return !mPolicyCache.isScreenCaptureAllowed(userHandle); 7759 } 7760 7761 private void updateScreenCaptureDisabled() { 7762 mHandler.post(() -> { 7763 try { 7764 mInjector.getIWindowManager().refreshScreenCaptureDisabled(); 7765 } catch (RemoteException e) { 7766 Slogf.w(LOG_TAG, "Unable to notify WindowManager.", e); 7767 } 7768 }); 7769 } 7770 7771 @Override 7772 public void setNearbyNotificationStreamingPolicy(int policy) { 7773 if (!mHasFeature) { 7774 return; 7775 } 7776 7777 final CallerIdentity caller = getCallerIdentity(); 7778 Preconditions.checkCallAuthorization( 7779 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 7780 7781 synchronized (getLockObject()) { 7782 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7783 if (admin.mNearbyNotificationStreamingPolicy != policy) { 7784 admin.mNearbyNotificationStreamingPolicy = policy; 7785 saveSettingsLocked(caller.getUserId()); 7786 } 7787 } 7788 } 7789 7790 @Override 7791 public int getNearbyNotificationStreamingPolicy(final int userId) { 7792 if (!mHasFeature) { 7793 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 7794 } 7795 7796 final CallerIdentity caller = getCallerIdentity(); 7797 Preconditions.checkCallAuthorization( 7798 isProfileOwner(caller) || isDefaultDeviceOwner(caller) 7799 || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY)); 7800 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)); 7801 7802 synchronized (getLockObject()) { 7803 if (mOwners.hasProfileOwner(userId) || mOwners.hasDeviceOwner()) { 7804 final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId); 7805 return admin.mNearbyNotificationStreamingPolicy; 7806 } 7807 } 7808 7809 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 7810 } 7811 7812 @Override 7813 public void setNearbyAppStreamingPolicy(int policy) { 7814 if (!mHasFeature) { 7815 return; 7816 } 7817 7818 final CallerIdentity caller = getCallerIdentity(); 7819 Preconditions.checkCallAuthorization( 7820 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 7821 7822 synchronized (getLockObject()) { 7823 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7824 if (admin.mNearbyAppStreamingPolicy != policy) { 7825 admin.mNearbyAppStreamingPolicy = policy; 7826 saveSettingsLocked(caller.getUserId()); 7827 } 7828 } 7829 } 7830 7831 @Override 7832 public int getNearbyAppStreamingPolicy(final int userId) { 7833 if (!mHasFeature) { 7834 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 7835 } 7836 7837 final CallerIdentity caller = getCallerIdentity(); 7838 Preconditions.checkCallAuthorization( 7839 isProfileOwner(caller) || isDefaultDeviceOwner(caller) 7840 || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY)); 7841 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)); 7842 7843 synchronized (getLockObject()) { 7844 if (mOwners.hasProfileOwner(userId) || mOwners.hasDeviceOwner()) { 7845 final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId); 7846 return admin.mNearbyAppStreamingPolicy; 7847 } 7848 } 7849 7850 return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY; 7851 } 7852 7853 /** 7854 * Set whether auto time is required by the specified admin (must be device or profile owner). 7855 */ 7856 @Override 7857 public void setAutoTimeRequired(ComponentName who, boolean required) { 7858 if (!mHasFeature) { 7859 return; 7860 } 7861 Objects.requireNonNull(who, "ComponentName is null"); 7862 final CallerIdentity caller = getCallerIdentity(who); 7863 7864 boolean requireAutoTimeChanged = false; 7865 synchronized (getLockObject()) { 7866 Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()), 7867 "Managed profile cannot set auto time required"); 7868 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 7869 if (admin.requireAutoTime != required) { 7870 admin.requireAutoTime = required; 7871 saveSettingsLocked(caller.getUserId()); 7872 requireAutoTimeChanged = true; 7873 } 7874 } 7875 // requireAutoTime is now backed by DISALLOW_CONFIG_DATE_TIME restriction, so propagate 7876 // updated restrictions to the framework. 7877 if (requireAutoTimeChanged) { 7878 pushUserRestrictions(caller.getUserId()); 7879 } 7880 // Turn AUTO_TIME on in settings if it is required 7881 if (required) { 7882 mInjector.binderWithCleanCallingIdentity( 7883 () -> mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 7884 1 /* AUTO_TIME on */)); 7885 } 7886 DevicePolicyEventLogger 7887 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_REQUIRED) 7888 .setAdmin(who) 7889 .setBoolean(required) 7890 .write(); 7891 } 7892 7893 /** 7894 * Returns whether or not auto time is required by the device owner or any profile owner. 7895 */ 7896 @Override 7897 public boolean getAutoTimeRequired() { 7898 if (!mHasFeature) { 7899 return false; 7900 } 7901 synchronized (getLockObject()) { 7902 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7903 if (deviceOwner != null && deviceOwner.requireAutoTime) { 7904 // If the device owner enforces auto time, we don't need to check the PO's 7905 return true; 7906 } 7907 7908 // Now check to see if any profile owner on any user enforces auto time 7909 for (Integer userId : mOwners.getProfileOwnerKeys()) { 7910 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 7911 if (profileOwner != null && profileOwner.requireAutoTime) { 7912 return true; 7913 } 7914 } 7915 7916 return false; 7917 } 7918 } 7919 7920 /** 7921 * Set whether auto time is enabled on the device. 7922 */ 7923 @Override 7924 public void setAutoTimeEnabled(ComponentName who, boolean enabled) { 7925 if (!mHasFeature) { 7926 return; 7927 } 7928 Objects.requireNonNull(who, "ComponentName is null"); 7929 7930 final CallerIdentity caller = getCallerIdentity(who); 7931 Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller) 7932 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(caller)); 7933 7934 mInjector.binderWithCleanCallingIdentity(() -> 7935 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, enabled ? 1 : 0)); 7936 7937 DevicePolicyEventLogger 7938 .createEvent(DevicePolicyEnums.SET_AUTO_TIME) 7939 .setAdmin(caller.getComponentName()) 7940 .setBoolean(enabled) 7941 .write(); 7942 } 7943 7944 /** 7945 * Returns whether auto time is used on the device or not. 7946 */ 7947 @Override 7948 public boolean getAutoTimeEnabled(ComponentName who) { 7949 if (!mHasFeature) { 7950 return false; 7951 } 7952 Objects.requireNonNull(who, "ComponentName is null"); 7953 7954 final CallerIdentity caller = getCallerIdentity(who); 7955 Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller) 7956 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(caller)); 7957 7958 return mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) > 0; 7959 } 7960 7961 /** 7962 * Set whether auto time zone is enabled on the device. 7963 */ 7964 @Override 7965 public void setAutoTimeZoneEnabled(ComponentName who, boolean enabled) { 7966 if (!mHasFeature) { 7967 return; 7968 } 7969 Objects.requireNonNull(who, "ComponentName is null"); 7970 7971 final CallerIdentity caller = getCallerIdentity(who); 7972 Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller) 7973 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(caller)); 7974 7975 mInjector.binderWithCleanCallingIdentity(() -> 7976 mInjector.settingsGlobalPutInt(Global.AUTO_TIME_ZONE, enabled ? 1 : 0)); 7977 7978 DevicePolicyEventLogger 7979 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_ZONE) 7980 .setAdmin(caller.getComponentName()) 7981 .setBoolean(enabled) 7982 .write(); 7983 } 7984 7985 /** 7986 * Returns whether auto time zone is used on the device or not. 7987 */ 7988 @Override 7989 public boolean getAutoTimeZoneEnabled(ComponentName who) { 7990 if (!mHasFeature) { 7991 return false; 7992 } 7993 Objects.requireNonNull(who, "ComponentName is null"); 7994 7995 final CallerIdentity caller = getCallerIdentity(who); 7996 Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller) 7997 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(caller)); 7998 7999 return mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) > 0; 8000 } 8001 8002 // TODO (b/137101239): remove this method in follow-up CL 8003 // since it's only used for split system user. 8004 @Override 8005 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 8006 throw new UnsupportedOperationException("This method was used by split system user only."); 8007 } 8008 8009 // TODO (b/137101239): remove this method in follow-up CL 8010 // since it's only used for split system user. 8011 @Override 8012 public boolean getForceEphemeralUsers(ComponentName who) { 8013 throw new UnsupportedOperationException("This method was used by split system user only."); 8014 } 8015 8016 @Override 8017 public boolean requestBugreport(ComponentName who) { 8018 if (!mHasFeature) { 8019 return false; 8020 } 8021 Objects.requireNonNull(who, "ComponentName is null"); 8022 // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport 8023 // which could still contain data related to that user. Should we disallow that, e.g. until 8024 // next boot? Might not be needed given that this still requires user consent. 8025 final CallerIdentity caller = getCallerIdentity(who); 8026 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 8027 checkAllUsersAreAffiliatedWithDevice(); 8028 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REQUEST_BUGREPORT); 8029 8030 if (mBugreportCollectionManager.requestBugreport()) { 8031 DevicePolicyEventLogger 8032 .createEvent(DevicePolicyEnums.REQUEST_BUGREPORT) 8033 .setAdmin(who) 8034 .write(); 8035 8036 final long currentTime = System.currentTimeMillis(); 8037 synchronized (getLockObject()) { 8038 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 8039 if (currentTime > policyData.mLastBugReportRequestTime) { 8040 policyData.mLastBugReportRequestTime = currentTime; 8041 saveSettingsLocked(UserHandle.USER_SYSTEM); 8042 } 8043 } 8044 8045 return true; 8046 } else { 8047 return false; 8048 } 8049 } 8050 8051 void sendDeviceOwnerCommand(String action, Bundle extras) { 8052 final int deviceOwnerUserId; 8053 final ComponentName receiverComponent; 8054 synchronized (getLockObject()) { 8055 deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 8056 receiverComponent = mOwners.getDeviceOwnerComponent(); 8057 } 8058 sendActiveAdminCommand(action, extras, deviceOwnerUserId, receiverComponent, 8059 /* inForeground */ false); 8060 } 8061 8062 void sendDeviceOwnerOrProfileOwnerCommand(String action, Bundle extras, int userId) { 8063 if (userId == UserHandle.USER_ALL) { 8064 userId = UserHandle.USER_SYSTEM; 8065 } 8066 boolean inForeground = false; 8067 ComponentName receiverComponent = null; 8068 if (action.equals(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE)) { 8069 inForeground = true; 8070 receiverComponent = resolveDelegateReceiver(DELEGATION_NETWORK_LOGGING, action, userId); 8071 } 8072 if (action.equals(DeviceAdminReceiver.ACTION_SECURITY_LOGS_AVAILABLE)) { 8073 inForeground = true; 8074 receiverComponent = resolveDelegateReceiver( 8075 DELEGATION_SECURITY_LOGGING, action, userId); 8076 } 8077 if (receiverComponent == null) { 8078 receiverComponent = getOwnerComponent(userId); 8079 } 8080 sendActiveAdminCommand(action, extras, userId, receiverComponent, inForeground); 8081 } 8082 8083 private void sendProfileOwnerCommand(String action, Bundle extras, @UserIdInt int userId) { 8084 sendActiveAdminCommand(action, extras, userId, mOwners.getProfileOwnerComponent(userId), 8085 /* inForeground */ false); 8086 } 8087 8088 private void sendActiveAdminCommand(String action, Bundle extras, 8089 @UserIdInt int userId, ComponentName receiverComponent, boolean inForeground) { 8090 final Intent intent = new Intent(action); 8091 intent.setComponent(receiverComponent); 8092 if (extras != null) { 8093 intent.putExtras(extras); 8094 } 8095 if (inForeground) { 8096 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 8097 } 8098 8099 if (VERBOSE_LOG) { 8100 Slogf.v(LOG_TAG, "sendActiveAdminCommand(): broadcasting " + action + " to " 8101 + receiverComponent.flattenToShortString() + " on user " + userId); 8102 } 8103 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 8104 } 8105 8106 private void sendOwnerChangedBroadcast(String broadcast, int userId) { 8107 final Intent intent = new Intent(broadcast) 8108 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 8109 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 8110 } 8111 8112 void sendBugreportToDeviceOwner(Uri bugreportUri, String bugreportHash) { 8113 synchronized (getLockObject()) { 8114 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 8115 intent.setComponent(mOwners.getDeviceOwnerComponent()); 8116 intent.setDataAndType(bugreportUri, RemoteBugreportManager.BUGREPORT_MIMETYPE); 8117 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 8118 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8119 8120 final UriGrantsManagerInternal ugm = LocalServices 8121 .getService(UriGrantsManagerInternal.class); 8122 final NeededUriGrants needed = ugm.checkGrantUriPermissionFromIntent(intent, 8123 Process.SHELL_UID, mOwners.getDeviceOwnerComponent().getPackageName(), 8124 mOwners.getDeviceOwnerUserId()); 8125 ugm.grantUriPermissionUncheckedFromIntent(needed, null); 8126 8127 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 8128 } 8129 } 8130 8131 void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash) { 8132 synchronized (getLockObject()) { 8133 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 8134 } 8135 } 8136 8137 Pair<String, String> getDeviceOwnerRemoteBugreportUriAndHash() { 8138 synchronized (getLockObject()) { 8139 final String uri = mOwners.getDeviceOwnerRemoteBugreportUri(); 8140 return uri == null ? null 8141 : new Pair<>(uri, mOwners.getDeviceOwnerRemoteBugreportHash()); 8142 } 8143 } 8144 8145 /** 8146 * Disables all device cameras according to the specified admin. 8147 */ 8148 @Override 8149 public void setCameraDisabled(ComponentName who, boolean disabled, boolean parent) { 8150 if (!mHasFeature) { 8151 return; 8152 } 8153 Objects.requireNonNull(who, "ComponentName is null"); 8154 8155 final CallerIdentity caller = getCallerIdentity(who); 8156 if (parent) { 8157 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 8158 } 8159 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_CAMERA_DISABLED); 8160 8161 final int userHandle = caller.getUserId(); 8162 synchronized (getLockObject()) { 8163 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 8164 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA, parent); 8165 if (ap.disableCamera != disabled) { 8166 ap.disableCamera = disabled; 8167 saveSettingsLocked(userHandle); 8168 } 8169 } 8170 // Tell the user manager that the restrictions have changed. 8171 pushUserRestrictions(userHandle); 8172 8173 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 8174 if (SecurityLog.isLoggingEnabled()) { 8175 SecurityLog.writeEvent(SecurityLog.TAG_CAMERA_POLICY_SET, 8176 who.getPackageName(), userHandle, affectedUserId, disabled ? 1 : 0); 8177 } 8178 DevicePolicyEventLogger 8179 .createEvent(DevicePolicyEnums.SET_CAMERA_DISABLED) 8180 .setAdmin(caller.getComponentName()) 8181 .setBoolean(disabled) 8182 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 8183 .write(); 8184 } 8185 8186 /** 8187 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 8188 * active admins. 8189 */ 8190 @Override 8191 public boolean getCameraDisabled(ComponentName who, int userHandle, boolean parent) { 8192 if (!mHasFeature) { 8193 return false; 8194 } 8195 8196 final CallerIdentity caller = getCallerIdentity(who); 8197 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle) 8198 || isCameraServerUid(caller)); 8199 8200 if (parent) { 8201 Preconditions.checkCallAuthorization( 8202 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId())); 8203 } 8204 8205 synchronized (getLockObject()) { 8206 if (who != null) { 8207 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 8208 return (admin != null) && admin.disableCamera; 8209 } 8210 // First, see if DO has set it. If so, it's device-wide. 8211 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 8212 if (deviceOwner != null && deviceOwner.disableCamera) { 8213 return true; 8214 } 8215 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 8216 // Return the strictest policy across all participating admins. 8217 List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(affectedUserId); 8218 // Determine whether or not the device camera is disabled for any active admins. 8219 for (ActiveAdmin admin : admins) { 8220 if (admin.disableCamera) { 8221 return true; 8222 } 8223 } 8224 return false; 8225 } 8226 } 8227 8228 @Override 8229 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 8230 if (!mHasFeature) { 8231 return; 8232 } 8233 Objects.requireNonNull(who, "ComponentName is null"); 8234 8235 final CallerIdentity caller = getCallerIdentity(who); 8236 8237 final int userHandle = caller.getUserId(); 8238 synchronized (getLockObject()) { 8239 ActiveAdmin ap = getActiveAdminForCallerLocked( 8240 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 8241 if (isManagedProfile(userHandle)) { 8242 if (parent) { 8243 if (isProfileOwnerOfOrganizationOwnedDevice(caller)) { 8244 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 8245 } else { 8246 which = which & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 8247 } 8248 } else { 8249 which = which & PROFILE_KEYGUARD_FEATURES; 8250 } 8251 } 8252 if (ap.disabledKeyguardFeatures != which) { 8253 ap.disabledKeyguardFeatures = which; 8254 saveSettingsLocked(userHandle); 8255 } 8256 } 8257 if (SecurityLog.isLoggingEnabled()) { 8258 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 8259 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET, 8260 who.getPackageName(), userHandle, affectedUserId, which); 8261 } 8262 DevicePolicyEventLogger 8263 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED_FEATURES) 8264 .setAdmin(caller.getComponentName()) 8265 .setInt(which) 8266 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 8267 .write(); 8268 } 8269 8270 /** 8271 * Gets the disabled state for features in keyguard for the given admin, 8272 * or the aggregate of all active admins if who is null. 8273 * This API is cached: invalidate with invalidateBinderCaches(). 8274 */ 8275 @Override 8276 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 8277 if (!mHasFeature) { 8278 return 0; 8279 } 8280 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 8281 8282 final CallerIdentity caller = getCallerIdentity(); 8283 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 8284 Preconditions.checkCallAuthorization( 8285 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid()) 8286 || isSystemUid(caller)); 8287 8288 final long ident = mInjector.binderClearCallingIdentity(); 8289 try { 8290 synchronized (getLockObject()) { 8291 if (who != null) { 8292 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 8293 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 8294 } 8295 8296 final List<ActiveAdmin> admins; 8297 if (!parent && isManagedProfile(userHandle)) { 8298 // If we are being asked about a managed profile, just return keyguard features 8299 // disabled by admins in the profile. 8300 admins = getUserDataUnchecked(userHandle).mAdminList; 8301 } else { 8302 // Otherwise return those set by admins in the user and its profiles. 8303 admins = getActiveAdminsForLockscreenPoliciesLocked( 8304 getProfileParentUserIfRequested(userHandle, parent)); 8305 } 8306 8307 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 8308 final int N = admins.size(); 8309 for (int i = 0; i < N; i++) { 8310 ActiveAdmin admin = admins.get(i); 8311 int userId = admin.getUserHandle().getIdentifier(); 8312 boolean isRequestedUser = !parent && (userId == userHandle); 8313 if (isRequestedUser || !isManagedProfile(userId)) { 8314 // If we are being asked explicitly about this user 8315 // return all disabled features even if its a managed profile. 8316 which |= admin.disabledKeyguardFeatures; 8317 } else { 8318 // Otherwise a managed profile is only allowed to disable 8319 // some features on the parent user. 8320 which |= (admin.disabledKeyguardFeatures 8321 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 8322 } 8323 } 8324 return which; 8325 } 8326 } finally { 8327 mInjector.binderRestoreCallingIdentity(ident); 8328 } 8329 } 8330 8331 @Override 8332 public void setKeepUninstalledPackages(ComponentName who, String callerPackage, 8333 List<String> packageList) { 8334 if (!mHasFeature) { 8335 return; 8336 } 8337 Objects.requireNonNull(packageList, "packageList is null"); 8338 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 8339 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 8340 && isDefaultDeviceOwner(caller)) 8341 || (caller.hasPackage() 8342 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES))); 8343 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEEP_UNINSTALLED_PACKAGES); 8344 8345 synchronized (getLockObject()) { 8346 // Get the device owner 8347 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 8348 // Set list of packages to be kept even if uninstalled. 8349 deviceOwner.keepUninstalledPackages = packageList; 8350 // Save settings. 8351 saveSettingsLocked(caller.getUserId()); 8352 // Notify package manager. 8353 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 8354 } 8355 DevicePolicyEventLogger 8356 .createEvent(DevicePolicyEnums.SET_KEEP_UNINSTALLED_PACKAGES) 8357 .setAdmin(caller.getPackageName()) 8358 .setBoolean(/* isDelegate */ who == null) 8359 .setStrings(packageList.toArray(new String[0])) 8360 .write(); 8361 } 8362 8363 @Override 8364 public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) { 8365 if (!mHasFeature) { 8366 return null; 8367 } 8368 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 8369 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 8370 && isDefaultDeviceOwner(caller)) 8371 || (caller.hasPackage() 8372 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES))); 8373 8374 synchronized (getLockObject()) { 8375 return getKeepUninstalledPackagesLocked(); 8376 } 8377 } 8378 8379 private List<String> getKeepUninstalledPackagesLocked() { 8380 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 8381 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 8382 } 8383 8384 /** 8385 * Logs a warning when the device doesn't have {@code PackageManager.FEATURE_DEVICE_ADMIN}. 8386 * 8387 * @param message action that was not executed; should not end with a period because the missing 8388 * feature will be appended to it. 8389 */ 8390 private void logMissingFeatureAction(String message) { 8391 Slogf.w(LOG_TAG, message + " because device does not have the " 8392 + PackageManager.FEATURE_DEVICE_ADMIN + " feature."); 8393 } 8394 8395 @Override 8396 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId, 8397 boolean setProfileOwnerOnCurrentUserIfNecessary) { 8398 if (!mHasFeature) { 8399 logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(admin) 8400 + " as device owner for user " + userId); 8401 return false; 8402 } 8403 Preconditions.checkArgument(admin != null); 8404 8405 final CallerIdentity caller = getCallerIdentity(); 8406 // Cannot be called while holding the lock: 8407 final boolean hasIncompatibleAccountsOrNonAdb = 8408 hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, admin); 8409 synchronized (getLockObject()) { 8410 enforceCanSetDeviceOwnerLocked(caller, admin, userId, hasIncompatibleAccountsOrNonAdb); 8411 Preconditions.checkArgument(isPackageInstalledForUser(admin.getPackageName(), userId), 8412 "Invalid component " + admin + " for device owner"); 8413 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 8414 Preconditions.checkArgument(activeAdmin != null && !getUserData( 8415 userId).mRemovingAdmins.contains(admin), "Not active admin: " + admin); 8416 8417 // Shutting down backup manager service permanently. 8418 toggleBackupServiceActive(UserHandle.USER_SYSTEM, /* makeActive= */ false); 8419 if (isAdb(caller)) { 8420 // Log device owner provisioning was started using adb. 8421 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 8422 DevicePolicyEventLogger 8423 .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB) 8424 .setAdmin(admin) 8425 .setStrings(LOG_TAG_DEVICE_OWNER) 8426 .write(); 8427 } 8428 8429 mOwners.setDeviceOwner(admin, ownerName, userId); 8430 mOwners.writeDeviceOwner(); 8431 setDeviceOwnershipSystemPropertyLocked(); 8432 8433 //TODO(b/180371154): when provisionFullyManagedDevice is used in tests, remove this 8434 // hard-coded default value setting. 8435 if (isAdb(caller)) { 8436 activeAdmin.mAdminCanGrantSensorsPermissions = true; 8437 mPolicyCache.setAdminCanGrantSensorsPermissions(userId, true); 8438 saveSettingsLocked(userId); 8439 } 8440 8441 mInjector.binderWithCleanCallingIdentity(() -> { 8442 // Restrict adding a managed profile when a device owner is set on the device. 8443 // That is to prevent the co-existence of a managed profile and a device owner 8444 // on the same device. 8445 // Instead, the device may be provisioned with an organization-owned managed 8446 // profile, such that the admin on that managed profile has extended management 8447 // capabilities that can affect the entire device (but not access private data 8448 // on the primary profile). 8449 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true, 8450 UserHandle.of(userId)); 8451 // Restrict adding a clone profile when a device owner is set on the device. 8452 // That is to prevent the co-existence of a clone profile and a device owner 8453 // on the same device. 8454 // CDD for reference : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support 8455 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, true, 8456 UserHandle.of(userId)); 8457 // TODO Send to system too? 8458 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId); 8459 }); 8460 mDeviceAdminServiceController.startServiceForOwner( 8461 admin.getPackageName(), userId, "set-device-owner"); 8462 8463 Slogf.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 8464 } 8465 8466 if (setProfileOwnerOnCurrentUserIfNecessary 8467 && mInjector.userManagerIsHeadlessSystemUserMode()) { 8468 int currentForegroundUser; 8469 synchronized (getLockObject()) { 8470 currentForegroundUser = getCurrentForegroundUserId(); 8471 } 8472 Slogf.i(LOG_TAG, "setDeviceOwner(): setting " + admin 8473 + " as profile owner on user " + currentForegroundUser); 8474 // Sets profile owner on current foreground user since 8475 // the human user will complete the DO setup workflow from there. 8476 manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin, 8477 /* managedUser= */ currentForegroundUser, /* adminExtras= */ null, 8478 /* showDisclaimer= */ false); 8479 } 8480 return true; 8481 } 8482 8483 /** 8484 * This API is cached: invalidate with invalidateBinderCaches(). 8485 */ 8486 @Override 8487 public boolean hasDeviceOwner() { 8488 final CallerIdentity caller = getCallerIdentity(); 8489 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 8490 || canManageUsers(caller) || isFinancedDeviceOwner(caller) 8491 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 8492 return mOwners.hasDeviceOwner(); 8493 } 8494 8495 boolean isDeviceOwner(ActiveAdmin admin) { 8496 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 8497 } 8498 8499 public boolean isDeviceOwner(ComponentName who, int userId) { 8500 synchronized (getLockObject()) { 8501 return mOwners.hasDeviceOwner() 8502 && mOwners.getDeviceOwnerUserId() == userId 8503 && mOwners.getDeviceOwnerComponent().equals(who); 8504 } 8505 } 8506 8507 /** 8508 * Returns {@code true} <b>only if</b> the caller is the device owner and the device owner type 8509 * is {@link DevicePolicyManager#DEVICE_OWNER_TYPE_DEFAULT}. {@code false} is returned for the 8510 * case where the caller is not the device owner, there is no device owner, or the device owner 8511 * type is not {@link DevicePolicyManager#DEVICE_OWNER_TYPE_DEFAULT}. 8512 * 8513 */ 8514 private boolean isDefaultDeviceOwner(CallerIdentity caller) { 8515 synchronized (getLockObject()) { 8516 return isDeviceOwnerLocked(caller) && getDeviceOwnerTypeLocked( 8517 mOwners.getDeviceOwnerPackageName()) == DEVICE_OWNER_TYPE_DEFAULT; 8518 } 8519 } 8520 8521 private boolean isDeviceOwnerLocked(CallerIdentity caller) { 8522 if (!mOwners.hasDeviceOwner() || mOwners.getDeviceOwnerUserId() != caller.getUserId()) { 8523 return false; 8524 } 8525 8526 if (caller.hasAdminComponent()) { 8527 return mOwners.getDeviceOwnerComponent().equals(caller.getComponentName()); 8528 } else { 8529 return isUidDeviceOwnerLocked(caller.getUid()); 8530 } 8531 } 8532 8533 private boolean isDeviceOwnerUserId(int userId) { 8534 synchronized (getLockObject()) { 8535 return mOwners.getDeviceOwnerComponent() != null 8536 && mOwners.getDeviceOwnerUserId() == userId; 8537 } 8538 } 8539 8540 private boolean isDeviceOwnerPackage(String packageName, int userId) { 8541 synchronized (getLockObject()) { 8542 return mOwners.hasDeviceOwner() 8543 && mOwners.getDeviceOwnerUserId() == userId 8544 && mOwners.getDeviceOwnerPackageName().equals(packageName); 8545 } 8546 } 8547 8548 private boolean isProfileOwnerPackage(String packageName, int userId) { 8549 synchronized (getLockObject()) { 8550 return mOwners.hasProfileOwner(userId) 8551 && mOwners.getProfileOwnerPackage(userId).equals(packageName); 8552 } 8553 } 8554 8555 public boolean isProfileOwner(ComponentName who, int userId) { 8556 final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() -> 8557 getProfileOwnerAsUser(userId)); 8558 return who != null && who.equals(profileOwner); 8559 } 8560 8561 /** 8562 * Returns {@code true} if the provided caller identity is of a profile owner. 8563 * @param caller identity of caller. 8564 * @return true if {@code identity} is a profile owner, false otherwise. 8565 */ 8566 public boolean isProfileOwner(CallerIdentity caller) { 8567 synchronized (getLockObject()) { 8568 final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() -> 8569 getProfileOwnerAsUser(caller.getUserId())); 8570 // No profile owner. 8571 if (profileOwner == null) { 8572 return false; 8573 } 8574 // The admin ComponentName was specified, check it directly. 8575 if (caller.hasAdminComponent()) { 8576 return profileOwner.equals(caller.getComponentName()); 8577 } else { 8578 return isUidProfileOwnerLocked(caller.getUid()); 8579 } 8580 } 8581 } 8582 8583 /** 8584 * Checks if the app uid provided is the profile owner. This method should only be called 8585 * if no componentName is available. 8586 * 8587 * @param appUid UID of the caller. 8588 * @return true if the caller is the profile owner 8589 */ 8590 private boolean isUidProfileOwnerLocked(int appUid) { 8591 ensureLocked(); 8592 8593 final int userId = UserHandle.getUserId(appUid); 8594 final ComponentName profileOwnerComponent = mOwners.getProfileOwnerComponent(userId); 8595 if (profileOwnerComponent == null) { 8596 return false; 8597 } 8598 for (ActiveAdmin admin : getUserData(userId).mAdminList) { 8599 final ComponentName currentAdminComponent = admin.info.getComponent(); 8600 if (admin.getUid() == appUid && profileOwnerComponent.equals(currentAdminComponent)) { 8601 return true; 8602 } 8603 } 8604 return false; 8605 } 8606 8607 private boolean hasProfileOwner(int userId) { 8608 synchronized (getLockObject()) { 8609 return mOwners.hasProfileOwner(userId); 8610 } 8611 } 8612 8613 /** 8614 * Returns {@code true} if the provided caller identity is of a profile owner of an organization 8615 * owned device. 8616 * 8617 * @param caller identity of caller 8618 * @return true if {@code identity} is a profile owner of an organization owned device, false 8619 * otherwise. 8620 */ 8621 private boolean isProfileOwnerOfOrganizationOwnedDevice(CallerIdentity caller) { 8622 return isProfileOwner(caller) && isProfileOwnerOfOrganizationOwnedDevice( 8623 caller.getUserId()); 8624 } 8625 8626 private boolean isProfileOwnerOfOrganizationOwnedDevice(int userId) { 8627 synchronized (getLockObject()) { 8628 return mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId); 8629 } 8630 } 8631 8632 private boolean isProfileOwnerOfOrganizationOwnedDevice(ComponentName who, int userId) { 8633 return isProfileOwner(who, userId) && isProfileOwnerOfOrganizationOwnedDevice(userId); 8634 } 8635 8636 private boolean isProfileOwnerOnUser0(CallerIdentity caller) { 8637 return isProfileOwner(caller) && caller.getUserHandle().isSystem(); 8638 } 8639 8640 private boolean isPackage(CallerIdentity caller, String packageName) { 8641 return isCallingFromPackage(packageName, caller.getUid()); 8642 } 8643 8644 @Override 8645 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 8646 if (!mHasFeature) { 8647 return null; 8648 } 8649 if (!callingUserOnly) { 8650 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()) 8651 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 8652 } 8653 synchronized (getLockObject()) { 8654 if (!mOwners.hasDeviceOwner()) { 8655 return null; 8656 } 8657 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 8658 mOwners.getDeviceOwnerUserId()) { 8659 return null; 8660 } 8661 return mOwners.getDeviceOwnerComponent(); 8662 } 8663 } 8664 8665 private int getDeviceOwnerUserIdUncheckedLocked() { 8666 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 8667 } 8668 8669 @Override 8670 public int getDeviceOwnerUserId() { 8671 if (!mHasFeature) { 8672 return UserHandle.USER_NULL; 8673 } 8674 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 8675 8676 synchronized (getLockObject()) { 8677 return getDeviceOwnerUserIdUncheckedLocked(); 8678 } 8679 } 8680 8681 /** 8682 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 8683 * MANAGE_USERS. 8684 */ 8685 @Override 8686 public String getDeviceOwnerName() { 8687 if (!mHasFeature) { 8688 return null; 8689 } 8690 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()) 8691 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 8692 8693 synchronized (getLockObject()) { 8694 if (!mOwners.hasDeviceOwner()) { 8695 return null; 8696 } 8697 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 8698 // Should setDeviceOwner/ProfileOwner still take a name? 8699 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 8700 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 8701 } 8702 } 8703 8704 /** Returns the active device owner or {@code null} if there is no device owner. */ 8705 @VisibleForTesting 8706 ActiveAdmin getDeviceOwnerAdminLocked() { 8707 ensureLocked(); 8708 ComponentName component = mOwners.getDeviceOwnerComponent(); 8709 if (component == null) { 8710 return null; 8711 } 8712 8713 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 8714 final int n = policy.mAdminList.size(); 8715 for (int i = 0; i < n; i++) { 8716 ActiveAdmin admin = policy.mAdminList.get(i); 8717 if (component.equals(admin.info.getComponent())) { 8718 return admin; 8719 } 8720 } 8721 Slogf.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 8722 return null; 8723 } 8724 8725 ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(int userId) { 8726 ensureLocked(); 8727 ActiveAdmin admin = getDeviceOwnerAdminLocked(); 8728 if (admin == null) { 8729 admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId); 8730 } 8731 return admin; 8732 } 8733 8734 ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceParentLocked(int userId) { 8735 ensureLocked(); 8736 ActiveAdmin admin = getDeviceOwnerAdminLocked(); 8737 if (admin != null) { 8738 return admin; 8739 } 8740 admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId); 8741 return admin != null ? admin.getParentActiveAdmin() : null; 8742 } 8743 8744 @Override 8745 public void clearDeviceOwner(String packageName) { 8746 Objects.requireNonNull(packageName, "packageName is null"); 8747 8748 final CallerIdentity caller = getCallerIdentity(packageName); 8749 synchronized (getLockObject()) { 8750 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 8751 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 8752 if (!mOwners.hasDeviceOwner() 8753 || !deviceOwnerComponent.getPackageName().equals(packageName) 8754 || (deviceOwnerUserId != caller.getUserId())) { 8755 throw new SecurityException( 8756 "clearDeviceOwner can only be called by the device owner"); 8757 } 8758 enforceUserUnlocked(deviceOwnerUserId); 8759 DevicePolicyData policy = getUserData(deviceOwnerUserId); 8760 if (policy.mPasswordTokenHandle != 0) { 8761 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, deviceOwnerUserId); 8762 } 8763 8764 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 8765 mInjector.binderWithCleanCallingIdentity(() -> { 8766 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 8767 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 8768 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, 8769 deviceOwnerUserId); 8770 }); 8771 Slogf.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 8772 } 8773 } 8774 8775 private void clearOverrideApnUnchecked() { 8776 if (!mHasTelephonyFeature) { 8777 return; 8778 } 8779 // Disable Override APNs and remove them from database. 8780 setOverrideApnsEnabledUnchecked(false); 8781 final List<ApnSetting> apns = getOverrideApnsUnchecked(); 8782 for (int i = 0; i < apns.size(); i ++) { 8783 removeOverrideApnUnchecked(apns.get(i).getId()); 8784 } 8785 } 8786 8787 private void clearManagedProfileApnUnchecked() { 8788 if (!mHasTelephonyFeature) { 8789 return; 8790 } 8791 final List<ApnSetting> apns = getOverrideApnsUnchecked(); 8792 for (ApnSetting apn : apns) { 8793 if (apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) { 8794 removeOverrideApnUnchecked(apn.getId()); 8795 } 8796 } 8797 } 8798 8799 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 8800 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner"); 8801 8802 if (admin != null) { 8803 admin.disableCamera = false; 8804 admin.userRestrictions = null; 8805 admin.defaultEnabledRestrictionsAlreadySet.clear(); 8806 admin.forceEphemeralUsers = false; 8807 admin.isNetworkLoggingEnabled = false; 8808 admin.requireAutoTime = false; 8809 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 8810 } 8811 final DevicePolicyData policyData = getUserData(userId); 8812 policyData.mCurrentInputMethodSet = false; 8813 saveSettingsLocked(userId); 8814 mPolicyCache.onUserRemoved(userId); 8815 final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM); 8816 systemPolicyData.mLastSecurityLogRetrievalTime = -1; 8817 systemPolicyData.mLastBugReportRequestTime = -1; 8818 systemPolicyData.mLastNetworkLogsRetrievalTime = -1; 8819 saveSettingsLocked(UserHandle.USER_SYSTEM); 8820 clearUserPoliciesLocked(userId); 8821 clearOverrideApnUnchecked(); 8822 clearApplicationRestrictions(userId); 8823 mInjector.getPackageManagerInternal().clearBlockUninstallForUser(userId); 8824 8825 mOwners.clearDeviceOwner(); 8826 mOwners.writeDeviceOwner(); 8827 8828 clearDeviceOwnerUserRestriction(UserHandle.of(userId)); 8829 mInjector.securityLogSetLoggingEnabledProperty(false); 8830 mSecurityLogMonitor.stop(); 8831 setNetworkLoggingActiveInternal(false); 8832 deleteTransferOwnershipBundleLocked(userId); 8833 toggleBackupServiceActive(UserHandle.USER_SYSTEM, true); 8834 pushUserControlDisabledPackagesLocked(userId); 8835 setGlobalSettingDeviceOwnerType(DEVICE_OWNER_TYPE_DEFAULT); 8836 } 8837 8838 private void clearApplicationRestrictions(int userId) { 8839 // Changing app restrictions involves disk IO, offload it to the background thread. 8840 mBackgroundHandler.post(() -> { 8841 final List<PackageInfo> installedPackageInfos = mInjector.getPackageManager(userId) 8842 .getInstalledPackages(MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE); 8843 final UserHandle userHandle = UserHandle.of(userId); 8844 for (final PackageInfo packageInfo : installedPackageInfos) { 8845 mInjector.getUserManager().setApplicationRestrictions( 8846 packageInfo.packageName, null /* restrictions */, userHandle); 8847 } 8848 }); 8849 } 8850 8851 @Override 8852 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 8853 if (!mHasFeature) { 8854 logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(who) 8855 + " as profile owner for user " + userHandle); 8856 return false; 8857 } 8858 Preconditions.checkArgument(who != null); 8859 8860 final CallerIdentity caller = getCallerIdentity(); 8861 // Cannot be called while holding the lock: 8862 final boolean hasIncompatibleAccountsOrNonAdb = 8863 hasIncompatibleAccountsOrNonAdbNoLock(caller, userHandle, who); 8864 synchronized (getLockObject()) { 8865 enforceCanSetProfileOwnerLocked( 8866 caller, who, userHandle, hasIncompatibleAccountsOrNonAdb); 8867 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 8868 Preconditions.checkArgument( 8869 isPackageInstalledForUser(who.getPackageName(), userHandle) 8870 && admin != null 8871 && !getUserData(userHandle).mRemovingAdmins.contains(who), 8872 "Not active admin: " + who); 8873 8874 final int parentUserId = getProfileParentId(userHandle); 8875 // When trying to set a profile owner on a new user, it may be that this user is 8876 // a profile - but it may not be a managed profile if there's a restriction on the 8877 // parent to add managed profiles (e.g. if the device has a device owner). 8878 if (parentUserId != userHandle && mUserManager.hasUserRestriction( 8879 UserManager.DISALLOW_ADD_MANAGED_PROFILE, 8880 UserHandle.of(parentUserId))) { 8881 Slogf.i(LOG_TAG, "Cannot set profile owner because of restriction."); 8882 return false; 8883 } 8884 8885 if (isAdb(caller)) { 8886 // Log profile owner provisioning was started using adb. 8887 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 8888 DevicePolicyEventLogger 8889 .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB) 8890 .setAdmin(who) 8891 .setStrings(LOG_TAG_PROFILE_OWNER) 8892 .write(); 8893 } 8894 8895 // Shutting down backup manager service permanently. 8896 toggleBackupServiceActive(userHandle, /* makeActive= */ false); 8897 8898 mOwners.setProfileOwner(who, ownerName, userHandle); 8899 mOwners.writeProfileOwner(userHandle); 8900 Slogf.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 8901 8902 mInjector.binderWithCleanCallingIdentity(() -> { 8903 if (mUserManager.isManagedProfile(userHandle)) { 8904 maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin, 8905 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 8906 ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin, 8907 true /* newOwner */); 8908 } 8909 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 8910 userHandle); 8911 }); 8912 mDeviceAdminServiceController.startServiceForOwner( 8913 who.getPackageName(), userHandle, "set-profile-owner"); 8914 return true; 8915 } 8916 } 8917 8918 private void toggleBackupServiceActive(int userId, boolean makeActive) { 8919 long ident = mInjector.binderClearCallingIdentity(); 8920 try { 8921 if (mInjector.getIBackupManager() != null) { 8922 mInjector.getIBackupManager() 8923 .setBackupServiceActive(userId, makeActive); 8924 } 8925 } catch (RemoteException e) { 8926 throw new IllegalStateException(String.format("Failed %s backup service.", 8927 makeActive ? "activating" : "deactivating"), e); 8928 } finally { 8929 mInjector.binderRestoreCallingIdentity(ident); 8930 } 8931 8932 } 8933 8934 @Override 8935 public void clearProfileOwner(ComponentName who) { 8936 if (!mHasFeature) { 8937 return; 8938 } 8939 Objects.requireNonNull(who, "ComponentName is null"); 8940 8941 final CallerIdentity caller = getCallerIdentity(who); 8942 final int userId = caller.getUserId(); 8943 Preconditions.checkCallingUser(!isManagedProfile(userId)); 8944 8945 enforceUserUnlocked(userId); 8946 synchronized (getLockObject()) { 8947 // Check if this is the profile owner who is calling 8948 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 8949 8950 mInjector.binderWithCleanCallingIdentity(() -> { 8951 clearProfileOwnerLocked(admin, userId); 8952 removeActiveAdminLocked(who, userId); 8953 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 8954 userId); 8955 }); 8956 Slogf.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 8957 } 8958 } 8959 8960 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 8961 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner"); 8962 8963 if (admin != null) { 8964 admin.disableCamera = false; 8965 admin.userRestrictions = null; 8966 admin.defaultEnabledRestrictionsAlreadySet.clear(); 8967 } 8968 final DevicePolicyData policyData = getUserData(userId); 8969 policyData.mCurrentInputMethodSet = false; 8970 policyData.mOwnerInstalledCaCerts.clear(); 8971 saveSettingsLocked(userId); 8972 clearUserPoliciesLocked(userId); 8973 clearApplicationRestrictions(userId); 8974 mOwners.removeProfileOwner(userId); 8975 mOwners.writeProfileOwner(userId); 8976 deleteTransferOwnershipBundleLocked(userId); 8977 toggleBackupServiceActive(userId, true); 8978 applyProfileRestrictionsIfDeviceOwnerLocked(); 8979 setNetworkLoggingActiveInternal(false); 8980 } 8981 8982 @Override 8983 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 8984 if (!mHasFeature) { 8985 return; 8986 } 8987 Objects.requireNonNull(who, "ComponentName is null"); 8988 8989 final CallerIdentity caller = getCallerIdentity(who); 8990 Preconditions.checkCallAuthorization( 8991 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 8992 8993 mInjector.binderWithCleanCallingIdentity(() -> 8994 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null)); 8995 8996 DevicePolicyEventLogger 8997 .createEvent(DevicePolicyEnums.SET_DEVICE_OWNER_LOCK_SCREEN_INFO) 8998 .setAdmin(caller.getComponentName()) 8999 .write(); 9000 } 9001 9002 @Override 9003 public CharSequence getDeviceOwnerLockScreenInfo() { 9004 return mLockPatternUtils.getDeviceOwnerInfo(); 9005 } 9006 9007 private void clearUserPoliciesLocked(int userId) { 9008 // Reset some of the user-specific policies. 9009 final DevicePolicyData policy = getUserData(userId); 9010 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 9011 // Clear delegations. 9012 policy.mDelegationMap.clear(); 9013 policy.mStatusBarDisabled = false; 9014 policy.mSecondaryLockscreenEnabled = false; 9015 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 9016 policy.mAffiliationIds.clear(); 9017 policy.mLockTaskPackages.clear(); 9018 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId); 9019 policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE; 9020 saveSettingsLocked(userId); 9021 9022 try { 9023 mIPermissionManager.updatePermissionFlagsForAllApps( 9024 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 9025 0 /* flagValues */, userId); 9026 pushUserRestrictions(userId); 9027 } catch (RemoteException re) { 9028 // Shouldn't happen. 9029 } 9030 } 9031 9032 @Override 9033 public boolean hasUserSetupCompleted() { 9034 return hasUserSetupCompleted(mInjector.userHandleGetCallingUserId()); 9035 } 9036 9037 // This checks only if the Setup Wizard has run. Since Wear devices pair before 9038 // completing Setup Wizard, and pairing involves transferring user data, calling 9039 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). 9040 private boolean hasUserSetupCompleted(int userHandle) { 9041 if (!mHasFeature) { 9042 return true; 9043 } 9044 return mInjector.hasUserSetupCompleted(getUserData(userHandle)); 9045 } 9046 9047 private boolean hasPaired(int userHandle) { 9048 if (!mHasFeature) { 9049 return true; 9050 } 9051 return getUserData(userHandle).mPaired; 9052 } 9053 9054 @Override 9055 public int getUserProvisioningState() { 9056 if (!mHasFeature) { 9057 return DevicePolicyManager.STATE_USER_UNMANAGED; 9058 } 9059 final CallerIdentity caller = getCallerIdentity(); 9060 Preconditions.checkCallAuthorization(canManageUsers(caller) 9061 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 9062 9063 return getUserProvisioningState(caller.getUserId()); 9064 } 9065 9066 private int getUserProvisioningState(int userHandle) { 9067 return getUserData(userHandle).mUserProvisioningState; 9068 } 9069 9070 @Override 9071 public void setUserProvisioningState(int newState, int userId) { 9072 if (!mHasFeature) { 9073 logMissingFeatureAction("Cannot set provisioning state " + newState + " for user " 9074 + userId); 9075 return; 9076 } 9077 9078 Preconditions.checkCallAuthorization( 9079 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 9080 9081 final CallerIdentity caller = getCallerIdentity(); 9082 final long id = mInjector.binderClearCallingIdentity(); 9083 try { 9084 int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 9085 // NOTE: multiple if statements are nested below so it can log more info on error 9086 if (userId != deviceOwnerUserId) { 9087 boolean hasProfileOwner = mOwners.hasProfileOwner(userId); 9088 if (!hasProfileOwner) { 9089 int managedUserId = getManagedUserId(userId); 9090 if (managedUserId == -1 && newState != STATE_USER_UNMANAGED) { 9091 // No managed device, user or profile, so setting provisioning state makes 9092 // no sense. 9093 String error = "Not allowed to change provisioning state unless a " 9094 + "device or profile owner is set."; 9095 Slogf.w(LOG_TAG, "setUserProvisioningState(newState=%d, userId=%d) failed: " 9096 + "deviceOwnerId=%d, hasProfileOwner=%b, managedUserId=%d, err=%s", 9097 newState, userId, deviceOwnerUserId, hasProfileOwner, 9098 managedUserId, error); 9099 throw new IllegalStateException(error); 9100 } 9101 } 9102 } 9103 9104 synchronized (getLockObject()) { 9105 boolean transitionCheckNeeded = true; 9106 9107 // Calling identity/permission checks. 9108 if (isAdb(caller)) { 9109 // ADB shell can only move directly from un-managed to finalized as part of 9110 // directly setting profile-owner or device-owner. 9111 if (getUserProvisioningState(userId) 9112 != DevicePolicyManager.STATE_USER_UNMANAGED 9113 || newState != STATE_USER_SETUP_FINALIZED) { 9114 throw new IllegalStateException("Not allowed to change provisioning state " 9115 + "unless current provisioning state is unmanaged, and new state" 9116 + "is finalized."); 9117 } 9118 transitionCheckNeeded = false; 9119 } 9120 9121 final DevicePolicyData policyData = getUserData(userId); 9122 if (transitionCheckNeeded) { 9123 // Optional state transition check for non-ADB case. 9124 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, 9125 newState); 9126 } 9127 policyData.mUserProvisioningState = newState; 9128 saveSettingsLocked(userId); 9129 } 9130 } finally { 9131 mInjector.binderRestoreCallingIdentity(id); 9132 } 9133 } 9134 9135 private void checkUserProvisioningStateTransition(int currentState, int newState) { 9136 // Valid transitions for normal use-cases. 9137 switch (currentState) { 9138 case DevicePolicyManager.STATE_USER_UNMANAGED: 9139 // Can move to any state from unmanaged (except itself as an edge case).. 9140 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 9141 return; 9142 } 9143 break; 9144 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 9145 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 9146 // Can only move to finalized from these states. 9147 if (newState == STATE_USER_SETUP_FINALIZED) { 9148 return; 9149 } 9150 break; 9151 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 9152 // Current user has a managed-profile, but current user is not managed, so 9153 // rather than moving to finalized state, go back to unmanaged once 9154 // profile provisioning is complete. 9155 if (newState == DevicePolicyManager.STATE_USER_PROFILE_FINALIZED) { 9156 return; 9157 } 9158 break; 9159 case STATE_USER_SETUP_FINALIZED: 9160 // Cannot transition out of finalized. 9161 break; 9162 case DevicePolicyManager.STATE_USER_PROFILE_FINALIZED: 9163 // Should only move to an unmanaged state after removing the work profile. 9164 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 9165 return; 9166 } 9167 break; 9168 } 9169 9170 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 9171 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 9172 + "from state [" + currentState + "]"); 9173 } 9174 9175 @Override 9176 public void setProfileEnabled(ComponentName who) { 9177 if (!mHasFeature) { 9178 logMissingFeatureAction("Cannot enable profile for " 9179 + ComponentName.flattenToShortString(who)); 9180 return; 9181 } 9182 Objects.requireNonNull(who, "ComponentName is null"); 9183 9184 final CallerIdentity caller = getCallerIdentity(who); 9185 final int userId = caller.getUserId(); 9186 Preconditions.checkCallAuthorization( 9187 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 9188 Preconditions.checkCallingUser(isManagedProfile(userId)); 9189 9190 synchronized (getLockObject()) { 9191 // Check if the profile is already enabled. 9192 UserInfo managedProfile = getUserInfo(userId); 9193 if (managedProfile.isEnabled()) { 9194 Slogf.e(LOG_TAG, 9195 "setProfileEnabled is called when the profile is already enabled"); 9196 return; 9197 } 9198 mInjector.binderWithCleanCallingIdentity(() -> { 9199 mUserManager.setUserEnabled(userId); 9200 UserInfo parent = mUserManager.getProfileParent(userId); 9201 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 9202 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 9203 UserHandle parentHandle = new UserHandle(parent.id); 9204 mLocalService.broadcastIntentToManifestReceivers(intent, 9205 parentHandle, /* requiresPermission= */ true); 9206 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 9207 Intent.FLAG_RECEIVER_FOREGROUND); 9208 mContext.sendBroadcastAsUser(intent, parentHandle); 9209 }); 9210 } 9211 } 9212 9213 @Override 9214 public void setProfileName(ComponentName who, String profileName) { 9215 Objects.requireNonNull(who, "ComponentName is null"); 9216 9217 final CallerIdentity caller = getCallerIdentity(who); 9218 Preconditions.checkCallAuthorization( 9219 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 9220 9221 final String truncatedProfileName = 9222 profileName.substring(0, Math.min(profileName.length(), MAX_PROFILE_NAME_LENGTH)); 9223 mInjector.binderWithCleanCallingIdentity(() -> { 9224 mUserManager.setUserName(caller.getUserId(), truncatedProfileName); 9225 DevicePolicyEventLogger 9226 .createEvent(DevicePolicyEnums.SET_PROFILE_NAME) 9227 .setAdmin(caller.getComponentName()) 9228 .write(); 9229 }); 9230 } 9231 9232 @Override 9233 public ComponentName getProfileOwnerAsUser(int userId) { 9234 if (!mHasFeature) { 9235 return null; 9236 } 9237 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 9238 9239 CallerIdentity caller = getCallerIdentity(); 9240 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId) 9241 || hasFullCrossUsersPermission(caller, userId)); 9242 9243 synchronized (getLockObject()) { 9244 return mOwners.getProfileOwnerComponent(userId); 9245 } 9246 } 9247 9248 // Returns the active profile owner for this user or null if the current user has no 9249 // profile owner. 9250 @VisibleForTesting 9251 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 9252 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 9253 if (profileOwner == null) { 9254 return null; 9255 } 9256 DevicePolicyData policy = getUserData(userHandle); 9257 final int n = policy.mAdminList.size(); 9258 for (int i = 0; i < n; i++) { 9259 ActiveAdmin admin = policy.mAdminList.get(i); 9260 if (profileOwner.equals(admin.info.getComponent())) { 9261 return admin; 9262 } 9263 } 9264 return null; 9265 } 9266 9267 /** 9268 * Returns the ActiveAdmin associated with the PO or DO on the given user. 9269 */ 9270 private @Nullable ActiveAdmin getDeviceOrProfileOwnerAdminLocked(int userHandle) { 9271 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 9272 if (admin == null && getDeviceOwnerUserIdUncheckedLocked() == userHandle) { 9273 admin = getDeviceOwnerAdminLocked(); 9274 } 9275 return admin; 9276 } 9277 9278 @GuardedBy("getLockObject()") 9279 ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked(int userHandle) { 9280 return mInjector.binderWithCleanCallingIdentity(() -> { 9281 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 9282 if (userInfo.isManagedProfile()) { 9283 if (getProfileOwnerAsUser(userInfo.id) != null 9284 && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) { 9285 ComponentName who = getProfileOwnerAsUser(userInfo.id); 9286 return getActiveAdminUncheckedLocked(who, userInfo.id); 9287 } 9288 } 9289 } 9290 return null; 9291 }); 9292 } 9293 9294 /** 9295 * This API is cached: invalidate with invalidateBinderCaches(). 9296 */ 9297 @Override 9298 public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent( 9299 @NonNull UserHandle userHandle) { 9300 if (!mHasFeature) { 9301 return null; 9302 } 9303 synchronized (getLockObject()) { 9304 final ComponentName doComponent = mOwners.getDeviceOwnerComponent(); 9305 final ComponentName poComponent = 9306 mOwners.getProfileOwnerComponent(userHandle.getIdentifier()); 9307 // Return test only admin if configured to do so. 9308 // TODO(b/182994391): Replace with more generic solution to override the supervision 9309 // component. 9310 if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) { 9311 if (isAdminTestOnlyLocked(doComponent, userHandle.getIdentifier())) { 9312 return doComponent; 9313 } else if (isAdminTestOnlyLocked(poComponent, userHandle.getIdentifier())) { 9314 return poComponent; 9315 } 9316 } 9317 9318 // Check profile owner first as that is what most likely is set. 9319 if (isSupervisionComponentLocked(poComponent)) { 9320 return poComponent; 9321 } 9322 9323 if (isSupervisionComponentLocked(doComponent)) { 9324 return doComponent; 9325 } 9326 9327 return null; 9328 } 9329 } 9330 9331 /** 9332 * Returns if the specified component is the supervision component. 9333 */ 9334 @Override 9335 public boolean isSupervisionComponent(@NonNull ComponentName who) { 9336 if (!mHasFeature) { 9337 return false; 9338 } 9339 synchronized (getLockObject()) { 9340 if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) { 9341 final CallerIdentity caller = getCallerIdentity(); 9342 if (isAdminTestOnlyLocked(who, caller.getUserId())) { 9343 return true; 9344 } 9345 } 9346 return isSupervisionComponentLocked(who); 9347 } 9348 } 9349 9350 private boolean isSupervisionComponentLocked(@Nullable ComponentName who) { 9351 if (who == null) { 9352 return false; 9353 } 9354 9355 final String configComponent = mContext.getResources().getString( 9356 com.android.internal.R.string.config_defaultSupervisionProfileOwnerComponent); 9357 if (configComponent != null) { 9358 final ComponentName componentName = ComponentName.unflattenFromString(configComponent); 9359 if (who.equals(componentName)) { 9360 return true; 9361 } 9362 } 9363 9364 // Check the system supervision role. 9365 final String configPackage = mContext.getResources().getString( 9366 com.android.internal.R.string.config_systemSupervision); 9367 9368 return who.getPackageName().equals(configPackage); 9369 } 9370 9371 @Override 9372 public String getProfileOwnerName(int userHandle) { 9373 if (!mHasFeature) { 9374 return null; 9375 } 9376 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()) 9377 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 9378 return getProfileOwnerNameUnchecked(userHandle); 9379 } 9380 9381 private String getProfileOwnerNameUnchecked(int userHandle) { 9382 ComponentName profileOwner = getProfileOwnerAsUser(userHandle); 9383 if (profileOwner == null) { 9384 return null; 9385 } 9386 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 9387 } 9388 9389 private @UserIdInt int getOrganizationOwnedProfileUserId() { 9390 for (UserInfo ui : mUserManagerInternal.getUserInfos()) { 9391 if (ui.isManagedProfile() && isProfileOwnerOfOrganizationOwnedDevice(ui.id)) { 9392 return ui.id; 9393 } 9394 } 9395 return UserHandle.USER_NULL; 9396 } 9397 9398 /** 9399 * This API is cached: invalidate with invalidateBinderCaches(). 9400 */ 9401 @Override 9402 public boolean isOrganizationOwnedDeviceWithManagedProfile() { 9403 if (!mHasFeature) { 9404 return false; 9405 } 9406 return getOrganizationOwnedProfileUserId() != UserHandle.USER_NULL; 9407 } 9408 9409 @Override 9410 public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) { 9411 final CallerIdentity caller = getCallerIdentity(); 9412 ensureCallerIdentityMatchesIfNotSystem(packageName, pid, uid, caller); 9413 9414 // Verify that the specified packages matches the provided uid. 9415 if (!doesPackageMatchUid(packageName, uid)) { 9416 return false; 9417 } 9418 // A device or profile owner must also have the READ_PHONE_STATE permission to access device 9419 // identifiers. If the package being checked does not have this permission then deny access. 9420 if (!hasPermission(permission.READ_PHONE_STATE, pid, uid)) { 9421 return false; 9422 } 9423 9424 // Allow access to the device owner or delegate cert installer or profile owner of an 9425 // affiliated user 9426 ComponentName deviceOwner = getDeviceOwnerComponent(true); 9427 if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName) 9428 || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) { 9429 return true; 9430 } 9431 final int userId = UserHandle.getUserId(uid); 9432 // Allow access to the profile owner for the specified user, or delegate cert installer 9433 // But only if this is an organization-owned device. 9434 ComponentName profileOwner = getProfileOwnerAsUser(userId); 9435 final boolean isCallerProfileOwnerOrDelegate = profileOwner != null 9436 && (profileOwner.getPackageName().equals(packageName) 9437 || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL)); 9438 if (isCallerProfileOwnerOrDelegate && (isProfileOwnerOfOrganizationOwnedDevice(userId) 9439 || isUserAffiliatedWithDevice(userId))) { 9440 return true; 9441 } 9442 9443 return false; 9444 } 9445 9446 private boolean doesPackageMatchUid(String packageName, int uid) { 9447 final int userId = UserHandle.getUserId(uid); 9448 try { 9449 ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(packageName, 0, userId); 9450 // Since this call goes directly to PackageManagerService a NameNotFoundException is not 9451 // thrown but null data can be returned; if the appInfo for the specified package cannot 9452 // be found then return false to prevent crashing the app. 9453 if (appInfo == null) { 9454 Slogf.w(LOG_TAG, "appInfo could not be found for package %s", packageName); 9455 return false; 9456 } else if (uid != appInfo.uid) { 9457 String message = String.format("Package %s (uid=%d) does not match provided uid %d", 9458 packageName, appInfo.uid, uid); 9459 Slogf.w(LOG_TAG, message); 9460 throw new SecurityException(message); 9461 } 9462 } catch (RemoteException e) { 9463 // If an exception is caught obtaining the appInfo just return false to prevent crashing 9464 // apps due to an internal error. 9465 Slogf.e(LOG_TAG, e, "Exception caught obtaining appInfo for package %s", packageName); 9466 return false; 9467 } 9468 return true; 9469 } 9470 9471 private void ensureCallerIdentityMatchesIfNotSystem(String packageName, int pid, int uid, 9472 CallerIdentity caller) { 9473 // If the caller is not a system app then it should only be able to check its own device 9474 // identifier access. 9475 int callingUid = caller.getUid(); 9476 int callingPid = mInjector.binderGetCallingPid(); 9477 if (UserHandle.getAppId(callingUid) >= Process.FIRST_APPLICATION_UID 9478 && (callingUid != uid || callingPid != pid)) { 9479 String message = String.format( 9480 "Calling uid %d, pid %d cannot check device identifier access for package %s " 9481 + "(uid=%d, pid=%d)", callingUid, callingPid, packageName, uid, pid); 9482 Slogf.w(LOG_TAG, message); 9483 throw new SecurityException(message); 9484 } 9485 } 9486 9487 /** 9488 * Canonical name for a given package. 9489 */ 9490 private String getApplicationLabel(String packageName, @UserIdInt int userId) { 9491 return mInjector.binderWithCleanCallingIdentity(() -> { 9492 final Context userContext; 9493 try { 9494 UserHandle userHandle = UserHandle.of(userId); 9495 userContext = mContext.createPackageContextAsUser(packageName, /* flags= */ 0, 9496 userHandle); 9497 } catch (PackageManager.NameNotFoundException nnfe) { 9498 Slogf.w(LOG_TAG, nnfe, "%s is not installed for user %d", packageName, userId); 9499 return null; 9500 } 9501 ApplicationInfo appInfo = userContext.getApplicationInfo(); 9502 CharSequence result = null; 9503 if (appInfo != null) { 9504 result = appInfo.loadUnsafeLabel(userContext.getPackageManager()); 9505 } 9506 return result != null ? result.toString() : null; 9507 }); 9508 } 9509 9510 /** 9511 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 9512 * permission. 9513 * The profile owner can only be set before the user setup phase has completed, 9514 * except for: 9515 * - SYSTEM_UID 9516 * - adb unless hasIncompatibleAccountsOrNonAdb is true. 9517 */ 9518 private void enforceCanSetProfileOwnerLocked( 9519 CallerIdentity caller, @Nullable ComponentName owner, int userHandle, 9520 boolean hasIncompatibleAccountsOrNonAdb) { 9521 UserInfo info = getUserInfo(userHandle); 9522 if (info == null) { 9523 // User doesn't exist. 9524 throw new IllegalArgumentException( 9525 "Attempted to set profile owner for invalid userId: " + userHandle); 9526 } 9527 if (info.isGuest()) { 9528 throw new IllegalStateException("Cannot set a profile owner on a guest"); 9529 } 9530 if (mOwners.hasProfileOwner(userHandle)) { 9531 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 9532 + "is already set."); 9533 } 9534 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 9535 throw new IllegalStateException("Trying to set the profile owner, but the user " 9536 + "already has a device owner."); 9537 } 9538 if (isAdb(caller)) { 9539 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 9540 && hasIncompatibleAccountsOrNonAdb) { 9541 throw new IllegalStateException("Not allowed to set the profile owner because " 9542 + "there are already some accounts on the profile"); 9543 } 9544 return; 9545 } 9546 Preconditions.checkCallAuthorization( 9547 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 9548 9549 if ((mIsWatch || hasUserSetupCompleted(userHandle))) { 9550 Preconditions.checkState(isSystemUid(caller), 9551 "Cannot set the profile owner on a user which is already set-up"); 9552 9553 if (!mIsWatch) { 9554 if (!isSupervisionComponentLocked(owner)) { 9555 throw new IllegalStateException("Unable to set non-default profile owner" 9556 + " post-setup " + owner); 9557 } 9558 } 9559 } 9560 } 9561 9562 /** 9563 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 9564 * permission. 9565 */ 9566 private void enforceCanSetDeviceOwnerLocked( 9567 CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int deviceOwnerUserId, 9568 boolean hasIncompatibleAccountsOrNonAdb) { 9569 if (!isAdb(caller)) { 9570 Preconditions.checkCallAuthorization( 9571 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 9572 } 9573 9574 final int code = checkDeviceOwnerProvisioningPreConditionLocked(owner, 9575 /* deviceOwnerUserId= */ deviceOwnerUserId, /* callingUserId*/ caller.getUserId(), 9576 isAdb(caller), hasIncompatibleAccountsOrNonAdb); 9577 if (code != STATUS_OK) { 9578 throw new IllegalStateException( 9579 computeProvisioningErrorString(code, deviceOwnerUserId)); 9580 } 9581 } 9582 9583 private static String computeProvisioningErrorString(int code, @UserIdInt int userId) { 9584 switch (code) { 9585 case STATUS_OK: 9586 return "OK"; 9587 case STATUS_HAS_DEVICE_OWNER: 9588 return "Trying to set the device owner, but device owner is already set."; 9589 case STATUS_USER_HAS_PROFILE_OWNER: 9590 return "Trying to set the device owner, but the user already has a profile owner."; 9591 case STATUS_USER_NOT_RUNNING: 9592 return "User " + userId + " not running."; 9593 case STATUS_NOT_SYSTEM_USER: 9594 return "User " + userId + " is not system user."; 9595 case STATUS_USER_SETUP_COMPLETED: 9596 return "Cannot set the device owner if the device is already set-up."; 9597 case STATUS_NONSYSTEM_USER_EXISTS: 9598 return "Not allowed to set the device owner because there are already several" 9599 + " users on the device."; 9600 case STATUS_ACCOUNTS_NOT_EMPTY: 9601 return "Not allowed to set the device owner because there are already some accounts" 9602 + " on the device."; 9603 case STATUS_HAS_PAIRED: 9604 return "Not allowed to set the device owner because this device has already " 9605 + "paired."; 9606 default: 9607 return "Unexpected @ProvisioningPreCondition: " + code; 9608 } 9609 9610 } 9611 9612 private void enforceUserUnlocked(int userId) { 9613 // Since we're doing this operation on behalf of an app, we only 9614 // want to use the actual "unlocked" state. 9615 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 9616 "User must be running and unlocked"); 9617 } 9618 9619 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 9620 if (parent) { 9621 enforceUserUnlocked(getProfileParentId(userId)); 9622 } else { 9623 enforceUserUnlocked(userId); 9624 } 9625 } 9626 9627 private boolean canManageUsers(CallerIdentity caller) { 9628 return hasCallingOrSelfPermission(permission.MANAGE_USERS); 9629 } 9630 9631 private boolean canQueryAdminPolicy(CallerIdentity caller) { 9632 return hasCallingOrSelfPermission(permission.QUERY_ADMIN_POLICY); 9633 } 9634 9635 private boolean hasPermission(String permission, int pid, int uid) { 9636 return mContext.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED; 9637 } 9638 9639 private boolean hasCallingPermission(String permission) { 9640 return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED; 9641 } 9642 9643 private boolean hasCallingOrSelfPermission(String permission) { 9644 return mContext.checkCallingOrSelfPermission(permission) 9645 == PackageManager.PERMISSION_GRANTED; 9646 } 9647 9648 private boolean hasPermissionForPreflight(CallerIdentity caller, String permission) { 9649 final int callingPid = mInjector.binderGetCallingPid(); 9650 final String packageName = mContext.getPackageName(); 9651 9652 return PermissionChecker.checkPermissionForPreflight(mContext, permission, callingPid, 9653 caller.getUid(), packageName) == PermissionChecker.PERMISSION_GRANTED; 9654 } 9655 9656 private boolean hasFullCrossUsersPermission(CallerIdentity caller, int userHandle) { 9657 return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller) 9658 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL); 9659 } 9660 9661 private boolean hasCrossUsersPermission(CallerIdentity caller, int userHandle) { 9662 return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller) 9663 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS); 9664 } 9665 9666 private boolean canUserUseLockTaskLocked(int userId) { 9667 if (isUserAffiliatedWithDeviceLocked(userId)) { 9668 return true; 9669 } 9670 9671 // Unaffiliated profile owners are not allowed to use lock when there is a device owner. 9672 if (mOwners.hasDeviceOwner()) { 9673 return false; 9674 } 9675 9676 final ComponentName profileOwner = getProfileOwnerAsUser(userId); 9677 if (profileOwner == null) { 9678 return false; 9679 } 9680 9681 // Managed profiles are not allowed to use lock task 9682 if (isManagedProfile(userId)) { 9683 return false; 9684 } 9685 9686 return true; 9687 } 9688 9689 private void enforceCanCallLockTaskLocked(CallerIdentity caller) { 9690 Preconditions.checkCallAuthorization(isProfileOwner(caller) 9691 || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller)); 9692 9693 final int userId = caller.getUserId(); 9694 if (!canUserUseLockTaskLocked(userId)) { 9695 throw new SecurityException("User " + userId + " is not allowed to use lock task"); 9696 } 9697 } 9698 9699 private boolean isSystemUid(CallerIdentity caller) { 9700 return UserHandle.isSameApp(caller.getUid(), Process.SYSTEM_UID); 9701 } 9702 9703 private boolean isRootUid(CallerIdentity caller) { 9704 return UserHandle.isSameApp(caller.getUid(), Process.ROOT_UID); 9705 } 9706 9707 private boolean isShellUid(CallerIdentity caller) { 9708 return UserHandle.isSameApp(caller.getUid(), Process.SHELL_UID); 9709 } 9710 9711 private boolean isCameraServerUid(CallerIdentity caller) { 9712 return UserHandle.isSameApp(caller.getUid(), Process.CAMERASERVER_UID); 9713 } 9714 9715 private @UserIdInt int getCurrentForegroundUserId() { 9716 try { 9717 UserInfo currentUser = mInjector.getIActivityManager().getCurrentUser(); 9718 if (currentUser == null) { 9719 // TODO(b/206107460): should not happen on production, but it's happening on unit 9720 // tests that are not properly setting the expectation (because they don't need it) 9721 Slogf.wtf(LOG_TAG, "getCurrentForegroundUserId(): mInjector.getIActivityManager()" 9722 + ".getCurrentUser() returned null, please ignore when running unit tests"); 9723 return ActivityManager.getCurrentUser(); 9724 } 9725 return currentUser.id; 9726 } catch (RemoteException e) { 9727 Slogf.wtf(LOG_TAG, "cannot get current user"); 9728 } 9729 return UserHandle.USER_NULL; 9730 } 9731 9732 @Override 9733 public List<UserHandle> listForegroundAffiliatedUsers() { 9734 checkIsDeviceOwner(getCallerIdentity()); 9735 9736 return mInjector.binderWithCleanCallingIdentity(() -> { 9737 int userId = getCurrentForegroundUserId(); 9738 boolean isAffiliated; 9739 synchronized (getLockObject()) { 9740 isAffiliated = isUserAffiliatedWithDeviceLocked(userId); 9741 } 9742 9743 if (!isAffiliated) return Collections.emptyList(); 9744 9745 List<UserHandle> users = new ArrayList<>(1); 9746 users.add(UserHandle.of(userId)); 9747 9748 return users; 9749 }); 9750 } 9751 9752 protected int getProfileParentId(int userHandle) { 9753 return mInjector.binderWithCleanCallingIdentity(() -> { 9754 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 9755 return parentUser != null ? parentUser.id : userHandle; 9756 }); 9757 } 9758 9759 private int getProfileParentUserIfRequested(int userHandle, boolean parent) { 9760 if (parent) { 9761 return getProfileParentId(userHandle); 9762 } 9763 9764 return userHandle; 9765 } 9766 9767 private int getCredentialOwner(final int userHandle, final boolean parent) { 9768 return mInjector.binderWithCleanCallingIdentity(() -> { 9769 int effectiveUserHandle = userHandle; 9770 if (parent) { 9771 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 9772 if (parentProfile != null) { 9773 effectiveUserHandle = parentProfile.id; 9774 } 9775 } 9776 return mUserManager.getCredentialOwnerProfile(effectiveUserHandle); 9777 }); 9778 } 9779 9780 private boolean isManagedProfile(int userHandle) { 9781 final UserInfo user = getUserInfo(userHandle); 9782 return user != null && user.isManagedProfile(); 9783 } 9784 9785 private void enableIfNecessary(String packageName, int userId) { 9786 try { 9787 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 9788 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId); 9789 if (ai.enabledSetting 9790 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 9791 mIPackageManager.setApplicationEnabledSetting(packageName, 9792 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 9793 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 9794 } 9795 } catch (RemoteException e) { 9796 } 9797 } 9798 9799 private void dumpPerUserData(IndentingPrintWriter pw) { 9800 int userCount = mUserData.size(); 9801 for (int i = 0; i < userCount; i++) { 9802 int userId = mUserData.keyAt(i); 9803 DevicePolicyData policy = getUserData(userId); 9804 policy.dump(pw); 9805 pw.println(); 9806 9807 if (userId == UserHandle.USER_SYSTEM) { 9808 pw.increaseIndent(); 9809 PersonalAppsSuspensionHelper.forUser(mContext, userId).dump(pw); 9810 pw.decreaseIndent(); 9811 pw.println(); 9812 } else { 9813 // pm.getUnsuspendablePackages() will fail if it's called for a different user; 9814 // as this dump is mostly useful for system user anyways, we can just ignore the 9815 // others (rather than changing the permission check in the PM method) 9816 Slogf.d(LOG_TAG, "skipping PersonalAppsSuspensionHelper.dump() for user " + userId); 9817 } 9818 } 9819 } 9820 9821 @Override 9822 protected void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) { 9823 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, printWriter)) return; 9824 9825 try (IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, " ")) { 9826 pw.println("Current Device Policy Manager state:"); 9827 pw.increaseIndent(); 9828 9829 dumpImmutableState(pw); 9830 synchronized (getLockObject()) { 9831 mOwners.dump(pw); 9832 pw.println(); 9833 mDeviceAdminServiceController.dump(pw); 9834 pw.println(); 9835 dumpPerUserData(pw); 9836 pw.println(); 9837 mConstants.dump(pw); 9838 pw.println(); 9839 mStatLogger.dump(pw); 9840 pw.println(); 9841 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 9842 pw.println("Logout user: " + getLogoutUserIdUnchecked()); 9843 pw.println(); 9844 9845 if (mPendingUserCreatedCallbackTokens.isEmpty()) { 9846 pw.println("no pending user created callback tokens"); 9847 } else { 9848 int size = mPendingUserCreatedCallbackTokens.size(); 9849 pw.printf("%d pending user created callback token%s\n", size, 9850 (size == 1 ? "" : "s")); 9851 } 9852 pw.println(); 9853 9854 mPolicyCache.dump(pw); 9855 pw.println(); 9856 mStateCache.dump(pw); 9857 pw.println(); 9858 } 9859 mHandler.post(() -> handleDump(pw)); 9860 dumpResources(pw); 9861 } 9862 } 9863 9864 // Dump state that is guarded by the handler 9865 private void handleDump(IndentingPrintWriter pw) { 9866 if (mNetworkLoggingNotificationUserId != UserHandle.USER_NULL) { 9867 pw.println("mNetworkLoggingNotificationUserId: " + mNetworkLoggingNotificationUserId); 9868 } 9869 } 9870 9871 private void dumpImmutableState(IndentingPrintWriter pw) { 9872 pw.println("Immutable state:"); 9873 pw.increaseIndent(); 9874 pw.printf("mHasFeature=%b\n", mHasFeature); 9875 pw.printf("mIsWatch=%b\n", mIsWatch); 9876 pw.printf("mIsAutomotive=%b\n", mIsAutomotive); 9877 pw.printf("mHasTelephonyFeature=%b\n", mHasTelephonyFeature); 9878 pw.printf("mSafetyChecker=%s\n", mSafetyChecker); 9879 pw.decreaseIndent(); 9880 } 9881 9882 private void dumpResources(IndentingPrintWriter pw) { 9883 mOverlayPackagesProvider.dump(pw); 9884 pw.println(); 9885 9886 pw.println("Other overlayable app resources"); 9887 pw.increaseIndent(); 9888 dumpResources(pw, mContext, "cross_profile_apps", R.array.cross_profile_apps); 9889 dumpResources(pw, mContext, "vendor_cross_profile_apps", R.array.vendor_cross_profile_apps); 9890 dumpResources(pw, mContext, "config_packagesExemptFromSuspension", 9891 R.array.config_packagesExemptFromSuspension); 9892 dumpResources(pw, mContext, "policy_exempt_apps", R.array.policy_exempt_apps); 9893 dumpResources(pw, mContext, "vendor_policy_exempt_apps", R.array.vendor_policy_exempt_apps); 9894 pw.decreaseIndent(); 9895 pw.println(); 9896 } 9897 9898 static void dumpResources(IndentingPrintWriter pw, Context context, String resName, int resId) { 9899 dumpApps(pw, resName, context.getResources().getStringArray(resId)); 9900 } 9901 9902 static void dumpApps(IndentingPrintWriter pw, String name, String[] apps) { 9903 dumpApps(pw, name, Arrays.asList(apps)); 9904 } 9905 9906 static void dumpApps(IndentingPrintWriter pw, String name, List apps) { 9907 if (apps == null || apps.isEmpty()) { 9908 pw.printf("%s: empty\n", name); 9909 return; 9910 } 9911 int size = apps.size(); 9912 pw.printf("%s: %d app%s\n", name, size, size == 1 ? "" : "s"); 9913 pw.increaseIndent(); 9914 for (int i = 0; i < size; i++) { 9915 pw.printf("%d: %s\n", i, apps.get(i)); 9916 } 9917 pw.decreaseIndent(); 9918 } 9919 9920 @Override 9921 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 9922 String[] args, ShellCallback callback, ResultReceiver resultReceiver) { 9923 new DevicePolicyManagerServiceShellCommand(DevicePolicyManagerService.this).exec( 9924 this, in, out, err, args, callback, resultReceiver); 9925 9926 } 9927 9928 private String getEncryptionStatusName(int encryptionStatus) { 9929 switch (encryptionStatus) { 9930 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 9931 return "inactive"; 9932 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 9933 return "block default key"; 9934 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 9935 return "block"; 9936 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 9937 return "per-user"; 9938 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 9939 return "unsupported"; 9940 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 9941 return "activating"; 9942 default: 9943 return "unknown"; 9944 } 9945 } 9946 9947 @Override 9948 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 9949 ComponentName activity) { 9950 Objects.requireNonNull(who, "ComponentName is null"); 9951 final CallerIdentity caller = getCallerIdentity(who); 9952 Preconditions.checkCallAuthorization(isProfileOwner(caller) 9953 || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller)); 9954 9955 final int userHandle = caller.getUserId(); 9956 synchronized (getLockObject()) { 9957 long id = mInjector.binderClearCallingIdentity(); 9958 try { 9959 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 9960 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 9961 } catch (RemoteException re) { 9962 // Shouldn't happen 9963 } finally { 9964 mInjector.binderRestoreCallingIdentity(id); 9965 } 9966 } 9967 final String activityPackage = 9968 (activity != null ? activity.getPackageName() : null); 9969 DevicePolicyEventLogger 9970 .createEvent(DevicePolicyEnums.ADD_PERSISTENT_PREFERRED_ACTIVITY) 9971 .setAdmin(who) 9972 .setStrings(activityPackage, getIntentFilterActions(filter)) 9973 .write(); 9974 } 9975 9976 @Override 9977 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 9978 Objects.requireNonNull(who, "ComponentName is null"); 9979 final CallerIdentity caller = getCallerIdentity(who); 9980 Preconditions.checkCallAuthorization(isProfileOwner(caller) 9981 || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller)); 9982 9983 final int userHandle = caller.getUserId(); 9984 synchronized (getLockObject()) { 9985 long id = mInjector.binderClearCallingIdentity(); 9986 try { 9987 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 9988 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 9989 } catch (RemoteException re) { 9990 // Shouldn't happen 9991 } finally { 9992 mInjector.binderRestoreCallingIdentity(id); 9993 } 9994 } 9995 } 9996 9997 @Override 9998 public void setDefaultSmsApplication(ComponentName admin, String packageName, boolean parent) { 9999 Objects.requireNonNull(admin, "ComponentName is null"); 10000 10001 final CallerIdentity caller = getCallerIdentity(admin); 10002 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 10003 || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller))); 10004 if (parent) { 10005 mInjector.binderWithCleanCallingIdentity(() -> enforcePackageIsSystemPackage( 10006 packageName, getProfileParentId(mInjector.userHandleGetCallingUserId()))); 10007 } 10008 10009 mInjector.binderWithCleanCallingIdentity(() -> 10010 SmsApplication.setDefaultApplication(packageName, mContext)); 10011 } 10012 10013 @Override 10014 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 10015 String packageName) { 10016 try { 10017 setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS); 10018 } catch (IllegalArgumentException e) { 10019 return false; 10020 } 10021 return true; 10022 } 10023 10024 @Override 10025 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 10026 final List<String> delegatePackages = getDelegatePackages(admin, 10027 DELEGATION_APP_RESTRICTIONS); 10028 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 10029 } 10030 10031 @Override 10032 public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) { 10033 return isCallerDelegate(callerPackage, getCallerIdentity().getUid(), 10034 DELEGATION_APP_RESTRICTIONS); 10035 } 10036 10037 @Override 10038 public void setApplicationRestrictions(ComponentName who, String callerPackage, 10039 String packageName, Bundle settings) { 10040 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 10041 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 10042 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 10043 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS))); 10044 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_RESTRICTIONS); 10045 10046 mInjector.binderWithCleanCallingIdentity(() -> { 10047 mUserManager.setApplicationRestrictions(packageName, settings, 10048 caller.getUserHandle()); 10049 DevicePolicyEventLogger 10050 .createEvent(DevicePolicyEnums.SET_APPLICATION_RESTRICTIONS) 10051 .setAdmin(caller.getPackageName()) 10052 .setBoolean(/* isDelegate */ who == null) 10053 .setStrings(packageName) 10054 .write(); 10055 }); 10056 } 10057 10058 @Override 10059 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 10060 PersistableBundle args, boolean parent) { 10061 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 10062 return; 10063 } 10064 Objects.requireNonNull(admin, "admin is null"); 10065 Objects.requireNonNull(agent, "agent is null"); 10066 enforceMaxPackageNameLength(agent.getPackageName()); 10067 final String agentAsString = agent.flattenToString(); 10068 enforceMaxStringLength(agentAsString, "agent name"); 10069 if (args != null) { 10070 enforceMaxStringLength(args, "args"); 10071 } 10072 final int userHandle = UserHandle.getCallingUserId(); 10073 synchronized (getLockObject()) { 10074 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 10075 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 10076 checkCanExecuteOrThrowUnsafe( 10077 DevicePolicyManager.OPERATION_SET_TRUST_AGENT_CONFIGURATION); 10078 10079 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 10080 saveSettingsLocked(userHandle); 10081 } 10082 } 10083 10084 @Override 10085 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 10086 ComponentName agent, int userHandle, boolean parent) { 10087 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 10088 return null; 10089 } 10090 Objects.requireNonNull(agent, "agent null"); 10091 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 10092 10093 final CallerIdentity caller = getCallerIdentity(admin); 10094 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 10095 10096 synchronized (getLockObject()) { 10097 final String componentName = agent.flattenToString(); 10098 if (admin != null) { 10099 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 10100 if (ap == null) return null; 10101 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 10102 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 10103 List<PersistableBundle> result = new ArrayList<>(); 10104 result.add(trustAgentInfo.options); 10105 return result; 10106 } 10107 10108 // Return strictest policy for this user and profiles that are visible from this user. 10109 List<PersistableBundle> result = null; 10110 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 10111 // of the options. If any admin doesn't have options, discard options for the rest 10112 // and return null. 10113 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 10114 getProfileParentUserIfRequested(userHandle, parent)); 10115 boolean allAdminsHaveOptions = true; 10116 final int N = admins.size(); 10117 for (int i = 0; i < N; i++) { 10118 final ActiveAdmin active = admins.get(i); 10119 10120 final boolean disablesTrust = (active.disabledKeyguardFeatures 10121 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 10122 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 10123 if (info != null && info.options != null && !info.options.isEmpty()) { 10124 if (disablesTrust) { 10125 if (result == null) { 10126 result = new ArrayList<>(); 10127 } 10128 result.add(info.options); 10129 } else { 10130 Slogf.w(LOG_TAG, "Ignoring admin %s because it has trust options but " 10131 + "doesn't declare KEYGUARD_DISABLE_TRUST_AGENTS", active.info); 10132 } 10133 } else if (disablesTrust) { 10134 allAdminsHaveOptions = false; 10135 break; 10136 } 10137 } 10138 return allAdminsHaveOptions ? result : null; 10139 } 10140 } 10141 10142 @Override 10143 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 10144 Objects.requireNonNull(who, "ComponentName is null"); 10145 final CallerIdentity caller = getCallerIdentity(who); 10146 Preconditions.checkCallAuthorization( 10147 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 10148 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_RESTRICTIONS_PROVIDER); 10149 10150 synchronized (getLockObject()) { 10151 int userHandle = caller.getUserId(); 10152 DevicePolicyData userData = getUserData(userHandle); 10153 userData.mRestrictionsProvider = permissionProvider; 10154 saveSettingsLocked(userHandle); 10155 } 10156 } 10157 10158 @Override 10159 public ComponentName getRestrictionsProvider(int userHandle) { 10160 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 10161 String.format(NOT_SYSTEM_CALLER_MSG, "query the permission provider")); 10162 synchronized (getLockObject()) { 10163 DevicePolicyData userData = getUserData(userHandle); 10164 return userData != null ? userData.mRestrictionsProvider : null; 10165 } 10166 } 10167 10168 @Override 10169 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 10170 Objects.requireNonNull(who, "ComponentName is null"); 10171 final CallerIdentity caller = getCallerIdentity(who); 10172 Preconditions.checkCallAuthorization( 10173 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 10174 int callingUserId = caller.getUserId(); 10175 synchronized (getLockObject()) { 10176 long id = mInjector.binderClearCallingIdentity(); 10177 try { 10178 UserInfo parent = mUserManager.getProfileParent(callingUserId); 10179 if (parent == null) { 10180 Slogf.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 10181 + "parent"); 10182 return; 10183 } 10184 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 10185 mIPackageManager.addCrossProfileIntentFilter( 10186 filter, who.getPackageName(), callingUserId, parent.id, 0); 10187 } 10188 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 10189 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 10190 parent.id, callingUserId, 0); 10191 } 10192 } catch (RemoteException re) { 10193 // Shouldn't happen 10194 } finally { 10195 mInjector.binderRestoreCallingIdentity(id); 10196 } 10197 } 10198 DevicePolicyEventLogger 10199 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_INTENT_FILTER) 10200 .setAdmin(who) 10201 .setStrings(getIntentFilterActions(filter)) 10202 .setInt(flags) 10203 .write(); 10204 } 10205 10206 private static String[] getIntentFilterActions(IntentFilter filter) { 10207 if (filter == null) { 10208 return null; 10209 } 10210 final int actionsCount = filter.countActions(); 10211 final String[] actions = new String[actionsCount]; 10212 for (int i = 0; i < actionsCount; i++) { 10213 actions[i] = filter.getAction(i); 10214 } 10215 return actions; 10216 } 10217 10218 @Override 10219 public void clearCrossProfileIntentFilters(ComponentName who) { 10220 Objects.requireNonNull(who, "ComponentName is null"); 10221 final CallerIdentity caller = getCallerIdentity(who); 10222 Preconditions.checkCallAuthorization( 10223 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 10224 10225 int callingUserId = caller.getUserId(); 10226 synchronized (getLockObject()) { 10227 long id = mInjector.binderClearCallingIdentity(); 10228 try { 10229 UserInfo parent = mUserManager.getProfileParent(callingUserId); 10230 if (parent == null) { 10231 Slogf.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 10232 + "parent"); 10233 return; 10234 } 10235 // Removing those that go from the managed profile to the parent. 10236 mIPackageManager.clearCrossProfileIntentFilters( 10237 callingUserId, who.getPackageName()); 10238 // And those that go from the parent to the managed profile. 10239 // If we want to support multiple managed profiles, we will have to only remove 10240 // those that have callingUserId as their target. 10241 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 10242 } catch (RemoteException re) { 10243 // Shouldn't happen 10244 } finally { 10245 mInjector.binderRestoreCallingIdentity(id); 10246 } 10247 } 10248 } 10249 10250 /** 10251 * @return true if all packages in enabledPackages are either in the list 10252 * permittedList or are a system app. 10253 */ 10254 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 10255 List<String> permittedList, int userIdToCheck) { 10256 long id = mInjector.binderClearCallingIdentity(); 10257 try { 10258 // If we have an enabled packages list for a managed profile the packages 10259 // we should check are installed for the parent user. 10260 UserInfo user = getUserInfo(userIdToCheck); 10261 if (user.isManagedProfile()) { 10262 userIdToCheck = user.profileGroupId; 10263 } 10264 10265 for (String enabledPackage : enabledPackages) { 10266 boolean systemService = false; 10267 try { 10268 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 10269 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 10270 userIdToCheck); 10271 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10272 } catch (RemoteException e) { 10273 Slogf.i(LOG_TAG, "Can't talk to package managed", e); 10274 } 10275 if (!systemService && !permittedList.contains(enabledPackage)) { 10276 return false; 10277 } 10278 } 10279 } finally { 10280 mInjector.binderRestoreCallingIdentity(id); 10281 } 10282 return true; 10283 } 10284 10285 /** 10286 * Invoke a method in AccessibilityManager ensuring the client is removed. 10287 */ 10288 private <T> T withAccessibilityManager( 10289 int userId, Function<AccessibilityManager, T> function) { 10290 // Not using AccessibilityManager.getInstance because that guesses 10291 // at the user you require based on callingUid and caches for a given 10292 // process. 10293 final IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 10294 final IAccessibilityManager service = iBinder == null 10295 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 10296 final AccessibilityManager am = new AccessibilityManager(mContext, service, userId); 10297 try { 10298 return function.apply(am); 10299 } finally { 10300 am.removeClient(); 10301 } 10302 } 10303 10304 @Override 10305 public boolean setPermittedAccessibilityServices(ComponentName who, List<String> packageList) { 10306 if (!mHasFeature) { 10307 return false; 10308 } 10309 Objects.requireNonNull(who, "ComponentName is null"); 10310 final CallerIdentity caller = getCallerIdentity(who); 10311 10312 if (packageList != null) { 10313 for (String pkg : packageList) { 10314 enforceMaxPackageNameLength(pkg); 10315 } 10316 10317 int userId = caller.getUserId(); 10318 final List<AccessibilityServiceInfo> enabledServices; 10319 long id = mInjector.binderClearCallingIdentity(); 10320 try { 10321 UserInfo user = getUserInfo(userId); 10322 if (user.isManagedProfile()) { 10323 userId = user.profileGroupId; 10324 } 10325 enabledServices = withAccessibilityManager(userId, 10326 am -> am.getEnabledAccessibilityServiceList(FEEDBACK_ALL_MASK)); 10327 } finally { 10328 mInjector.binderRestoreCallingIdentity(id); 10329 } 10330 10331 if (enabledServices != null) { 10332 List<String> enabledPackages = new ArrayList<>(); 10333 for (AccessibilityServiceInfo service : enabledServices) { 10334 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 10335 } 10336 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 10337 userId)) { 10338 Slogf.e(LOG_TAG, "Cannot set permitted accessibility services, " 10339 + "because it contains already enabled accesibility services."); 10340 return false; 10341 } 10342 } 10343 } 10344 10345 synchronized (getLockObject()) { 10346 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 10347 admin.permittedAccessiblityServices = packageList; 10348 saveSettingsLocked(UserHandle.getCallingUserId()); 10349 } 10350 final String[] packageArray = 10351 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null; 10352 DevicePolicyEventLogger 10353 .createEvent(DevicePolicyEnums.SET_PERMITTED_ACCESSIBILITY_SERVICES) 10354 .setAdmin(who) 10355 .setStrings(packageArray) 10356 .write(); 10357 return true; 10358 } 10359 10360 @Override 10361 public List<String> getPermittedAccessibilityServices(ComponentName who) { 10362 if (!mHasFeature) { 10363 return null; 10364 } 10365 Objects.requireNonNull(who, "ComponentName is null"); 10366 final CallerIdentity caller = getCallerIdentity(who); 10367 Preconditions.checkCallAuthorization( 10368 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 10369 10370 synchronized (getLockObject()) { 10371 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 10372 return admin.permittedAccessiblityServices; 10373 } 10374 } 10375 10376 @Override 10377 public List<String> getPermittedAccessibilityServicesForUser(int userId) { 10378 if (!mHasFeature) { 10379 return null; 10380 } 10381 final CallerIdentity caller = getCallerIdentity(); 10382 Preconditions.checkCallAuthorization(canManageUsers(caller) || canQueryAdminPolicy(caller)); 10383 10384 synchronized (getLockObject()) { 10385 List<String> result = null; 10386 // If we have multiple profiles we return the intersection of the 10387 // permitted lists. This can happen in cases where we have a device 10388 // and profile owner. 10389 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 10390 for (int profileId : profileIds) { 10391 // Just loop though all admins, only device or profiles 10392 // owners can have permitted lists set. 10393 DevicePolicyData policy = getUserDataUnchecked(profileId); 10394 final int N = policy.mAdminList.size(); 10395 for (int j = 0; j < N; j++) { 10396 ActiveAdmin admin = policy.mAdminList.get(j); 10397 List<String> fromAdmin = admin.permittedAccessiblityServices; 10398 if (fromAdmin != null) { 10399 if (result == null) { 10400 result = new ArrayList<>(fromAdmin); 10401 } else { 10402 result.retainAll(fromAdmin); 10403 } 10404 } 10405 } 10406 } 10407 10408 // If we have a permitted list add all system accessibility services. 10409 if (result != null) { 10410 long id = mInjector.binderClearCallingIdentity(); 10411 try { 10412 UserInfo user = getUserInfo(userId); 10413 if (user.isManagedProfile()) { 10414 userId = user.profileGroupId; 10415 } 10416 final List<AccessibilityServiceInfo> installedServices = 10417 withAccessibilityManager(userId, 10418 AccessibilityManager::getInstalledAccessibilityServiceList); 10419 10420 if (installedServices != null) { 10421 for (AccessibilityServiceInfo service : installedServices) { 10422 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 10423 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 10424 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10425 result.add(serviceInfo.packageName); 10426 } 10427 } 10428 } 10429 } finally { 10430 mInjector.binderRestoreCallingIdentity(id); 10431 } 10432 } 10433 10434 return result; 10435 } 10436 } 10437 10438 @Override 10439 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 10440 int userHandle) { 10441 if (!mHasFeature) { 10442 return true; 10443 } 10444 Objects.requireNonNull(who, "ComponentName is null"); 10445 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 10446 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 10447 String.format(NOT_SYSTEM_CALLER_MSG, 10448 "query if an accessibility service is disabled by admin")); 10449 10450 synchronized (getLockObject()) { 10451 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 10452 if (admin == null) { 10453 return false; 10454 } 10455 if (admin.permittedAccessiblityServices == null) { 10456 return true; 10457 } 10458 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 10459 admin.permittedAccessiblityServices, userHandle); 10460 } 10461 } 10462 10463 @Override 10464 public boolean setPermittedInputMethods(ComponentName who, List<String> packageList, 10465 boolean calledOnParentInstance) { 10466 if (!mHasFeature) { 10467 return false; 10468 } 10469 Objects.requireNonNull(who, "ComponentName is null"); 10470 10471 final CallerIdentity caller = getCallerIdentity(who); 10472 final int userId = getProfileParentUserIfRequested( 10473 caller.getUserId(), calledOnParentInstance); 10474 if (calledOnParentInstance) { 10475 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 10476 Preconditions.checkArgument(packageList == null || packageList.isEmpty(), 10477 "Permitted input methods must allow all input methods or only " 10478 + "system input methods when called on the parent instance of an " 10479 + "organization-owned device"); 10480 } else { 10481 Preconditions.checkCallAuthorization( 10482 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 10483 } 10484 10485 if (packageList != null) { 10486 for (String pkg : packageList) { 10487 enforceMaxPackageNameLength(pkg); 10488 } 10489 10490 List<InputMethodInfo> enabledImes = mInjector.binderWithCleanCallingIdentity(() -> 10491 InputMethodManagerInternal.get().getEnabledInputMethodListAsUser(userId)); 10492 if (enabledImes != null) { 10493 List<String> enabledPackages = new ArrayList<String>(); 10494 for (InputMethodInfo ime : enabledImes) { 10495 enabledPackages.add(ime.getPackageName()); 10496 } 10497 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 10498 userId)) { 10499 Slogf.e(LOG_TAG, "Cannot set permitted input methods, because the list of " 10500 + "permitted input methods excludes an already-enabled input method."); 10501 return false; 10502 } 10503 } 10504 } 10505 10506 synchronized (getLockObject()) { 10507 final ActiveAdmin admin = getParentOfAdminIfRequired( 10508 getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParentInstance); 10509 admin.permittedInputMethods = packageList; 10510 saveSettingsLocked(caller.getUserId()); 10511 } 10512 10513 DevicePolicyEventLogger 10514 .createEvent(DevicePolicyEnums.SET_PERMITTED_INPUT_METHODS) 10515 .setAdmin(who) 10516 .setStrings(getStringArrayForLogging(packageList, calledOnParentInstance)) 10517 .write(); 10518 return true; 10519 } 10520 10521 private String[] getStringArrayForLogging(List list, boolean calledOnParentInstance) { 10522 List<String> stringList = new ArrayList<String>(); 10523 stringList.add(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT); 10524 if (list == null) { 10525 stringList.add(NULL_STRING_ARRAY); 10526 } else { 10527 stringList.addAll((List<String>) list); 10528 } 10529 return stringList.toArray(new String[0]); 10530 } 10531 10532 @Override 10533 public List<String> getPermittedInputMethods(ComponentName who, 10534 boolean calledOnParentInstance) { 10535 if (!mHasFeature) { 10536 return null; 10537 } 10538 Objects.requireNonNull(who, "ComponentName is null"); 10539 10540 final CallerIdentity caller = getCallerIdentity(who); 10541 if (calledOnParentInstance) { 10542 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 10543 } else { 10544 Preconditions.checkCallAuthorization( 10545 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 10546 } 10547 10548 synchronized (getLockObject()) { 10549 final ActiveAdmin admin = getParentOfAdminIfRequired( 10550 getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParentInstance); 10551 return admin.permittedInputMethods; 10552 } 10553 } 10554 10555 @Override 10556 public @Nullable List<String> getPermittedInputMethodsAsUser(@UserIdInt int userId) { 10557 final CallerIdentity caller = getCallerIdentity(); 10558 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 10559 Preconditions.checkCallAuthorization(canManageUsers(caller) || canQueryAdminPolicy(caller)); 10560 final long callingIdentity = Binder.clearCallingIdentity(); 10561 try { 10562 return getPermittedInputMethodsUnchecked(userId); 10563 } finally { 10564 Binder.restoreCallingIdentity(callingIdentity); 10565 } 10566 } 10567 10568 private @Nullable List<String> getPermittedInputMethodsUnchecked(@UserIdInt int userId) { 10569 synchronized (getLockObject()) { 10570 List<String> result = null; 10571 // Only device or profile owners can have permitted lists set. 10572 List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(userId); 10573 for (ActiveAdmin admin: admins) { 10574 List<String> fromAdmin = admin.permittedInputMethods; 10575 if (fromAdmin != null) { 10576 if (result == null) { 10577 result = new ArrayList<String>(fromAdmin); 10578 } else { 10579 result.retainAll(fromAdmin); 10580 } 10581 } 10582 } 10583 10584 // If we have a permitted list add all system input methods. 10585 if (result != null) { 10586 List<InputMethodInfo> imes = InputMethodManagerInternal 10587 .get().getInputMethodListAsUser(userId); 10588 if (imes != null) { 10589 for (InputMethodInfo ime : imes) { 10590 ServiceInfo serviceInfo = ime.getServiceInfo(); 10591 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 10592 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10593 result.add(serviceInfo.packageName); 10594 } 10595 } 10596 } 10597 } 10598 return result; 10599 } 10600 } 10601 10602 @Override 10603 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 10604 int userHandle, boolean calledOnParentInstance) { 10605 if (!mHasFeature) { 10606 return true; 10607 } 10608 Objects.requireNonNull(who, "ComponentName is null"); 10609 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 10610 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 10611 String.format(NOT_SYSTEM_CALLER_MSG, 10612 "query if an input method is disabled by admin")); 10613 10614 synchronized (getLockObject()) { 10615 ActiveAdmin admin = getParentOfAdminIfRequired( 10616 getActiveAdminUncheckedLocked(who, userHandle), calledOnParentInstance); 10617 if (admin == null) { 10618 return false; 10619 } 10620 if (admin.permittedInputMethods == null) { 10621 return true; 10622 } 10623 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 10624 admin.permittedInputMethods, userHandle); 10625 } 10626 } 10627 10628 @Override 10629 public boolean setPermittedCrossProfileNotificationListeners( 10630 ComponentName who, List<String> packageList) { 10631 if (!mHasFeature) { 10632 return false; 10633 } 10634 Objects.requireNonNull(who, "ComponentName is null"); 10635 final CallerIdentity caller = getCallerIdentity(who); 10636 10637 if (!isManagedProfile(caller.getUserId())) { 10638 return false; 10639 } 10640 10641 synchronized (getLockObject()) { 10642 ActiveAdmin admin = getProfileOwnerLocked(caller); 10643 admin.permittedNotificationListeners = packageList; 10644 saveSettingsLocked(caller.getUserId()); 10645 } 10646 return true; 10647 } 10648 10649 @Override 10650 public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) { 10651 if (!mHasFeature) { 10652 return null; 10653 } 10654 Objects.requireNonNull(who, "ComponentName is null"); 10655 final CallerIdentity caller = getCallerIdentity(who); 10656 10657 synchronized (getLockObject()) { 10658 // API contract is to return null if there are no permitted cross-profile notification 10659 // listeners, including in Device Owner mode. 10660 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 10661 return admin.permittedNotificationListeners; 10662 } 10663 } 10664 10665 @Override 10666 public boolean isNotificationListenerServicePermitted(String packageName, int userId) { 10667 if (!mHasFeature) { 10668 return true; 10669 } 10670 10671 Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty"); 10672 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 10673 String.format(NOT_SYSTEM_CALLER_MSG, 10674 "query if a notification listener service is permitted")); 10675 10676 synchronized (getLockObject()) { 10677 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 10678 if (profileOwner == null || profileOwner.permittedNotificationListeners == null) { 10679 return true; 10680 } 10681 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 10682 profileOwner.permittedNotificationListeners, userId); 10683 10684 } 10685 } 10686 10687 private void maybeSendAdminEnabledBroadcastLocked(int userHandle) { 10688 DevicePolicyData policyData = getUserData(userHandle); 10689 if (policyData.mAdminBroadcastPending) { 10690 // Send the initialization data to profile owner and delete the data 10691 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 10692 boolean clearInitBundle = true; 10693 if (admin != null) { 10694 PersistableBundle initBundle = policyData.mInitBundle; 10695 clearInitBundle = sendAdminCommandLocked(admin, 10696 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 10697 initBundle == null ? null : new Bundle(initBundle), 10698 /* result= */ null , 10699 /* inForeground= */ true); 10700 } 10701 if (clearInitBundle) { 10702 // If there's no admin or we've successfully called the admin, clear the init bundle 10703 // otherwise, keep it around 10704 policyData.mInitBundle = null; 10705 policyData.mAdminBroadcastPending = false; 10706 saveSettingsLocked(userHandle); 10707 } 10708 } 10709 } 10710 10711 @Override 10712 public UserHandle createAndManageUser(ComponentName admin, String name, 10713 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 10714 Objects.requireNonNull(admin, "admin is null"); 10715 Objects.requireNonNull(profileOwner, "profileOwner is null"); 10716 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 10717 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 10718 + admin + " are not in the same package"); 10719 } 10720 final CallerIdentity caller = getCallerIdentity(admin); 10721 // Only allow the system user to use this method 10722 Preconditions.checkCallAuthorization(caller.getUserHandle().isSystem(), 10723 "createAndManageUser was called from non-system user"); 10724 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 10725 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CREATE_AND_MANAGE_USER); 10726 10727 final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0; 10728 final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0 10729 && UserManager.isDeviceInDemoMode(mContext); 10730 final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0; 10731 final int targetSdkVersion; 10732 10733 // Create user. 10734 UserHandle user = null; 10735 synchronized (getLockObject()) { 10736 final long id = mInjector.binderClearCallingIdentity(); 10737 try { 10738 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion( 10739 caller.getUid()); 10740 10741 // Return detail error code for checks inside 10742 // UserManagerService.createUserInternalUnchecked. 10743 DeviceStorageMonitorInternal deviceStorageMonitorInternal = 10744 LocalServices.getService(DeviceStorageMonitorInternal.class); 10745 if (deviceStorageMonitorInternal.isMemoryLow()) { 10746 if (targetSdkVersion >= Build.VERSION_CODES.P) { 10747 throw new ServiceSpecificException( 10748 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage"); 10749 } else { 10750 return null; 10751 } 10752 } 10753 10754 String userType = demo ? UserManager.USER_TYPE_FULL_DEMO 10755 : UserManager.USER_TYPE_FULL_SECONDARY; 10756 int userInfoFlags = ephemeral ? UserInfo.FLAG_EPHEMERAL : 0; 10757 10758 if (!mUserManager.canAddMoreUsers(userType)) { 10759 if (targetSdkVersion >= Build.VERSION_CODES.P) { 10760 throw new ServiceSpecificException( 10761 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached"); 10762 } else { 10763 return null; 10764 } 10765 } 10766 10767 String[] disallowedPackages = null; 10768 if (!leaveAllSystemAppsEnabled) { 10769 disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin, 10770 UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray( 10771 new String[0]); 10772 } 10773 10774 Object token = new Object(); 10775 Slogf.d(LOG_TAG, "Adding new pending token: " + token); 10776 mPendingUserCreatedCallbackTokens.add(token); 10777 try { 10778 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 10779 userType, userInfoFlags, disallowedPackages, token); 10780 if (userInfo != null) { 10781 user = userInfo.getUserHandle(); 10782 } 10783 } catch (UserManager.CheckedUserOperationException e) { 10784 Slogf.e(LOG_TAG, "Couldn't createUserEvenWhenDisallowed", e); 10785 } 10786 } finally { 10787 mInjector.binderRestoreCallingIdentity(id); 10788 } 10789 } // synchronized 10790 10791 if (user == null) { 10792 if (targetSdkVersion >= Build.VERSION_CODES.P) { 10793 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN, 10794 "failed to create user"); 10795 } else { 10796 return null; 10797 } 10798 } 10799 10800 final int userHandle = user.getIdentifier(); 10801 final long id = mInjector.binderClearCallingIdentity(); 10802 try { 10803 maybeInstallDevicePolicyManagementRoleHolderInUser(userHandle); 10804 10805 manageUserUnchecked(admin, profileOwner, userHandle, adminExtras, 10806 /* showDisclaimer= */ true); 10807 10808 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 10809 Settings.Secure.putIntForUser(mContext.getContentResolver(), 10810 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 10811 } 10812 10813 sendProvisioningCompletedBroadcast( 10814 userHandle, ACTION_PROVISION_MANAGED_USER, leaveAllSystemAppsEnabled); 10815 10816 return user; 10817 } catch (Throwable re) { 10818 mUserManager.removeUser(userHandle); 10819 if (targetSdkVersion >= Build.VERSION_CODES.P) { 10820 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN, 10821 re.getMessage()); 10822 } else { 10823 return null; 10824 } 10825 } finally { 10826 mInjector.binderRestoreCallingIdentity(id); 10827 } 10828 } 10829 10830 private void sendProvisioningCompletedBroadcast( 10831 int user, String action, boolean leaveAllSystemAppsEnabled) { 10832 final Intent intent = new Intent(DevicePolicyManager.ACTION_PROVISIONING_COMPLETED) 10833 .putExtra(Intent.EXTRA_USER_HANDLE, user) 10834 .putExtra(Intent.EXTRA_USER, UserHandle.of(user)) 10835 .putExtra( 10836 DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED, 10837 leaveAllSystemAppsEnabled) 10838 .putExtra(DevicePolicyManager.EXTRA_PROVISIONING_ACTION, 10839 action) 10840 .setPackage(getManagedProvisioningPackage(mContext)) 10841 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10842 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM); 10843 } 10844 10845 private void manageUserUnchecked(ComponentName admin, ComponentName profileOwner, 10846 @UserIdInt int userId, @Nullable PersistableBundle adminExtras, 10847 boolean showDisclaimer) { 10848 synchronized (getLockObject()) { 10849 if (VERBOSE_LOG) { 10850 Slogf.v(LOG_TAG, "manageUserUnchecked(): admin=" + admin + ", po=" + profileOwner 10851 + ", userId=" + userId + ", hasAdminExtras=" + (adminExtras != null) 10852 + ", showDisclaimer=" + showDisclaimer); 10853 } 10854 } 10855 final String adminPkg = admin.getPackageName(); 10856 mInjector.binderWithCleanCallingIdentity(() -> { 10857 try { 10858 // Install the profile owner if not present. 10859 if (!mIPackageManager.isPackageAvailable(adminPkg, userId)) { 10860 mIPackageManager.installExistingPackageAsUser(adminPkg, userId, 10861 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 10862 PackageManager.INSTALL_REASON_POLICY, 10863 /* allowlistedRestrictedPermissions= */ null); 10864 } 10865 } catch (RemoteException e) { 10866 // Does not happen, same process 10867 Slogf.wtf(LOG_TAG, e, "Failed to install admin package %s for user %d", 10868 adminPkg, userId); 10869 } 10870 }); 10871 10872 // Set admin. 10873 setActiveAdmin(profileOwner, /* refreshing= */ true, userId); 10874 final String ownerName = getProfileOwnerNameUnchecked( 10875 Process.myUserHandle().getIdentifier()); 10876 setProfileOwner(profileOwner, ownerName, userId); 10877 10878 synchronized (getLockObject()) { 10879 DevicePolicyData policyData = getUserData(userId); 10880 policyData.mInitBundle = adminExtras; 10881 policyData.mAdminBroadcastPending = true; 10882 policyData.mNewUserDisclaimer = showDisclaimer 10883 ? DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED 10884 : DevicePolicyData.NEW_USER_DISCLAIMER_NOT_NEEDED; 10885 saveSettingsLocked(userId); 10886 10887 } 10888 } 10889 10890 private void handleNewUserCreated(UserInfo user, @Nullable Object token) { 10891 if (VERBOSE_LOG) { 10892 Slogf.v(LOG_TAG, "handleNewUserCreated(): user=" + user.toFullString() 10893 + ", token=" + token); 10894 } 10895 10896 final int userId = user.id; 10897 if (token != null) { 10898 synchronized (getLockObject()) { 10899 if (mPendingUserCreatedCallbackTokens.contains(token)) { 10900 // Ignore because it was triggered by createAndManageUser() 10901 Slogf.d(LOG_TAG, "handleNewUserCreated(): ignoring for user " + userId 10902 + " due to token " + token); 10903 mPendingUserCreatedCallbackTokens.remove(token); 10904 return; 10905 } 10906 } 10907 } 10908 10909 if (!mOwners.hasDeviceOwner() || !user.isFull() || user.isManagedProfile() 10910 || user.isGuest()) { 10911 return; 10912 } 10913 10914 if (mInjector.userManagerIsHeadlessSystemUserMode()) { 10915 ComponentName admin = mOwners.getDeviceOwnerComponent(); 10916 Slogf.i(LOG_TAG, "Automatically setting profile owner (" + admin + ") on new user " 10917 + userId); 10918 manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin, 10919 /* managedUser= */ userId, /* adminExtras= */ null, /* showDisclaimer= */ true); 10920 } else { 10921 Slogf.i(LOG_TAG, "User %d added on DO mode; setting ShowNewUserDisclaimer", userId); 10922 setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED); 10923 } 10924 } 10925 10926 @Override 10927 public void acknowledgeNewUserDisclaimer(@UserIdInt int userId) { 10928 CallerIdentity callerIdentity = getCallerIdentity(); 10929 Preconditions.checkCallAuthorization(canManageUsers(callerIdentity) 10930 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)); 10931 10932 setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_ACKNOWLEDGED); 10933 } 10934 10935 private void setShowNewUserDisclaimer(@UserIdInt int userId, String value) { 10936 Slogf.i(LOG_TAG, "Setting new user disclaimer for user " + userId + " as " + value); 10937 synchronized (getLockObject()) { 10938 DevicePolicyData policyData = getUserData(userId); 10939 policyData.mNewUserDisclaimer = value; 10940 saveSettingsLocked(userId); 10941 } 10942 } 10943 10944 private void showNewUserDisclaimerIfNecessary(@UserIdInt int userId) { 10945 boolean mustShow; 10946 synchronized (getLockObject()) { 10947 DevicePolicyData policyData = getUserData(userId); 10948 if (VERBOSE_LOG) { 10949 Slogf.v(LOG_TAG, "showNewUserDisclaimerIfNecessary(" + userId + "): " 10950 + policyData.mNewUserDisclaimer + ")"); 10951 } 10952 mustShow = DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED 10953 .equals(policyData.mNewUserDisclaimer); 10954 } 10955 if (!mustShow) return; 10956 10957 Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_NEW_USER_DISCLAIMER); 10958 10959 // TODO(b/172691310): add CTS tests to make sure disclaimer is shown 10960 Slogf.i(LOG_TAG, "Dispatching ACTION_SHOW_NEW_USER_DISCLAIMER intent"); 10961 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 10962 } 10963 10964 @Override 10965 public boolean isNewUserDisclaimerAcknowledged(@UserIdInt int userId) { 10966 CallerIdentity callerIdentity = getCallerIdentity(); 10967 Preconditions.checkCallAuthorization(canManageUsers(callerIdentity) 10968 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)); 10969 synchronized (getLockObject()) { 10970 DevicePolicyData policyData = getUserData(userId); 10971 return policyData.isNewUserDisclaimerAcknowledged(); 10972 } 10973 } 10974 10975 @Override 10976 public boolean removeUser(ComponentName who, UserHandle userHandle) { 10977 Objects.requireNonNull(who, "ComponentName is null"); 10978 Objects.requireNonNull(userHandle, "UserHandle is null"); 10979 final CallerIdentity caller = getCallerIdentity(who); 10980 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 10981 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_USER); 10982 10983 return mInjector.binderWithCleanCallingIdentity(() -> { 10984 String restriction = isManagedProfile(userHandle.getIdentifier()) 10985 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 10986 : UserManager.DISALLOW_REMOVE_USER; 10987 if (isAdminAffectedByRestriction(who, restriction, caller.getUserId())) { 10988 Slogf.w(LOG_TAG, "The device owner cannot remove a user because %s is enabled, and " 10989 + "was not set by the device owner", restriction); 10990 return false; 10991 } 10992 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 10993 }); 10994 } 10995 10996 private boolean isAdminAffectedByRestriction( 10997 ComponentName admin, String userRestriction, int userId) { 10998 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 10999 case UserManager.RESTRICTION_NOT_SET: 11000 return false; 11001 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 11002 return !isDeviceOwner(admin, userId); 11003 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 11004 return !isProfileOwner(admin, userId); 11005 default: 11006 return true; 11007 } 11008 } 11009 11010 @Override 11011 public boolean switchUser(ComponentName who, UserHandle userHandle) { 11012 Objects.requireNonNull(who, "ComponentName is null"); 11013 final CallerIdentity caller = getCallerIdentity(who); 11014 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 11015 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SWITCH_USER); 11016 11017 boolean switched = false; 11018 // Save previous logout user id in case of failure 11019 int logoutUserId = getLogoutUserIdUnchecked(); 11020 synchronized (getLockObject()) { 11021 long id = mInjector.binderClearCallingIdentity(); 11022 try { 11023 int userId = UserHandle.USER_SYSTEM; 11024 if (userHandle != null) { 11025 userId = userHandle.getIdentifier(); 11026 } 11027 Slogf.i(LOG_TAG, "Switching to user %d (logout user is %d)", userId, logoutUserId); 11028 setLogoutUserIdLocked(UserHandle.USER_CURRENT); 11029 switched = mInjector.getIActivityManager().switchUser(userId); 11030 if (!switched) { 11031 Slogf.w(LOG_TAG, "Failed to switch to user %d", userId); 11032 } else { 11033 Slogf.d(LOG_TAG, "Switched"); 11034 } 11035 return switched; 11036 } catch (RemoteException e) { 11037 Slogf.e(LOG_TAG, "Couldn't switch user", e); 11038 return false; 11039 } finally { 11040 mInjector.binderRestoreCallingIdentity(id); 11041 if (!switched) { 11042 setLogoutUserIdLocked(logoutUserId); 11043 } 11044 } 11045 } 11046 } 11047 11048 @Override 11049 public int getLogoutUserId() { 11050 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()) 11051 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)); 11052 11053 return getLogoutUserIdUnchecked(); 11054 } 11055 11056 private @UserIdInt int getLogoutUserIdUnchecked() { 11057 synchronized (getLockObject()) { 11058 return mLogoutUserId; 11059 } 11060 } 11061 11062 private void clearLogoutUser() { 11063 synchronized (getLockObject()) { 11064 setLogoutUserIdLocked(UserHandle.USER_NULL); 11065 } 11066 } 11067 11068 @GuardedBy("getLockObject()") 11069 private void setLogoutUserIdLocked(@UserIdInt int userId) { 11070 if (userId == UserHandle.USER_CURRENT) { 11071 userId = getCurrentForegroundUserId(); 11072 } 11073 11074 Slogf.d(LOG_TAG, "setLogoutUserId(): %d -> %d", mLogoutUserId, userId); 11075 mLogoutUserId = userId; 11076 } 11077 11078 @Override 11079 public int startUserInBackground(ComponentName who, UserHandle userHandle) { 11080 Objects.requireNonNull(who, "ComponentName is null"); 11081 Objects.requireNonNull(userHandle, "UserHandle is null"); 11082 final CallerIdentity caller = getCallerIdentity(who); 11083 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 11084 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_START_USER_IN_BACKGROUND); 11085 11086 final int userId = userHandle.getIdentifier(); 11087 if (isManagedProfile(userId)) { 11088 Slogf.w(LOG_TAG, "Managed profile cannot be started in background"); 11089 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 11090 } 11091 11092 final long id = mInjector.binderClearCallingIdentity(); 11093 try { 11094 if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) { 11095 Slogf.w(LOG_TAG, "Cannot start user %d, too many users in background", userId); 11096 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS; 11097 } 11098 11099 Slogf.i(LOG_TAG, "Starting user %d in background", userId); 11100 if (mInjector.getIActivityManager().startUserInBackground(userId)) { 11101 return UserManager.USER_OPERATION_SUCCESS; 11102 } else { 11103 Slogf.w(LOG_TAG, "failed to start user %d in background", userId); 11104 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 11105 } 11106 } catch (RemoteException e) { 11107 // Same process, should not happen. 11108 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 11109 } finally { 11110 mInjector.binderRestoreCallingIdentity(id); 11111 } 11112 } 11113 11114 @Override 11115 public int stopUser(ComponentName who, UserHandle userHandle) { 11116 Objects.requireNonNull(who, "ComponentName is null"); 11117 Objects.requireNonNull(userHandle, "UserHandle is null"); 11118 final CallerIdentity caller = getCallerIdentity(who); 11119 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 11120 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_STOP_USER); 11121 11122 final int userId = userHandle.getIdentifier(); 11123 if (isManagedProfile(userId)) { 11124 Slogf.w(LOG_TAG, "Managed profile cannot be stopped"); 11125 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 11126 } 11127 11128 return stopUserUnchecked(userId); 11129 } 11130 11131 @Override 11132 public int logoutUser(ComponentName who) { 11133 Objects.requireNonNull(who, "ComponentName is null"); 11134 final CallerIdentity caller = getCallerIdentity(who); 11135 Preconditions.checkCallAuthorization( 11136 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 11137 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOGOUT_USER); 11138 11139 final int callingUserId = caller.getUserId(); 11140 synchronized (getLockObject()) { 11141 if (!isUserAffiliatedWithDeviceLocked(callingUserId)) { 11142 throw new SecurityException("Admin " + who + 11143 " is neither the device owner or affiliated user's profile owner."); 11144 } 11145 } 11146 11147 if (isManagedProfile(callingUserId)) { 11148 Slogf.w(LOG_TAG, "Managed profile cannot be logout"); 11149 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 11150 } 11151 11152 if (callingUserId != mInjector 11153 .binderWithCleanCallingIdentity(() -> getCurrentForegroundUserId())) { 11154 Slogf.d(LOG_TAG, "logoutUser(): user %d is in background, just stopping, not switching", 11155 callingUserId); 11156 return stopUserUnchecked(callingUserId); 11157 } 11158 11159 return logoutUserUnchecked(/* userIdToStop= */ callingUserId); 11160 } 11161 11162 @Override 11163 public int logoutUserInternal() { 11164 CallerIdentity caller = getCallerIdentity(); 11165 Preconditions.checkCallAuthorization(canManageUsers(caller) 11166 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)); 11167 11168 int currentUserId = getCurrentForegroundUserId(); 11169 if (VERBOSE_LOG) { 11170 Slogf.v(LOG_TAG, "logout() called by uid %d; current user is %d", caller.getUid(), 11171 currentUserId); 11172 } 11173 int result = logoutUserUnchecked(currentUserId); 11174 if (VERBOSE_LOG) { 11175 Slogf.v(LOG_TAG, "Result of logout(): %d", result); 11176 } 11177 return result; 11178 } 11179 11180 private int logoutUserUnchecked(@UserIdInt int userIdToStop) { 11181 int logoutUserId = getLogoutUserIdUnchecked(); 11182 if (logoutUserId == UserHandle.USER_NULL) { 11183 // Could happen on devices using headless system user mode when called before calling 11184 // switchUser() or startUserInBackground() first 11185 Slogf.w(LOG_TAG, "logoutUser(): could not determine which user to switch to"); 11186 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 11187 } 11188 final long id = mInjector.binderClearCallingIdentity(); 11189 try { 11190 Slogf.i(LOG_TAG, "logoutUser(): switching to user %d", logoutUserId); 11191 if (!mInjector.getIActivityManager().switchUser(logoutUserId)) { 11192 Slogf.w(LOG_TAG, "Failed to switch to user %d", logoutUserId); 11193 // This should never happen as target user is determined by getPreviousUserId() 11194 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 11195 } 11196 clearLogoutUser(); 11197 } catch (RemoteException e) { 11198 // Same process, should not happen. 11199 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 11200 } finally { 11201 mInjector.binderRestoreCallingIdentity(id); 11202 } 11203 11204 return stopUserUnchecked(userIdToStop); 11205 } 11206 11207 private int stopUserUnchecked(@UserIdInt int userId) { 11208 Slogf.i(LOG_TAG, "Stopping user %d", userId); 11209 final long id = mInjector.binderClearCallingIdentity(); 11210 try { 11211 switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) { 11212 case ActivityManager.USER_OP_SUCCESS: 11213 return UserManager.USER_OPERATION_SUCCESS; 11214 case ActivityManager.USER_OP_IS_CURRENT: 11215 return UserManager.USER_OPERATION_ERROR_CURRENT_USER; 11216 default: 11217 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 11218 } 11219 } catch (RemoteException e) { 11220 // Same process, should not happen. 11221 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 11222 } finally { 11223 mInjector.binderRestoreCallingIdentity(id); 11224 } 11225 } 11226 11227 @Override 11228 public List<UserHandle> getSecondaryUsers(ComponentName who) { 11229 Objects.requireNonNull(who, "ComponentName is null"); 11230 final CallerIdentity caller = getCallerIdentity(who); 11231 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 11232 11233 return mInjector.binderWithCleanCallingIdentity(() -> { 11234 final List<UserInfo> userInfos = mInjector.getUserManager().getAliveUsers(); 11235 final List<UserHandle> userHandles = new ArrayList<>(); 11236 for (UserInfo userInfo : userInfos) { 11237 UserHandle userHandle = userInfo.getUserHandle(); 11238 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) { 11239 userHandles.add(userInfo.getUserHandle()); 11240 } 11241 } 11242 return userHandles; 11243 }); 11244 } 11245 11246 @Override 11247 public boolean isEphemeralUser(ComponentName who) { 11248 Objects.requireNonNull(who, "ComponentName is null"); 11249 11250 final CallerIdentity caller = getCallerIdentity(who); 11251 Preconditions.checkCallAuthorization( 11252 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 11253 11254 return mInjector.binderWithCleanCallingIdentity( 11255 () -> mInjector.getUserManager().isUserEphemeral(caller.getUserId())); 11256 } 11257 11258 @Override 11259 public Bundle getApplicationRestrictions(ComponentName who, String callerPackage, 11260 String packageName) { 11261 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11262 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11263 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 11264 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS))); 11265 11266 return mInjector.binderWithCleanCallingIdentity(() -> { 11267 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, 11268 caller.getUserHandle()); 11269 // if no restrictions were saved, mUserManager.getApplicationRestrictions 11270 // returns null, but DPM method should return an empty Bundle as per JavaDoc 11271 return bundle != null ? bundle : Bundle.EMPTY; 11272 }); 11273 } 11274 11275 /** 11276 * Returns the apps that are non-exempt from some policies (such as suspension), and populates 11277 * the given set with the apps that are exempt. 11278 * 11279 * @param packageNames apps to check 11280 * @param outputExemptApps will be populate with subset of {@code packageNames} that is exempt 11281 * from some policy restrictions 11282 * 11283 * @return subset of {@code packageNames} that is affected by some policy restrictions. 11284 */ 11285 private String[] populateNonExemptAndExemptFromPolicyApps(String[] packageNames, 11286 Set<String> outputExemptApps) { 11287 Preconditions.checkArgument(outputExemptApps.isEmpty(), "outputExemptApps is not empty"); 11288 List<String> exemptAppsList = listPolicyExemptAppsUnchecked(); 11289 if (exemptAppsList.isEmpty()) { 11290 return packageNames; 11291 } 11292 // Using a set so contains() is O(1) 11293 Set<String> exemptApps = new HashSet<>(exemptAppsList); 11294 List<String> nonExemptApps = new ArrayList<>(packageNames.length); 11295 for (int i = 0; i < packageNames.length; i++) { 11296 String app = packageNames[i]; 11297 if (exemptApps.contains(app)) { 11298 outputExemptApps.add(app); 11299 } else { 11300 nonExemptApps.add(app); 11301 } 11302 } 11303 String[] result = new String[nonExemptApps.size()]; 11304 nonExemptApps.toArray(result); 11305 return result; 11306 } 11307 11308 @Override 11309 public String[] setPackagesSuspended(ComponentName who, String callerPackage, 11310 String[] packageNames, boolean suspended) { 11311 Objects.requireNonNull(packageNames, "array of packages cannot be null"); 11312 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11313 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11314 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 11315 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS))); 11316 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PACKAGES_SUSPENDED); 11317 11318 // Must remove the exempt apps from the input before calling PM, then add them back to 11319 // the array returned to the caller 11320 Set<String> exemptApps = new HashSet<>(); 11321 packageNames = populateNonExemptAndExemptFromPolicyApps(packageNames, exemptApps); 11322 11323 String[] nonSuspendedPackages = null; 11324 synchronized (getLockObject()) { 11325 long id = mInjector.binderClearCallingIdentity(); 11326 try { 11327 nonSuspendedPackages = mIPackageManager.setPackagesSuspendedAsUser(packageNames, 11328 suspended, null, null, null, PLATFORM_PACKAGE_NAME, caller.getUserId()); 11329 } catch (RemoteException re) { 11330 // Shouldn't happen. 11331 Slogf.e(LOG_TAG, "Failed talking to the package manager", re); 11332 } finally { 11333 mInjector.binderRestoreCallingIdentity(id); 11334 } 11335 } 11336 DevicePolicyEventLogger 11337 .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED) 11338 .setAdmin(caller.getPackageName()) 11339 .setBoolean(/* isDelegate */ who == null) 11340 .setStrings(packageNames) 11341 .write(); 11342 11343 if (nonSuspendedPackages == null) { 11344 Slogf.w(LOG_TAG, "PM failed to suspend packages (%s)", Arrays.toString(packageNames)); 11345 return packageNames; 11346 } 11347 if (exemptApps.isEmpty()) { 11348 return nonSuspendedPackages; 11349 } 11350 11351 String[] result = buildNonSuspendedPackagesUnionArray(nonSuspendedPackages, exemptApps); 11352 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Returning %s", Arrays.toString(result)); 11353 return result; 11354 } 11355 11356 /** 11357 * Returns an array containing the union of the given non-suspended packages and 11358 * exempt apps. Assumes both parameters are non-null and non-empty. 11359 */ 11360 private String[] buildNonSuspendedPackagesUnionArray(String[] nonSuspendedPackages, 11361 Set<String> exemptApps) { 11362 String[] result = new String[nonSuspendedPackages.length + exemptApps.size()]; 11363 int index = 0; 11364 for (String app : nonSuspendedPackages) { 11365 result[index++] = app; 11366 } 11367 for (String app : exemptApps) { 11368 result[index++] = app; 11369 } 11370 return result; 11371 } 11372 11373 @Override 11374 public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) { 11375 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11376 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11377 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 11378 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS))); 11379 11380 synchronized (getLockObject()) { 11381 long id = mInjector.binderClearCallingIdentity(); 11382 try { 11383 return mIPackageManager.isPackageSuspendedForUser(packageName, caller.getUserId()); 11384 } catch (RemoteException re) { 11385 // Shouldn't happen. 11386 Slogf.e(LOG_TAG, "Failed talking to the package manager", re); 11387 } finally { 11388 mInjector.binderRestoreCallingIdentity(id); 11389 } 11390 return false; 11391 } 11392 } 11393 11394 @Override 11395 public List<String> listPolicyExemptApps() { 11396 CallerIdentity caller = getCallerIdentity(); 11397 Preconditions.checkCallAuthorization( 11398 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS) 11399 || isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 11400 11401 return listPolicyExemptAppsUnchecked(); 11402 } 11403 11404 private List<String> listPolicyExemptAppsUnchecked() { 11405 // TODO(b/181238156): decide whether it should only list the apps set by the resources, 11406 // or also the "critical" apps defined by PersonalAppsSuspensionHelper (like SMS app). 11407 // If it's the latter, refactor PersonalAppsSuspensionHelper so it (or a superclass) takes 11408 // the resources on constructor. 11409 String[] core = mContext.getResources().getStringArray(R.array.policy_exempt_apps); 11410 String[] vendor = mContext.getResources().getStringArray(R.array.vendor_policy_exempt_apps); 11411 11412 int size = core.length + vendor.length; 11413 Set<String> apps = new ArraySet<>(size); 11414 for (String app : core) { 11415 apps.add(app); 11416 } 11417 for (String app : vendor) { 11418 apps.add(app); 11419 } 11420 11421 return new ArrayList<>(apps); 11422 } 11423 11424 @Override 11425 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner, 11426 boolean parent) { 11427 Objects.requireNonNull(who, "ComponentName is null"); 11428 11429 final CallerIdentity caller = getCallerIdentity(who); 11430 11431 if (!UserRestrictionsUtils.isValidRestriction(key)) { 11432 return; 11433 } 11434 11435 int userHandle = caller.getUserId(); 11436 synchronized (getLockObject()) { 11437 final ActiveAdmin activeAdmin = getParentOfAdminIfRequired( 11438 getProfileOwnerOrDeviceOwnerLocked(caller), parent); 11439 11440 if (isDefaultDeviceOwner(caller)) { 11441 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 11442 throw new SecurityException("Device owner cannot set user restriction " + key); 11443 } 11444 Preconditions.checkArgument(!parent, 11445 "Cannot use the parent instance in Device Owner mode"); 11446 } else if (isFinancedDeviceOwner(caller)) { 11447 if (!UserRestrictionsUtils.canFinancedDeviceOwnerChange(key)) { 11448 throw new SecurityException("Cannot set user restriction " + key 11449 + " when managing a financed device"); 11450 } 11451 Preconditions.checkArgument(!parent, 11452 "Cannot use the parent instance in Financed Device Owner mode"); 11453 } else { 11454 boolean profileOwnerCanChangeOnItself = !parent 11455 && UserRestrictionsUtils.canProfileOwnerChange(key, userHandle); 11456 boolean orgOwnedProfileOwnerCanChangesGlobally = parent 11457 && isProfileOwnerOfOrganizationOwnedDevice(caller) 11458 && UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange( 11459 key); 11460 11461 if (!profileOwnerCanChangeOnItself && !orgOwnedProfileOwnerCanChangesGlobally) { 11462 throw new SecurityException("Profile owner cannot set user restriction " + key); 11463 } 11464 } 11465 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION); 11466 11467 // Save the restriction to ActiveAdmin. 11468 final Bundle restrictions = activeAdmin.ensureUserRestrictions(); 11469 if (enabledFromThisOwner) { 11470 restrictions.putBoolean(key, true); 11471 } else { 11472 restrictions.remove(key); 11473 } 11474 saveUserRestrictionsLocked(userHandle); 11475 } 11476 final int eventId = enabledFromThisOwner 11477 ? DevicePolicyEnums.ADD_USER_RESTRICTION 11478 : DevicePolicyEnums.REMOVE_USER_RESTRICTION; 11479 DevicePolicyEventLogger 11480 .createEvent(eventId) 11481 .setAdmin(caller.getComponentName()) 11482 .setStrings(key, parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 11483 .write(); 11484 if (SecurityLog.isLoggingEnabled()) { 11485 final int eventTag = enabledFromThisOwner 11486 ? SecurityLog.TAG_USER_RESTRICTION_ADDED 11487 : SecurityLog.TAG_USER_RESTRICTION_REMOVED; 11488 SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key); 11489 } 11490 } 11491 11492 private void saveUserRestrictionsLocked(int userId) { 11493 saveSettingsLocked(userId); 11494 pushUserRestrictions(userId); 11495 sendChangedNotification(userId); 11496 } 11497 11498 /** 11499 * Pushes the user restrictions originating from a specific user. 11500 * 11501 * If called by the profile owner of an organization-owned device, the global and local 11502 * user restrictions will be an accumulation of the global user restrictions from the profile 11503 * owner active admin and its parent active admin. The key of the local user restrictions set 11504 * will be the target user id. 11505 */ 11506 private void pushUserRestrictions(int originatingUserId) { 11507 final Bundle global; 11508 final RestrictionsSet local = new RestrictionsSet(); 11509 final boolean isDeviceOwner; 11510 synchronized (getLockObject()) { 11511 isDeviceOwner = mOwners.isDeviceOwnerUserId(originatingUserId); 11512 if (isDeviceOwner) { 11513 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 11514 if (deviceOwner == null) { 11515 return; // Shouldn't happen. 11516 } 11517 global = deviceOwner.getGlobalUserRestrictions(OWNER_TYPE_DEVICE_OWNER); 11518 local.updateRestrictions(originatingUserId, deviceOwner.getLocalUserRestrictions( 11519 OWNER_TYPE_DEVICE_OWNER)); 11520 } else { 11521 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(originatingUserId); 11522 if (profileOwner == null) { 11523 return; 11524 } 11525 global = profileOwner.getGlobalUserRestrictions(OWNER_TYPE_PROFILE_OWNER); 11526 local.updateRestrictions(originatingUserId, profileOwner.getLocalUserRestrictions( 11527 OWNER_TYPE_PROFILE_OWNER)); 11528 // Global (device-wide) and local user restrictions set by the profile owner of an 11529 // organization-owned device are stored in the parent ActiveAdmin instance. 11530 if (isProfileOwnerOfOrganizationOwnedDevice( 11531 profileOwner.getUserHandle().getIdentifier())) { 11532 // The global restrictions set on the parent ActiveAdmin instance need to be 11533 // merged with the global restrictions set on the profile owner ActiveAdmin 11534 // instance, since both are to be applied device-wide. 11535 UserRestrictionsUtils.merge(global, 11536 profileOwner.getParentActiveAdmin().getGlobalUserRestrictions( 11537 OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE)); 11538 // The local restrictions set on the parent ActiveAdmin instance are only to be 11539 // applied to the primary user. They therefore need to be added the local 11540 // restriction set with the primary user id as the key, in this case the 11541 // primary user id is the target user. 11542 local.updateRestrictions( 11543 getProfileParentId(profileOwner.getUserHandle().getIdentifier()), 11544 profileOwner.getParentActiveAdmin().getLocalUserRestrictions( 11545 OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE)); 11546 } 11547 } 11548 } 11549 mUserManagerInternal.setDevicePolicyUserRestrictions(originatingUserId, global, local, 11550 isDeviceOwner); 11551 } 11552 11553 @Override 11554 public Bundle getUserRestrictions(ComponentName who, boolean parent) { 11555 if (!mHasFeature) { 11556 return null; 11557 } 11558 Objects.requireNonNull(who, "ComponentName is null"); 11559 11560 final CallerIdentity caller = getCallerIdentity(who); 11561 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 11562 || isFinancedDeviceOwner(caller) 11563 || isProfileOwner(caller) 11564 || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller))); 11565 11566 synchronized (getLockObject()) { 11567 final ActiveAdmin activeAdmin = getParentOfAdminIfRequired( 11568 getProfileOwnerOrDeviceOwnerLocked(caller), parent); 11569 return activeAdmin.userRestrictions; 11570 } 11571 } 11572 11573 @Override 11574 public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName, 11575 boolean hidden, boolean parent) { 11576 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11577 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11578 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 11579 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS))); 11580 11581 List<String> exemptApps = listPolicyExemptAppsUnchecked(); 11582 if (exemptApps.contains(packageName)) { 11583 Slogf.d(LOG_TAG, "setApplicationHidden(): ignoring %s as it's on policy-exempt list", 11584 packageName); 11585 return false; 11586 } 11587 11588 final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId(); 11589 boolean result; 11590 synchronized (getLockObject()) { 11591 if (parent) { 11592 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice( 11593 caller.getUserId()) && isManagedProfile(caller.getUserId())); 11594 // Ensure the package provided is a system package, this is to ensure that this 11595 // API cannot be used to leak if certain non-system package exists in the person 11596 // profile. 11597 mInjector.binderWithCleanCallingIdentity(() -> 11598 enforcePackageIsSystemPackage(packageName, userId)); 11599 } 11600 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_HIDDEN); 11601 11602 if (VERBOSE_LOG) { 11603 Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)", 11604 packageName, hidden, userId); 11605 } 11606 result = mInjector.binderWithCleanCallingIdentity(() -> mIPackageManager 11607 .setApplicationHiddenSettingAsUser(packageName, hidden, userId)); 11608 } 11609 DevicePolicyEventLogger 11610 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN) 11611 .setAdmin(caller.getPackageName()) 11612 .setBoolean(/* isDelegate */ who == null) 11613 .setStrings(packageName, hidden ? "hidden" : "not_hidden", 11614 parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT) 11615 .write(); 11616 return result; 11617 } 11618 11619 @Override 11620 public boolean isApplicationHidden(ComponentName who, String callerPackage, 11621 String packageName, boolean parent) { 11622 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11623 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11624 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 11625 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS))); 11626 11627 final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId(); 11628 synchronized (getLockObject()) { 11629 if (parent) { 11630 Preconditions.checkCallAuthorization( 11631 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()) 11632 && isManagedProfile(caller.getUserId())); 11633 // Ensure the package provided is a system package. 11634 mInjector.binderWithCleanCallingIdentity(() -> 11635 enforcePackageIsSystemPackage(packageName, userId)); 11636 } 11637 11638 return mInjector.binderWithCleanCallingIdentity( 11639 () -> mIPackageManager.getApplicationHiddenSettingAsUser(packageName, userId)); 11640 } 11641 } 11642 11643 private void enforcePackageIsSystemPackage(String packageName, int userId) 11644 throws RemoteException { 11645 boolean isSystem; 11646 try { 11647 isSystem = isSystemApp(mIPackageManager, packageName, userId); 11648 } catch (IllegalArgumentException e) { 11649 isSystem = false; 11650 } 11651 if (!isSystem) { 11652 throw new IllegalArgumentException("The provided package is not a system package"); 11653 } 11654 } 11655 11656 @Override 11657 public void enableSystemApp(ComponentName who, String callerPackage, String packageName) { 11658 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11659 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11660 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 11661 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP))); 11662 11663 synchronized (getLockObject()) { 11664 final boolean isDemo = isCurrentUserDemo(); 11665 int userId = caller.getUserId(); 11666 long id = mInjector.binderClearCallingIdentity(); 11667 try { 11668 if (VERBOSE_LOG) { 11669 Slogf.v(LOG_TAG, "installing " + packageName + " for " + userId); 11670 } 11671 11672 Preconditions.checkArgument(isDemo || isSystemApp(mIPackageManager, packageName, 11673 getProfileParentId(userId)), "Only system apps can be enabled this way"); 11674 11675 // Install the app. 11676 mIPackageManager.installExistingPackageAsUser(packageName, userId, 11677 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 11678 PackageManager.INSTALL_REASON_POLICY, null); 11679 if (isDemo) { 11680 // Ensure the app is also ENABLED for demo users. 11681 mIPackageManager.setApplicationEnabledSetting(packageName, 11682 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 11683 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 11684 } 11685 } catch (RemoteException re) { 11686 // shouldn't happen 11687 Slogf.wtf(LOG_TAG, "Failed to install " + packageName, re); 11688 } finally { 11689 mInjector.binderRestoreCallingIdentity(id); 11690 } 11691 } 11692 DevicePolicyEventLogger 11693 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP) 11694 .setAdmin(caller.getPackageName()) 11695 .setBoolean(/* isDelegate */ who == null) 11696 .setStrings(packageName) 11697 .write(); 11698 } 11699 11700 @Override 11701 public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) { 11702 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11703 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11704 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 11705 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP))); 11706 11707 int numberOfAppsInstalled = 0; 11708 synchronized (getLockObject()) { 11709 long id = mInjector.binderClearCallingIdentity(); 11710 try { 11711 final int parentUserId = getProfileParentId(caller.getUserId()); 11712 List<ResolveInfo> activitiesToEnable = mIPackageManager 11713 .queryIntentActivities(intent, 11714 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11715 PackageManager.MATCH_DIRECT_BOOT_AWARE 11716 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 11717 parentUserId) 11718 .getList(); 11719 11720 if (VERBOSE_LOG) { 11721 Slogf.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 11722 } 11723 if (activitiesToEnable != null) { 11724 for (ResolveInfo info : activitiesToEnable) { 11725 if (info.activityInfo != null) { 11726 String packageName = info.activityInfo.packageName; 11727 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 11728 numberOfAppsInstalled++; 11729 mIPackageManager.installExistingPackageAsUser(packageName, 11730 caller.getUserId(), 11731 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 11732 PackageManager.INSTALL_REASON_POLICY, null); 11733 } else { 11734 Slogf.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 11735 + " system app"); 11736 } 11737 } 11738 } 11739 } 11740 } catch (RemoteException e) { 11741 // shouldn't happen 11742 Slogf.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 11743 return 0; 11744 } finally { 11745 mInjector.binderRestoreCallingIdentity(id); 11746 } 11747 } 11748 DevicePolicyEventLogger 11749 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP_WITH_INTENT) 11750 .setAdmin(caller.getPackageName()) 11751 .setBoolean(/* isDelegate */ who == null) 11752 .setStrings(intent.getAction()) 11753 .write(); 11754 return numberOfAppsInstalled; 11755 } 11756 11757 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 11758 throws RemoteException { 11759 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 11760 userId); 11761 if (appInfo == null) { 11762 throw new IllegalArgumentException("The application " + packageName + 11763 " is not present on this device"); 11764 } 11765 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11766 } 11767 11768 @Override 11769 public boolean installExistingPackage(ComponentName who, String callerPackage, 11770 String packageName) { 11771 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11772 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11773 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 11774 || (caller.hasPackage() 11775 && isCallerDelegate(caller, DELEGATION_INSTALL_EXISTING_PACKAGE))); 11776 11777 boolean result; 11778 synchronized (getLockObject()) { 11779 Preconditions.checkCallAuthorization( 11780 isUserAffiliatedWithDeviceLocked(caller.getUserId()), 11781 "Admin %s is neither the device owner or " 11782 + "affiliated user's profile owner.", who); 11783 final long id = mInjector.binderClearCallingIdentity(); 11784 try { 11785 if (VERBOSE_LOG) { 11786 Slogf.v(LOG_TAG, "installing " + packageName + " for " + caller.getUserId()); 11787 } 11788 11789 // Install the package. 11790 result = mIPackageManager.installExistingPackageAsUser(packageName, 11791 caller.getUserId(), 11792 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 11793 PackageManager.INSTALL_REASON_POLICY, null) 11794 == PackageManager.INSTALL_SUCCEEDED; 11795 } catch (RemoteException re) { 11796 // shouldn't happen 11797 return false; 11798 } finally { 11799 mInjector.binderRestoreCallingIdentity(id); 11800 } 11801 } 11802 if (result) { 11803 DevicePolicyEventLogger 11804 .createEvent(DevicePolicyEnums.INSTALL_EXISTING_PACKAGE) 11805 .setAdmin(caller.getPackageName()) 11806 .setBoolean(/* isDelegate */ who == null) 11807 .setStrings(packageName) 11808 .write(); 11809 } 11810 return result; 11811 } 11812 11813 @Override 11814 public void setAccountManagementDisabled(ComponentName who, String accountType, 11815 boolean disabled, boolean parent) { 11816 if (!mHasFeature) { 11817 return; 11818 } 11819 Objects.requireNonNull(who, "ComponentName is null"); 11820 enforceMaxStringLength(accountType, "account type"); 11821 11822 final CallerIdentity caller = getCallerIdentity(who); 11823 synchronized (getLockObject()) { 11824 /* 11825 * When called on the parent DPM instance (parent == true), affects active admin 11826 * selection in two ways: 11827 * * The ActiveAdmin must be of an org-owned profile owner. 11828 * * The parent ActiveAdmin instance should be used for managing the restriction. 11829 */ 11830 final ActiveAdmin ap; 11831 if (parent) { 11832 ap = getParentOfAdminIfRequired(getOrganizationOwnedProfileOwnerLocked(caller), 11833 parent); 11834 } else { 11835 ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller), parent); 11836 } 11837 11838 if (disabled) { 11839 ap.accountTypesWithManagementDisabled.add(accountType); 11840 } else { 11841 ap.accountTypesWithManagementDisabled.remove(accountType); 11842 } 11843 saveSettingsLocked(UserHandle.getCallingUserId()); 11844 } 11845 } 11846 11847 @Override 11848 public String[] getAccountTypesWithManagementDisabled() { 11849 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId(), false); 11850 } 11851 11852 @Override 11853 public String[] getAccountTypesWithManagementDisabledAsUser(int userId, boolean parent) { 11854 if (!mHasFeature) { 11855 return null; 11856 } 11857 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 11858 11859 final CallerIdentity caller = getCallerIdentity(); 11860 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 11861 11862 synchronized (getLockObject()) { 11863 final ArraySet<String> resultSet = new ArraySet<>(); 11864 11865 if (!parent) { 11866 final DevicePolicyData policy = getUserData(userId); 11867 for (ActiveAdmin admin : policy.mAdminList) { 11868 resultSet.addAll(admin.accountTypesWithManagementDisabled); 11869 } 11870 } 11871 11872 // Check if there's a profile owner of an org-owned device and the method is called for 11873 // the parent user of this profile owner. 11874 final ActiveAdmin orgOwnedAdmin = 11875 getProfileOwnerOfOrganizationOwnedDeviceLocked(userId); 11876 final boolean shouldGetParentAccounts = orgOwnedAdmin != null && (parent 11877 || UserHandle.getUserId(orgOwnedAdmin.getUid()) != userId); 11878 if (shouldGetParentAccounts) { 11879 resultSet.addAll( 11880 orgOwnedAdmin.getParentActiveAdmin().accountTypesWithManagementDisabled); 11881 } 11882 return resultSet.toArray(new String[resultSet.size()]); 11883 } 11884 } 11885 11886 @Override 11887 public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName, 11888 boolean uninstallBlocked) { 11889 final CallerIdentity caller = getCallerIdentity(who, callerPackage); 11890 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 11891 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller) 11892 || isFinancedDeviceOwner(caller))) 11893 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_BLOCK_UNINSTALL))); 11894 11895 final int userId = caller.getUserId(); 11896 synchronized (getLockObject()) { 11897 long id = mInjector.binderClearCallingIdentity(); 11898 try { 11899 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 11900 } catch (RemoteException re) { 11901 // Shouldn't happen. 11902 Slogf.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 11903 } finally { 11904 mInjector.binderRestoreCallingIdentity(id); 11905 } 11906 } 11907 if (uninstallBlocked) { 11908 final PackageManagerInternal pmi = mInjector.getPackageManagerInternal(); 11909 pmi.removeNonSystemPackageSuspensions(packageName, userId); 11910 pmi.removeDistractingPackageRestrictions(packageName, userId); 11911 pmi.flushPackageRestrictions(userId); 11912 } 11913 DevicePolicyEventLogger 11914 .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED) 11915 .setAdmin(caller.getPackageName()) 11916 .setBoolean(/* isDelegate */ who == null) 11917 .setStrings(packageName) 11918 .write(); 11919 } 11920 11921 @Override 11922 public boolean isUninstallBlocked(ComponentName who, String packageName) { 11923 // This function should return true if and only if the package is blocked by 11924 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 11925 // when the package is a system app, or when it is an active device admin. 11926 final int userId = UserHandle.getCallingUserId(); 11927 11928 synchronized (getLockObject()) { 11929 //TODO: This is a silly access control check. Remove. 11930 if (who != null) { 11931 final CallerIdentity caller = getCallerIdentity(who); 11932 Preconditions.checkCallAuthorization( 11933 isProfileOwner(caller) || isDefaultDeviceOwner(caller) 11934 || isFinancedDeviceOwner(caller)); 11935 } 11936 try { 11937 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 11938 } catch (RemoteException re) { 11939 // Shouldn't happen. 11940 Slogf.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 11941 } 11942 } 11943 return false; 11944 } 11945 11946 @Override 11947 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 11948 if (!mHasFeature) { 11949 return; 11950 } 11951 Objects.requireNonNull(who, "ComponentName is null"); 11952 final CallerIdentity caller = getCallerIdentity(who); 11953 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 11954 11955 synchronized (getLockObject()) { 11956 ActiveAdmin admin = getProfileOwnerLocked(caller); 11957 if (admin.disableCallerId != disabled) { 11958 admin.disableCallerId = disabled; 11959 saveSettingsLocked(caller.getUserId()); 11960 } 11961 } 11962 DevicePolicyEventLogger 11963 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALLER_ID_DISABLED) 11964 .setAdmin(who) 11965 .setBoolean(disabled) 11966 .write(); 11967 } 11968 11969 @Override 11970 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 11971 if (!mHasFeature) { 11972 return false; 11973 } 11974 Objects.requireNonNull(who, "ComponentName is null"); 11975 final CallerIdentity caller = getCallerIdentity(who); 11976 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 11977 11978 synchronized (getLockObject()) { 11979 ActiveAdmin admin = getProfileOwnerLocked(caller); 11980 return admin.disableCallerId; 11981 } 11982 } 11983 11984 @Override 11985 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 11986 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 11987 11988 final CallerIdentity caller = getCallerIdentity(); 11989 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)); 11990 11991 synchronized (getLockObject()) { 11992 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 11993 return (admin != null) ? admin.disableCallerId : false; 11994 } 11995 } 11996 11997 @Override 11998 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 11999 if (!mHasFeature) { 12000 return; 12001 } 12002 Objects.requireNonNull(who, "ComponentName is null"); 12003 final CallerIdentity caller = getCallerIdentity(who); 12004 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 12005 12006 synchronized (getLockObject()) { 12007 ActiveAdmin admin = getProfileOwnerLocked(caller); 12008 if (admin.disableContactsSearch != disabled) { 12009 admin.disableContactsSearch = disabled; 12010 saveSettingsLocked(caller.getUserId()); 12011 } 12012 } 12013 DevicePolicyEventLogger 12014 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED) 12015 .setAdmin(who) 12016 .setBoolean(disabled) 12017 .write(); 12018 } 12019 12020 @Override 12021 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 12022 if (!mHasFeature) { 12023 return false; 12024 } 12025 Objects.requireNonNull(who, "ComponentName is null"); 12026 final CallerIdentity caller = getCallerIdentity(who); 12027 Preconditions.checkCallAuthorization(isProfileOwner(caller)); 12028 12029 synchronized (getLockObject()) { 12030 ActiveAdmin admin = getProfileOwnerLocked(caller); 12031 return admin.disableContactsSearch; 12032 } 12033 } 12034 12035 @Override 12036 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 12037 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 12038 12039 final CallerIdentity caller = getCallerIdentity(); 12040 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)); 12041 12042 synchronized (getLockObject()) { 12043 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 12044 return (admin != null) ? admin.disableContactsSearch : false; 12045 } 12046 } 12047 12048 @Override 12049 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 12050 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 12051 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 12052 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 12053 final int callingUserId = UserHandle.getCallingUserId(); 12054 12055 mInjector.binderWithCleanCallingIdentity(() -> { 12056 synchronized (getLockObject()) { 12057 final int managedUserId = getManagedUserId(callingUserId); 12058 if (managedUserId < 0) { 12059 return; 12060 } 12061 if (isCrossProfileQuickContactDisabled(managedUserId)) { 12062 if (VERBOSE_LOG) { 12063 Slogf.v(LOG_TAG, "Cross-profile contacts access disabled for user %d", 12064 managedUserId); 12065 } 12066 return; 12067 } 12068 ContactsInternal.startQuickContactWithErrorToastForUser( 12069 mContext, intent, new UserHandle(managedUserId)); 12070 } 12071 }); 12072 } 12073 12074 /** 12075 * @return true if cross-profile QuickContact is disabled 12076 */ 12077 private boolean isCrossProfileQuickContactDisabled(@UserIdInt int userId) { 12078 return getCrossProfileCallerIdDisabledForUser(userId) 12079 && getCrossProfileContactsSearchDisabledForUser(userId); 12080 } 12081 12082 /** 12083 * @return the user ID of the managed user that is linked to the current user, if any. 12084 * Otherwise -1. 12085 */ 12086 public int getManagedUserId(@UserIdInt int callingUserId) { 12087 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "getManagedUserId: callingUserId=%d", callingUserId); 12088 12089 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 12090 if (ui.id == callingUserId || !ui.isManagedProfile()) { 12091 continue; // Caller user self, or not a managed profile. Skip. 12092 } 12093 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Managed user=%d", ui.id); 12094 return ui.id; 12095 } 12096 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Managed user not found."); 12097 return -1; 12098 } 12099 12100 @Override 12101 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 12102 if (!mHasFeature) { 12103 return; 12104 } 12105 Objects.requireNonNull(who, "ComponentName is null"); 12106 12107 final CallerIdentity caller = getCallerIdentity(who); 12108 Preconditions.checkCallAuthorization( 12109 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 12110 12111 synchronized (getLockObject()) { 12112 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 12113 if (admin.disableBluetoothContactSharing != disabled) { 12114 admin.disableBluetoothContactSharing = disabled; 12115 saveSettingsLocked(caller.getUserId()); 12116 } 12117 } 12118 DevicePolicyEventLogger 12119 .createEvent(DevicePolicyEnums.SET_BLUETOOTH_CONTACT_SHARING_DISABLED) 12120 .setAdmin(who) 12121 .setBoolean(disabled) 12122 .write(); 12123 } 12124 12125 @Override 12126 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 12127 if (!mHasFeature) { 12128 return false; 12129 } 12130 Objects.requireNonNull(who, "ComponentName is null"); 12131 12132 final CallerIdentity caller = getCallerIdentity(who); 12133 Preconditions.checkCallAuthorization( 12134 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 12135 12136 synchronized (getLockObject()) { 12137 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 12138 return admin.disableBluetoothContactSharing; 12139 } 12140 } 12141 12142 @Override 12143 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 12144 // TODO: Should there be a check to make sure this relationship is 12145 // within a profile group? 12146 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 12147 synchronized (getLockObject()) { 12148 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 12149 return (admin != null) ? admin.disableBluetoothContactSharing : false; 12150 } 12151 } 12152 12153 @Override 12154 public void setSecondaryLockscreenEnabled(ComponentName who, boolean enabled) { 12155 Objects.requireNonNull(who, "ComponentName is null"); 12156 12157 // Check can set secondary lockscreen enabled 12158 final CallerIdentity caller = getCallerIdentity(who); 12159 Preconditions.checkCallAuthorization( 12160 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 12161 Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()), 12162 "User %d is not allowed to call setSecondaryLockscreenEnabled", 12163 caller.getUserId()); 12164 12165 synchronized (getLockObject()) { 12166 // Allow testOnly admins to bypass supervision config requirement. 12167 Preconditions.checkCallAuthorization(isAdminTestOnlyLocked(who, caller.getUserId()) 12168 || isSupervisionComponentLocked(caller.getComponentName()), "Admin %s is not " 12169 + "the default supervision component", caller.getComponentName()); 12170 DevicePolicyData policy = getUserData(caller.getUserId()); 12171 policy.mSecondaryLockscreenEnabled = enabled; 12172 saveSettingsLocked(caller.getUserId()); 12173 } 12174 } 12175 12176 @Override 12177 public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) { 12178 synchronized (getLockObject()) { 12179 return getUserData(userHandle.getIdentifier()).mSecondaryLockscreenEnabled; 12180 } 12181 } 12182 12183 private boolean isManagedProfileOwner(CallerIdentity caller) { 12184 return isProfileOwner(caller) && isManagedProfile(caller.getUserId()); 12185 } 12186 12187 @Override 12188 public void setPreferentialNetworkServiceConfigs( 12189 List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) { 12190 if (!mHasFeature) { 12191 return; 12192 } 12193 final CallerIdentity caller = getCallerIdentity(); 12194 Preconditions.checkCallAuthorization((isProfileOwner(caller) 12195 && isManagedProfile(caller.getUserId())) 12196 || isDefaultDeviceOwner(caller), 12197 "Caller is not managed profile owner or device owner;" 12198 + " only managed profile owner or device owner may control the preferential" 12199 + " network service"); 12200 synchronized (getLockObject()) { 12201 final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked( 12202 caller.getUserId()); 12203 if (!requiredAdmin.mPreferentialNetworkServiceConfigs.equals( 12204 preferentialNetworkServiceConfigs)) { 12205 requiredAdmin.mPreferentialNetworkServiceConfigs = 12206 new ArrayList<>(preferentialNetworkServiceConfigs); 12207 saveSettingsLocked(caller.getUserId()); 12208 } 12209 } 12210 updateNetworkPreferenceForUser(caller.getUserId(), preferentialNetworkServiceConfigs); 12211 DevicePolicyEventLogger 12212 .createEvent(DevicePolicyEnums.SET_PREFERENTIAL_NETWORK_SERVICE_ENABLED) 12213 .setBoolean(preferentialNetworkServiceConfigs 12214 .stream().anyMatch(c -> c.isEnabled())) 12215 .write(); 12216 } 12217 12218 @Override 12219 public List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() { 12220 if (!mHasFeature) { 12221 return List.of(PreferentialNetworkServiceConfig.DEFAULT); 12222 } 12223 12224 final CallerIdentity caller = getCallerIdentity(); 12225 Preconditions.checkCallAuthorization((isProfileOwner(caller) 12226 && isManagedProfile(caller.getUserId())) 12227 || isDefaultDeviceOwner(caller), 12228 "Caller is not managed profile owner or device owner;" 12229 + " only managed profile owner or device owner may retrieve the " 12230 + "preferential network service configurations"); 12231 synchronized (getLockObject()) { 12232 final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked( 12233 caller.getUserId()); 12234 return requiredAdmin.mPreferentialNetworkServiceConfigs; 12235 } 12236 } 12237 12238 @Override 12239 public void setLockTaskPackages(ComponentName who, String[] packages) 12240 throws SecurityException { 12241 Objects.requireNonNull(who, "ComponentName is null"); 12242 Objects.requireNonNull(packages, "packages is null"); 12243 for (String pkg : packages) { 12244 enforceMaxPackageNameLength(pkg); 12245 } 12246 12247 final CallerIdentity caller = getCallerIdentity(who); 12248 12249 synchronized (getLockObject()) { 12250 enforceCanCallLockTaskLocked(caller); 12251 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_PACKAGES); 12252 final int userHandle = caller.getUserId(); 12253 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 12254 } 12255 } 12256 12257 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 12258 DevicePolicyData policy = getUserData(userHandle); 12259 policy.mLockTaskPackages = packages; 12260 12261 // Store the settings persistently. 12262 saveSettingsLocked(userHandle); 12263 updateLockTaskPackagesLocked(packages, userHandle); 12264 } 12265 12266 @Override 12267 public String[] getLockTaskPackages(ComponentName who) { 12268 Objects.requireNonNull(who, "ComponentName is null"); 12269 final CallerIdentity caller = getCallerIdentity(who); 12270 final int userHandle = caller.getUserId(); 12271 12272 synchronized (getLockObject()) { 12273 enforceCanCallLockTaskLocked(caller); 12274 final List<String> packages = getUserData(userHandle).mLockTaskPackages; 12275 return packages.toArray(new String[packages.size()]); 12276 } 12277 } 12278 12279 @Override 12280 public boolean isLockTaskPermitted(String pkg) { 12281 // Check policy-exempt apps first, as it doesn't require the lock 12282 if (listPolicyExemptAppsUnchecked().contains(pkg)) { 12283 if (VERBOSE_LOG) { 12284 Slogf.v(LOG_TAG, "isLockTaskPermitted(%s): returning true for policy-exempt app", 12285 pkg); 12286 } 12287 return true; 12288 } 12289 12290 final int userId = mInjector.userHandleGetCallingUserId(); 12291 synchronized (getLockObject()) { 12292 return getUserData(userId).mLockTaskPackages.contains(pkg); 12293 } 12294 } 12295 12296 @Override 12297 public void setLockTaskFeatures(ComponentName who, int flags) { 12298 Objects.requireNonNull(who, "ComponentName is null"); 12299 12300 // Throw if Overview is used without Home. 12301 boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0; 12302 boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0; 12303 Preconditions.checkArgument(hasHome || !hasOverview, 12304 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME"); 12305 boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0; 12306 Preconditions.checkArgument(hasHome || !hasNotification, 12307 "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME"); 12308 12309 final CallerIdentity caller = getCallerIdentity(who); 12310 final int userHandle = caller.getUserId(); 12311 synchronized (getLockObject()) { 12312 enforceCanCallLockTaskLocked(caller); 12313 enforceCanSetLockTaskFeaturesOnFinancedDevice(caller, flags); 12314 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_FEATURES); 12315 setLockTaskFeaturesLocked(userHandle, flags); 12316 } 12317 } 12318 12319 private void setLockTaskFeaturesLocked(int userHandle, int flags) { 12320 DevicePolicyData policy = getUserData(userHandle); 12321 policy.mLockTaskFeatures = flags; 12322 saveSettingsLocked(userHandle); 12323 updateLockTaskFeaturesLocked(flags, userHandle); 12324 } 12325 12326 @Override 12327 public int getLockTaskFeatures(ComponentName who) { 12328 Objects.requireNonNull(who, "ComponentName is null"); 12329 final CallerIdentity caller = getCallerIdentity(who); 12330 final int userHandle = caller.getUserId(); 12331 synchronized (getLockObject()) { 12332 enforceCanCallLockTaskLocked(caller); 12333 return getUserData(userHandle).mLockTaskFeatures; 12334 } 12335 } 12336 12337 private void maybeClearLockTaskPolicyLocked() { 12338 mInjector.binderWithCleanCallingIdentity(() -> { 12339 final List<UserInfo> userInfos = mUserManager.getAliveUsers(); 12340 for (int i = userInfos.size() - 1; i >= 0; i--) { 12341 int userId = userInfos.get(i).id; 12342 if (canUserUseLockTaskLocked(userId)) { 12343 continue; 12344 } 12345 12346 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages; 12347 if (!lockTaskPackages.isEmpty()) { 12348 Slogf.d(LOG_TAG, 12349 "User id " + userId + " not affiliated. Clearing lock task packages"); 12350 setLockTaskPackagesLocked(userId, Collections.<String>emptyList()); 12351 } 12352 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures; 12353 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){ 12354 Slogf.d(LOG_TAG, 12355 "User id " + userId + " not affiliated. Clearing lock task features"); 12356 setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE); 12357 } 12358 } 12359 }); 12360 } 12361 12362 private void enforceCanSetLockTaskFeaturesOnFinancedDevice(CallerIdentity caller, int flags) { 12363 int allowedFlags = LOCK_TASK_FEATURE_SYSTEM_INFO | LOCK_TASK_FEATURE_KEYGUARD 12364 | LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_GLOBAL_ACTIONS 12365 | LOCK_TASK_FEATURE_NOTIFICATIONS; 12366 12367 if (!isFinancedDeviceOwner(caller)) { 12368 return; 12369 } 12370 12371 if ((flags == 0) || ((flags & ~(allowedFlags)) != 0)) { 12372 throw new SecurityException( 12373 "Permitted lock task features when managing a financed device: " 12374 + "LOCK_TASK_FEATURE_SYSTEM_INFO, LOCK_TASK_FEATURE_KEYGUARD, " 12375 + "LOCK_TASK_FEATURE_HOME, LOCK_TASK_FEATURE_GLOBAL_ACTIONS, " 12376 + "or LOCK_TASK_FEATURE_NOTIFICATIONS"); 12377 } 12378 } 12379 12380 @Override 12381 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 12382 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 12383 String.format(NOT_SYSTEM_CALLER_MSG, "call notifyLockTaskModeChanged")); 12384 synchronized (getLockObject()) { 12385 final DevicePolicyData policy = getUserData(userHandle); 12386 12387 if (policy.mStatusBarDisabled) { 12388 // Status bar is managed by LockTaskController during LockTask, so we cancel this 12389 // policy when LockTask starts, and reapply it when LockTask ends 12390 setStatusBarDisabledInternal(!isEnabled, userHandle); 12391 } 12392 12393 Bundle adminExtras = new Bundle(); 12394 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 12395 for (ActiveAdmin admin : policy.mAdminList) { 12396 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 12397 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 12398 if (ownsDevice || ownsProfile) { 12399 if (isEnabled) { 12400 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 12401 adminExtras, null); 12402 } else { 12403 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 12404 } 12405 DevicePolicyEventLogger 12406 .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED) 12407 .setAdmin(admin.info.getPackageName()) 12408 .setBoolean(isEnabled) 12409 .setStrings(pkg) 12410 .write(); 12411 } 12412 } 12413 } 12414 } 12415 12416 @Override 12417 public void setGlobalSetting(ComponentName who, String setting, String value) { 12418 Objects.requireNonNull(who, "ComponentName is null"); 12419 final CallerIdentity caller = getCallerIdentity(who); 12420 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 12421 12422 DevicePolicyEventLogger 12423 .createEvent(DevicePolicyEnums.SET_GLOBAL_SETTING) 12424 .setAdmin(who) 12425 .setStrings(setting, value) 12426 .write(); 12427 12428 synchronized (getLockObject()) { 12429 // Some settings are no supported any more. However we do not want to throw a 12430 // SecurityException to avoid breaking apps. 12431 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 12432 Slogf.i(LOG_TAG, "Global setting no longer supported: %s", setting); 12433 return; 12434 } 12435 12436 if (!GLOBAL_SETTINGS_ALLOWLIST.contains(setting) 12437 && !UserManager.isDeviceInDemoMode(mContext)) { 12438 throw new SecurityException(String.format( 12439 "Permission denial: device owners cannot update %1$s", setting)); 12440 } 12441 12442 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 12443 // ignore if it contradicts an existing policy 12444 long timeMs = getMaximumTimeToLock( 12445 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 12446 if (timeMs > 0 && timeMs < Long.MAX_VALUE) { 12447 return; 12448 } 12449 } 12450 12451 mInjector.binderWithCleanCallingIdentity( 12452 () -> mInjector.settingsGlobalPutString(setting, value)); 12453 } 12454 } 12455 12456 @Override 12457 public void setSystemSetting(ComponentName who, String setting, String value) { 12458 Objects.requireNonNull(who, "ComponentName is null"); 12459 Preconditions.checkStringNotEmpty(setting, "String setting is null or empty"); 12460 final CallerIdentity caller = getCallerIdentity(who); 12461 Preconditions.checkCallAuthorization( 12462 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 12463 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_SETTING); 12464 12465 synchronized (getLockObject()) { 12466 if (!SYSTEM_SETTINGS_ALLOWLIST.contains(setting)) { 12467 throw new SecurityException(String.format( 12468 "Permission denial: device owners cannot update %1$s", setting)); 12469 } 12470 12471 mInjector.binderWithCleanCallingIdentity(() -> 12472 mInjector.settingsSystemPutStringForUser(setting, value, caller.getUserId())); 12473 } 12474 } 12475 12476 @Override 12477 public void setConfiguredNetworksLockdownState(ComponentName who, boolean lockdown) { 12478 if (!mHasFeature) { 12479 return; 12480 } 12481 Preconditions.checkNotNull(who, "ComponentName is null"); 12482 12483 final CallerIdentity caller = getCallerIdentity(who); 12484 Preconditions.checkCallAuthorization( 12485 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 12486 12487 mInjector.binderWithCleanCallingIdentity(() -> 12488 mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 12489 lockdown ? 1 : 0)); 12490 12491 DevicePolicyEventLogger 12492 .createEvent(DevicePolicyEnums.ALLOW_MODIFICATION_OF_ADMIN_CONFIGURED_NETWORKS) 12493 .setAdmin(caller.getComponentName()) 12494 .setBoolean(lockdown) 12495 .write(); 12496 } 12497 12498 @Override 12499 public boolean hasLockdownAdminConfiguredNetworks(ComponentName who) { 12500 if (!mHasFeature) { 12501 return false; 12502 } 12503 Preconditions.checkNotNull(who, "ComponentName is null"); 12504 12505 final CallerIdentity caller = getCallerIdentity(who); 12506 Preconditions.checkCallAuthorization( 12507 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 12508 12509 return mInjector.binderWithCleanCallingIdentity(() -> 12510 mInjector.settingsGlobalGetInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) > 0); 12511 } 12512 12513 @Override 12514 public void setLocationEnabled(ComponentName who, boolean locationEnabled) { 12515 Preconditions.checkNotNull(who, "ComponentName is null"); 12516 12517 final CallerIdentity caller = getCallerIdentity(who); 12518 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 12519 12520 UserHandle userHandle = caller.getUserHandle(); 12521 if (mIsAutomotive && !locationEnabled) { 12522 Slogf.i(LOG_TAG, "setLocationEnabled(%s, %b): ignoring for user %s on automotive build", 12523 who.flattenToShortString(), locationEnabled, userHandle); 12524 return; 12525 } 12526 12527 mInjector.binderWithCleanCallingIdentity(() -> { 12528 boolean wasLocationEnabled = mInjector.getLocationManager().isLocationEnabledForUser( 12529 userHandle); 12530 Slogf.v(LOG_TAG, "calling locationMgr.setLocationEnabledForUser(%b, %s) when it was %b", 12531 locationEnabled, userHandle, wasLocationEnabled); 12532 mInjector.getLocationManager().setLocationEnabledForUser(locationEnabled, userHandle); 12533 12534 // make a best effort to only show the notification if the admin is actually enabling 12535 // location. this is subject to race conditions with settings changes, but those are 12536 // unlikely to realistically interfere 12537 if (locationEnabled && !wasLocationEnabled) { 12538 showLocationSettingsEnabledNotification(userHandle); 12539 } 12540 }); 12541 12542 DevicePolicyEventLogger 12543 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING) 12544 .setAdmin(who) 12545 .setStrings(Settings.Secure.LOCATION_MODE, Integer.toString( 12546 locationEnabled ? Settings.Secure.LOCATION_MODE_ON 12547 : Settings.Secure.LOCATION_MODE_OFF)) 12548 .write(); 12549 } 12550 12551 private void showLocationSettingsEnabledNotification(UserHandle user) { 12552 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) 12553 .addFlags(FLAG_ACTIVITY_NEW_TASK); 12554 // Fill the component explicitly to prevent the PendingIntent from being intercepted 12555 // and fired with crafted target. b/155183624 12556 ActivityInfo targetInfo = intent.resolveActivityInfo( 12557 mInjector.getPackageManager(user.getIdentifier()), 12558 PackageManager.MATCH_SYSTEM_ONLY); 12559 if (targetInfo != null) { 12560 intent.setComponent(targetInfo.getComponentName()); 12561 } else { 12562 Slogf.wtf(LOG_TAG, "Failed to resolve intent for location settings"); 12563 } 12564 12565 // Simple notification clicks are immutable 12566 PendingIntent locationSettingsIntent = mInjector.pendingIntentGetActivityAsUser(mContext, 0, 12567 intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE, null, 12568 user); 12569 Notification notification = new Notification.Builder(mContext, 12570 SystemNotificationChannels.DEVICE_ADMIN) 12571 .setSmallIcon(R.drawable.ic_info_outline) 12572 .setContentTitle(getLocationChangedTitle()) 12573 .setContentText(getLocationChangedText()) 12574 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 12575 .setShowWhen(true) 12576 .setContentIntent(locationSettingsIntent) 12577 .setAutoCancel(true) 12578 .build(); 12579 mHandler.post(() -> mInjector.getNotificationManager().notify( 12580 SystemMessage.NOTE_LOCATION_CHANGED, notification)); 12581 } 12582 12583 private String getLocationChangedTitle() { 12584 return getUpdatableString( 12585 LOCATION_CHANGED_TITLE, R.string.location_changed_notification_title); 12586 } 12587 12588 private String getLocationChangedText() { 12589 return getUpdatableString( 12590 LOCATION_CHANGED_MESSAGE, R.string.location_changed_notification_text); 12591 } 12592 12593 @Override 12594 public boolean setTime(ComponentName who, long millis) { 12595 Objects.requireNonNull(who, "ComponentName is null"); 12596 12597 final CallerIdentity caller = getCallerIdentity(who); 12598 Preconditions.checkCallAuthorization( 12599 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 12600 12601 // Don't allow set time when auto time is on. 12602 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) { 12603 return false; 12604 } 12605 DevicePolicyEventLogger 12606 .createEvent(DevicePolicyEnums.SET_TIME) 12607 .setAdmin(caller.getComponentName()) 12608 .write(); 12609 mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis)); 12610 return true; 12611 } 12612 12613 @Override 12614 public boolean setTimeZone(ComponentName who, String timeZone) { 12615 Objects.requireNonNull(who, "ComponentName is null"); 12616 12617 final CallerIdentity caller = getCallerIdentity(who); 12618 Preconditions.checkCallAuthorization( 12619 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 12620 12621 // Don't allow set timezone when auto timezone is on. 12622 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) { 12623 return false; 12624 } 12625 mInjector.binderWithCleanCallingIdentity(() -> 12626 mInjector.getAlarmManager().setTimeZone(timeZone)); 12627 12628 DevicePolicyEventLogger 12629 .createEvent(DevicePolicyEnums.SET_TIME_ZONE) 12630 .setAdmin(caller.getComponentName()) 12631 .write(); 12632 return true; 12633 } 12634 12635 @Override 12636 public void setSecureSetting(ComponentName who, String setting, String value) { 12637 Objects.requireNonNull(who, "ComponentName is null"); 12638 final CallerIdentity caller = getCallerIdentity(who); 12639 Preconditions.checkCallAuthorization( 12640 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 12641 12642 int callingUserId = caller.getUserId(); 12643 synchronized (getLockObject()) { 12644 if (isDeviceOwner(who, callingUserId)) { 12645 if (!SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.contains(setting) 12646 && !isCurrentUserDemo()) { 12647 throw new SecurityException(String.format( 12648 "Permission denial: Device owners cannot update %1$s", setting)); 12649 } 12650 } else if (!SECURE_SETTINGS_ALLOWLIST.contains(setting) && !isCurrentUserDemo()) { 12651 throw new SecurityException(String.format( 12652 "Permission denial: Profile owners cannot update %1$s", setting)); 12653 } 12654 if (setting.equals(Settings.Secure.LOCATION_MODE) 12655 && isSetSecureSettingLocationModeCheckEnabled(who.getPackageName(), 12656 callingUserId)) { 12657 throw new UnsupportedOperationException(Settings.Secure.LOCATION_MODE + " is " 12658 + "deprecated. Please use setLocationEnabled() instead."); 12659 } 12660 if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) { 12661 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) { 12662 throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS 12663 + " is deprecated. Please use one of the user restrictions " 12664 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or " 12665 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY + " instead."); 12666 } 12667 if (!mUserManager.isManagedProfile(callingUserId)) { 12668 Slogf.e(LOG_TAG, "Ignoring setSecureSetting request for " 12669 + setting + ". User restriction " 12670 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or " 12671 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY 12672 + " should be used instead."); 12673 } else { 12674 try { 12675 setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 12676 (Integer.parseInt(value) == 0) ? true : false, /* parent */ false); 12677 DevicePolicyEventLogger 12678 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING) 12679 .setAdmin(who) 12680 .setStrings(setting, value) 12681 .write(); 12682 } catch (NumberFormatException exc) { 12683 Slogf.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting); 12684 } 12685 } 12686 return; 12687 } 12688 mInjector.binderWithCleanCallingIdentity(() -> { 12689 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) { 12690 final String currentValue = mInjector.settingsSecureGetStringForUser( 12691 Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId); 12692 if (!TextUtils.equals(currentValue, value)) { 12693 // Tell the content observer that the next change will be due to the owner 12694 // changing the value. There is a small race condition here that we cannot 12695 // avoid: Change notifications are sent asynchronously, so it is possible 12696 // that there are prior notifications queued up before the one we are about 12697 // to trigger. This is a corner case that will have no impact in practice. 12698 mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId); 12699 } 12700 getUserData(callingUserId).mCurrentInputMethodSet = true; 12701 saveSettingsLocked(callingUserId); 12702 } 12703 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 12704 // Notify the user if it's the location mode setting that's been set, to any value 12705 // other than 'off'. 12706 if (setting.equals(Settings.Secure.LOCATION_MODE) 12707 && (Integer.parseInt(value) != 0)) { 12708 showLocationSettingsEnabledNotification(UserHandle.of(callingUserId)); 12709 } 12710 }); 12711 } 12712 DevicePolicyEventLogger 12713 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING) 12714 .setAdmin(who) 12715 .setStrings(setting, value) 12716 .write(); 12717 } 12718 12719 private boolean isSetSecureSettingLocationModeCheckEnabled(String packageName, int userId) { 12720 return mInjector.isChangeEnabled(USE_SET_LOCATION_ENABLED, packageName, userId); 12721 } 12722 12723 @Override 12724 public void setMasterVolumeMuted(ComponentName who, boolean on) { 12725 Objects.requireNonNull(who, "ComponentName is null"); 12726 final CallerIdentity caller = getCallerIdentity(who); 12727 Preconditions.checkCallAuthorization( 12728 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 12729 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_MASTER_VOLUME_MUTED); 12730 12731 synchronized (getLockObject()) { 12732 setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on, /* parent */ false); 12733 DevicePolicyEventLogger 12734 .createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED) 12735 .setAdmin(who) 12736 .setBoolean(on) 12737 .write(); 12738 } 12739 } 12740 12741 @Override 12742 public boolean isMasterVolumeMuted(ComponentName who) { 12743 Objects.requireNonNull(who, "ComponentName is null"); 12744 final CallerIdentity caller = getCallerIdentity(who); 12745 Preconditions.checkCallAuthorization( 12746 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 12747 12748 synchronized (getLockObject()) { 12749 AudioManager audioManager = 12750 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 12751 return audioManager.isMasterMute(); 12752 } 12753 } 12754 12755 @Override 12756 public void setUserIcon(ComponentName who, Bitmap icon) { 12757 Objects.requireNonNull(who, "ComponentName is null"); 12758 final CallerIdentity caller = getCallerIdentity(who); 12759 Preconditions.checkCallAuthorization( 12760 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 12761 12762 synchronized (getLockObject()) { 12763 mInjector.binderWithCleanCallingIdentity( 12764 () -> mUserManagerInternal.setUserIcon(caller.getUserId(), icon)); 12765 } 12766 DevicePolicyEventLogger 12767 .createEvent(DevicePolicyEnums.SET_USER_ICON) 12768 .setAdmin(who) 12769 .write(); 12770 } 12771 12772 @Override 12773 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 12774 Objects.requireNonNull(who, "ComponentName is null"); 12775 final CallerIdentity caller = getCallerIdentity(who); 12776 Preconditions.checkCallAuthorization( 12777 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 12778 12779 final int userId = caller.getUserId(); 12780 synchronized (getLockObject()) { 12781 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId), 12782 String.format( 12783 "Admin %s is neither the device owner or affiliated user's profile " 12784 + "owner.", who)); 12785 } 12786 if (isManagedProfile(userId)) { 12787 throw new SecurityException("Managed profile cannot disable keyguard"); 12788 } 12789 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEYGUARD_DISABLED); 12790 12791 long ident = mInjector.binderClearCallingIdentity(); 12792 try { 12793 // disallow disabling the keyguard if a password is currently set 12794 if (disabled && mLockPatternUtils.isSecure(userId)) { 12795 return false; 12796 } 12797 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 12798 if (disabled) { 12799 mInjector 12800 .getIWindowManager() 12801 .dismissKeyguard(null /* callback */, null /* message */); 12802 } 12803 DevicePolicyEventLogger 12804 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED) 12805 .setAdmin(who) 12806 .setBoolean(disabled) 12807 .write(); 12808 } catch (RemoteException e) { 12809 // Same process, does not happen. 12810 } finally { 12811 mInjector.binderRestoreCallingIdentity(ident); 12812 } 12813 return true; 12814 } 12815 12816 @Override 12817 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 12818 final CallerIdentity caller = getCallerIdentity(who); 12819 Preconditions.checkCallAuthorization( 12820 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 12821 12822 int userId = caller.getUserId(); 12823 synchronized (getLockObject()) { 12824 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId), 12825 "Admin " + who 12826 + " is neither the device owner or affiliated user's profile owner."); 12827 if (isManagedProfile(userId)) { 12828 throw new SecurityException("Managed profile cannot disable status bar"); 12829 } 12830 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_STATUS_BAR_DISABLED); 12831 12832 DevicePolicyData policy = getUserData(userId); 12833 if (policy.mStatusBarDisabled != disabled) { 12834 boolean isLockTaskMode = false; 12835 try { 12836 isLockTaskMode = mInjector.getIActivityTaskManager().getLockTaskModeState() 12837 != LOCK_TASK_MODE_NONE; 12838 } catch (RemoteException e) { 12839 Slogf.e(LOG_TAG, "Failed to get LockTask mode"); 12840 } 12841 if (!isLockTaskMode) { 12842 if (!setStatusBarDisabledInternal(disabled, userId)) { 12843 return false; 12844 } 12845 } 12846 policy.mStatusBarDisabled = disabled; 12847 saveSettingsLocked(userId); 12848 } 12849 } 12850 DevicePolicyEventLogger 12851 .createEvent(DevicePolicyEnums.SET_STATUS_BAR_DISABLED) 12852 .setAdmin(who) 12853 .setBoolean(disabled) 12854 .write(); 12855 return true; 12856 } 12857 12858 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 12859 long ident = mInjector.binderClearCallingIdentity(); 12860 try { 12861 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 12862 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 12863 if (statusBarService != null) { 12864 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 12865 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 12866 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 12867 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 12868 return true; 12869 } 12870 } catch (RemoteException e) { 12871 Slogf.e(LOG_TAG, "Failed to disable the status bar", e); 12872 } finally { 12873 mInjector.binderRestoreCallingIdentity(ident); 12874 } 12875 return false; 12876 } 12877 12878 /** 12879 * We need to update the internal state of whether a user has completed setup or a 12880 * device has paired once. After that, we ignore any changes that reset the 12881 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 12882 * as we don't trust any apps that might try to reset them. 12883 * <p> 12884 * Unfortunately, we don't know which user's setup state was changed, so we write all of 12885 * them. 12886 */ 12887 void updateUserSetupCompleteAndPaired() { 12888 List<UserInfo> users = mUserManager.getAliveUsers(); 12889 final int N = users.size(); 12890 for (int i = 0; i < N; i++) { 12891 int userHandle = users.get(i).id; 12892 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 12893 userHandle) != 0) { 12894 DevicePolicyData policy = getUserData(userHandle); 12895 if (!policy.mUserSetupComplete) { 12896 policy.mUserSetupComplete = true; 12897 if (userHandle == UserHandle.USER_SYSTEM) { 12898 mStateCache.setDeviceProvisioned(true); 12899 } 12900 synchronized (getLockObject()) { 12901 saveSettingsLocked(userHandle); 12902 } 12903 } 12904 } 12905 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 12906 userHandle) != 0) { 12907 DevicePolicyData policy = getUserData(userHandle); 12908 if (!policy.mPaired) { 12909 policy.mPaired = true; 12910 synchronized (getLockObject()) { 12911 saveSettingsLocked(userHandle); 12912 } 12913 } 12914 } 12915 } 12916 } 12917 12918 private class SetupContentObserver extends ContentObserver { 12919 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 12920 Settings.Secure.USER_SETUP_COMPLETE); 12921 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 12922 Settings.Global.DEVICE_PROVISIONED); 12923 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 12924 private final Uri mDefaultImeChanged = Settings.Secure.getUriFor( 12925 Settings.Secure.DEFAULT_INPUT_METHOD); 12926 12927 @GuardedBy("getLockObject()") 12928 private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>(); 12929 12930 public SetupContentObserver(Handler handler) { 12931 super(handler); 12932 } 12933 12934 void register() { 12935 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 12936 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 12937 if (mIsWatch) { 12938 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 12939 } 12940 mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL); 12941 } 12942 12943 @GuardedBy("getLockObject()") 12944 private void addPendingChangeByOwnerLocked(int userId) { 12945 mUserIdsWithPendingChangesByOwner.add(userId); 12946 } 12947 12948 @Override 12949 public void onChange(boolean selfChange, Uri uri, int userId) { 12950 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 12951 updateUserSetupCompleteAndPaired(); 12952 } else if (mDeviceProvisioned.equals(uri)) { 12953 synchronized (getLockObject()) { 12954 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 12955 // is delayed until device is marked as provisioned. 12956 setDeviceOwnershipSystemPropertyLocked(); 12957 } 12958 } else if (mDefaultImeChanged.equals(uri)) { 12959 synchronized (getLockObject()) { 12960 if (mUserIdsWithPendingChangesByOwner.contains(userId)) { 12961 // This change notification was triggered by the owner changing the current 12962 // IME. Ignore it. 12963 mUserIdsWithPendingChangesByOwner.remove(userId); 12964 } else { 12965 // This change notification was triggered by the user manually changing the 12966 // current IME. 12967 getUserData(userId).mCurrentInputMethodSet = false; 12968 saveSettingsLocked(userId); 12969 } 12970 } 12971 } 12972 } 12973 } 12974 12975 private class DevicePolicyConstantsObserver extends ContentObserver { 12976 final Uri mConstantsUri = 12977 Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS); 12978 12979 DevicePolicyConstantsObserver(Handler handler) { 12980 super(handler); 12981 } 12982 12983 void register() { 12984 mInjector.registerContentObserver( 12985 mConstantsUri, /* notifyForDescendents= */ false, this, UserHandle.USER_ALL); 12986 } 12987 12988 @Override 12989 public void onChange(boolean selfChange, Uri uri, int userId) { 12990 mConstants = loadConstants(); 12991 invalidateBinderCaches(); 12992 12993 mInjector.binderWithCleanCallingIdentity(() -> { 12994 final Intent intent = new Intent( 12995 DevicePolicyManager.ACTION_DEVICE_POLICY_CONSTANTS_CHANGED); 12996 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 12997 final List<UserInfo> users = mUserManager.getAliveUsers(); 12998 for (int i = 0; i < users.size(); i++) { 12999 mContext.sendBroadcastAsUser(intent, UserHandle.of(users.get(i).id)); 13000 } 13001 }); 13002 } 13003 } 13004 13005 @VisibleForTesting 13006 final class LocalService extends DevicePolicyManagerInternal 13007 implements DevicePolicyManagerLiteInternal { 13008 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 13009 13010 @Override 13011 public List<String> getCrossProfileWidgetProviders(int profileId) { 13012 synchronized (getLockObject()) { 13013 if (mOwners == null) { 13014 return Collections.emptyList(); 13015 } 13016 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 13017 if (ownerComponent == null) { 13018 return Collections.emptyList(); 13019 } 13020 13021 DevicePolicyData policy = getUserDataUnchecked(profileId); 13022 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 13023 13024 if (admin == null || admin.crossProfileWidgetProviders == null 13025 || admin.crossProfileWidgetProviders.isEmpty()) { 13026 return Collections.emptyList(); 13027 } 13028 13029 return admin.crossProfileWidgetProviders; 13030 } 13031 } 13032 13033 @Override 13034 public void addOnCrossProfileWidgetProvidersChangeListener( 13035 OnCrossProfileWidgetProvidersChangeListener listener) { 13036 synchronized (getLockObject()) { 13037 if (mWidgetProviderListeners == null) { 13038 mWidgetProviderListeners = new ArrayList<>(); 13039 } 13040 if (!mWidgetProviderListeners.contains(listener)) { 13041 mWidgetProviderListeners.add(listener); 13042 } 13043 } 13044 } 13045 13046 @Override 13047 public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent( 13048 @NonNull UserHandle userHandle) { 13049 return DevicePolicyManagerService.this.getProfileOwnerOrDeviceOwnerSupervisionComponent( 13050 userHandle); 13051 } 13052 13053 @Override 13054 public boolean isActiveDeviceOwner(int uid) { 13055 return isDefaultDeviceOwner(new CallerIdentity(uid, null, null)); 13056 } 13057 13058 @Override 13059 public boolean isActiveProfileOwner(int uid) { 13060 return isProfileOwner(new CallerIdentity(uid, null, null)); 13061 } 13062 13063 @Override 13064 public boolean isActiveSupervisionApp(int uid) { 13065 if (!isProfileOwner(new CallerIdentity(uid, null, null))) { 13066 return false; 13067 } 13068 synchronized (getLockObject()) { 13069 final ActiveAdmin admin = getProfileOwnerAdminLocked(UserHandle.getUserId(uid)); 13070 if (admin == null) { 13071 return false; 13072 } 13073 13074 return isSupervisionComponentLocked(admin.info.getComponent()); 13075 } 13076 } 13077 13078 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 13079 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 13080 synchronized (getLockObject()) { 13081 listeners = new ArrayList<>(mWidgetProviderListeners); 13082 } 13083 final int listenerCount = listeners.size(); 13084 for (int i = 0; i < listenerCount; i++) { 13085 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 13086 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 13087 } 13088 } 13089 13090 @Override 13091 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 13092 // This method is called from AM with its lock held, so don't take the DPMS lock. 13093 // b/29242568 13094 13095 if (getEnforcingAdminAndUserDetailsInternal(userId, null) != null 13096 || useDefaultIfNoAdmin) { 13097 return DevicePolicyManagerService.this.createShowAdminSupportIntent(userId); 13098 } 13099 return null; 13100 } 13101 13102 @Override 13103 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 13104 Intent intent = null; 13105 if (getEnforcingAdminAndUserDetailsInternal(userId, userRestriction) != null) { 13106 intent = DevicePolicyManagerService.this.createShowAdminSupportIntent(userId); 13107 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, userRestriction); 13108 } 13109 return intent; 13110 } 13111 13112 @Override 13113 public boolean isUserAffiliatedWithDevice(int userId) { 13114 return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId); 13115 } 13116 13117 @Override 13118 public boolean canSilentlyInstallPackage(String callerPackage, int callerUid) { 13119 if (callerPackage == null) { 13120 return false; 13121 } 13122 13123 CallerIdentity caller = new CallerIdentity(callerUid, null, null); 13124 if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid)) 13125 && (isActiveProfileOwner(callerUid) 13126 || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller))) { 13127 // device owner or a profile owner affiliated with the device owner 13128 return true; 13129 } 13130 return false; 13131 } 13132 13133 @Override 13134 public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) { 13135 mInjector.binderWithCleanCallingIdentity(() -> { 13136 synchronized (getLockObject()) { 13137 updateMaximumTimeToLockLocked(userId); 13138 updatePasswordQualityCacheForUserGroup(userId); 13139 } 13140 }); 13141 DevicePolicyEventLogger 13142 .createEvent(DevicePolicyEnums.SEPARATE_PROFILE_CHALLENGE_CHANGED) 13143 .setBoolean(isSeparateProfileChallengeEnabled(userId)) 13144 .write(); 13145 invalidateBinderCaches(); 13146 } 13147 13148 @Override 13149 public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) { 13150 synchronized (getLockObject()) { 13151 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING, 13152 UserHandle.of(userId))) { 13153 Slogf.e(LOG_TAG, "printing is enabled for user %d", userId); 13154 return null; 13155 } 13156 String ownerPackage = mOwners.getProfileOwnerPackage(userId); 13157 if (ownerPackage == null) { 13158 ownerPackage = mOwners.getDeviceOwnerPackageName(); 13159 } 13160 final String packageName = ownerPackage; 13161 PackageManager pm = mInjector.getPackageManager(); 13162 PackageInfo packageInfo = mInjector.binderWithCleanCallingIdentity(() -> { 13163 try { 13164 return pm.getPackageInfo(packageName, 0); 13165 } catch (NameNotFoundException e) { 13166 Slogf.e(LOG_TAG, "getPackageInfo error", e); 13167 return null; 13168 } 13169 }); 13170 if (packageInfo == null) { 13171 Slogf.e(LOG_TAG, "packageInfo is inexplicably null"); 13172 return null; 13173 } 13174 ApplicationInfo appInfo = packageInfo.applicationInfo; 13175 if (appInfo == null) { 13176 Slogf.e(LOG_TAG, "appInfo is inexplicably null"); 13177 return null; 13178 } 13179 CharSequence appLabel = pm.getApplicationLabel(appInfo); 13180 if (appLabel == null) { 13181 Slogf.e(LOG_TAG, "appLabel is inexplicably null"); 13182 return null; 13183 } 13184 return getUpdatableString( 13185 PRINTING_DISABLED_NAMED_ADMIN, 13186 R.string.printing_disabled_by, 13187 appLabel); 13188 } 13189 } 13190 13191 @Override 13192 protected DevicePolicyCache getDevicePolicyCache() { 13193 return mPolicyCache; 13194 } 13195 13196 @Override 13197 protected DeviceStateCache getDeviceStateCache() { 13198 return mStateCache; 13199 } 13200 13201 @Override 13202 public List<String> getAllCrossProfilePackages() { 13203 return DevicePolicyManagerService.this.getAllCrossProfilePackages(); 13204 } 13205 13206 @Override 13207 public List<String> getDefaultCrossProfilePackages() { 13208 return DevicePolicyManagerService.this.getDefaultCrossProfilePackages(); 13209 } 13210 13211 @Override 13212 public void broadcastIntentToManifestReceivers( 13213 Intent intent, UserHandle parentHandle, boolean requiresPermission) { 13214 Objects.requireNonNull(intent); 13215 Objects.requireNonNull(parentHandle); 13216 Slogf.i(LOG_TAG, "Sending %s broadcast to manifest receivers.", intent.getAction()); 13217 broadcastIntentToCrossProfileManifestReceivers( 13218 intent, parentHandle, requiresPermission); 13219 broadcastIntentToDevicePolicyManagerRoleHolder(intent, parentHandle); 13220 } 13221 13222 private void broadcastIntentToCrossProfileManifestReceivers( 13223 Intent intent, UserHandle userHandle, boolean requiresPermission) { 13224 final int userId = userHandle.getIdentifier(); 13225 try { 13226 final List<ResolveInfo> receivers = mIPackageManager.queryIntentReceivers( 13227 intent, /* resolvedType= */ null, 13228 STOCK_PM_FLAGS, userId).getList(); 13229 for (ResolveInfo receiver : receivers) { 13230 final String packageName = receiver.getComponentInfo().packageName; 13231 if (checkCrossProfilePackagePermissions(packageName, userId, 13232 requiresPermission) 13233 || checkModifyQuietModePermission(packageName, userId)) { 13234 Slogf.i(LOG_TAG, "Sending %s broadcast to %s.", intent.getAction(), 13235 packageName); 13236 final Intent packageIntent = new Intent(intent) 13237 .setComponent(receiver.getComponentInfo().getComponentName()) 13238 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 13239 mContext.sendBroadcastAsUser(packageIntent, userHandle); 13240 } 13241 } 13242 } catch (RemoteException ex) { 13243 Slogf.w(LOG_TAG, "Cannot get list of broadcast receivers for %s because: %s.", 13244 intent.getAction(), ex); 13245 } 13246 } 13247 13248 private void broadcastIntentToDevicePolicyManagerRoleHolder( 13249 Intent intent, UserHandle userHandle) { 13250 final int userId = userHandle.getIdentifier(); 13251 final String packageName = getDevicePolicyManagementRoleHolderPackageName(mContext); 13252 if (packageName == null) { 13253 return; 13254 } 13255 try { 13256 final Intent packageIntent = new Intent(intent) 13257 .setPackage(packageName); 13258 final List<ResolveInfo> receivers = mIPackageManager.queryIntentReceivers( 13259 packageIntent, 13260 /* resolvedType= */ null, 13261 STOCK_PM_FLAGS, 13262 userId).getList(); 13263 if (receivers.isEmpty()) { 13264 return; 13265 } 13266 for (ResolveInfo receiver : receivers) { 13267 final Intent componentIntent = new Intent(packageIntent) 13268 .setComponent(receiver.getComponentInfo().getComponentName()) 13269 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 13270 mContext.sendBroadcastAsUser(componentIntent, userHandle); 13271 } 13272 } catch (RemoteException ex) { 13273 Slogf.w(LOG_TAG, "Cannot get list of broadcast receivers for %s because: %s.", 13274 intent.getAction(), ex); 13275 } 13276 } 13277 13278 /** 13279 * Checks whether the package {@code packageName} has the {@code MODIFY_QUIET_MODE} 13280 * permission granted for the user {@code userId}. 13281 */ 13282 private boolean checkModifyQuietModePermission(String packageName, @UserIdInt int userId) { 13283 try { 13284 final int uid = Objects.requireNonNull( 13285 mInjector.getPackageManager().getApplicationInfoAsUser( 13286 Objects.requireNonNull(packageName), /* flags= */ 0, userId)).uid; 13287 return PackageManager.PERMISSION_GRANTED 13288 == ActivityManager.checkComponentPermission( 13289 android.Manifest.permission.MODIFY_QUIET_MODE, uid, /* owningUid= */ 13290 -1, /* exported= */ true); 13291 } catch (NameNotFoundException ex) { 13292 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.", 13293 packageName); 13294 return false; 13295 } 13296 } 13297 13298 /** 13299 * Checks whether the package {@code packageName} has the required permissions to receive 13300 * cross-profile broadcasts on behalf of the user {@code userId}. 13301 */ 13302 private boolean checkCrossProfilePackagePermissions(String packageName, 13303 @UserIdInt int userId, boolean requiresPermission) { 13304 final PackageManagerInternal pmInternal = LocalServices.getService( 13305 PackageManagerInternal.class); 13306 final AndroidPackage androidPackage = pmInternal.getPackage(packageName); 13307 if (androidPackage == null || !androidPackage.isCrossProfile()) { 13308 return false; 13309 } 13310 if (!requiresPermission) { 13311 return true; 13312 } 13313 if (!isPackageEnabled(packageName, userId)) { 13314 return false; 13315 } 13316 try { 13317 final CrossProfileAppsInternal crossProfileAppsService = LocalServices.getService( 13318 CrossProfileAppsInternal.class); 13319 return crossProfileAppsService.verifyPackageHasInteractAcrossProfilePermission( 13320 packageName, userId); 13321 } catch (NameNotFoundException ex) { 13322 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.", 13323 packageName); 13324 return false; 13325 } 13326 } 13327 13328 private boolean isPackageEnabled(String packageName, @UserIdInt int userId) { 13329 final int callingUid = Binder.getCallingUid(); 13330 final long ident = Binder.clearCallingIdentity(); 13331 try { 13332 final PackageInfo info = mInjector.getPackageManagerInternal() 13333 .getPackageInfo( 13334 packageName, 13335 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 13336 callingUid, 13337 userId); 13338 return info != null && info.applicationInfo.enabled; 13339 } finally { 13340 Binder.restoreCallingIdentity(ident); 13341 } 13342 } 13343 13344 @Override 13345 public ComponentName getProfileOwnerAsUser(@UserIdInt int userId) { 13346 return DevicePolicyManagerService.this.getProfileOwnerAsUser(userId); 13347 } 13348 13349 @Override 13350 public int getDeviceOwnerUserId() { 13351 return DevicePolicyManagerService.this.getDeviceOwnerUserId(); 13352 } 13353 13354 @Override 13355 public boolean isDeviceOrProfileOwnerInCallingUser(String packageName) { 13356 return isDeviceOwnerInCallingUser(packageName) 13357 || isProfileOwnerInCallingUser(packageName); 13358 } 13359 13360 private boolean isDeviceOwnerInCallingUser(String packageName) { 13361 final ComponentName deviceOwnerInCallingUser = 13362 DevicePolicyManagerService.this.getDeviceOwnerComponent( 13363 /* callingUserOnly= */ true); 13364 return deviceOwnerInCallingUser != null 13365 && packageName.equals(deviceOwnerInCallingUser.getPackageName()); 13366 } 13367 13368 private boolean isProfileOwnerInCallingUser(String packageName) { 13369 final ComponentName profileOwnerInCallingUser = 13370 getProfileOwnerAsUser(UserHandle.getCallingUserId()); 13371 return profileOwnerInCallingUser != null 13372 && packageName.equals(profileOwnerInCallingUser.getPackageName()); 13373 } 13374 13375 @Override 13376 public boolean supportsResetOp(int op) { 13377 return op == AppOpsManager.OP_INTERACT_ACROSS_PROFILES 13378 && LocalServices.getService(CrossProfileAppsInternal.class) != null; 13379 } 13380 13381 @Override 13382 public void resetOp(int op, String packageName, @UserIdInt int userId) { 13383 if (op != AppOpsManager.OP_INTERACT_ACROSS_PROFILES) { 13384 throw new IllegalArgumentException("Unsupported op for DPM reset: " + op); 13385 } 13386 LocalServices.getService(CrossProfileAppsInternal.class) 13387 .setInteractAcrossProfilesAppOp( 13388 packageName, findInteractAcrossProfilesResetMode(packageName), userId); 13389 } 13390 13391 @Override 13392 public void notifyUnsafeOperationStateChanged(DevicePolicySafetyChecker checker, int reason, 13393 boolean isSafe) { 13394 // TODO(b/178494483): use EventLog instead 13395 // TODO(b/178494483): log metrics? 13396 if (VERBOSE_LOG) { 13397 Slogf.v(LOG_TAG, "notifyUnsafeOperationStateChanged(): %s=%b", 13398 DevicePolicyManager.operationSafetyReasonToString(reason), isSafe); 13399 } 13400 Preconditions.checkArgument(mSafetyChecker == checker, 13401 "invalid checker: should be %s, was %s", mSafetyChecker, checker); 13402 13403 Bundle extras = new Bundle(); 13404 extras.putInt(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_REASON, reason); 13405 extras.putBoolean(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_STATE, isSafe); 13406 13407 if (mOwners.hasDeviceOwner()) { 13408 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying DO"); 13409 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED, 13410 extras); 13411 } 13412 for (int profileOwnerId : mOwners.getProfileOwnerKeys()) { 13413 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying PO for user " + profileOwnerId); 13414 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED, 13415 extras, profileOwnerId); 13416 } 13417 } 13418 13419 private @Mode int findInteractAcrossProfilesResetMode(String packageName) { 13420 return getDefaultCrossProfilePackages().contains(packageName) 13421 ? AppOpsManager.MODE_ALLOWED 13422 : AppOpsManager.opToDefaultMode(AppOpsManager.OP_INTERACT_ACROSS_PROFILES); 13423 } 13424 } 13425 13426 private Intent createShowAdminSupportIntent(int userId) { 13427 // This method is called with AMS lock held, so don't take DPMS lock 13428 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 13429 intent.putExtra(Intent.EXTRA_USER_ID, userId); 13430 intent.setFlags(FLAG_ACTIVITY_NEW_TASK); 13431 return intent; 13432 } 13433 13434 /** 13435 * @param restriction The restriction enforced by admin. It could be any user restriction or 13436 * policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA}, 13437 * {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE} and {@link 13438 * DevicePolicyManager#POLICY_SUSPEND_PACKAGES}. 13439 */ 13440 private Bundle getEnforcingAdminAndUserDetailsInternal(int userId, String restriction) { 13441 Bundle result = null; 13442 13443 // For POLICY_SUSPEND_PACKAGES return PO or DO to keep the behavior same as 13444 // before the bug fix for b/192245204. 13445 if (restriction == null || DevicePolicyManager.POLICY_SUSPEND_PACKAGES.equals( 13446 restriction)) { 13447 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 13448 if (profileOwner != null) { 13449 result = new Bundle(); 13450 result.putInt(Intent.EXTRA_USER_ID, userId); 13451 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN, 13452 profileOwner); 13453 return result; 13454 } 13455 final Pair<Integer, ComponentName> deviceOwner = 13456 mOwners.getDeviceOwnerUserIdAndComponent(); 13457 if (deviceOwner != null && deviceOwner.first == userId) { 13458 result = new Bundle(); 13459 result.putInt(Intent.EXTRA_USER_ID, userId); 13460 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN, 13461 deviceOwner.second); 13462 return result; 13463 } 13464 } else if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) 13465 || DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) { 13466 synchronized (getLockObject()) { 13467 final DevicePolicyData policy = getUserData(userId); 13468 final int N = policy.mAdminList.size(); 13469 for (int i = 0; i < N; i++) { 13470 final ActiveAdmin admin = policy.mAdminList.get(i); 13471 if ((admin.disableCamera && 13472 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) 13473 || (admin.disableScreenCapture && DevicePolicyManager 13474 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) { 13475 result = new Bundle(); 13476 result.putInt(Intent.EXTRA_USER_ID, userId); 13477 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN, 13478 admin.info.getComponent()); 13479 return result; 13480 } 13481 } 13482 // For the camera, a device owner on a different user can disable it globally, 13483 // so we need an additional check. 13484 if (result == null 13485 && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) { 13486 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 13487 if (admin != null && admin.disableCamera) { 13488 result = new Bundle(); 13489 result.putInt(Intent.EXTRA_USER_ID, mOwners.getDeviceOwnerUserId()); 13490 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN, 13491 admin.info.getComponent()); 13492 return result; 13493 } 13494 } 13495 } 13496 } else { 13497 long ident = mInjector.binderClearCallingIdentity(); 13498 try { 13499 List<UserManager.EnforcingUser> sources = mUserManager 13500 .getUserRestrictionSources(restriction, UserHandle.of(userId)); 13501 if (sources == null) { 13502 // The restriction is not enforced. 13503 return null; 13504 } 13505 int sizeBefore = sources.size(); 13506 if (sizeBefore > 1) { 13507 Slogf.d(LOG_TAG, "getEnforcingAdminAndUserDetailsInternal(%d, %s): " 13508 + "%d sources found, excluding those set by UserManager", 13509 userId, restriction, sizeBefore); 13510 sources = getDevicePolicySources(sources); 13511 } 13512 if (sources.isEmpty()) { 13513 // The restriction is not enforced (or is just enforced by the system) 13514 return null; 13515 } 13516 13517 if (sources.size() > 1) { 13518 // In this case, we'll show an admin support dialog that does not 13519 // specify the admin. 13520 // TODO(b/128928355): if this restriction is enforced by multiple DPCs, return 13521 // the admin for the calling user. 13522 Slogf.w(LOG_TAG, "getEnforcingAdminAndUserDetailsInternal(%d, %s): multiple " 13523 + "sources for restriction %s on user %d", restriction, userId); 13524 result = new Bundle(); 13525 result.putInt(Intent.EXTRA_USER_ID, userId); 13526 return result; 13527 } 13528 final UserManager.EnforcingUser enforcingUser = sources.get(0); 13529 final int sourceType = enforcingUser.getUserRestrictionSource(); 13530 final int enforcingUserId = enforcingUser.getUserHandle().getIdentifier(); 13531 if (sourceType == UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) { 13532 // Restriction was enforced by PO 13533 final ComponentName profileOwner = mOwners.getProfileOwnerComponent( 13534 enforcingUserId); 13535 if (profileOwner != null) { 13536 result = new Bundle(); 13537 result.putInt(Intent.EXTRA_USER_ID, enforcingUserId); 13538 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN, 13539 profileOwner); 13540 return result; 13541 } 13542 } else if (sourceType == UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) { 13543 // Restriction was enforced by DO 13544 final Pair<Integer, ComponentName> deviceOwner = 13545 mOwners.getDeviceOwnerUserIdAndComponent(); 13546 if (deviceOwner != null) { 13547 result = new Bundle(); 13548 result.putInt(Intent.EXTRA_USER_ID, deviceOwner.first); 13549 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN, 13550 deviceOwner.second); 13551 return result; 13552 } 13553 } else if (sourceType == UserManager.RESTRICTION_SOURCE_SYSTEM) { 13554 /* 13555 * In this case, the user restriction is enforced by the system. 13556 * So we won't show an admin support intent, even if it is also 13557 * enforced by a profile/device owner. 13558 */ 13559 return null; 13560 } 13561 } finally { 13562 mInjector.binderRestoreCallingIdentity(ident); 13563 } 13564 } 13565 return null; 13566 } 13567 13568 /** 13569 * Excludes restrictions imposed by UserManager. 13570 */ 13571 private List<UserManager.EnforcingUser> getDevicePolicySources( 13572 List<UserManager.EnforcingUser> sources) { 13573 int sizeBefore = sources.size(); 13574 List<UserManager.EnforcingUser> realSources = new ArrayList<>(sizeBefore); 13575 for (int i = 0; i < sizeBefore; i++) { 13576 UserManager.EnforcingUser source = sources.get(i); 13577 int type = source.getUserRestrictionSource(); 13578 if (type != UserManager.RESTRICTION_SOURCE_PROFILE_OWNER 13579 && type != UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) { 13580 // TODO(b/128928355): add unit test 13581 Slogf.d(LOG_TAG, "excluding source of type %s at index %d", 13582 userRestrictionSourceToString(type), i); 13583 continue; 13584 } 13585 realSources.add(source); 13586 } 13587 return realSources; 13588 } 13589 13590 private static String userRestrictionSourceToString(@UserRestrictionSource int source) { 13591 return DebugUtils.flagsToString(UserManager.class, "RESTRICTION_", source); 13592 } 13593 13594 /** 13595 * @param restriction The restriction enforced by admin. It could be any user restriction or 13596 * policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and 13597 * {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}. 13598 * @return Details of admin and user which enforced the restriction for the userId. 13599 */ 13600 @Override 13601 public Bundle getEnforcingAdminAndUserDetails(int userId, String restriction) { 13602 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity())); 13603 return getEnforcingAdminAndUserDetailsInternal(userId, restriction); 13604 } 13605 13606 /** 13607 * @param restriction The restriction enforced by admin. It could be any user restriction or 13608 * policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and 13609 * {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}. 13610 */ 13611 @Override 13612 public Intent createAdminSupportIntent(String restriction) { 13613 Objects.requireNonNull(restriction); 13614 final CallerIdentity caller = getCallerIdentity(); 13615 final int userId = caller.getUserId(); 13616 Intent intent = null; 13617 if (getEnforcingAdminAndUserDetailsInternal(userId, restriction) != null) { 13618 intent = createShowAdminSupportIntent(userId); 13619 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction); 13620 } 13621 return intent; 13622 } 13623 13624 /** 13625 * Returns true if specified admin is allowed to limit passwords and has a 13626 * {@code mPasswordPolicy.quality} of at least {@code minPasswordQuality} 13627 */ 13628 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 13629 if (admin.mPasswordPolicy.quality < minPasswordQuality) { 13630 return false; 13631 } 13632 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 13633 } 13634 13635 @Override 13636 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 13637 if (policy != null) { 13638 // throws exception if policy type is invalid 13639 policy.validateType(); 13640 // throws exception if freeze period is invalid 13641 policy.validateFreezePeriods(); 13642 Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 13643 // throws exception if freeze period is incompatible with previous freeze period record 13644 policy.validateAgainstPreviousFreezePeriod(record.first, record.second, 13645 LocalDate.now()); 13646 } 13647 final CallerIdentity caller = getCallerIdentity(who); 13648 13649 synchronized (getLockObject()) { 13650 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller) 13651 || isDefaultDeviceOwner(caller)); 13652 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_UPDATE_POLICY); 13653 13654 if (policy == null) { 13655 mOwners.clearSystemUpdatePolicy(); 13656 } else { 13657 mOwners.setSystemUpdatePolicy(policy); 13658 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false); 13659 } 13660 mOwners.writeDeviceOwner(); 13661 } 13662 mInjector.binderWithCleanCallingIdentity(() -> mContext.sendBroadcastAsUser( 13663 new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM)); 13664 DevicePolicyEventLogger 13665 .createEvent(DevicePolicyEnums.SET_SYSTEM_UPDATE_POLICY) 13666 .setAdmin(who) 13667 .setInt(policy != null ? policy.getPolicyType() : 0) 13668 .write(); 13669 } 13670 13671 @Override 13672 public SystemUpdatePolicy getSystemUpdatePolicy() { 13673 synchronized (getLockObject()) { 13674 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 13675 if (policy != null && !policy.isValid()) { 13676 Slogf.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 13677 return null; 13678 } 13679 return policy; 13680 } 13681 } 13682 13683 private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) { 13684 return (!date.isBefore(range.first) && !date.isAfter(range.second)); 13685 } 13686 13687 /** 13688 * keeps track of the last continuous period when the system is under OTA freeze. 13689 * 13690 * DPMS keeps track of the previous dates during which OTA was freezed as a result of an 13691 * system update policy with freeze periods in effect. This is needed to make robust 13692 * validation on new system update polices, for example to prevent the OTA from being 13693 * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period 13694 * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting 13695 * a new freeze period after a few days. 13696 * 13697 * @param saveIfChanged whether to persist the result on disk if freeze period record is 13698 * updated. This should only be set to {@code false} if there is a guaranteed 13699 * mOwners.writeDeviceOwner() later in the control flow to reduce the number of 13700 * disk writes. Otherwise you risk inconsistent on-disk state. 13701 * 13702 * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod 13703 */ 13704 private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) { 13705 Slogf.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord"); 13706 synchronized (getLockObject()) { 13707 final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 13708 if (policy == null) { 13709 return; 13710 } 13711 final LocalDate now = LocalDate.now(); 13712 final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now); 13713 if (currentPeriod == null) { 13714 return; 13715 } 13716 final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 13717 final LocalDate start = record.first; 13718 final LocalDate end = record.second; 13719 final boolean changed; 13720 if (end == null || start == null) { 13721 // Start a new period if there is none at the moment 13722 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 13723 } else if (now.equals(end.plusDays(1))) { 13724 // Extend the existing period 13725 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 13726 } else if (now.isAfter(end.plusDays(1))) { 13727 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) { 13728 // The device might be off for some period. If the past freeze record 13729 // is within range of the current freeze period, assume the device was off 13730 // during the period [end, now] and extend the freeze record to [start, now]. 13731 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 13732 } else { 13733 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 13734 } 13735 } else if (now.isBefore(start)) { 13736 // Systm clock was adjusted backwards, restart record 13737 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 13738 } else /* start <= now <= end */ { 13739 changed = false; 13740 } 13741 if (changed && saveIfChanged) { 13742 mOwners.writeDeviceOwner(); 13743 } 13744 } 13745 } 13746 13747 @Override 13748 public void clearSystemUpdatePolicyFreezePeriodRecord() { 13749 Preconditions.checkCallAuthorization(isAdb(getCallerIdentity()) 13750 || hasCallingOrSelfPermission(permission.CLEAR_FREEZE_PERIOD), 13751 "Caller must be shell, or hold CLEAR_FREEZE_PERIOD permission to call " 13752 + "clearSystemUpdatePolicyFreezePeriodRecord"); 13753 synchronized (getLockObject()) { 13754 // Print out current record to help diagnosed CTS failures 13755 Slogf.i(LOG_TAG, "Clear freeze period record: " 13756 + mOwners.getSystemUpdateFreezePeriodRecordAsString()); 13757 if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) { 13758 mOwners.writeDeviceOwner(); 13759 } 13760 } 13761 } 13762 13763 /** 13764 * Checks if any of the packages associated with the UID of the app provided is that 13765 * of the device owner. 13766 * @param appUid UID of the app to check. 13767 * @return {@code true} if any of the packages are the device owner, {@code false} otherwise. 13768 */ 13769 private boolean isUidDeviceOwnerLocked(int appUid) { 13770 ensureLocked(); 13771 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 13772 .getPackageName(); 13773 try { 13774 String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(appUid); 13775 if (pkgs == null) { 13776 return false; 13777 } 13778 13779 for (String pkg : pkgs) { 13780 if (deviceOwnerPackageName.equals(pkg)) { 13781 return true; 13782 } 13783 } 13784 } catch (RemoteException e) { 13785 return false; 13786 } 13787 return false; 13788 } 13789 13790 @Override 13791 public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) { 13792 Preconditions.checkCallAuthorization( 13793 hasCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE), 13794 "Only the system update service can broadcast update information"); 13795 13796 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 13797 Slogf.w(LOG_TAG, "Only the system update service in the system user can broadcast " 13798 + "update information."); 13799 return; 13800 } 13801 13802 if (!mOwners.saveSystemUpdateInfo(info)) { 13803 // Pending system update hasn't changed, don't send duplicate notification. 13804 return; 13805 } 13806 13807 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE) 13808 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 13809 info == null ? -1 : info.getReceivedTime()); 13810 13811 mInjector.binderWithCleanCallingIdentity(() -> { 13812 synchronized (getLockObject()) { 13813 // Broadcast to device owner first if there is one. 13814 if (mOwners.hasDeviceOwner()) { 13815 final UserHandle deviceOwnerUser = 13816 UserHandle.of(mOwners.getDeviceOwnerUserId()); 13817 intent.setComponent(mOwners.getDeviceOwnerComponent()); 13818 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 13819 } 13820 } 13821 // Get running users. 13822 final int runningUserIds[]; 13823 try { 13824 runningUserIds = mInjector.getIActivityManager().getRunningUserIds(); 13825 } catch (RemoteException e) { 13826 // Shouldn't happen. 13827 Slogf.e(LOG_TAG, "Could not retrieve the list of running users", e); 13828 return; 13829 } 13830 // Send broadcasts to corresponding profile owners if any. 13831 for (final int userId : runningUserIds) { 13832 synchronized (getLockObject()) { 13833 final ComponentName profileOwnerPackage = 13834 mOwners.getProfileOwnerComponent(userId); 13835 if (profileOwnerPackage != null) { 13836 intent.setComponent(profileOwnerPackage); 13837 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 13838 } 13839 } 13840 } 13841 }); 13842 } 13843 13844 @Override 13845 public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) { 13846 Objects.requireNonNull(admin, "ComponentName is null"); 13847 13848 final CallerIdentity caller = getCallerIdentity(admin); 13849 Preconditions.checkCallAuthorization( 13850 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 13851 13852 return mOwners.getSystemUpdateInfo(); 13853 } 13854 13855 @Override 13856 public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) { 13857 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 13858 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 13859 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller))) 13860 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT))); 13861 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_POLICY); 13862 13863 final int forUser = caller.getUserId(); 13864 synchronized (getLockObject()) { 13865 DevicePolicyData userPolicy = getUserData(forUser); 13866 if (userPolicy.mPermissionPolicy != policy) { 13867 userPolicy.mPermissionPolicy = policy; 13868 mPolicyCache.setPermissionPolicy(forUser, policy); 13869 saveSettingsLocked(forUser); 13870 } 13871 } 13872 DevicePolicyEventLogger 13873 .createEvent(DevicePolicyEnums.SET_PERMISSION_POLICY) 13874 .setAdmin(caller.getPackageName()) 13875 .setInt(policy) 13876 .setBoolean(/* isDelegate */ admin == null) 13877 .write(); 13878 } 13879 13880 private void updatePermissionPolicyCache(int userId) { 13881 synchronized (getLockObject()) { 13882 DevicePolicyData userPolicy = getUserData(userId); 13883 mPolicyCache.setPermissionPolicy(userId, userPolicy.mPermissionPolicy); 13884 } 13885 } 13886 13887 @Override 13888 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 13889 int userId = UserHandle.getCallingUserId(); 13890 return mPolicyCache.getPermissionPolicy(userId); 13891 } 13892 13893 @Override 13894 public void setPermissionGrantState(ComponentName admin, String callerPackage, 13895 String packageName, String permission, int grantState, RemoteCallback callback) 13896 throws RemoteException { 13897 Objects.requireNonNull(callback); 13898 13899 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 13900 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 13901 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller) 13902 || isFinancedDeviceOwner(caller))) 13903 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT))); 13904 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_GRANT_STATE); 13905 13906 synchronized (getLockObject()) { 13907 if (isFinancedDeviceOwner(caller)) { 13908 enforcePermissionGrantStateOnFinancedDevice(packageName, permission); 13909 } 13910 long ident = mInjector.binderClearCallingIdentity(); 13911 try { 13912 boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId()) 13913 >= android.os.Build.VERSION_CODES.Q; 13914 if (!isPostQAdmin) { 13915 // Legacy admins assume that they cannot control pre-M apps 13916 if (getTargetSdk(packageName, caller.getUserId()) 13917 < android.os.Build.VERSION_CODES.M) { 13918 callback.sendResult(null); 13919 return; 13920 } 13921 } 13922 if (!isRuntimePermission(permission)) { 13923 callback.sendResult(null); 13924 return; 13925 } 13926 if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 13927 || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED 13928 || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) { 13929 AdminPermissionControlParams permissionParams = 13930 new AdminPermissionControlParams(packageName, permission, grantState, 13931 canAdminGrantSensorsPermissionsForUser(caller.getUserId())); 13932 mInjector.getPermissionControllerManager(caller.getUserHandle()) 13933 .setRuntimePermissionGrantStateByDeviceAdmin(caller.getPackageName(), 13934 permissionParams, mContext.getMainExecutor(), 13935 (permissionWasSet) -> { 13936 if (isPostQAdmin && !permissionWasSet) { 13937 callback.sendResult(null); 13938 return; 13939 } 13940 13941 DevicePolicyEventLogger 13942 .createEvent(DevicePolicyEnums 13943 .SET_PERMISSION_GRANT_STATE) 13944 .setAdmin(caller.getPackageName()) 13945 .setStrings(permission) 13946 .setInt(grantState) 13947 .setBoolean(/* isDelegate */ admin == null) 13948 .write(); 13949 13950 callback.sendResult(Bundle.EMPTY); 13951 }); 13952 } 13953 } catch (SecurityException e) { 13954 Slogf.e(LOG_TAG, "Could not set permission grant state", e); 13955 13956 callback.sendResult(null); 13957 } finally { 13958 mInjector.binderRestoreCallingIdentity(ident); 13959 } 13960 } 13961 } 13962 13963 private void enforcePermissionGrantStateOnFinancedDevice( 13964 String packageName, String permission) { 13965 if (!Manifest.permission.READ_PHONE_STATE.equals(permission)) { 13966 throw new SecurityException(permission + " cannot be used when managing a financed" 13967 + " device for permission grant state"); 13968 } else if (!mOwners.getDeviceOwnerPackageName().equals(packageName)) { 13969 throw new SecurityException("Device owner package is the only package that can be used" 13970 + " for permission grant state when managing a financed device"); 13971 } 13972 } 13973 13974 @Override 13975 public int getPermissionGrantState(ComponentName admin, String callerPackage, 13976 String packageName, String permission) throws RemoteException { 13977 final CallerIdentity caller = getCallerIdentity(admin, callerPackage); 13978 Preconditions.checkCallAuthorization(isSystemUid(caller) || (caller.hasAdminComponent() 13979 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller) 13980 || isFinancedDeviceOwner(caller))) 13981 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT))); 13982 13983 synchronized (getLockObject()) { 13984 if (isFinancedDeviceOwner(caller)) { 13985 enforcePermissionGrantStateOnFinancedDevice(packageName, permission); 13986 } 13987 return mInjector.binderWithCleanCallingIdentity(() -> { 13988 int granted; 13989 if (getTargetSdk(caller.getPackageName(), caller.getUserId()) 13990 < android.os.Build.VERSION_CODES.Q) { 13991 // The per-Q behavior was to not check the app-ops state. 13992 granted = mIPackageManager.checkPermission(permission, packageName, 13993 caller.getUserId()); 13994 } else { 13995 try { 13996 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 13997 caller.getUserId()); 13998 if (PermissionChecker.checkPermissionForPreflight(mContext, permission, 13999 PermissionChecker.PID_UNKNOWN, uid, packageName) 14000 != PermissionChecker.PERMISSION_GRANTED) { 14001 granted = PackageManager.PERMISSION_DENIED; 14002 } else { 14003 granted = PackageManager.PERMISSION_GRANTED; 14004 } 14005 } catch (NameNotFoundException e) { 14006 throw new RemoteException("Cannot check if " + permission 14007 + "is a runtime permission", e, false, true); 14008 } 14009 } 14010 int permFlags = mInjector.getPackageManager().getPermissionFlags( 14011 permission, packageName, caller.getUserHandle()); 14012 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 14013 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 14014 // Not controlled by policy 14015 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 14016 } else { 14017 // Policy controlled so return result based on permission grant state 14018 return granted == PackageManager.PERMISSION_GRANTED 14019 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 14020 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 14021 } 14022 }); 14023 } 14024 } 14025 14026 boolean isPackageInstalledForUser(String packageName, int userHandle) { 14027 return mInjector.binderWithCleanCallingIdentity(() -> { 14028 try { 14029 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 14030 userHandle); 14031 return (pi != null) && (pi.applicationInfo.flags != 0); 14032 } catch (RemoteException re) { 14033 throw new RuntimeException("Package manager has died", re); 14034 } 14035 }); 14036 } 14037 14038 private boolean isRuntimePermission(String permissionName) { 14039 try { 14040 final PackageManager packageManager = mInjector.getPackageManager(); 14041 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0); 14042 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 14043 == PermissionInfo.PROTECTION_DANGEROUS; 14044 } catch (NameNotFoundException e) { 14045 return false; 14046 } 14047 } 14048 14049 @Override 14050 public boolean isProvisioningAllowed(String action, String packageName) { 14051 Objects.requireNonNull(packageName); 14052 14053 final CallerIdentity caller = getCallerIdentity(); 14054 final long ident = mInjector.binderClearCallingIdentity(); 14055 try { 14056 final List<String> callerUidPackageNames = Arrays.asList( 14057 mInjector.getPackageManager().getPackagesForUid(caller.getUid())); 14058 Preconditions.checkArgument(callerUidPackageNames.contains(packageName), 14059 "Caller uid doesn't match the one for the provided package."); 14060 } finally { 14061 mInjector.binderRestoreCallingIdentity(ident); 14062 } 14063 14064 return checkProvisioningPreconditionSkipPermission(action, packageName) == STATUS_OK; 14065 } 14066 14067 @Override 14068 public int checkProvisioningPrecondition(String action, String packageName) { 14069 Objects.requireNonNull(packageName, "packageName is null"); 14070 14071 Preconditions.checkCallAuthorization( 14072 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 14073 14074 return checkProvisioningPreconditionSkipPermission(action, packageName); 14075 } 14076 14077 private int checkProvisioningPreconditionSkipPermission(String action, 14078 String packageName) { 14079 if (!mHasFeature) { 14080 logMissingFeatureAction("Cannot check provisioning for action " + action); 14081 return STATUS_DEVICE_ADMIN_NOT_SUPPORTED; 14082 } 14083 if (!isProvisioningAllowed()) { 14084 return STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS; 14085 } 14086 final int code = checkProvisioningPreConditionSkipPermissionNoLog(action, packageName); 14087 if (code != STATUS_OK) { 14088 Slogf.d(LOG_TAG, "checkProvisioningPreCondition(" + action + ", " + packageName 14089 + ") failed: " 14090 + computeProvisioningErrorString(code, mInjector.userHandleGetCallingUserId())); 14091 } 14092 return code; 14093 } 14094 14095 /** 14096 * Checks if provisioning is allowed during regular usage (non-developer/CTS). This could 14097 * return {@code false} if the device has an overlaid config value set to false. If not set, 14098 * the default is true. 14099 */ 14100 private boolean isProvisioningAllowed() { 14101 boolean isDeveloperMode = isDeveloperMode(mContext); 14102 boolean isProvisioningAllowedForNormalUsers = SystemProperties.getBoolean( 14103 ALLOW_USER_PROVISIONING_KEY, /* defValue= */ true); 14104 14105 return isDeveloperMode || isProvisioningAllowedForNormalUsers; 14106 } 14107 14108 private static boolean isDeveloperMode(Context context) { 14109 return Global.getInt(context.getContentResolver(), Global.ADB_ENABLED, 0) > 0; 14110 } 14111 14112 private int checkProvisioningPreConditionSkipPermissionNoLog(String action, 14113 String packageName) { 14114 final int callingUserId = mInjector.userHandleGetCallingUserId(); 14115 if (action != null) { 14116 switch (action) { 14117 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 14118 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 14119 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 14120 case DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE: 14121 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 14122 } 14123 } 14124 throw new IllegalArgumentException("Unknown provisioning action " + action); 14125 } 14126 14127 /** 14128 * The device owner can only be set before the setup phase of the primary user has completed, 14129 * except for adb command if no accounts or additional users are present on the device. 14130 */ 14131 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 14132 @UserIdInt int deviceOwnerUserId, @UserIdInt int callingUserId, boolean isAdb, 14133 boolean hasIncompatibleAccountsOrNonAdb) { 14134 if (mOwners.hasDeviceOwner()) { 14135 return STATUS_HAS_DEVICE_OWNER; 14136 } 14137 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 14138 return STATUS_USER_HAS_PROFILE_OWNER; 14139 } 14140 14141 boolean isHeadlessSystemUserMode = mInjector.userManagerIsHeadlessSystemUserMode(); 14142 // System user is always running in headless system user mode. 14143 if (!isHeadlessSystemUserMode 14144 && !mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 14145 return STATUS_USER_NOT_RUNNING; 14146 } 14147 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 14148 return STATUS_HAS_PAIRED; 14149 } 14150 14151 if (isHeadlessSystemUserMode) { 14152 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 14153 Slogf.e(LOG_TAG, "In headless system user mode, " 14154 + "device owner can only be set on headless system user."); 14155 return STATUS_NOT_SYSTEM_USER; 14156 } 14157 } 14158 14159 if (isAdb) { 14160 // If shell command runs after user setup completed check device status. Otherwise, OK. 14161 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 14162 // In non-headless system user mode, DO can be setup only if 14163 // there's no non-system user. 14164 // In headless system user mode, DO can be setup only if there are 14165 // two users: the headless system user and the foreground user. 14166 // If there could be multiple foreground users, this constraint should be modified. 14167 14168 int maxNumberOfExistingUsers = isHeadlessSystemUserMode ? 2 : 1; 14169 if (mUserManager.getUserCount() > maxNumberOfExistingUsers) { 14170 return STATUS_NONSYSTEM_USER_EXISTS; 14171 } 14172 14173 int currentForegroundUser = getCurrentForegroundUserId(); 14174 if (callingUserId != currentForegroundUser 14175 && mInjector.userManagerIsHeadlessSystemUserMode() 14176 && currentForegroundUser == UserHandle.USER_SYSTEM) { 14177 Slogf.wtf(LOG_TAG, "In headless system user mode, " 14178 + "current user cannot be system user when setting device owner"); 14179 return STATUS_SYSTEM_USER; 14180 } 14181 if (hasIncompatibleAccountsOrNonAdb) { 14182 return STATUS_ACCOUNTS_NOT_EMPTY; 14183 } 14184 } 14185 return STATUS_OK; 14186 } else { 14187 // DO has to be user 0 14188 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 14189 return STATUS_NOT_SYSTEM_USER; 14190 } 14191 // Only provision DO before setup wizard completes 14192 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 14193 return STATUS_USER_SETUP_COMPLETED; 14194 } 14195 return STATUS_OK; 14196 } 14197 } 14198 14199 private int checkDeviceOwnerProvisioningPreCondition(@UserIdInt int callingUserId) { 14200 synchronized (getLockObject()) { 14201 final int deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode() 14202 ? UserHandle.USER_SYSTEM 14203 : callingUserId; 14204 Slogf.i(LOG_TAG, "Calling user %d, device owner will be set on user %d", 14205 callingUserId, deviceOwnerUserId); 14206 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb. 14207 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 14208 deviceOwnerUserId, callingUserId, /* isAdb= */ false, 14209 /* hasIncompatibleAccountsOrNonAdb=*/ true); 14210 } 14211 } 14212 14213 private int checkManagedProfileProvisioningPreCondition(String packageName, 14214 @UserIdInt int callingUserId) { 14215 if (!hasFeatureManagedUsers()) { 14216 return STATUS_MANAGED_USERS_NOT_SUPPORTED; 14217 } 14218 if (getProfileOwnerAsUser(callingUserId) != null) { 14219 // Managed user cannot have a managed profile. 14220 return STATUS_USER_HAS_PROFILE_OWNER; 14221 } 14222 14223 final long ident = mInjector.binderClearCallingIdentity(); 14224 try { 14225 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 14226 final boolean hasDeviceOwner; 14227 synchronized (getLockObject()) { 14228 hasDeviceOwner = getDeviceOwnerAdminLocked() != null; 14229 } 14230 14231 final boolean addingProfileRestricted = mUserManager.hasUserRestriction( 14232 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserHandle); 14233 14234 if (mUserManager.getUserInfo(callingUserId).isProfile()) { 14235 Slogf.i(LOG_TAG, "Calling user %d is a profile, cannot add another.", 14236 callingUserId); 14237 // The check is called from inside a managed profile. A managed profile cannot 14238 // be provisioned from within another managed profile. 14239 return STATUS_CANNOT_ADD_MANAGED_PROFILE; 14240 } 14241 14242 // If there's a device owner, the restriction on adding a managed profile must be set. 14243 if (hasDeviceOwner && !addingProfileRestricted) { 14244 Slogf.wtf(LOG_TAG, "Has a device owner but no restriction on adding a profile."); 14245 } 14246 14247 // Do not allow adding a managed profile if there's a restriction. 14248 if (addingProfileRestricted) { 14249 Slogf.i(LOG_TAG, "Adding a profile is restricted: User %s Has device owner? %b", 14250 callingUserHandle, hasDeviceOwner); 14251 return STATUS_CANNOT_ADD_MANAGED_PROFILE; 14252 } 14253 14254 // Bail out if we are trying to provision a work profile but one already exists. 14255 if (!mUserManager.canAddMoreManagedProfiles( 14256 callingUserId, /* allowedToRemoveOne= */ false)) { 14257 Slogf.i(LOG_TAG, "A work profile already exists."); 14258 return STATUS_CANNOT_ADD_MANAGED_PROFILE; 14259 } 14260 } finally { 14261 mInjector.binderRestoreCallingIdentity(ident); 14262 } 14263 return STATUS_OK; 14264 } 14265 14266 private void checkIsDeviceOwner(CallerIdentity caller) { 14267 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller), caller.getUid() 14268 + " is not device owner"); 14269 } 14270 14271 /** 14272 * Return device owner or profile owner set on a given user. 14273 */ 14274 private @Nullable ComponentName getOwnerComponent(int userId) { 14275 synchronized (getLockObject()) { 14276 if (mOwners.getDeviceOwnerUserId() == userId) { 14277 return mOwners.getDeviceOwnerComponent(); 14278 } 14279 if (mOwners.hasProfileOwner(userId)) { 14280 return mOwners.getProfileOwnerComponent(userId); 14281 } 14282 } 14283 return null; 14284 } 14285 14286 private boolean hasFeatureManagedUsers() { 14287 try { 14288 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 14289 } catch (RemoteException e) { 14290 return false; 14291 } 14292 } 14293 14294 @Override 14295 public String getWifiMacAddress(ComponentName admin) { 14296 Objects.requireNonNull(admin, "ComponentName is null"); 14297 14298 final CallerIdentity caller = getCallerIdentity(admin); 14299 Preconditions.checkCallAuthorization( 14300 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 14301 14302 return mInjector.binderWithCleanCallingIdentity(() -> { 14303 String[] macAddresses = mInjector.getWifiManager().getFactoryMacAddresses(); 14304 if (macAddresses == null) { 14305 return null; 14306 } 14307 DevicePolicyEventLogger 14308 .createEvent(DevicePolicyEnums.GET_WIFI_MAC_ADDRESS) 14309 .setAdmin(caller.getComponentName()) 14310 .write(); 14311 return macAddresses.length > 0 ? macAddresses[0] : null; 14312 }); 14313 } 14314 14315 /** 14316 * Returns the target sdk version number that the given packageName was built for 14317 * in the given user. 14318 */ 14319 private int getTargetSdk(String packageName, int userId) { 14320 final ApplicationInfo ai; 14321 try { 14322 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 14323 return ai == null ? 0 : ai.targetSdkVersion; 14324 } catch (RemoteException e) { 14325 // Shouldn't happen 14326 return 0; 14327 } 14328 } 14329 14330 @Override 14331 public boolean isManagedProfile(ComponentName admin) { 14332 Objects.requireNonNull(admin, "ComponentName is null"); 14333 14334 final CallerIdentity caller = getCallerIdentity(admin); 14335 Preconditions.checkCallAuthorization( 14336 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 14337 14338 return isManagedProfile(caller.getUserId()); 14339 } 14340 14341 @Override 14342 public void reboot(ComponentName admin) { 14343 Objects.requireNonNull(admin, "ComponentName is null"); 14344 final CallerIdentity caller = getCallerIdentity(admin); 14345 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 14346 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REBOOT); 14347 mInjector.binderWithCleanCallingIdentity(() -> { 14348 // Make sure there are no ongoing calls on the device. 14349 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 14350 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 14351 } 14352 DevicePolicyEventLogger 14353 .createEvent(DevicePolicyEnums.REBOOT) 14354 .setAdmin(admin) 14355 .write(); 14356 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 14357 }); 14358 } 14359 14360 @Override 14361 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 14362 if (!mHasFeature) { 14363 return; 14364 } 14365 Objects.requireNonNull(who, "ComponentName is null"); 14366 message = truncateIfLonger(message, MAX_SHORT_SUPPORT_MESSAGE_LENGTH); 14367 14368 final CallerIdentity caller = getCallerIdentity(who); 14369 synchronized (getLockObject()) { 14370 ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid()); 14371 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 14372 admin.shortSupportMessage = message; 14373 saveSettingsLocked(caller.getUserId()); 14374 } 14375 } 14376 DevicePolicyEventLogger 14377 .createEvent(DevicePolicyEnums.SET_SHORT_SUPPORT_MESSAGE) 14378 .setAdmin(who) 14379 .write(); 14380 } 14381 14382 @Override 14383 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 14384 if (!mHasFeature) { 14385 return null; 14386 } 14387 Objects.requireNonNull(who, "ComponentName is null"); 14388 final CallerIdentity caller = getCallerIdentity(who); 14389 synchronized (getLockObject()) { 14390 ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid()); 14391 return admin.shortSupportMessage; 14392 } 14393 } 14394 14395 @Override 14396 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 14397 if (!mHasFeature) { 14398 return; 14399 } 14400 14401 message = truncateIfLonger(message, MAX_LONG_SUPPORT_MESSAGE_LENGTH); 14402 14403 Objects.requireNonNull(who, "ComponentName is null"); 14404 final CallerIdentity caller = getCallerIdentity(who); 14405 synchronized (getLockObject()) { 14406 ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid()); 14407 if (!TextUtils.equals(admin.longSupportMessage, message)) { 14408 admin.longSupportMessage = message; 14409 saveSettingsLocked(caller.getUserId()); 14410 } 14411 } 14412 DevicePolicyEventLogger 14413 .createEvent(DevicePolicyEnums.SET_LONG_SUPPORT_MESSAGE) 14414 .setAdmin(who) 14415 .write(); 14416 } 14417 14418 @Override 14419 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 14420 if (!mHasFeature) { 14421 return null; 14422 } 14423 Objects.requireNonNull(who, "ComponentName is null"); 14424 final CallerIdentity caller = getCallerIdentity(who); 14425 synchronized (getLockObject()) { 14426 ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid()); 14427 return admin.longSupportMessage; 14428 } 14429 } 14430 14431 @Override 14432 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 14433 if (!mHasFeature) { 14434 return null; 14435 } 14436 Objects.requireNonNull(who, "ComponentName is null"); 14437 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 14438 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user")); 14439 14440 synchronized (getLockObject()) { 14441 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 14442 if (admin != null) { 14443 return admin.shortSupportMessage; 14444 } 14445 } 14446 return null; 14447 } 14448 14449 @Override 14450 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 14451 if (!mHasFeature) { 14452 return null; 14453 } 14454 Objects.requireNonNull(who, "ComponentName is null"); 14455 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 14456 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user")); 14457 14458 synchronized (getLockObject()) { 14459 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 14460 if (admin != null) { 14461 return admin.longSupportMessage; 14462 } 14463 } 14464 return null; 14465 } 14466 14467 @Override 14468 public void setOrganizationColor(@NonNull ComponentName who, int color) { 14469 if (!mHasFeature) { 14470 return; 14471 } 14472 Objects.requireNonNull(who, "ComponentName is null"); 14473 14474 final CallerIdentity caller = getCallerIdentity(who); 14475 Preconditions.checkCallingUser(isManagedProfile(caller.getUserId())); 14476 14477 synchronized (getLockObject()) { 14478 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14479 admin.organizationColor = color; 14480 saveSettingsLocked(caller.getUserId()); 14481 } 14482 DevicePolicyEventLogger 14483 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_COLOR) 14484 .setAdmin(caller.getComponentName()) 14485 .write(); 14486 } 14487 14488 @Override 14489 public void setOrganizationColorForUser(int color, int userId) { 14490 if (!mHasFeature) { 14491 return; 14492 } 14493 Preconditions.checkArgumentNonnegative(userId, "Invalid userId"); 14494 14495 final CallerIdentity caller = getCallerIdentity(); 14496 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId)); 14497 Preconditions.checkCallAuthorization(canManageUsers(caller)); 14498 Preconditions.checkCallAuthorization(isManagedProfile(userId), "You can not " 14499 + "set organization color outside a managed profile, userId = %d", userId); 14500 14501 synchronized (getLockObject()) { 14502 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 14503 admin.organizationColor = color; 14504 saveSettingsLocked(userId); 14505 } 14506 } 14507 14508 @Override 14509 public int getOrganizationColor(@NonNull ComponentName who) { 14510 if (!mHasFeature) { 14511 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 14512 } 14513 Objects.requireNonNull(who, "ComponentName is null"); 14514 14515 final CallerIdentity caller = getCallerIdentity(who); 14516 Preconditions.checkCallingUser(isManagedProfile(caller.getUserId())); 14517 14518 synchronized (getLockObject()) { 14519 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14520 return admin.organizationColor; 14521 } 14522 } 14523 14524 @Override 14525 public int getOrganizationColorForUser(int userHandle) { 14526 if (!mHasFeature) { 14527 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 14528 } 14529 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 14530 14531 final CallerIdentity caller = getCallerIdentity(); 14532 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 14533 Preconditions.checkCallAuthorization(isManagedProfile(userHandle), "You can " 14534 + "not get organization color outside a managed profile, userId = %d", userHandle); 14535 14536 synchronized (getLockObject()) { 14537 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 14538 return (profileOwner != null) 14539 ? profileOwner.organizationColor 14540 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 14541 } 14542 } 14543 14544 @Override 14545 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 14546 if (!mHasFeature) { 14547 return; 14548 } 14549 Objects.requireNonNull(who, "ComponentName is null"); 14550 final CallerIdentity caller = getCallerIdentity(who); 14551 14552 text = truncateIfLonger(text, MAX_ORG_NAME_LENGTH); 14553 14554 synchronized (getLockObject()) { 14555 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14556 if (!TextUtils.equals(admin.organizationName, text)) { 14557 admin.organizationName = (text == null || text.length() == 0) 14558 ? null : text.toString(); 14559 saveSettingsLocked(caller.getUserId()); 14560 } 14561 } 14562 } 14563 14564 @Override 14565 public CharSequence getOrganizationName(@NonNull ComponentName who) { 14566 if (!mHasFeature) { 14567 return null; 14568 } 14569 Objects.requireNonNull(who, "ComponentName is null"); 14570 14571 final CallerIdentity caller = getCallerIdentity(who); 14572 Preconditions.checkCallingUser(isManagedProfile(caller.getUserId())); 14573 14574 synchronized (getLockObject()) { 14575 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14576 return admin.organizationName; 14577 } 14578 } 14579 14580 /** 14581 * This API is cached: invalidate with invalidateBinderCaches(). 14582 */ 14583 @Override 14584 public CharSequence getDeviceOwnerOrganizationName() { 14585 if (!mHasFeature) { 14586 return null; 14587 } 14588 final CallerIdentity caller = getCallerIdentity(); 14589 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 14590 || canManageUsers(caller) || isFinancedDeviceOwner(caller)); 14591 synchronized (getLockObject()) { 14592 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 14593 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 14594 } 14595 } 14596 14597 /** 14598 * This API is cached: invalidate with invalidateBinderCaches(). 14599 */ 14600 @Override 14601 public CharSequence getOrganizationNameForUser(int userHandle) { 14602 if (!mHasFeature) { 14603 return null; 14604 } 14605 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 14606 14607 final CallerIdentity caller = getCallerIdentity(); 14608 Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); 14609 Preconditions.checkCallAuthorization(canManageUsers(caller)); 14610 Preconditions.checkCallAuthorization(isManagedProfile(userHandle), 14611 "You can not get organization name outside a managed profile, userId = %d", 14612 userHandle); 14613 14614 synchronized (getLockObject()) { 14615 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 14616 return (profileOwner != null) 14617 ? profileOwner.organizationName 14618 : null; 14619 } 14620 } 14621 14622 @Override 14623 public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) { 14624 Objects.requireNonNull(who); 14625 Objects.requireNonNull(packageNames); 14626 final CallerIdentity caller = getCallerIdentity(who); 14627 Preconditions.checkCallAuthorization( 14628 isDefaultDeviceOwner(caller) || isProfileOwner(caller), 14629 "Admin %s does not own the profile", caller.getComponentName()); 14630 14631 if (!mHasFeature) { 14632 return packageNames; 14633 } 14634 synchronized (getLockObject()) { 14635 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14636 return mInjector.binderWithCleanCallingIdentity(() -> { 14637 final List<String> excludedPkgs = removeInvalidPkgsForMeteredDataRestriction( 14638 caller.getUserId(), packageNames); 14639 admin.meteredDisabledPackages = packageNames; 14640 pushMeteredDisabledPackages(caller.getUserId()); 14641 saveSettingsLocked(caller.getUserId()); 14642 return excludedPkgs; 14643 }); 14644 } 14645 } 14646 14647 private List<String> removeInvalidPkgsForMeteredDataRestriction( 14648 int userId, List<String> pkgNames) { 14649 final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId); 14650 final List<String> excludedPkgs = new ArrayList<>(); 14651 for (int i = pkgNames.size() - 1; i >= 0; --i) { 14652 final String pkgName = pkgNames.get(i); 14653 // If the package is an active admin, don't restrict it. 14654 if (activeAdmins.contains(pkgName)) { 14655 excludedPkgs.add(pkgName); 14656 continue; 14657 } 14658 // If the package doesn't exist, don't restrict it. 14659 try { 14660 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) { 14661 excludedPkgs.add(pkgName); 14662 } 14663 } catch (RemoteException e) { 14664 // Should not happen 14665 } 14666 } 14667 pkgNames.removeAll(excludedPkgs); 14668 return excludedPkgs; 14669 } 14670 14671 @Override 14672 public List<String> getMeteredDataDisabledPackages(ComponentName who) { 14673 Objects.requireNonNull(who); 14674 14675 if (!mHasFeature) { 14676 return new ArrayList<>(); 14677 } 14678 final CallerIdentity caller = getCallerIdentity(who); 14679 Preconditions.checkCallAuthorization( 14680 isDefaultDeviceOwner(caller) || isProfileOwner(caller), 14681 "Admin %s does not own the profile", caller.getComponentName()); 14682 14683 synchronized (getLockObject()) { 14684 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 14685 return admin.meteredDisabledPackages == null 14686 ? new ArrayList<>() : admin.meteredDisabledPackages; 14687 } 14688 } 14689 14690 @Override 14691 public boolean isMeteredDataDisabledPackageForUser(ComponentName who, 14692 String packageName, int userId) { 14693 Objects.requireNonNull(who); 14694 14695 if (!mHasFeature) { 14696 return false; 14697 } 14698 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 14699 String.format(NOT_SYSTEM_CALLER_MSG, "query restricted pkgs for a specific user")); 14700 14701 synchronized (getLockObject()) { 14702 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 14703 if (admin != null && admin.meteredDisabledPackages != null) { 14704 return admin.meteredDisabledPackages.contains(packageName); 14705 } 14706 } 14707 return false; 14708 } 14709 14710 @Override 14711 public void setProfileOwnerOnOrganizationOwnedDevice(ComponentName who, int userId, 14712 boolean isProfileOwnerOnOrganizationOwnedDevice) { 14713 if (!mHasFeature) { 14714 return; 14715 } 14716 // As the caller is the system, it must specify the component name of the profile owner 14717 // as a safety check. 14718 Objects.requireNonNull(who); 14719 14720 final CallerIdentity caller = getCallerIdentity(); 14721 // Only adb or system apps with the right permission can mark a profile owner on 14722 // organization-owned device. 14723 if (!(isAdb(caller) || hasCallingPermission(permission.MARK_DEVICE_ORGANIZATION_OWNED) 14724 || hasCallingPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS))) { 14725 throw new SecurityException( 14726 "Only the system can mark a profile owner of organization-owned device."); 14727 } 14728 // Only a test admin can be unmarked as a profile owner on an organization-owned device. 14729 synchronized (getLockObject()) { 14730 if (!isProfileOwnerOnOrganizationOwnedDevice && !isAdminTestOnlyLocked(who, userId)) { 14731 throw new SecurityException("Only a test admin can be unmarked as a " 14732 + "profile owner of organization-owned device."); 14733 } 14734 } 14735 14736 if (isAdb(caller)) { 14737 if (hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, who)) { 14738 throw new SecurityException( 14739 "Can only be called from ADB if the device has no accounts."); 14740 } 14741 } else { 14742 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 14743 throw new IllegalStateException( 14744 "Cannot mark profile owner as managing an organization-owned device after" 14745 + " set-up"); 14746 } 14747 } 14748 14749 // Grant access under lock. 14750 synchronized (getLockObject()) { 14751 setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(who, userId, 14752 isProfileOwnerOnOrganizationOwnedDevice); 14753 } 14754 } 14755 14756 @GuardedBy("getLockObject()") 14757 private void setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked( 14758 ComponentName who, int userId, boolean isProfileOwnerOnOrganizationOwnedDevice) { 14759 // Make sure that the user has a profile owner and that the specified 14760 // component is the profile owner of that user. 14761 if (!isProfileOwner(who, userId)) { 14762 throw new IllegalArgumentException(String.format( 14763 "Component %s is not a Profile Owner of user %d", 14764 who.flattenToString(), userId)); 14765 } 14766 14767 Slogf.i(LOG_TAG, "%s %s as profile owner on organization-owned device for user %d", 14768 isProfileOwnerOnOrganizationOwnedDevice ? "Marking" : "Unmarking", 14769 who.flattenToString(), userId); 14770 14771 // First, set restriction on removing the profile. 14772 mInjector.binderWithCleanCallingIdentity(() -> { 14773 // Clear restriction as user. 14774 final UserHandle parentUser = mUserManager.getProfileParent(UserHandle.of(userId)); 14775 if (parentUser == null) { 14776 throw new IllegalStateException(String.format("User %d is not a profile", userId)); 14777 } 14778 if (!parentUser.isSystem()) { 14779 throw new IllegalStateException( 14780 String.format("Only the profile owner of a managed profile on the" 14781 + " primary user can be granted access to device identifiers, not" 14782 + " on user %d", parentUser.getIdentifier())); 14783 } 14784 14785 mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 14786 isProfileOwnerOnOrganizationOwnedDevice, 14787 parentUser); 14788 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, 14789 isProfileOwnerOnOrganizationOwnedDevice, 14790 parentUser); 14791 }); 14792 14793 // setProfileOwnerOfOrganizationOwnedDevice will trigger writing of the profile owner 14794 // data, no need to do it manually. 14795 mOwners.setProfileOwnerOfOrganizationOwnedDevice(userId, 14796 isProfileOwnerOnOrganizationOwnedDevice); 14797 } 14798 14799 private void pushMeteredDisabledPackages(int userId) { 14800 wtfIfInLock(); 14801 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages( 14802 getMeteredDisabledPackages(userId), userId); 14803 } 14804 14805 private Set<String> getMeteredDisabledPackages(int userId) { 14806 synchronized (getLockObject()) { 14807 final Set<String> restrictedPkgs = new ArraySet<>(); 14808 final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId); 14809 if (admin != null && admin.meteredDisabledPackages != null) { 14810 restrictedPkgs.addAll(admin.meteredDisabledPackages); 14811 } 14812 14813 return restrictedPkgs; 14814 } 14815 } 14816 14817 @Override 14818 public void setAffiliationIds(ComponentName admin, List<String> ids) { 14819 if (!mHasFeature) { 14820 return; 14821 } 14822 if (ids == null) { 14823 throw new IllegalArgumentException("ids must not be null"); 14824 } 14825 for (String id : ids) { 14826 Preconditions.checkArgument(!TextUtils.isEmpty(id), "ids must not have empty string"); 14827 enforceMaxStringLength(id, "affiliation id"); 14828 } 14829 14830 final Set<String> affiliationIds = new ArraySet<>(ids); 14831 final CallerIdentity caller = getCallerIdentity(admin); 14832 Preconditions.checkCallAuthorization( 14833 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 14834 final int callingUserId = caller.getUserId(); 14835 14836 synchronized (getLockObject()) { 14837 getUserData(callingUserId).mAffiliationIds = affiliationIds; 14838 saveSettingsLocked(callingUserId); 14839 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 14840 // Affiliation ids specified by the device owner are additionally stored in 14841 // UserHandle.USER_SYSTEM's DevicePolicyData. 14842 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 14843 saveSettingsLocked(UserHandle.USER_SYSTEM); 14844 } 14845 14846 // Affiliation status for any user, not just the calling user, might have changed. 14847 // The device owner user will still be affiliated after changing its affiliation ids, 14848 // but as a result of that other users might become affiliated or un-affiliated. 14849 maybePauseDeviceWideLoggingLocked(); 14850 maybeResumeDeviceWideLoggingLocked(); 14851 maybeClearLockTaskPolicyLocked(); 14852 updateAdminCanGrantSensorsPermissionCache(callingUserId); 14853 } 14854 } 14855 14856 @Override 14857 public List<String> getAffiliationIds(ComponentName admin) { 14858 if (!mHasFeature) { 14859 return Collections.emptyList(); 14860 } 14861 14862 Objects.requireNonNull(admin); 14863 final CallerIdentity caller = getCallerIdentity(admin); 14864 Preconditions.checkCallAuthorization( 14865 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 14866 14867 synchronized (getLockObject()) { 14868 return new ArrayList<String>(getUserData(caller.getUserId()).mAffiliationIds); 14869 } 14870 } 14871 14872 @Override 14873 public boolean isCallingUserAffiliated() { 14874 if (!mHasFeature) { 14875 return false; 14876 } 14877 14878 synchronized (getLockObject()) { 14879 return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId()); 14880 } 14881 } 14882 14883 @Override 14884 public boolean isAffiliatedUser(@UserIdInt int userId) { 14885 if (!mHasFeature) { 14886 return false; 14887 } 14888 final CallerIdentity caller = getCallerIdentity(); 14889 Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)); 14890 14891 return isUserAffiliatedWithDevice(userId); 14892 } 14893 14894 private boolean isUserAffiliatedWithDevice(@UserIdInt int userId) { 14895 synchronized (getLockObject()) { 14896 return isUserAffiliatedWithDeviceLocked(userId); 14897 } 14898 } 14899 14900 private boolean isUserAffiliatedWithDeviceLocked(@UserIdInt int userId) { 14901 if (!mOwners.hasDeviceOwner()) { 14902 return false; 14903 } 14904 if (userId == UserHandle.USER_SYSTEM) { 14905 // The system user is always affiliated in a DO device, 14906 // even if in headless system user mode. 14907 return true; 14908 } 14909 if (userId == mOwners.getDeviceOwnerUserId()) { 14910 // The user that the DO is installed on is always affiliated with the device. 14911 return true; 14912 } 14913 14914 final ComponentName profileOwner = getProfileOwnerAsUser(userId); 14915 if (profileOwner == null) { 14916 return false; 14917 } 14918 14919 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 14920 final Set<String> deviceAffiliationIds = 14921 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 14922 for (String id : userAffiliationIds) { 14923 if (deviceAffiliationIds.contains(id)) { 14924 return true; 14925 } 14926 } 14927 return false; 14928 } 14929 14930 private boolean areAllUsersAffiliatedWithDeviceLocked() { 14931 return mInjector.binderWithCleanCallingIdentity(() -> { 14932 final List<UserInfo> userInfos = mUserManager.getAliveUsers(); 14933 for (int i = 0; i < userInfos.size(); i++) { 14934 int userId = userInfos.get(i).id; 14935 if (!isUserAffiliatedWithDeviceLocked(userId)) { 14936 Slogf.d(LOG_TAG, "User id " + userId + " not affiliated."); 14937 return false; 14938 } 14939 } 14940 return true; 14941 }); 14942 } 14943 14944 private @UserIdInt int getSecurityLoggingEnabledUser() { 14945 synchronized (getLockObject()) { 14946 if (mOwners.hasDeviceOwner()) { 14947 return UserHandle.USER_ALL; 14948 } 14949 } 14950 return getOrganizationOwnedProfileUserId(); 14951 } 14952 14953 @Override 14954 public void setSecurityLoggingEnabled(ComponentName admin, String packageName, 14955 boolean enabled) { 14956 if (!mHasFeature) { 14957 return; 14958 } 14959 final CallerIdentity caller = getCallerIdentity(admin, packageName); 14960 14961 synchronized (getLockObject()) { 14962 if (admin != null) { 14963 Preconditions.checkCallAuthorization( 14964 isProfileOwnerOfOrganizationOwnedDevice(caller) 14965 || isDefaultDeviceOwner(caller)); 14966 } else { 14967 // A delegate app passes a null admin component, which is expected 14968 Preconditions.checkCallAuthorization( 14969 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING)); 14970 } 14971 14972 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 14973 return; 14974 } 14975 mInjector.securityLogSetLoggingEnabledProperty(enabled); 14976 if (enabled) { 14977 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser()); 14978 maybePauseDeviceWideLoggingLocked(); 14979 } else { 14980 mSecurityLogMonitor.stop(); 14981 } 14982 } 14983 DevicePolicyEventLogger 14984 .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED) 14985 .setAdmin(admin) 14986 .setBoolean(enabled) 14987 .write(); 14988 } 14989 14990 @Override 14991 public boolean isSecurityLoggingEnabled(ComponentName admin, String packageName) { 14992 if (!mHasFeature) { 14993 return false; 14994 } 14995 14996 synchronized (getLockObject()) { 14997 if (!isSystemUid(getCallerIdentity())) { 14998 final CallerIdentity caller = getCallerIdentity(admin, packageName); 14999 if (admin != null) { 15000 Preconditions.checkCallAuthorization( 15001 isProfileOwnerOfOrganizationOwnedDevice(caller) 15002 || isDefaultDeviceOwner(caller)); 15003 } else { 15004 // A delegate app passes a null admin component, which is expected 15005 Preconditions.checkCallAuthorization( 15006 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING)); 15007 } 15008 } 15009 return mInjector.securityLogGetLoggingEnabledProperty(); 15010 } 15011 } 15012 15013 private void recordSecurityLogRetrievalTime() { 15014 synchronized (getLockObject()) { 15015 final long currentTime = System.currentTimeMillis(); 15016 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 15017 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 15018 policyData.mLastSecurityLogRetrievalTime = currentTime; 15019 saveSettingsLocked(UserHandle.USER_SYSTEM); 15020 } 15021 } 15022 } 15023 15024 @Override 15025 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin, 15026 String packageName) { 15027 if (!mHasFeature) { 15028 return null; 15029 } 15030 15031 final CallerIdentity caller = getCallerIdentity(admin, packageName); 15032 if (admin != null) { 15033 Preconditions.checkCallAuthorization( 15034 isProfileOwnerOfOrganizationOwnedDevice(caller) 15035 || isDefaultDeviceOwner(caller)); 15036 } else { 15037 // A delegate app passes a null admin component, which is expected 15038 Preconditions.checkCallAuthorization( 15039 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING)); 15040 } 15041 15042 Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile() 15043 || areAllUsersAffiliatedWithDeviceLocked()); 15044 15045 DevicePolicyEventLogger 15046 .createEvent(DevicePolicyEnums.RETRIEVE_PRE_REBOOT_SECURITY_LOGS) 15047 .setAdmin(caller.getComponentName()) 15048 .write(); 15049 15050 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs) 15051 || !mInjector.securityLogGetLoggingEnabledProperty()) { 15052 return null; 15053 } 15054 15055 recordSecurityLogRetrievalTime(); 15056 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 15057 try { 15058 SecurityLog.readPreviousEvents(output); 15059 int enabledUser = getSecurityLoggingEnabledUser(); 15060 if (enabledUser != UserHandle.USER_ALL) { 15061 SecurityLog.redactEvents(output, enabledUser); 15062 } 15063 return new ParceledListSlice<SecurityEvent>(output); 15064 } catch (IOException e) { 15065 Slogf.w(LOG_TAG, "Fail to read previous events" , e); 15066 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 15067 } 15068 } 15069 15070 @Override 15071 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin, 15072 String packageName) { 15073 if (!mHasFeature) { 15074 return null; 15075 } 15076 15077 final CallerIdentity caller = getCallerIdentity(admin, packageName); 15078 if (admin != null) { 15079 Preconditions.checkCallAuthorization( 15080 isProfileOwnerOfOrganizationOwnedDevice(caller) 15081 || isDefaultDeviceOwner(caller)); 15082 } else { 15083 // A delegate app passes a null admin component, which is expected 15084 Preconditions.checkCallAuthorization( 15085 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING)); 15086 } 15087 Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile() 15088 || areAllUsersAffiliatedWithDeviceLocked()); 15089 15090 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 15091 return null; 15092 } 15093 15094 recordSecurityLogRetrievalTime(); 15095 15096 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 15097 DevicePolicyEventLogger 15098 .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS) 15099 .setAdmin(caller.getComponentName()) 15100 .write(); 15101 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 15102 } 15103 15104 @Override 15105 public long forceSecurityLogs() { 15106 Preconditions.checkCallAuthorization(isAdb(getCallerIdentity()) 15107 || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS), 15108 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call " 15109 + "forceSecurityLogs"); 15110 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 15111 throw new IllegalStateException("logging is not available"); 15112 } 15113 return mSecurityLogMonitor.forceLogs(); 15114 } 15115 15116 @Override 15117 public boolean isUninstallInQueue(final String packageName) { 15118 final CallerIdentity caller = getCallerIdentity(); 15119 Preconditions.checkCallAuthorization( 15120 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 15121 15122 Pair<String, Integer> packageUserPair = new Pair<>(packageName, caller.getUserId()); 15123 synchronized (getLockObject()) { 15124 return mPackagesToRemove.contains(packageUserPair); 15125 } 15126 } 15127 15128 @Override 15129 public void uninstallPackageWithActiveAdmins(final String packageName) { 15130 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 15131 15132 final CallerIdentity caller = getCallerIdentity(); 15133 Preconditions.checkCallAuthorization( 15134 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)); 15135 15136 final int userId = caller.getUserId(); 15137 enforceUserUnlocked(userId); 15138 15139 final ComponentName profileOwner = getProfileOwnerAsUser(userId); 15140 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 15141 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 15142 } 15143 15144 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 15145 if (getDeviceOwnerUserId() == userId && deviceOwner != null 15146 && packageName.equals(deviceOwner.getPackageName())) { 15147 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 15148 } 15149 15150 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 15151 synchronized (getLockObject()) { 15152 mPackagesToRemove.add(packageUserPair); 15153 } 15154 15155 // All active admins on the user. 15156 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 15157 15158 // Active admins in the target package. 15159 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 15160 if (allActiveAdmins != null) { 15161 for (ComponentName activeAdmin : allActiveAdmins) { 15162 if (packageName.equals(activeAdmin.getPackageName())) { 15163 packageActiveAdmins.add(activeAdmin); 15164 removeActiveAdmin(activeAdmin, userId); 15165 } 15166 } 15167 } 15168 if (packageActiveAdmins.size() == 0) { 15169 startUninstallIntent(packageName, userId); 15170 } else { 15171 mHandler.postDelayed(new Runnable() { 15172 @Override 15173 public void run() { 15174 for (ComponentName activeAdmin : packageActiveAdmins) { 15175 removeAdminArtifacts(activeAdmin, userId); 15176 } 15177 startUninstallIntent(packageName, userId); 15178 } 15179 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 15180 } 15181 } 15182 15183 @Override 15184 public boolean isDeviceProvisioned() { 15185 final CallerIdentity caller = getCallerIdentity(); 15186 Preconditions.checkCallAuthorization(canManageUsers(caller)); 15187 15188 synchronized (getLockObject()) { 15189 return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete; 15190 } 15191 } 15192 15193 private boolean isCurrentUserDemo() { 15194 if (UserManager.isDeviceInDemoMode(mContext)) { 15195 final int userId = mInjector.userHandleGetCallingUserId(); 15196 return mInjector.binderWithCleanCallingIdentity( 15197 () -> mUserManager.getUserInfo(userId).isDemo()); 15198 } 15199 return false; 15200 } 15201 15202 private void removePackageIfRequired(final String packageName, final int userId) { 15203 if (!packageHasActiveAdmins(packageName, userId)) { 15204 // Will not do anything if uninstall was not requested or was already started. 15205 startUninstallIntent(packageName, userId); 15206 } 15207 } 15208 15209 private void startUninstallIntent(final String packageName, final int userId) { 15210 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 15211 synchronized (getLockObject()) { 15212 if (!mPackagesToRemove.contains(packageUserPair)) { 15213 // Do nothing if uninstall was not requested or was already started. 15214 return; 15215 } 15216 mPackagesToRemove.remove(packageUserPair); 15217 } 15218 if (!isPackageInstalledForUser(packageName, userId)) { 15219 // Package does not exist. Nothing to do. 15220 return; 15221 } 15222 15223 try { // force stop the package before uninstalling 15224 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 15225 } catch (RemoteException re) { 15226 Slogf.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 15227 } 15228 final Uri packageURI = Uri.parse("package:" + packageName); 15229 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 15230 uninstallIntent.setFlags(FLAG_ACTIVITY_NEW_TASK); 15231 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 15232 } 15233 15234 /** 15235 * Removes the admin from the policy. Ideally called after the admin's 15236 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 15237 * 15238 * @param adminReceiver The admin to remove 15239 * @param userHandle The user for which this admin has to be removed. 15240 */ 15241 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 15242 synchronized (getLockObject()) { 15243 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 15244 if (admin == null) { 15245 return; 15246 } 15247 final DevicePolicyData policy = getUserData(userHandle); 15248 final boolean doProxyCleanup = admin.info.usesPolicy( 15249 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 15250 policy.mAdminList.remove(admin); 15251 policy.mAdminMap.remove(adminReceiver); 15252 policy.validatePasswordOwner(); 15253 if (doProxyCleanup) { 15254 resetGlobalProxyLocked(policy); 15255 } 15256 pushActiveAdminPackagesLocked(userHandle); 15257 saveSettingsLocked(userHandle); 15258 updateMaximumTimeToLockLocked(userHandle); 15259 policy.mRemovingAdmins.remove(adminReceiver); 15260 pushScreenCapturePolicy(userHandle); 15261 15262 Slogf.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 15263 } 15264 pushMeteredDisabledPackages(userHandle); 15265 // The removed admin might have disabled camera, so update user 15266 // restrictions. 15267 pushUserRestrictions(userHandle); 15268 } 15269 15270 @Override 15271 public void setDeviceProvisioningConfigApplied() { 15272 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 15273 15274 synchronized (getLockObject()) { 15275 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 15276 policy.mDeviceProvisioningConfigApplied = true; 15277 saveSettingsLocked(UserHandle.USER_SYSTEM); 15278 } 15279 } 15280 15281 @Override 15282 public boolean isDeviceProvisioningConfigApplied() { 15283 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())); 15284 15285 synchronized (getLockObject()) { 15286 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 15287 return policy.mDeviceProvisioningConfigApplied; 15288 } 15289 } 15290 15291 /** 15292 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 15293 * 15294 * It's added for testing only. Please use this API carefully if it's used by other system app 15295 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 15296 * apps. 15297 */ 15298 @Override 15299 public void forceUpdateUserSetupComplete(@UserIdInt int userId) { 15300 Preconditions.checkCallAuthorization( 15301 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 15302 15303 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 15304 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 15305 DevicePolicyData policy = getUserData(userId); 15306 policy.mUserSetupComplete = isUserCompleted; 15307 mStateCache.setDeviceProvisioned(isUserCompleted); 15308 synchronized (getLockObject()) { 15309 saveSettingsLocked(userId); 15310 } 15311 } 15312 15313 @Override 15314 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 15315 if (!mHasFeature) { 15316 return; 15317 } 15318 Objects.requireNonNull(admin, "ComponentName is null"); 15319 15320 final CallerIdentity caller = getCallerIdentity(admin); 15321 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 15322 || isProfileOwner(caller) || isFinancedDeviceOwner(caller)); 15323 15324 toggleBackupServiceActive(caller.getUserId(), enabled); 15325 } 15326 15327 @Override 15328 public boolean isBackupServiceEnabled(ComponentName admin) { 15329 if (!mHasFeature) { 15330 return true; 15331 } 15332 Objects.requireNonNull(admin, "ComponentName is null"); 15333 15334 final CallerIdentity caller = getCallerIdentity(admin); 15335 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 15336 || isProfileOwner(caller) || isFinancedDeviceOwner(caller)); 15337 15338 return mInjector.binderWithCleanCallingIdentity(() -> { 15339 synchronized (getLockObject()) { 15340 try { 15341 IBackupManager ibm = mInjector.getIBackupManager(); 15342 return ibm != null && ibm.isBackupServiceActive(caller.getUserId()); 15343 } catch (RemoteException e) { 15344 throw new IllegalStateException("Failed requesting backup service state.", e); 15345 } 15346 } 15347 }); 15348 } 15349 15350 @Override 15351 public boolean bindDeviceAdminServiceAsUser( 15352 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 15353 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 15354 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 15355 if (!mHasFeature) { 15356 return false; 15357 } 15358 Objects.requireNonNull(admin); 15359 Objects.requireNonNull(caller); 15360 Objects.requireNonNull(serviceIntent); 15361 Preconditions.checkArgument( 15362 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 15363 "Service intent must be explicit (with a package name or component): " 15364 + serviceIntent); 15365 Objects.requireNonNull(connection); 15366 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 15367 "target user id must be different from the calling user id"); 15368 15369 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 15370 throw new SecurityException("Not allowed to bind to target user id"); 15371 } 15372 15373 final String targetPackage; 15374 synchronized (getLockObject()) { 15375 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 15376 } 15377 15378 final long callingIdentity = mInjector.binderClearCallingIdentity(); 15379 try { 15380 // Validate and sanitize the incoming service intent. 15381 final Intent sanitizedIntent = 15382 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 15383 if (sanitizedIntent == null) { 15384 // Fail, cannot lookup the target service. 15385 return false; 15386 } 15387 // Ask ActivityManager to bind it. Notice that we are binding the service with the 15388 // caller app instead of DevicePolicyManagerService. 15389 return mInjector.getIActivityManager().bindService( 15390 caller, activtiyToken, serviceIntent, 15391 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 15392 connection, flags, mContext.getOpPackageName(), 15393 targetUserId) != 0; 15394 } catch (RemoteException ex) { 15395 // Same process, should not happen. 15396 } finally { 15397 mInjector.binderRestoreCallingIdentity(callingIdentity); 15398 } 15399 15400 // Failed to bind. 15401 return false; 15402 } 15403 15404 @Override 15405 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 15406 if (!mHasFeature) { 15407 return Collections.emptyList(); 15408 } 15409 Objects.requireNonNull(admin); 15410 final CallerIdentity caller = getCallerIdentity(admin); 15411 Preconditions.checkCallAuthorization( 15412 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 15413 15414 synchronized (getLockObject()) { 15415 final int callingUserId = caller.getUserId(); 15416 return mInjector.binderWithCleanCallingIdentity(() -> { 15417 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 15418 if (!isDeviceOwner(admin, callingUserId)) { 15419 // Profile owners can only bind to the device owner. 15420 if (canUserBindToDeviceOwnerLocked(callingUserId)) { 15421 targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId())); 15422 } 15423 } else { 15424 // Caller is the device owner: Look for profile owners that it can bind to. 15425 final List<UserInfo> userInfos = mUserManager.getAliveUsers(); 15426 for (int i = 0; i < userInfos.size(); i++) { 15427 final int userId = userInfos.get(i).id; 15428 if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) { 15429 targetUsers.add(UserHandle.of(userId)); 15430 } 15431 } 15432 } 15433 15434 return targetUsers; 15435 }); 15436 } 15437 } 15438 15439 private boolean canUserBindToDeviceOwnerLocked(int userId) { 15440 // There has to be a device owner, under another user id. 15441 if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) { 15442 return false; 15443 } 15444 15445 // The user must have a profile owner that belongs to the same package as the device owner. 15446 if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals( 15447 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) { 15448 return false; 15449 } 15450 15451 // The user must be affiliated. 15452 return isUserAffiliatedWithDeviceLocked(userId); 15453 } 15454 15455 /** 15456 * Return true if a given user has any accounts that'll prevent installing a device or profile 15457 * owner {@code owner}. 15458 * - If the user has no accounts, then return false. 15459 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 15460 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 15461 * ..._DISALLOWED, return true. 15462 * - Otherwise return false. 15463 * 15464 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used 15465 * when the caller is not ADB. 15466 * 15467 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 15468 */ 15469 private boolean hasIncompatibleAccountsOrNonAdbNoLock(CallerIdentity caller, 15470 int userId, @Nullable ComponentName owner) { 15471 if (!isAdb(caller)) { 15472 return true; 15473 } 15474 wtfIfInLock(); 15475 15476 return mInjector.binderWithCleanCallingIdentity(() -> { 15477 final AccountManager am = AccountManager.get(mContext); 15478 final Account accounts[] = am.getAccountsAsUser(userId); 15479 if (accounts.length == 0) { 15480 return false; 15481 } 15482 synchronized (getLockObject()) { 15483 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 15484 Slogf.w(LOG_TAG, 15485 "Non test-only owner can't be installed with existing accounts."); 15486 return true; 15487 } 15488 } 15489 15490 final String[] feature_allow = 15491 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 15492 final String[] feature_disallow = 15493 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 15494 15495 boolean compatible = true; 15496 for (Account account : accounts) { 15497 if (hasAccountFeatures(am, account, feature_disallow)) { 15498 Slogf.e(LOG_TAG, "%s has %s", account, feature_disallow[0]); 15499 compatible = false; 15500 break; 15501 } 15502 if (!hasAccountFeatures(am, account, feature_allow)) { 15503 Slogf.e(LOG_TAG, "%s doesn't have %s", account, feature_allow[0]); 15504 compatible = false; 15505 break; 15506 } 15507 } 15508 if (compatible) { 15509 Slogf.w(LOG_TAG, "All accounts are compatible"); 15510 } else { 15511 Slogf.e(LOG_TAG, "Found incompatible accounts"); 15512 } 15513 return !compatible; 15514 }); 15515 } 15516 15517 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 15518 try { 15519 return am.hasFeatures(account, features, null, null).getResult(); 15520 } catch (Exception e) { 15521 Slogf.w(LOG_TAG, "Failed to get account feature", e); 15522 return false; 15523 } 15524 } 15525 15526 private boolean isAdb(CallerIdentity caller) { 15527 return isShellUid(caller) || isRootUid(caller); 15528 } 15529 15530 @Override 15531 public void setNetworkLoggingEnabled(@Nullable ComponentName admin, 15532 @NonNull String packageName, boolean enabled) { 15533 if (!mHasFeature) { 15534 return; 15535 } 15536 final CallerIdentity caller = getCallerIdentity(admin, packageName); 15537 final boolean isManagedProfileOwner = isProfileOwner(caller) 15538 && isManagedProfile(caller.getUserId()); 15539 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 15540 && (isDefaultDeviceOwner(caller) || isManagedProfileOwner)) 15541 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING))); 15542 15543 synchronized (getLockObject()) { 15544 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 15545 // already in the requested state 15546 return; 15547 } 15548 final ActiveAdmin activeAdmin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId()); 15549 activeAdmin.isNetworkLoggingEnabled = enabled; 15550 if (!enabled) { 15551 activeAdmin.numNetworkLoggingNotifications = 0; 15552 activeAdmin.lastNetworkLoggingNotificationTimeMs = 0; 15553 } 15554 saveSettingsLocked(caller.getUserId()); 15555 setNetworkLoggingActiveInternal(enabled); 15556 15557 DevicePolicyEventLogger 15558 .createEvent(DevicePolicyEnums.SET_NETWORK_LOGGING_ENABLED) 15559 .setAdmin(caller.getPackageName()) 15560 .setBoolean(/* isDelegate */ admin == null) 15561 .setInt(enabled ? 1 : 0) 15562 .setStrings(isManagedProfileOwner 15563 ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER) 15564 .write(); 15565 } 15566 } 15567 15568 private void setNetworkLoggingActiveInternal(boolean active) { 15569 mInjector.binderWithCleanCallingIdentity(() -> { 15570 boolean shouldSendNotification = false; 15571 synchronized (getLockObject()) { 15572 if (active) { 15573 if (mNetworkLogger == null) { 15574 final int affectedUserId = getNetworkLoggingAffectedUser(); 15575 mNetworkLogger = new NetworkLogger(this, 15576 mInjector.getPackageManagerInternal(), 15577 affectedUserId == UserHandle.USER_SYSTEM 15578 ? UserHandle.USER_ALL : affectedUserId); 15579 } 15580 if (!mNetworkLogger.startNetworkLogging()) { 15581 mNetworkLogger = null; 15582 Slogf.wtf(LOG_TAG, "Network logging could not be started due to the logging" 15583 + " service not being available yet."); 15584 } 15585 maybePauseDeviceWideLoggingLocked(); 15586 shouldSendNotification = shouldSendNetworkLoggingNotificationLocked(); 15587 } else { 15588 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 15589 Slogf.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 15590 + " service not being available yet."); 15591 } 15592 mNetworkLogger = null; 15593 } 15594 } 15595 if (active) { 15596 if (shouldSendNotification) { 15597 mHandler.post(() -> handleSendNetworkLoggingNotification()); 15598 } 15599 } else { 15600 mHandler.post(() -> handleCancelNetworkLoggingNotification()); 15601 } 15602 }); 15603 } 15604 15605 private @UserIdInt int getNetworkLoggingAffectedUser() { 15606 synchronized (getLockObject()) { 15607 if (mOwners.hasDeviceOwner()) { 15608 return mOwners.getDeviceOwnerUserId(); 15609 } else { 15610 return mInjector.binderWithCleanCallingIdentity( 15611 () -> getManagedUserId(UserHandle.USER_SYSTEM)); 15612 } 15613 } 15614 } 15615 15616 private ActiveAdmin getNetworkLoggingControllingAdminLocked() { 15617 int affectedUserId = getNetworkLoggingAffectedUser(); 15618 if (affectedUserId < 0) { 15619 return null; 15620 } 15621 return getDeviceOrProfileOwnerAdminLocked(affectedUserId); 15622 } 15623 15624 @Override 15625 public long forceNetworkLogs() { 15626 Preconditions.checkCallAuthorization(isAdb(getCallerIdentity()) 15627 || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS), 15628 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call " 15629 + "forceNetworkLogs"); 15630 synchronized (getLockObject()) { 15631 if (!isNetworkLoggingEnabledInternalLocked()) { 15632 throw new IllegalStateException("logging is not available"); 15633 } 15634 if (mNetworkLogger != null) { 15635 return mInjector.binderWithCleanCallingIdentity( 15636 () -> mNetworkLogger.forceBatchFinalization()); 15637 } 15638 return 0; 15639 } 15640 } 15641 15642 /** Pauses security and network logging if there are unaffiliated users on the device */ 15643 @GuardedBy("getLockObject()") 15644 private void maybePauseDeviceWideLoggingLocked() { 15645 if (!areAllUsersAffiliatedWithDeviceLocked()) { 15646 if (mOwners.hasDeviceOwner()) { 15647 Slogf.i(LOG_TAG, "There are unaffiliated users, network logging will be " 15648 + "paused if enabled."); 15649 if (mNetworkLogger != null) { 15650 mNetworkLogger.pause(); 15651 } 15652 } 15653 if (!isOrganizationOwnedDeviceWithManagedProfile()) { 15654 Slogf.i(LOG_TAG, "Not org-owned managed profile device, security logging will be " 15655 + "paused if enabled."); 15656 mSecurityLogMonitor.pause(); 15657 } 15658 } 15659 } 15660 15661 /** Resumes security and network logging (if they are enabled) if all users are affiliated */ 15662 @GuardedBy("getLockObject()") 15663 private void maybeResumeDeviceWideLoggingLocked() { 15664 boolean allUsersAffiliated = areAllUsersAffiliatedWithDeviceLocked(); 15665 boolean orgOwnedProfileDevice = isOrganizationOwnedDeviceWithManagedProfile(); 15666 mInjector.binderWithCleanCallingIdentity(() -> { 15667 if (allUsersAffiliated || orgOwnedProfileDevice) { 15668 mSecurityLogMonitor.resume(); 15669 } 15670 // If there is no device owner, then per-user network logging may be enabled for the 15671 // managed profile. In which case, all users do not need to be affiliated. 15672 if (allUsersAffiliated || !mOwners.hasDeviceOwner()) { 15673 if (mNetworkLogger != null) { 15674 mNetworkLogger.resume(); 15675 } 15676 } 15677 }); 15678 } 15679 15680 /** Deletes any security and network logs that might have been collected so far */ 15681 @GuardedBy("getLockObject()") 15682 private void discardDeviceWideLogsLocked() { 15683 mSecurityLogMonitor.discardLogs(); 15684 if (mNetworkLogger != null) { 15685 mNetworkLogger.discardLogs(); 15686 } 15687 // TODO: We should discard pre-boot security logs here too, as otherwise those 15688 // logs (which might contain data from the user just removed) will be 15689 // available after next boot. 15690 } 15691 15692 /** 15693 * This API is cached: invalidate with invalidateBinderCaches(). 15694 */ 15695 @Override 15696 public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin, 15697 @NonNull String packageName) { 15698 if (!mHasFeature) { 15699 return false; 15700 } 15701 final CallerIdentity caller = getCallerIdentity(admin, packageName); 15702 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 15703 && (isDefaultDeviceOwner(caller) 15704 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId())))) 15705 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)) 15706 || hasCallingOrSelfPermission(permission.MANAGE_USERS)); 15707 15708 synchronized (getLockObject()) { 15709 return isNetworkLoggingEnabledInternalLocked(); 15710 } 15711 } 15712 15713 private boolean isNetworkLoggingEnabledInternalLocked() { 15714 ActiveAdmin activeAdmin = getNetworkLoggingControllingAdminLocked(); 15715 return (activeAdmin != null) && activeAdmin.isNetworkLoggingEnabled; 15716 } 15717 15718 /* 15719 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 15720 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 15721 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 15722 * 15723 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 15724 */ 15725 @Override 15726 public List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin, 15727 @NonNull String packageName, long batchToken) { 15728 if (!mHasFeature) { 15729 return null; 15730 } 15731 final CallerIdentity caller = getCallerIdentity(admin, packageName); 15732 final boolean isManagedProfileOwner = isProfileOwner(caller) 15733 && isManagedProfile(caller.getUserId()); 15734 Preconditions.checkCallAuthorization((caller.hasAdminComponent() 15735 && (isDefaultDeviceOwner(caller) || isManagedProfileOwner)) 15736 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING))); 15737 if (mOwners.hasDeviceOwner()) { 15738 checkAllUsersAreAffiliatedWithDevice(); 15739 } 15740 15741 synchronized (getLockObject()) { 15742 if (mNetworkLogger == null || !isNetworkLoggingEnabledInternalLocked()) { 15743 return null; 15744 } 15745 DevicePolicyEventLogger 15746 .createEvent(DevicePolicyEnums.RETRIEVE_NETWORK_LOGS) 15747 .setAdmin(caller.getPackageName()) 15748 .setBoolean(/* isDelegate */ admin == null) 15749 .setStrings(isManagedProfileOwner 15750 ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER) 15751 .write(); 15752 15753 final long currentTime = System.currentTimeMillis(); 15754 DevicePolicyData policyData = getUserData(caller.getUserId()); 15755 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 15756 policyData.mLastNetworkLogsRetrievalTime = currentTime; 15757 saveSettingsLocked(caller.getUserId()); 15758 } 15759 return mNetworkLogger.retrieveLogs(batchToken); 15760 } 15761 } 15762 15763 /** 15764 * Returns whether it's time to post another network logging notification. When returning true, 15765 * this method has the side-effect of updating the recorded last network logging notification 15766 * time to now. 15767 */ 15768 private boolean shouldSendNetworkLoggingNotificationLocked() { 15769 ensureLocked(); 15770 // Send a network logging notification if the admin is a device owner, not profile owner. 15771 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 15772 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 15773 return false; 15774 } 15775 if (deviceOwner.numNetworkLoggingNotifications 15776 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 15777 return false; 15778 } 15779 final long now = System.currentTimeMillis(); 15780 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 15781 return false; 15782 } 15783 deviceOwner.numNetworkLoggingNotifications++; 15784 if (deviceOwner.numNetworkLoggingNotifications 15785 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 15786 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 15787 } else { 15788 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 15789 } 15790 saveSettingsLocked(deviceOwner.getUserHandle().getIdentifier()); 15791 return true; 15792 } 15793 15794 private void handleSendNetworkLoggingNotification() { 15795 final PackageManagerInternal pm = mInjector.getPackageManagerInternal(); 15796 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 15797 intent.setPackage(pm.getSystemUiServiceComponent().getPackageName()); 15798 mNetworkLoggingNotificationUserId = getCurrentForegroundUserId(); 15799 // Simple notification clicks are immutable 15800 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 15801 PendingIntent.FLAG_IMMUTABLE, UserHandle.CURRENT); 15802 15803 final String title = getNetworkLoggingTitle(); 15804 final String text = getNetworkLoggingText(); 15805 Notification notification = 15806 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 15807 .setSmallIcon(R.drawable.ic_info_outline) 15808 .setContentTitle(title) 15809 .setContentText(text) 15810 .setTicker(title) 15811 .setShowWhen(true) 15812 .setContentIntent(pendingIntent) 15813 .setStyle(new Notification.BigTextStyle().bigText(text)) 15814 .build(); 15815 Slogf.i(LOG_TAG, "Sending network logging notification to user %d", 15816 mNetworkLoggingNotificationUserId); 15817 mInjector.getNotificationManager().notifyAsUser(/* tag= */ null, 15818 SystemMessage.NOTE_NETWORK_LOGGING, notification, 15819 UserHandle.of(mNetworkLoggingNotificationUserId)); 15820 } 15821 15822 private String getNetworkLoggingTitle() { 15823 return getUpdatableString( 15824 NETWORK_LOGGING_TITLE, R.string.network_logging_notification_title); 15825 } 15826 15827 private String getNetworkLoggingText() { 15828 return getUpdatableString( 15829 NETWORK_LOGGING_MESSAGE, R.string.network_logging_notification_text); 15830 } 15831 15832 private void handleCancelNetworkLoggingNotification() { 15833 if (mNetworkLoggingNotificationUserId == UserHandle.USER_NULL) { 15834 // Happens when setNetworkLoggingActive(false) is called before called with true 15835 Slogf.d(LOG_TAG, "Not cancelling network logging notification for USER_NULL"); 15836 return; 15837 } 15838 15839 Slogf.i(LOG_TAG, "Cancelling network logging notification for user %d", 15840 mNetworkLoggingNotificationUserId); 15841 mInjector.getNotificationManager().cancelAsUser(/* tag= */ null, 15842 SystemMessage.NOTE_NETWORK_LOGGING, 15843 UserHandle.of(mNetworkLoggingNotificationUserId)); 15844 mNetworkLoggingNotificationUserId = UserHandle.USER_NULL; 15845 } 15846 15847 /** 15848 * Return the package name of owner in a given user. 15849 */ 15850 private String getOwnerPackageNameForUserLocked(int userId) { 15851 return mOwners.getDeviceOwnerUserId() == userId 15852 ? mOwners.getDeviceOwnerPackageName() 15853 : mOwners.getProfileOwnerPackage(userId); 15854 } 15855 15856 /** 15857 * @param rawIntent Original service intent specified by caller. It must be explicit. 15858 * @param expectedPackageName The expected package name of the resolved service. 15859 * @return Intent that have component explicitly set. {@code null} if no service is resolved 15860 * with the given intent. 15861 * @throws SecurityException if the intent is resolved to an invalid service. 15862 */ 15863 private Intent createCrossUserServiceIntent( 15864 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 15865 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 15866 ResolveInfo info = mIPackageManager.resolveService( 15867 rawIntent, 15868 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 15869 0, // flags 15870 targetUserId); 15871 if (info == null || info.serviceInfo == null) { 15872 Slogf.e(LOG_TAG, "Fail to look up the service: %s or user %d is not running", rawIntent, 15873 targetUserId); 15874 return null; 15875 } 15876 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 15877 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 15878 } 15879 // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release. 15880 if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) { 15881 throw new SecurityException( 15882 "Service must be protected by BIND_DEVICE_ADMIN permission"); 15883 } 15884 // It is the system server to bind the service, it would be extremely dangerous if it 15885 // can be exploited to bind any service. Set the component explicitly to make sure we 15886 // do not bind anything accidentally. 15887 rawIntent.setComponent(info.serviceInfo.getComponentName()); 15888 return rawIntent; 15889 } 15890 15891 @Override getLastSecurityLogRetrievalTime()15892 public long getLastSecurityLogRetrievalTime() { 15893 final CallerIdentity caller = getCallerIdentity(); 15894 Preconditions.checkCallAuthorization( 15895 isDefaultDeviceOwner(caller) || canManageUsers(caller)); 15896 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 15897 } 15898 15899 @Override getLastBugReportRequestTime()15900 public long getLastBugReportRequestTime() { 15901 final CallerIdentity caller = getCallerIdentity(); 15902 Preconditions.checkCallAuthorization( 15903 isDefaultDeviceOwner(caller) || canManageUsers(caller)); 15904 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 15905 } 15906 15907 @Override getLastNetworkLogRetrievalTime()15908 public long getLastNetworkLogRetrievalTime() { 15909 final CallerIdentity caller = getCallerIdentity(); 15910 15911 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 15912 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId())) 15913 || canManageUsers(caller)); 15914 final int affectedUserId = getNetworkLoggingAffectedUser(); 15915 return affectedUserId >= 0 ? getUserData(affectedUserId).mLastNetworkLogsRetrievalTime : -1; 15916 } 15917 15918 @Override setResetPasswordToken(ComponentName admin, byte[] token)15919 public boolean setResetPasswordToken(ComponentName admin, byte[] token) { 15920 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 15921 return false; 15922 } 15923 if (token == null || token.length < 32) { 15924 throw new IllegalArgumentException("token must be at least 32-byte long"); 15925 } 15926 final CallerIdentity caller = getCallerIdentity(admin); 15927 Preconditions.checkCallAuthorization( 15928 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 15929 15930 synchronized (getLockObject()) { 15931 final int userHandle = caller.getUserId(); 15932 15933 DevicePolicyData policy = getUserData(userHandle); 15934 return mInjector.binderWithCleanCallingIdentity(() -> { 15935 if (policy.mPasswordTokenHandle != 0) { 15936 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle); 15937 } 15938 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, 15939 userHandle, /*EscrowTokenStateChangeCallback*/ null); 15940 saveSettingsLocked(userHandle); 15941 return policy.mPasswordTokenHandle != 0; 15942 }); 15943 } 15944 } 15945 15946 @Override 15947 public boolean clearResetPasswordToken(ComponentName admin) { 15948 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 15949 return false; 15950 } 15951 final CallerIdentity caller = getCallerIdentity(admin); 15952 Preconditions.checkCallAuthorization( 15953 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 15954 15955 synchronized (getLockObject()) { 15956 final int userHandle = caller.getUserId(); 15957 15958 DevicePolicyData policy = getUserData(userHandle); 15959 if (policy.mPasswordTokenHandle != 0) { 15960 return mInjector.binderWithCleanCallingIdentity(() -> { 15961 boolean result = mLockPatternUtils.removeEscrowToken( 15962 policy.mPasswordTokenHandle, userHandle); 15963 policy.mPasswordTokenHandle = 0; 15964 saveSettingsLocked(userHandle); 15965 return result; 15966 }); 15967 } 15968 } 15969 return false; 15970 } 15971 15972 @Override 15973 public boolean isResetPasswordTokenActive(ComponentName admin) { 15974 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 15975 return false; 15976 } 15977 final CallerIdentity caller = getCallerIdentity(admin); 15978 Preconditions.checkCallAuthorization( 15979 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 15980 15981 synchronized (getLockObject()) { 15982 return isResetPasswordTokenActiveForUserLocked(caller.getUserId()); 15983 } 15984 } 15985 15986 private boolean isResetPasswordTokenActiveForUserLocked(int userHandle) { 15987 DevicePolicyData policy = getUserData(userHandle); 15988 if (policy.mPasswordTokenHandle != 0) { 15989 return mInjector.binderWithCleanCallingIdentity(() -> 15990 mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle, userHandle)); 15991 } 15992 return false; 15993 } 15994 15995 @Override 15996 public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, 15997 int flags) { 15998 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 15999 return false; 16000 } 16001 Objects.requireNonNull(token); 16002 16003 final CallerIdentity caller = getCallerIdentity(admin); 16004 Preconditions.checkCallAuthorization( 16005 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 16006 16007 synchronized (getLockObject()) { 16008 DevicePolicyData policy = getUserData(caller.getUserId()); 16009 if (policy.mPasswordTokenHandle != 0) { 16010 final String password = passwordOrNull != null ? passwordOrNull : ""; 16011 final boolean result = resetPasswordInternal(password, policy.mPasswordTokenHandle, 16012 token, flags, caller); 16013 if (result) { 16014 DevicePolicyEventLogger 16015 .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN) 16016 .setAdmin(caller.getComponentName()) 16017 .write(); 16018 } 16019 return result; 16020 } else { 16021 Slogf.w(LOG_TAG, "No saved token handle"); 16022 } 16023 } 16024 return false; 16025 } 16026 16027 @Override 16028 public boolean isCurrentInputMethodSetByOwner() { 16029 final CallerIdentity caller = getCallerIdentity(); 16030 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 16031 || isProfileOwner(caller) || isSystemUid(caller), 16032 "Only profile owner, device owner and system may call this method."); 16033 return getUserData(caller.getUserId()).mCurrentInputMethodSet; 16034 } 16035 16036 @Override 16037 public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) { 16038 final int userId = user.getIdentifier(); 16039 final CallerIdentity caller = getCallerIdentity(); 16040 Preconditions.checkCallAuthorization((userId == caller.getUserId()) 16041 || isProfileOwner(caller) || isDefaultDeviceOwner(caller) 16042 || hasFullCrossUsersPermission(caller, userId)); 16043 16044 synchronized (getLockObject()) { 16045 return new StringParceledListSlice( 16046 new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts)); 16047 } 16048 } 16049 16050 @Override 16051 public void clearApplicationUserData(ComponentName admin, String packageName, 16052 IPackageDataObserver callback) { 16053 Objects.requireNonNull(admin, "ComponentName is null"); 16054 Objects.requireNonNull(packageName, "packageName is null"); 16055 Objects.requireNonNull(callback, "callback is null"); 16056 16057 final CallerIdentity caller = getCallerIdentity(admin); 16058 Preconditions.checkCallAuthorization( 16059 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 16060 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CLEAR_APPLICATION_USER_DATA); 16061 16062 long ident = mInjector.binderClearCallingIdentity(); 16063 try { 16064 ActivityManager.getService().clearApplicationUserData(packageName, false, callback, 16065 caller.getUserId()); 16066 } catch(RemoteException re) { 16067 // Same process, should not happen. 16068 } catch (SecurityException se) { 16069 // This can happen e.g. for device admin packages, do not throw out the exception, 16070 // because callers have no means to know beforehand for which packages this might 16071 // happen. If so, we send back that removal failed. 16072 Slogf.w(LOG_TAG, "Not allowed to clear application user data for package " 16073 + packageName, se); 16074 try { 16075 callback.onRemoveCompleted(packageName, false); 16076 } catch (RemoteException re) { 16077 // Caller is no longer available, ignore 16078 } 16079 } finally { 16080 mInjector.binderRestoreCallingIdentity(ident); 16081 } 16082 } 16083 16084 @Override 16085 public void setLogoutEnabled(ComponentName admin, boolean enabled) { 16086 if (!mHasFeature) { 16087 return; 16088 } 16089 Objects.requireNonNull(admin, "ComponentName is null"); 16090 final CallerIdentity caller = getCallerIdentity(admin); 16091 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16092 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOGOUT_ENABLED); 16093 16094 synchronized (getLockObject()) { 16095 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 16096 if (deviceOwner.isLogoutEnabled == enabled) { 16097 // already in the requested state 16098 return; 16099 } 16100 deviceOwner.isLogoutEnabled = enabled; 16101 saveSettingsLocked(caller.getUserId()); 16102 } 16103 } 16104 16105 @Override 16106 public boolean isLogoutEnabled() { 16107 if (!mHasFeature) { 16108 return false; 16109 } 16110 synchronized (getLockObject()) { 16111 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 16112 return (deviceOwner != null) && deviceOwner.isLogoutEnabled; 16113 } 16114 } 16115 16116 @Override 16117 public List<String> getDisallowedSystemApps(ComponentName admin, int userId, 16118 String provisioningAction) throws RemoteException { 16119 Preconditions.checkCallAuthorization( 16120 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 16121 16122 return new ArrayList<>( 16123 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction)); 16124 } 16125 16126 @Override 16127 public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target, 16128 @Nullable PersistableBundle bundle) { 16129 if (!mHasFeature) { 16130 return; 16131 } 16132 Objects.requireNonNull(admin, "ComponentName is null"); 16133 Objects.requireNonNull(target, "Target cannot be null."); 16134 Preconditions.checkArgument(!admin.equals(target), 16135 "Provided administrator and target are the same object."); 16136 Preconditions.checkArgument(!admin.getPackageName().equals(target.getPackageName()), 16137 "Provided administrator and target have the same package name."); 16138 if (bundle != null) { 16139 enforceMaxStringLength(bundle, "bundle"); 16140 } 16141 16142 final CallerIdentity caller = getCallerIdentity(admin); 16143 Preconditions.checkCallAuthorization( 16144 isDefaultDeviceOwner(caller) || isProfileOwner(caller)); 16145 16146 final int callingUserId = caller.getUserId(); 16147 final DevicePolicyData policy = getUserData(callingUserId); 16148 final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId, 16149 /* throwForMissingPermission= */ true); 16150 checkActiveAdminPrecondition(target, incomingDeviceInfo, policy); 16151 Preconditions.checkArgument(incomingDeviceInfo.supportsTransferOwnership(), 16152 "Provided target does not support ownership transfer."); 16153 16154 final long id = mInjector.binderClearCallingIdentity(); 16155 String ownerType = null; 16156 try { 16157 synchronized (getLockObject()) { 16158 /* 16159 * We must ensure the whole process is atomic to prevent the device from ending up 16160 * in an invalid state (e.g. no active admin). This could happen if the device 16161 * is rebooted or work mode is turned off mid-transfer. 16162 * In order to guarantee atomicity, we: 16163 * 16164 * 1. Save an atomic journal file describing the transfer process 16165 * 2. Perform the transfer itself 16166 * 3. Delete the journal file 16167 * 16168 * That way if the journal file exists on device boot, we know that the transfer 16169 * must be reverted back to the original administrator. This logic is implemented in 16170 * revertTransferOwnershipIfNecessaryLocked. 16171 * */ 16172 if (bundle == null) { 16173 bundle = new PersistableBundle(); 16174 } 16175 if (isProfileOwner(caller)) { 16176 ownerType = ADMIN_TYPE_PROFILE_OWNER; 16177 prepareTransfer(admin, target, bundle, callingUserId, 16178 ADMIN_TYPE_PROFILE_OWNER); 16179 transferProfileOwnershipLocked(admin, target, callingUserId); 16180 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 16181 getTransferOwnershipAdminExtras(bundle), callingUserId); 16182 postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId); 16183 if (isUserAffiliatedWithDeviceLocked(callingUserId)) { 16184 notifyAffiliatedProfileTransferOwnershipComplete(callingUserId); 16185 } 16186 } else if (isDefaultDeviceOwner(caller)) { 16187 ownerType = ADMIN_TYPE_DEVICE_OWNER; 16188 prepareTransfer(admin, target, bundle, callingUserId, 16189 ADMIN_TYPE_DEVICE_OWNER); 16190 transferDeviceOwnershipLocked(admin, target, callingUserId); 16191 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 16192 getTransferOwnershipAdminExtras(bundle)); 16193 postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId); 16194 } 16195 } 16196 } finally { 16197 mInjector.binderRestoreCallingIdentity(id); 16198 } 16199 DevicePolicyEventLogger 16200 .createEvent(DevicePolicyEnums.TRANSFER_OWNERSHIP) 16201 .setAdmin(admin) 16202 .setStrings(target.getPackageName(), ownerType) 16203 .write(); 16204 } 16205 16206 private void prepareTransfer(ComponentName admin, ComponentName target, 16207 PersistableBundle bundle, int callingUserId, String adminType) { 16208 saveTransferOwnershipBundleLocked(bundle, callingUserId); 16209 mTransferOwnershipMetadataManager.saveMetadataFile( 16210 new TransferOwnershipMetadataManager.Metadata(admin, target, 16211 callingUserId, adminType)); 16212 } 16213 16214 private void postTransfer(String broadcast, int callingUserId) { 16215 deleteTransferOwnershipMetadataFileLocked(); 16216 sendOwnerChangedBroadcast(broadcast, callingUserId); 16217 } 16218 16219 private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) { 16220 final Bundle extras = new Bundle(); 16221 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId)); 16222 sendDeviceOwnerCommand( 16223 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras); 16224 } 16225 16226 /** 16227 * Transfers the profile owner for user with id profileOwnerUserId from admin to target. 16228 */ 16229 private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target, 16230 int profileOwnerUserId) { 16231 transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId); 16232 mOwners.transferProfileOwner(target, profileOwnerUserId); 16233 Slogf.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId); 16234 mOwners.writeProfileOwner(profileOwnerUserId); 16235 mDeviceAdminServiceController.startServiceForOwner( 16236 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner"); 16237 } 16238 16239 /** 16240 * Transfers the device owner for user with id userId from admin to target. 16241 */ 16242 private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) { 16243 transferActiveAdminUncheckedLocked(target, admin, userId); 16244 mOwners.transferDeviceOwnership(target); 16245 Slogf.i(LOG_TAG, "Device owner set: " + target + " on user " + userId); 16246 mOwners.writeDeviceOwner(); 16247 mDeviceAdminServiceController.startServiceForOwner( 16248 target.getPackageName(), userId, "transfer-device-owner"); 16249 } 16250 16251 private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) { 16252 Bundle extras = new Bundle(); 16253 if (bundle != null) { 16254 extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle); 16255 } 16256 return extras; 16257 } 16258 16259 @Override 16260 public void setStartUserSessionMessage( 16261 ComponentName admin, CharSequence startUserSessionMessage) { 16262 if (!mHasFeature) { 16263 return; 16264 } 16265 Objects.requireNonNull(admin, "ComponentName is null"); 16266 final CallerIdentity caller = getCallerIdentity(admin); 16267 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16268 16269 final String startUserSessionMessageString = 16270 startUserSessionMessage != null ? startUserSessionMessage.toString() : null; 16271 16272 synchronized (getLockObject()) { 16273 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 16274 if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) { 16275 return; 16276 } 16277 deviceOwner.startUserSessionMessage = startUserSessionMessageString; 16278 saveSettingsLocked(caller.getUserId()); 16279 } 16280 16281 mInjector.getActivityManagerInternal() 16282 .setSwitchingFromSystemUserMessage(startUserSessionMessageString); 16283 } 16284 16285 @Override 16286 public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) { 16287 if (!mHasFeature) { 16288 return; 16289 } 16290 Objects.requireNonNull(admin, "ComponentName is null"); 16291 final CallerIdentity caller = getCallerIdentity(admin); 16292 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16293 16294 final String endUserSessionMessageString = 16295 endUserSessionMessage != null ? endUserSessionMessage.toString() : null; 16296 16297 synchronized (getLockObject()) { 16298 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 16299 if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) { 16300 return; 16301 } 16302 deviceOwner.endUserSessionMessage = endUserSessionMessageString; 16303 saveSettingsLocked(caller.getUserId()); 16304 } 16305 16306 mInjector.getActivityManagerInternal() 16307 .setSwitchingToSystemUserMessage(endUserSessionMessageString); 16308 } 16309 16310 @Override 16311 public String getStartUserSessionMessage(ComponentName admin) { 16312 if (!mHasFeature) { 16313 return null; 16314 } 16315 Objects.requireNonNull(admin, "ComponentName is null"); 16316 final CallerIdentity caller = getCallerIdentity(admin); 16317 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16318 16319 synchronized (getLockObject()) { 16320 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 16321 return deviceOwner.startUserSessionMessage; 16322 } 16323 } 16324 16325 @Override 16326 public String getEndUserSessionMessage(ComponentName admin) { 16327 if (!mHasFeature) { 16328 return null; 16329 } 16330 Objects.requireNonNull(admin, "ComponentName is null"); 16331 final CallerIdentity caller = getCallerIdentity(admin); 16332 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16333 16334 synchronized (getLockObject()) { 16335 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 16336 return deviceOwner.endUserSessionMessage; 16337 } 16338 } 16339 16340 private void deleteTransferOwnershipMetadataFileLocked() { 16341 mTransferOwnershipMetadataManager.deleteMetadataFile(); 16342 } 16343 16344 @Override 16345 @Nullable 16346 public PersistableBundle getTransferOwnershipBundle() { 16347 final CallerIdentity caller = getCallerIdentity(); 16348 Preconditions.checkCallAuthorization( 16349 isProfileOwner(caller) || isDefaultDeviceOwner(caller)); 16350 16351 synchronized (getLockObject()) { 16352 final int callingUserId = caller.getUserId(); 16353 final File bundleFile = new File( 16354 mPathProvider.getUserSystemDirectory(callingUserId), 16355 TRANSFER_OWNERSHIP_PARAMETERS_XML); 16356 if (!bundleFile.exists()) { 16357 return null; 16358 } 16359 try (FileInputStream stream = new FileInputStream(bundleFile)) { 16360 TypedXmlPullParser parser = Xml.resolvePullParser(stream); 16361 parser.next(); 16362 return PersistableBundle.restoreFromXml(parser); 16363 } catch (IOException | XmlPullParserException | IllegalArgumentException e) { 16364 Slogf.e(LOG_TAG, "Caught exception while trying to load the " 16365 + "owner transfer parameters from file " + bundleFile, e); 16366 return null; 16367 } 16368 } 16369 } 16370 16371 @Override 16372 public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) { 16373 if (!mHasFeature || !mHasTelephonyFeature) { 16374 return -1; 16375 } 16376 Objects.requireNonNull(who, "ComponentName is null"); 16377 Objects.requireNonNull(apnSetting, "ApnSetting is null in addOverrideApn"); 16378 final CallerIdentity caller = getCallerIdentity(who); 16379 if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) { 16380 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 16381 || isManagedProfileOwner(caller)); 16382 } else { 16383 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16384 } 16385 16386 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class); 16387 if (tm != null) { 16388 return mInjector.binderWithCleanCallingIdentity( 16389 () -> tm.addDevicePolicyOverrideApn(mContext, apnSetting)); 16390 } else { 16391 Slogf.w(LOG_TAG, "TelephonyManager is null when trying to add override apn"); 16392 return INVALID_APN_ID; 16393 } 16394 } 16395 16396 @Override 16397 public boolean updateOverrideApn(@NonNull ComponentName who, int apnId, 16398 @NonNull ApnSetting apnSetting) { 16399 if (!mHasFeature || !mHasTelephonyFeature) { 16400 return false; 16401 } 16402 Objects.requireNonNull(who, "ComponentName is null"); 16403 Objects.requireNonNull(apnSetting, "ApnSetting is null in updateOverrideApn"); 16404 final CallerIdentity caller = getCallerIdentity(who); 16405 ApnSetting apn = getApnSetting(apnId); 16406 if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE 16407 && apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) { 16408 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 16409 || isManagedProfileOwner(caller)); 16410 } else { 16411 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16412 } 16413 16414 if (apnId < 0) { 16415 return false; 16416 } 16417 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class); 16418 if (tm != null) { 16419 return mInjector.binderWithCleanCallingIdentity( 16420 () -> tm.modifyDevicePolicyOverrideApn(mContext, apnId, apnSetting)); 16421 } else { 16422 Slogf.w(LOG_TAG, "TelephonyManager is null when trying to modify override apn"); 16423 return false; 16424 } 16425 } 16426 16427 @Override 16428 public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) { 16429 if (!mHasFeature || !mHasTelephonyFeature) { 16430 return false; 16431 } 16432 Objects.requireNonNull(who, "ComponentName is null"); 16433 final CallerIdentity caller = getCallerIdentity(who); 16434 ApnSetting apn = getApnSetting(apnId); 16435 if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) { 16436 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 16437 || isManagedProfileOwner(caller)); 16438 } else { 16439 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16440 } 16441 return removeOverrideApnUnchecked(apnId); 16442 } 16443 16444 private boolean removeOverrideApnUnchecked(int apnId) { 16445 if(apnId < 0) { 16446 return false; 16447 } 16448 int numDeleted = mInjector.binderWithCleanCallingIdentity( 16449 () -> mContext.getContentResolver().delete( 16450 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null)); 16451 return numDeleted > 0; 16452 } 16453 16454 private ApnSetting getApnSetting(int apnId) { 16455 if (apnId < 0) { 16456 return null; 16457 } 16458 ApnSetting apnSetting = null; 16459 Cursor cursor = mInjector.binderWithCleanCallingIdentity( 16460 () -> mContext.getContentResolver().query( 16461 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null, null, 16462 Telephony.Carriers.DEFAULT_SORT_ORDER)); 16463 if (cursor != null) { 16464 while (cursor.moveToNext()) { 16465 apnSetting = ApnSetting.makeApnSetting(cursor); 16466 if (apnSetting != null) { 16467 break; 16468 } 16469 } 16470 cursor.close(); 16471 } 16472 return apnSetting; 16473 } 16474 16475 @Override 16476 public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) { 16477 if (!mHasFeature || !mHasTelephonyFeature) { 16478 return Collections.emptyList(); 16479 } 16480 Objects.requireNonNull(who, "ComponentName is null"); 16481 final CallerIdentity caller = getCallerIdentity(who); 16482 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) 16483 || isManagedProfileOwner(caller)); 16484 List<ApnSetting> apnSettings = getOverrideApnsUnchecked(); 16485 if (isProfileOwner(caller)) { 16486 List<ApnSetting> apnSettingList = new ArrayList<>(); 16487 for (ApnSetting apnSetting : apnSettings) { 16488 if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) { 16489 apnSettingList.add(apnSetting); 16490 } 16491 } 16492 return apnSettingList; 16493 } else { 16494 return apnSettings; 16495 } 16496 } 16497 16498 private List<ApnSetting> getOverrideApnsUnchecked() { 16499 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class); 16500 if (tm != null) { 16501 return mInjector.binderWithCleanCallingIdentity( 16502 () -> tm.getDevicePolicyOverrideApns(mContext)); 16503 } 16504 Slogf.w(LOG_TAG, "TelephonyManager is null when trying to get override apns"); 16505 return Collections.emptyList(); 16506 } 16507 16508 @Override 16509 public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) { 16510 if (!mHasFeature || !mHasTelephonyFeature) { 16511 return; 16512 } 16513 Objects.requireNonNull(who, "ComponentName is null"); 16514 final CallerIdentity caller = getCallerIdentity(who); 16515 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16516 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_OVERRIDE_APNS_ENABLED); 16517 16518 setOverrideApnsEnabledUnchecked(enabled); 16519 } 16520 16521 private void setOverrideApnsEnabledUnchecked(boolean enabled) { 16522 ContentValues value = new ContentValues(); 16523 value.put(ENFORCE_KEY, enabled); 16524 mInjector.binderWithCleanCallingIdentity(() -> mContext.getContentResolver().update( 16525 ENFORCE_MANAGED_URI, value, null, null)); 16526 } 16527 16528 @Override 16529 public boolean isOverrideApnEnabled(@NonNull ComponentName who) { 16530 if (!mHasFeature || !mHasTelephonyFeature) { 16531 return false; 16532 } 16533 Objects.requireNonNull(who, "ComponentName is null"); 16534 final CallerIdentity caller = getCallerIdentity(who); 16535 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16536 16537 Cursor enforceCursor = mInjector.binderWithCleanCallingIdentity( 16538 () -> mContext.getContentResolver().query( 16539 ENFORCE_MANAGED_URI, null, null, null, null)); 16540 16541 if (enforceCursor == null) { 16542 return false; 16543 } 16544 try { 16545 if (enforceCursor.moveToFirst()) { 16546 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1; 16547 } 16548 } catch (IllegalArgumentException e) { 16549 Slogf.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain " 16550 + "correct info.", e); 16551 } finally { 16552 enforceCursor.close(); 16553 } 16554 return false; 16555 } 16556 16557 @VisibleForTesting 16558 void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) { 16559 final File parametersFile = new File( 16560 mPathProvider.getUserSystemDirectory(userId), 16561 TRANSFER_OWNERSHIP_PARAMETERS_XML); 16562 final AtomicFile atomicFile = new AtomicFile(parametersFile); 16563 FileOutputStream stream = null; 16564 try { 16565 stream = atomicFile.startWrite(); 16566 final TypedXmlSerializer serializer = Xml.resolveSerializer(stream); 16567 serializer.startDocument(null, true); 16568 serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 16569 bundle.saveToXml(serializer); 16570 serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 16571 serializer.endDocument(); 16572 atomicFile.finishWrite(stream); 16573 } catch (IOException | XmlPullParserException e) { 16574 Slogf.e(LOG_TAG, "Caught exception while trying to save the " 16575 + "owner transfer parameters to file " + parametersFile, e); 16576 parametersFile.delete(); 16577 atomicFile.failWrite(stream); 16578 } 16579 } 16580 16581 void deleteTransferOwnershipBundleLocked(int userId) { 16582 final File parametersFile = new File(mPathProvider.getUserSystemDirectory(userId), 16583 TRANSFER_OWNERSHIP_PARAMETERS_XML); 16584 parametersFile.delete(); 16585 } 16586 16587 private void logPasswordQualitySetIfSecurityLogEnabled(ComponentName who, int userId, 16588 boolean parent, PasswordPolicy passwordPolicy) { 16589 if (SecurityLog.isLoggingEnabled()) { 16590 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 16591 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(), 16592 userId, affectedUserId, passwordPolicy.length, passwordPolicy.quality, 16593 passwordPolicy.letters, passwordPolicy.nonLetter, passwordPolicy.numeric, 16594 passwordPolicy.upperCase, passwordPolicy.lowerCase, passwordPolicy.symbols); 16595 } 16596 } 16597 16598 private static String getManagedProvisioningPackage(Context context) { 16599 return context.getResources().getString(R.string.config_managed_provisioning_package); 16600 } 16601 16602 private void putPrivateDnsSettings(int mode, @Nullable String host) { 16603 // Set Private DNS settings using system permissions, as apps cannot write 16604 // to global settings. 16605 mInjector.binderWithCleanCallingIdentity(() -> { 16606 ConnectivitySettingsManager.setPrivateDnsMode(mContext, mode); 16607 ConnectivitySettingsManager.setPrivateDnsHostname(mContext, host); 16608 }); 16609 } 16610 16611 @Override 16612 public int setGlobalPrivateDns(@NonNull ComponentName who, int mode, String privateDnsHost) { 16613 if (!mHasFeature) { 16614 return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING; 16615 } 16616 Objects.requireNonNull(who, "ComponentName is null"); 16617 final CallerIdentity caller = getCallerIdentity(who); 16618 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16619 checkAllUsersAreAffiliatedWithDevice(); 16620 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_GLOBAL_PRIVATE_DNS); 16621 16622 switch (mode) { 16623 case PRIVATE_DNS_MODE_OPPORTUNISTIC: 16624 if (!TextUtils.isEmpty(privateDnsHost)) { 16625 throw new IllegalArgumentException( 16626 "Host provided for opportunistic mode, but is not needed."); 16627 } 16628 putPrivateDnsSettings(ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC, 16629 null); 16630 return PRIVATE_DNS_SET_NO_ERROR; 16631 case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME: 16632 if (TextUtils.isEmpty(privateDnsHost) 16633 || !NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) { 16634 throw new IllegalArgumentException( 16635 String.format("Provided hostname %s is not valid", privateDnsHost)); 16636 } 16637 16638 // Connectivity check will have been performed in the DevicePolicyManager before 16639 // the call here. 16640 putPrivateDnsSettings( 16641 ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, 16642 privateDnsHost); 16643 return PRIVATE_DNS_SET_NO_ERROR; 16644 default: 16645 throw new IllegalArgumentException( 16646 String.format("Provided mode, %d, is not a valid mode.", mode)); 16647 } 16648 } 16649 16650 @Override 16651 public int getGlobalPrivateDnsMode(@NonNull ComponentName who) { 16652 if (!mHasFeature) { 16653 return PRIVATE_DNS_MODE_UNKNOWN; 16654 } 16655 Objects.requireNonNull(who, "ComponentName is null"); 16656 final CallerIdentity caller = getCallerIdentity(who); 16657 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16658 16659 final int currentMode = ConnectivitySettingsManager.getPrivateDnsMode(mContext); 16660 switch (currentMode) { 16661 case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OFF: 16662 return PRIVATE_DNS_MODE_OFF; 16663 case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC: 16664 return PRIVATE_DNS_MODE_OPPORTUNISTIC; 16665 case ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME: 16666 return PRIVATE_DNS_MODE_PROVIDER_HOSTNAME; 16667 } 16668 16669 return PRIVATE_DNS_MODE_UNKNOWN; 16670 } 16671 16672 @Override 16673 public String getGlobalPrivateDnsHost(@NonNull ComponentName who) { 16674 if (!mHasFeature) { 16675 return null; 16676 } 16677 Objects.requireNonNull(who, "ComponentName is null"); 16678 final CallerIdentity caller = getCallerIdentity(who); 16679 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)); 16680 return mInjector.settingsGlobalGetString(PRIVATE_DNS_SPECIFIER); 16681 } 16682 16683 @Override 16684 public void installUpdateFromFile(ComponentName admin, 16685 ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback) { 16686 Objects.requireNonNull(admin, "ComponentName is null"); 16687 16688 final CallerIdentity caller = getCallerIdentity(admin); 16689 Preconditions.checkCallAuthorization( 16690 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)); 16691 checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_SYSTEM_UPDATE); 16692 16693 DevicePolicyEventLogger 16694 .createEvent(DevicePolicyEnums.INSTALL_SYSTEM_UPDATE) 16695 .setAdmin(caller.getComponentName()) 16696 .setBoolean(isDeviceAB()) 16697 .write(); 16698 16699 mInjector.binderWithCleanCallingIdentity(() -> { 16700 UpdateInstaller updateInstaller; 16701 if (isDeviceAB()) { 16702 updateInstaller = new AbUpdateInstaller( 16703 mContext, updateFileDescriptor, callback, mInjector, mConstants); 16704 } else { 16705 updateInstaller = new NonAbUpdateInstaller( 16706 mContext, updateFileDescriptor, callback, mInjector, mConstants); 16707 } 16708 updateInstaller.startInstallUpdate(); 16709 }); 16710 } 16711 16712 private boolean isDeviceAB() { 16713 return "true".equalsIgnoreCase(android.os.SystemProperties 16714 .get(AB_DEVICE_KEY, "")); 16715 } 16716 16717 @Override 16718 public void setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames) { 16719 if (!mHasFeature) { 16720 return; 16721 } 16722 Objects.requireNonNull(who, "ComponentName is null"); 16723 final CallerIdentity caller = getCallerIdentity(who); 16724 16725 synchronized (getLockObject()) { 16726 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16727 admin.mCrossProfileCalendarPackages = packageNames; 16728 saveSettingsLocked(caller.getUserId()); 16729 } 16730 DevicePolicyEventLogger 16731 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALENDAR_PACKAGES) 16732 .setAdmin(who) 16733 .setStrings(packageNames == null ? null 16734 : packageNames.toArray(new String[packageNames.size()])) 16735 .write(); 16736 } 16737 16738 @Override 16739 public List<String> getCrossProfileCalendarPackages(ComponentName who) { 16740 if (!mHasFeature) { 16741 return Collections.emptyList(); 16742 } 16743 Objects.requireNonNull(who, "ComponentName is null"); 16744 final CallerIdentity caller = getCallerIdentity(who); 16745 16746 synchronized (getLockObject()) { 16747 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16748 return admin.mCrossProfileCalendarPackages; 16749 } 16750 } 16751 16752 @Override 16753 public boolean isPackageAllowedToAccessCalendarForUser(String packageName, 16754 int userHandle) { 16755 if (!mHasFeature) { 16756 return false; 16757 } 16758 Preconditions.checkStringNotEmpty(packageName, "Package name is null or empty"); 16759 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 16760 16761 final CallerIdentity caller = getCallerIdentity(); 16762 final int packageUid = mInjector.binderWithCleanCallingIdentity(() -> { 16763 try { 16764 return mInjector.getPackageManager().getPackageUidAsUser(packageName, userHandle); 16765 } catch (NameNotFoundException e) { 16766 Slogf.w(LOG_TAG, e, 16767 "Couldn't find package %s in user %d", packageName, userHandle); 16768 return -1; 16769 } 16770 }); 16771 if (caller.getUid() != packageUid) { 16772 Preconditions.checkCallAuthorization( 16773 hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS) 16774 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL)); 16775 } 16776 16777 synchronized (getLockObject()) { 16778 if (mInjector.settingsSecureGetIntForUser( 16779 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userHandle) == 0) { 16780 return false; 16781 } 16782 final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 16783 if (admin != null) { 16784 if (admin.mCrossProfileCalendarPackages == null) { 16785 return true; 16786 } 16787 return admin.mCrossProfileCalendarPackages.contains(packageName); 16788 } 16789 } 16790 return false; 16791 } 16792 16793 @Override 16794 public List<String> getCrossProfileCalendarPackagesForUser(int userHandle) { 16795 if (!mHasFeature) { 16796 return Collections.emptyList(); 16797 } 16798 Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId"); 16799 Preconditions.checkCallAuthorization( 16800 hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS) 16801 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL)); 16802 16803 synchronized (getLockObject()) { 16804 final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 16805 if (admin != null) { 16806 return admin.mCrossProfileCalendarPackages; 16807 } 16808 } 16809 return Collections.emptyList(); 16810 } 16811 16812 @Override 16813 public void setCrossProfilePackages(ComponentName who, List<String> packageNames) { 16814 if (!mHasFeature) { 16815 return; 16816 } 16817 Objects.requireNonNull(who, "ComponentName is null"); 16818 Objects.requireNonNull(packageNames, "Package names is null"); 16819 final CallerIdentity caller = getCallerIdentity(who); 16820 16821 final List<String> previousCrossProfilePackages; 16822 synchronized (getLockObject()) { 16823 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16824 previousCrossProfilePackages = admin.mCrossProfilePackages; 16825 if (packageNames.equals(previousCrossProfilePackages)) { 16826 return; 16827 } 16828 admin.mCrossProfilePackages = packageNames; 16829 saveSettingsLocked(caller.getUserId()); 16830 } 16831 logSetCrossProfilePackages(who, packageNames); 16832 final CrossProfileApps crossProfileApps = mContext.getSystemService(CrossProfileApps.class); 16833 mInjector.binderWithCleanCallingIdentity( 16834 () -> crossProfileApps.resetInteractAcrossProfilesAppOps( 16835 previousCrossProfilePackages, new HashSet<>(packageNames))); 16836 } 16837 16838 private void logSetCrossProfilePackages(ComponentName who, List<String> packageNames) { 16839 DevicePolicyEventLogger 16840 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_PACKAGES) 16841 .setAdmin(who) 16842 .setStrings(packageNames.toArray(new String[packageNames.size()])) 16843 .write(); 16844 } 16845 16846 @Override 16847 public List<String> getCrossProfilePackages(ComponentName who) { 16848 if (!mHasFeature) { 16849 return Collections.emptyList(); 16850 } 16851 Objects.requireNonNull(who, "ComponentName is null"); 16852 final CallerIdentity caller = getCallerIdentity(who); 16853 16854 synchronized (getLockObject()) { 16855 final ActiveAdmin admin = getProfileOwnerLocked(caller); 16856 return admin.mCrossProfilePackages; 16857 } 16858 } 16859 16860 @Override 16861 public List<String> getAllCrossProfilePackages() { 16862 if (!mHasFeature) { 16863 return Collections.emptyList(); 16864 } 16865 final CallerIdentity caller = getCallerIdentity(); 16866 Preconditions.checkCallAuthorization( 16867 isSystemUid(caller) || isRootUid(caller) || hasCallingPermission( 16868 permission.INTERACT_ACROSS_USERS) || hasCallingPermission( 16869 permission.INTERACT_ACROSS_USERS_FULL) || hasPermissionForPreflight( 16870 caller, permission.INTERACT_ACROSS_PROFILES)); 16871 16872 synchronized (getLockObject()) { 16873 final List<ActiveAdmin> admins = getProfileOwnerAdminsForCurrentProfileGroup(); 16874 final List<String> packages = getCrossProfilePackagesForAdmins(admins); 16875 16876 packages.addAll(getDefaultCrossProfilePackages()); 16877 16878 return packages; 16879 } 16880 } 16881 16882 private List<String> getCrossProfilePackagesForAdmins(List<ActiveAdmin> admins) { 16883 final List<String> packages = new ArrayList<>(); 16884 for (int i = 0; i < admins.size(); i++) { 16885 packages.addAll(admins.get(i).mCrossProfilePackages); 16886 } 16887 return packages; 16888 } 16889 16890 @Override 16891 public List<String> getDefaultCrossProfilePackages() { 16892 Set<String> crossProfilePackages = new HashSet<>(); 16893 16894 Collections.addAll(crossProfilePackages, mContext.getResources() 16895 .getStringArray(R.array.cross_profile_apps)); 16896 Collections.addAll(crossProfilePackages, mContext.getResources() 16897 .getStringArray(R.array.vendor_cross_profile_apps)); 16898 16899 return new ArrayList<>(crossProfilePackages); 16900 } 16901 16902 private List<ActiveAdmin> getProfileOwnerAdminsForCurrentProfileGroup() { 16903 synchronized (getLockObject()) { 16904 final List<ActiveAdmin> admins = new ArrayList<>(); 16905 int[] users = mUserManager.getProfileIdsWithDisabled( 16906 mInjector.userHandleGetCallingUserId()); 16907 for (int i = 0; i < users.length; i++) { 16908 final ComponentName componentName = getProfileOwnerAsUser(users[i]); 16909 if (componentName != null) { 16910 ActiveAdmin admin = getActiveAdminUncheckedLocked(componentName, users[i]); 16911 if (admin != null) { 16912 admins.add(admin); 16913 } 16914 } 16915 } 16916 return admins; 16917 } 16918 } 16919 16920 @Override 16921 public boolean isManagedKiosk() { 16922 if (!mHasFeature) { 16923 return false; 16924 } 16925 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()) 16926 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 16927 16928 long id = mInjector.binderClearCallingIdentity(); 16929 try { 16930 return isManagedKioskInternal(); 16931 } catch (RemoteException e) { 16932 throw new IllegalStateException(e); 16933 } finally { 16934 mInjector.binderRestoreCallingIdentity(id); 16935 } 16936 } 16937 16938 private boolean isUnattendedManagedKioskUnchecked() { 16939 try { 16940 return isManagedKioskInternal() 16941 && getPowerManagerInternal().wasDeviceIdleFor(UNATTENDED_MANAGED_KIOSK_MS); 16942 } catch (RemoteException e) { 16943 throw new IllegalStateException(e); 16944 } 16945 } 16946 16947 @Override 16948 public boolean isUnattendedManagedKiosk() { 16949 if (!mHasFeature) { 16950 return false; 16951 } 16952 Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()) 16953 || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 16954 16955 return mInjector.binderWithCleanCallingIdentity(() -> isUnattendedManagedKioskUnchecked()); 16956 } 16957 16958 /** 16959 * Returns whether the device is currently being used as a publicly-accessible dedicated device. 16960 * Assumes that feature checks and permission checks have already been performed, and that the 16961 * calling identity has been cleared. 16962 */ 16963 private boolean isManagedKioskInternal() throws RemoteException { 16964 return mOwners.hasDeviceOwner() 16965 && mInjector.getIActivityManager().getLockTaskModeState() 16966 == ActivityManager.LOCK_TASK_MODE_LOCKED 16967 && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO) 16968 && !deviceHasKeyguard() 16969 && !inEphemeralUserSession(); 16970 } 16971 16972 private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException { 16973 //TODO(b/175285301): Explicitly get the user's identity to check. 16974 int lockTaskFeatures = 16975 getUserData(getCurrentForegroundUserId()).mLockTaskFeatures; 16976 return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature; 16977 } 16978 16979 private boolean deviceHasKeyguard() { 16980 for (UserInfo userInfo : mUserManager.getUsers()) { 16981 if (mLockPatternUtils.isSecure(userInfo.id)) { 16982 return true; 16983 } 16984 } 16985 return false; 16986 } 16987 16988 private boolean inEphemeralUserSession() { 16989 for (UserInfo userInfo : mUserManager.getUsers()) { 16990 if (mInjector.getUserManager().isUserEphemeral(userInfo.id)) { 16991 return true; 16992 } 16993 } 16994 return false; 16995 } 16996 16997 private PowerManagerInternal getPowerManagerInternal() { 16998 return mInjector.getPowerManagerInternal(); 16999 } 17000 17001 @Override 17002 public boolean startViewCalendarEventInManagedProfile(String packageName, long eventId, 17003 long start, long end, boolean allDay, int flags) { 17004 if (!mHasFeature) { 17005 return false; 17006 } 17007 Preconditions.checkStringNotEmpty(packageName, "Package name is empty"); 17008 17009 final CallerIdentity caller = getCallerIdentity(); 17010 if (!isCallingFromPackage(packageName, caller.getUid())) { 17011 throw new SecurityException("Input package name doesn't align with actual " 17012 + "calling package."); 17013 } 17014 return mInjector.binderWithCleanCallingIdentity(() -> { 17015 final int workProfileUserId = getManagedUserId(caller.getUserId()); 17016 if (workProfileUserId < 0) { 17017 return false; 17018 } 17019 if (!isPackageAllowedToAccessCalendarForUser(packageName, workProfileUserId)) { 17020 Slogf.d(LOG_TAG, "Package %s is not allowed to access cross-profile calendar APIs", 17021 packageName); 17022 return false; 17023 } 17024 final Intent intent = new Intent( 17025 CalendarContract.ACTION_VIEW_MANAGED_PROFILE_CALENDAR_EVENT); 17026 intent.setPackage(packageName); 17027 intent.putExtra(CalendarContract.EXTRA_EVENT_ID, eventId); 17028 intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start); 17029 intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end); 17030 intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay); 17031 intent.setFlags(flags); 17032 try { 17033 mContext.startActivityAsUser(intent, UserHandle.of(workProfileUserId)); 17034 } catch (ActivityNotFoundException e) { 17035 Slogf.e(LOG_TAG, "View event activity not found", e); 17036 return false; 17037 } 17038 return true; 17039 }); 17040 } 17041 17042 private boolean isCallingFromPackage(String packageName, int callingUid) { 17043 return mInjector.binderWithCleanCallingIdentity(() -> { 17044 try { 17045 final int packageUid = mInjector.getPackageManager().getPackageUidAsUser( 17046 packageName, UserHandle.getUserId(callingUid)); 17047 return packageUid == callingUid; 17048 } catch (NameNotFoundException e) { 17049 Slogf.d(LOG_TAG, "Calling package not found", e); 17050 return false; 17051 } 17052 }); 17053 } 17054 17055 private DevicePolicyConstants loadConstants() { 17056 return DevicePolicyConstants.loadFromString( 17057 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS)); 17058 } 17059 17060 @Override 17061 public void setUserControlDisabledPackages(ComponentName who, List<String> packages) { 17062 Objects.requireNonNull(who, "ComponentName is null"); 17063 Objects.requireNonNull(packages, "packages is null"); 17064 final CallerIdentity caller = getCallerIdentity(who); 17065 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) || isProfileOwner(caller) 17066 || isFinancedDeviceOwner(caller)); 17067 checkCanExecuteOrThrowUnsafe( 17068 DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES); 17069 17070 synchronized (getLockObject()) { 17071 ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(caller.getUserId()); 17072 if (!Objects.equals(owner.protectedPackages, packages)) { 17073 owner.protectedPackages = packages.isEmpty() ? null : packages; 17074 saveSettingsLocked(caller.getUserId()); 17075 pushUserControlDisabledPackagesLocked(caller.getUserId()); 17076 } 17077 } 17078 17079 DevicePolicyEventLogger 17080 .createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES) 17081 .setAdmin(who) 17082 .setStrings(packages.toArray(new String[packages.size()])) 17083 .write(); 17084 } 17085 17086 @Override 17087 public List<String> getUserControlDisabledPackages(ComponentName who) { 17088 Objects.requireNonNull(who, "ComponentName is null"); 17089 17090 final CallerIdentity caller = getCallerIdentity(who); 17091 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) || isProfileOwner(caller) 17092 || isFinancedDeviceOwner(caller)); 17093 17094 synchronized (getLockObject()) { 17095 ActiveAdmin deviceOwner = getDeviceOrProfileOwnerAdminLocked(caller.getUserId()); 17096 return deviceOwner.protectedPackages != null 17097 ? deviceOwner.protectedPackages : Collections.emptyList(); 17098 } 17099 } 17100 17101 @Override 17102 public void setCommonCriteriaModeEnabled(ComponentName who, boolean enabled) { 17103 Objects.requireNonNull(who, "Admin component name must be provided"); 17104 final CallerIdentity caller = getCallerIdentity(who); 17105 Preconditions.checkCallAuthorization( 17106 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller), 17107 "Common Criteria mode can only be controlled by a device owner or " 17108 + "a profile owner on an organization-owned device."); 17109 synchronized (getLockObject()) { 17110 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 17111 admin.mCommonCriteriaMode = enabled; 17112 saveSettingsLocked(caller.getUserId()); 17113 } 17114 DevicePolicyEventLogger 17115 .createEvent(DevicePolicyEnums.SET_COMMON_CRITERIA_MODE) 17116 .setAdmin(who) 17117 .setBoolean(enabled) 17118 .write(); 17119 } 17120 17121 @Override 17122 public boolean isCommonCriteriaModeEnabled(ComponentName who) { 17123 if (who != null) { 17124 final CallerIdentity caller = getCallerIdentity(who); 17125 Preconditions.checkCallAuthorization( 17126 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller), 17127 "Common Criteria mode can only be controlled by a device owner or " 17128 + "a profile owner on an organization-owned device."); 17129 17130 synchronized (getLockObject()) { 17131 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 17132 return admin.mCommonCriteriaMode; 17133 } 17134 } 17135 // Return aggregated state if caller is not admin (who == null). 17136 synchronized (getLockObject()) { 17137 // Only DO or COPE PO can turn on CC mode, so take a shortcut here and only look at 17138 // their ActiveAdmin, instead of iterating through all admins. 17139 final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 17140 UserHandle.USER_SYSTEM); 17141 return admin != null ? admin.mCommonCriteriaMode : false; 17142 } 17143 } 17144 17145 @Override 17146 public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(ComponentName who) { 17147 Objects.requireNonNull(who, "ComponentName is null"); 17148 17149 final CallerIdentity caller = getCallerIdentity(who); 17150 // DO shouldn't be able to use this method. 17151 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 17152 17153 synchronized (getLockObject()) { 17154 final ActiveAdmin admin = getProfileOwnerLocked(caller); 17155 final long deadline = admin.mProfileOffDeadline; 17156 final int result = makeSuspensionReasons(admin.mSuspendPersonalApps, 17157 deadline != 0 && mInjector.systemCurrentTimeMillis() > deadline); 17158 Slogf.d(LOG_TAG, "getPersonalAppsSuspendedReasons user: %d; result: %d", 17159 mInjector.userHandleGetCallingUserId(), result); 17160 return result; 17161 } 17162 } 17163 17164 private @PersonalAppsSuspensionReason int makeSuspensionReasons( 17165 boolean explicit, boolean timeout) { 17166 int result = PERSONAL_APPS_NOT_SUSPENDED; 17167 if (explicit) { 17168 result |= PERSONAL_APPS_SUSPENDED_EXPLICITLY; 17169 } 17170 if (timeout) { 17171 result |= PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT; 17172 } 17173 return result; 17174 } 17175 17176 @Override 17177 public void setPersonalAppsSuspended(ComponentName who, boolean suspended) { 17178 Objects.requireNonNull(who, "ComponentName is null"); 17179 17180 final CallerIdentity caller = getCallerIdentity(who); 17181 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 17182 Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller)); 17183 17184 final int callingUserId = caller.getUserId(); 17185 synchronized (getLockObject()) { 17186 final ActiveAdmin admin = getProfileOwnerLocked(caller); 17187 boolean shouldSaveSettings = false; 17188 if (admin.mSuspendPersonalApps != suspended) { 17189 admin.mSuspendPersonalApps = suspended; 17190 shouldSaveSettings = true; 17191 } 17192 if (admin.mProfileOffDeadline != 0) { 17193 admin.mProfileOffDeadline = 0; 17194 shouldSaveSettings = true; 17195 } 17196 if (shouldSaveSettings) { 17197 saveSettingsLocked(callingUserId); 17198 } 17199 } 17200 17201 mInjector.binderWithCleanCallingIdentity(() -> updatePersonalAppsSuspension( 17202 callingUserId, mUserManager.isUserUnlocked(callingUserId))); 17203 17204 DevicePolicyEventLogger 17205 .createEvent(DevicePolicyEnums.SET_PERSONAL_APPS_SUSPENDED) 17206 .setAdmin(caller.getComponentName()) 17207 .setBoolean(suspended) 17208 .write(); 17209 } 17210 17211 /** Starts an activity to check policy compliance or request compliance acknowledgement. */ 17212 private void triggerPolicyComplianceCheckIfNeeded(int profileUserId, boolean suspended) { 17213 synchronized (getLockObject()) { 17214 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId); 17215 if (profileOwner == null) { 17216 Slogf.wtf(LOG_TAG, "Profile owner not found for compliance check"); 17217 return; 17218 } 17219 if (suspended) { 17220 // If suspended, DPC will need to show an activity. 17221 final Intent intent = new Intent(ACTION_CHECK_POLICY_COMPLIANCE); 17222 intent.setPackage(profileOwner.info.getPackageName()); 17223 mContext.startActivityAsUser(intent, UserHandle.of(profileUserId)); 17224 } else if (profileOwner.mProfileOffDeadline > 0) { 17225 // If not suspended, but deadline set, DPC needs to acknowledge compliance so that 17226 // the deadline can be reset. 17227 sendAdminCommandLocked(profileOwner, ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED, 17228 /* adminExtras= */ null, /* receiver= */ null, /* inForeground = */ true); 17229 } 17230 } 17231 } 17232 17233 /** 17234 * Checks whether personal apps should be suspended according to the policy and applies the 17235 * change if needed. 17236 * 17237 * @param unlocked whether the profile is currently running unlocked. 17238 */ 17239 private boolean updatePersonalAppsSuspension(int profileUserId, boolean unlocked) { 17240 final boolean shouldSuspend; 17241 synchronized (getLockObject()) { 17242 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId); 17243 if (profileOwner != null) { 17244 final int notificationState = 17245 updateProfileOffDeadlineLocked(profileUserId, profileOwner, unlocked); 17246 final boolean suspendedExplicitly = profileOwner.mSuspendPersonalApps; 17247 final boolean suspendedByTimeout = profileOwner.mProfileOffDeadline == -1; 17248 Slogf.d(LOG_TAG, 17249 "Personal apps suspended explicitly: %b, by timeout: %b, notification: %d", 17250 suspendedExplicitly, suspendedByTimeout, notificationState); 17251 updateProfileOffDeadlineNotificationLocked( 17252 profileUserId, profileOwner, notificationState); 17253 shouldSuspend = suspendedExplicitly || suspendedByTimeout; 17254 } else { 17255 shouldSuspend = false; 17256 } 17257 } 17258 17259 final int parentUserId = getProfileParentId(profileUserId); 17260 suspendPersonalAppsInternal(parentUserId, shouldSuspend); 17261 return shouldSuspend; 17262 } 17263 17264 /** 17265 * Checks work profile time off policy, scheduling personal apps suspension via alarm if 17266 * necessary. 17267 * @return notification state 17268 */ 17269 private int updateProfileOffDeadlineLocked( 17270 int profileUserId, ActiveAdmin profileOwner, boolean unlocked) { 17271 final long now = mInjector.systemCurrentTimeMillis(); 17272 if (profileOwner.mProfileOffDeadline != 0 && now > profileOwner.mProfileOffDeadline) { 17273 Slogf.i(LOG_TAG, "Profile off deadline has been reached, unlocked: " + unlocked); 17274 if (profileOwner.mProfileOffDeadline != -1) { 17275 // Move the deadline far to the past so that it cannot be rolled back by TZ change. 17276 profileOwner.mProfileOffDeadline = -1; 17277 saveSettingsLocked(profileUserId); 17278 } 17279 return unlocked ? PROFILE_OFF_NOTIFICATION_NONE : PROFILE_OFF_NOTIFICATION_SUSPENDED; 17280 } 17281 boolean shouldSaveSettings = false; 17282 if (profileOwner.mSuspendPersonalApps) { 17283 // When explicit suspension is active, deadline shouldn't be set. 17284 if (profileOwner.mProfileOffDeadline != 0) { 17285 profileOwner.mProfileOffDeadline = 0; 17286 shouldSaveSettings = true; 17287 } 17288 } else if (profileOwner.mProfileOffDeadline != 0 17289 && (profileOwner.mProfileMaximumTimeOffMillis == 0)) { 17290 // There is a deadline but either there is no policy -> clear 17291 // the deadline. 17292 Slogf.i(LOG_TAG, "Profile off deadline is reset to zero"); 17293 profileOwner.mProfileOffDeadline = 0; 17294 shouldSaveSettings = true; 17295 } else if (profileOwner.mProfileOffDeadline == 0 17296 && (profileOwner.mProfileMaximumTimeOffMillis != 0 && !unlocked)) { 17297 // There profile is locked and there is a policy, but the deadline is not set -> set the 17298 // deadline. 17299 Slogf.i(LOG_TAG, "Profile off deadline is set."); 17300 profileOwner.mProfileOffDeadline = now + profileOwner.mProfileMaximumTimeOffMillis; 17301 shouldSaveSettings = true; 17302 } 17303 17304 if (shouldSaveSettings) { 17305 saveSettingsLocked(profileUserId); 17306 } 17307 17308 final long alarmTime; 17309 final int notificationState; 17310 if (unlocked || profileOwner.mProfileOffDeadline == 0) { 17311 alarmTime = 0; 17312 notificationState = PROFILE_OFF_NOTIFICATION_NONE; 17313 } else if (profileOwner.mProfileOffDeadline - now < MANAGED_PROFILE_OFF_WARNING_PERIOD) { 17314 // The deadline is close, upon the alarm personal apps should be suspended. 17315 alarmTime = profileOwner.mProfileOffDeadline; 17316 notificationState = PROFILE_OFF_NOTIFICATION_WARNING; 17317 } else { 17318 // The deadline is quite far, upon the alarm we should warn the user first, so the 17319 // alarm is scheduled earlier than the actual deadline. 17320 alarmTime = profileOwner.mProfileOffDeadline - MANAGED_PROFILE_OFF_WARNING_PERIOD; 17321 notificationState = PROFILE_OFF_NOTIFICATION_NONE; 17322 } 17323 17324 final AlarmManager am = mInjector.getAlarmManager(); 17325 final Intent intent = new Intent(ACTION_PROFILE_OFF_DEADLINE); 17326 intent.setPackage(mContext.getPackageName()); 17327 // Broadcast alarms sent by system are immutable 17328 final PendingIntent pi = mInjector.pendingIntentGetBroadcast( 17329 mContext, REQUEST_PROFILE_OFF_DEADLINE, intent, 17330 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT 17331 | PendingIntent.FLAG_IMMUTABLE); 17332 17333 if (alarmTime == 0) { 17334 Slogf.i(LOG_TAG, "Profile off deadline alarm is removed."); 17335 am.cancel(pi); 17336 } else { 17337 Slogf.i(LOG_TAG, "Profile off deadline alarm is set."); 17338 am.set(AlarmManager.RTC, alarmTime, pi); 17339 } 17340 17341 return notificationState; 17342 } 17343 17344 private void suspendPersonalAppsInternal(int userId, boolean suspended) { 17345 if (getUserData(userId).mAppsSuspended == suspended) { 17346 return; 17347 } 17348 Slogf.i(LOG_TAG, "%s personal apps for user %d", suspended ? "Suspending" : "Unsuspending", 17349 userId); 17350 17351 if (suspended) { 17352 suspendPersonalAppsInPackageManager(userId); 17353 } else { 17354 mInjector.getPackageManagerInternal().unsuspendForSuspendingPackage( 17355 PLATFORM_PACKAGE_NAME, userId); 17356 } 17357 17358 synchronized (getLockObject()) { 17359 getUserData(userId).mAppsSuspended = suspended; 17360 saveSettingsLocked(userId); 17361 } 17362 } 17363 17364 private void suspendPersonalAppsInPackageManager(int userId) { 17365 mInjector.binderWithCleanCallingIdentity(() -> { 17366 try { 17367 final String[] appsToSuspend = mInjector.getPersonalAppsForSuspension(userId); 17368 final String[] failedApps = mIPackageManager.setPackagesSuspendedAsUser( 17369 appsToSuspend, true, null, null, null, PLATFORM_PACKAGE_NAME, userId); 17370 if (!ArrayUtils.isEmpty(failedApps)) { 17371 Slogf.wtf(LOG_TAG, "Failed to suspend apps: " + String.join(",", failedApps)); 17372 } 17373 } catch (RemoteException re) { 17374 // Shouldn't happen. 17375 Slogf.e(LOG_TAG, "Failed talking to the package manager", re); 17376 } 17377 }); 17378 } 17379 17380 @GuardedBy("getLockObject()") 17381 private void updateProfileOffDeadlineNotificationLocked( 17382 int profileUserId, ActiveAdmin profileOwner, int notificationState) { 17383 if (notificationState == PROFILE_OFF_NOTIFICATION_NONE) { 17384 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED); 17385 return; 17386 } 17387 17388 final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION); 17389 intent.setPackage(mContext.getPackageName()); 17390 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 17391 17392 // Simple notification action button clicks are immutable 17393 final PendingIntent pendingIntent = mInjector.pendingIntentGetBroadcast(mContext, 17394 0 /* requestCode */, intent, 17395 PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); 17396 17397 final Notification.Action turnProfileOnButton = new Notification.Action.Builder( 17398 /* icon= */ null, getPersonalAppSuspensionButtonText(), pendingIntent).build(); 17399 17400 final String text; 17401 final boolean ongoing; 17402 if (notificationState == PROFILE_OFF_NOTIFICATION_WARNING) { 17403 // Round to the closest integer number of days. 17404 final int maxDays = (int) 17405 ((profileOwner.mProfileMaximumTimeOffMillis + MS_PER_DAY / 2) / MS_PER_DAY); 17406 final String date = DateUtils.formatDateTime( 17407 mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_DATE); 17408 final String time = DateUtils.formatDateTime( 17409 mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_TIME); 17410 text = getPersonalAppSuspensionSoonText(date, time, maxDays); 17411 ongoing = false; 17412 } else { 17413 text = getPersonalAppSuspensionText(); 17414 ongoing = true; 17415 } 17416 final int color = mContext.getColor(R.color.personal_apps_suspension_notification_color); 17417 final Bundle extras = new Bundle(); 17418 // TODO: Create a separate string for this. 17419 extras.putString( 17420 Notification.EXTRA_SUBSTITUTE_APP_NAME, getWorkProfileContentDescription()); 17421 17422 final Notification notification = 17423 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 17424 .setSmallIcon(R.drawable.ic_corp_badge_no_background) 17425 .setOngoing(ongoing) 17426 .setAutoCancel(false) 17427 .setContentTitle(getPersonalAppSuspensionTitle()) 17428 .setContentText(text) 17429 .setStyle(new Notification.BigTextStyle().bigText(text)) 17430 .setColor(color) 17431 .addAction(turnProfileOnButton) 17432 .addExtras(extras) 17433 .build(); 17434 mInjector.getNotificationManager().notify( 17435 SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED, notification); 17436 } 17437 17438 private String getPersonalAppSuspensionButtonText() { 17439 return getUpdatableString( 17440 PERSONAL_APP_SUSPENSION_TURN_ON_PROFILE, 17441 R.string.personal_apps_suspended_turn_profile_on); 17442 } 17443 17444 private String getPersonalAppSuspensionTitle() { 17445 return getUpdatableString( 17446 PERSONAL_APP_SUSPENSION_TITLE, R.string.personal_apps_suspension_title); 17447 } 17448 17449 private String getPersonalAppSuspensionText() { 17450 return getUpdatableString( 17451 PERSONAL_APP_SUSPENSION_MESSAGE, R.string.personal_apps_suspension_text); 17452 } 17453 17454 private String getPersonalAppSuspensionSoonText(String date, String time, int maxDays) { 17455 return getUpdatableString( 17456 PERSONAL_APP_SUSPENSION_SOON_MESSAGE, R.string.personal_apps_suspension_soon_text, 17457 date, time, maxDays); 17458 } 17459 17460 private String getWorkProfileContentDescription() { 17461 return getUpdatableString( 17462 NOTIFICATION_WORK_PROFILE_CONTENT_DESCRIPTION, 17463 R.string.notification_work_profile_content_description); 17464 } 17465 17466 @Override 17467 public void setManagedProfileMaximumTimeOff(ComponentName who, long timeoutMillis) { 17468 Objects.requireNonNull(who, "ComponentName is null"); 17469 Preconditions.checkArgumentNonnegative(timeoutMillis, "Timeout must be non-negative."); 17470 17471 final CallerIdentity caller = getCallerIdentity(who); 17472 // DO shouldn't be able to use this method. 17473 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 17474 Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller)); 17475 17476 final int userId = caller.getUserId(); 17477 synchronized (getLockObject()) { 17478 final ActiveAdmin admin = getProfileOwnerLocked(caller); 17479 17480 // Ensure the timeout is long enough to avoid having bad user experience. 17481 if (timeoutMillis > 0 && timeoutMillis < MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD 17482 && !isAdminTestOnlyLocked(who, userId)) { 17483 timeoutMillis = MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD; 17484 } 17485 if (admin.mProfileMaximumTimeOffMillis == timeoutMillis) { 17486 return; 17487 } 17488 admin.mProfileMaximumTimeOffMillis = timeoutMillis; 17489 saveSettingsLocked(userId); 17490 } 17491 17492 mInjector.binderWithCleanCallingIdentity( 17493 () -> updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked())); 17494 17495 DevicePolicyEventLogger 17496 .createEvent(DevicePolicyEnums.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF) 17497 .setAdmin(caller.getComponentName()) 17498 .setTimePeriod(timeoutMillis) 17499 .write(); 17500 } 17501 17502 private boolean canHandleCheckPolicyComplianceIntent(CallerIdentity caller) { 17503 mInjector.binderWithCleanCallingIdentity(() -> { 17504 final Intent intent = new Intent(DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE); 17505 intent.setPackage(caller.getPackageName()); 17506 final List<ResolveInfo> handlers = 17507 mInjector.getPackageManager().queryIntentActivitiesAsUser(intent, /* flags= */ 17508 0, caller.getUserId()); 17509 return !handlers.isEmpty(); 17510 }); 17511 return true; 17512 } 17513 17514 @Override 17515 public long getManagedProfileMaximumTimeOff(ComponentName who) { 17516 Objects.requireNonNull(who, "ComponentName is null"); 17517 17518 final CallerIdentity caller = getCallerIdentity(who); 17519 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 17520 17521 synchronized (getLockObject()) { 17522 final ActiveAdmin admin = getProfileOwnerLocked(caller); 17523 return admin.mProfileMaximumTimeOffMillis; 17524 } 17525 } 17526 17527 @Override 17528 public void acknowledgeDeviceCompliant() { 17529 final CallerIdentity caller = getCallerIdentity(); 17530 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 17531 enforceUserUnlocked(caller.getUserId()); 17532 17533 synchronized (getLockObject()) { 17534 final ActiveAdmin admin = getProfileOwnerLocked(caller); 17535 if (admin.mProfileOffDeadline > 0) { 17536 admin.mProfileOffDeadline = 0; 17537 saveSettingsLocked(caller.getUserId()); 17538 } 17539 } 17540 } 17541 17542 @Override 17543 public boolean isComplianceAcknowledgementRequired() { 17544 final CallerIdentity caller = getCallerIdentity(); 17545 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)); 17546 enforceUserUnlocked(caller.getUserId()); 17547 17548 synchronized (getLockObject()) { 17549 final ActiveAdmin admin = getProfileOwnerLocked(caller); 17550 return admin.mProfileOffDeadline != 0; 17551 } 17552 } 17553 17554 @Override 17555 public boolean canProfileOwnerResetPasswordWhenLocked(int userId) { 17556 Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()), 17557 String.format(NOT_SYSTEM_CALLER_MSG, 17558 "call canProfileOwnerResetPasswordWhenLocked")); 17559 synchronized (getLockObject()) { 17560 final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(userId); 17561 if (poAdmin == null 17562 || getEncryptionStatus() != ENCRYPTION_STATUS_ACTIVE_PER_USER 17563 || !isResetPasswordTokenActiveForUserLocked(userId)) { 17564 return false; 17565 } 17566 final ApplicationInfo poAppInfo; 17567 try { 17568 poAppInfo = mIPackageManager.getApplicationInfo( 17569 poAdmin.info.getPackageName(), 0 /* flags */, userId); 17570 } catch (RemoteException e) { 17571 Slogf.e(LOG_TAG, "Failed to query PO app info", e); 17572 return false; 17573 } 17574 if (poAppInfo == null) { 17575 Slogf.wtf(LOG_TAG, "Cannot find AppInfo for profile owner"); 17576 return false; 17577 } 17578 if (!poAppInfo.isEncryptionAware()) { 17579 return false; 17580 } 17581 Slogf.d(LOG_TAG, "PO should be able to reset password from direct boot"); 17582 return true; 17583 } 17584 } 17585 17586 @Override 17587 public String getEnrollmentSpecificId(String callerPackage) { 17588 if (!mHasFeature) { 17589 return ""; 17590 } 17591 17592 final CallerIdentity caller = getCallerIdentity(callerPackage); 17593 Preconditions.checkCallAuthorization( 17594 isDefaultDeviceOwner(caller) || isProfileOwner(caller) 17595 || isCallerDelegate(caller, DELEGATION_CERT_INSTALL)); 17596 17597 synchronized (getLockObject()) { 17598 final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked( 17599 caller.getUserId()); 17600 final String esid = requiredAdmin.mEnrollmentSpecificId; 17601 return esid != null ? esid : ""; 17602 } 17603 } 17604 17605 @Override 17606 public void setOrganizationIdForUser( 17607 @NonNull String callerPackage, @NonNull String organizationId, int userId) { 17608 if (!mHasFeature) { 17609 return; 17610 } 17611 Objects.requireNonNull(callerPackage); 17612 17613 final CallerIdentity caller = getCallerIdentity(callerPackage); 17614 // Only the DPC can set this ID. 17615 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) || isProfileOwner(caller), 17616 "Only a Device Owner or Profile Owner may set the Enterprise ID."); 17617 // Empty enterprise ID must not be provided in calls to this method. 17618 Preconditions.checkArgument(!TextUtils.isEmpty(organizationId), 17619 "Enterprise ID may not be empty."); 17620 17621 Slogf.i(LOG_TAG, "Setting Enterprise ID to %s for user %d", organizationId, userId); 17622 17623 synchronized (mESIDInitilizationLock) { 17624 if (mEsidCalculator == null) { 17625 mInjector.binderWithCleanCallingIdentity(() -> { 17626 mEsidCalculator = mInjector.newEnterpriseSpecificIdCalculator(); 17627 }); 17628 } 17629 } 17630 17631 final String ownerPackage; 17632 synchronized (getLockObject()) { 17633 final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 17634 // As the caller is the system, it must specify the component name of the profile owner 17635 // as a safety check. 17636 Preconditions.checkCallAuthorization( 17637 owner != null && owner.getUserHandle().getIdentifier() == userId, 17638 String.format("The Profile Owner or Device Owner may only set the Enterprise ID" 17639 + " on its own user, called on user %d but owner user is %d", userId, 17640 owner.getUserHandle().getIdentifier())); 17641 ownerPackage = owner.info.getPackageName(); 17642 Preconditions.checkState( 17643 TextUtils.isEmpty(owner.mOrganizationId) || owner.mOrganizationId.equals( 17644 organizationId), 17645 "The organization ID has been previously set to a different value and cannot " 17646 + "be changed"); 17647 final String dpcPackage = owner.info.getPackageName(); 17648 final String esid = mEsidCalculator.calculateEnterpriseId(dpcPackage, 17649 organizationId); 17650 owner.mOrganizationId = organizationId; 17651 owner.mEnrollmentSpecificId = esid; 17652 saveSettingsLocked(userId); 17653 } 17654 17655 DevicePolicyEventLogger 17656 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_ID) 17657 .setAdmin(ownerPackage) 17658 .setBoolean(isManagedProfile(userId)) 17659 .write(); 17660 } 17661 17662 @Override 17663 public void clearOrganizationIdForUser(int userHandle) { 17664 Preconditions.checkCallAuthorization( 17665 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 17666 17667 synchronized (getLockObject()) { 17668 final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userHandle); 17669 owner.mOrganizationId = null; 17670 owner.mEnrollmentSpecificId = null; 17671 saveSettingsLocked(userHandle); 17672 } 17673 } 17674 17675 @Override 17676 public UserHandle createAndProvisionManagedProfile( 17677 @NonNull ManagedProfileProvisioningParams provisioningParams, 17678 @NonNull String callerPackage) { 17679 Objects.requireNonNull(provisioningParams, "provisioningParams is null"); 17680 Objects.requireNonNull(callerPackage, "callerPackage is null"); 17681 17682 final ComponentName admin = provisioningParams.getProfileAdminComponentName(); 17683 Objects.requireNonNull(admin, "admin is null"); 17684 17685 final CallerIdentity caller = getCallerIdentity(callerPackage); 17686 Preconditions.checkCallAuthorization( 17687 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 17688 17689 provisioningParams.logParams(callerPackage); 17690 17691 UserInfo userInfo = null; 17692 final long identity = Binder.clearCallingIdentity(); 17693 try { 17694 final int result = checkProvisioningPreconditionSkipPermission( 17695 ACTION_PROVISION_MANAGED_PROFILE, admin.getPackageName()); 17696 if (result != STATUS_OK) { 17697 throw new ServiceSpecificException( 17698 ERROR_PRE_CONDITION_FAILED, 17699 "Provisioning preconditions failed with result: " + result); 17700 } 17701 17702 final long startTime = SystemClock.elapsedRealtime(); 17703 17704 onCreateAndProvisionManagedProfileStarted(provisioningParams); 17705 17706 final Set<String> nonRequiredApps = provisioningParams.isLeaveAllSystemAppsEnabled() 17707 ? Collections.emptySet() 17708 : mOverlayPackagesProvider.getNonRequiredApps( 17709 admin, caller.getUserId(), ACTION_PROVISION_MANAGED_PROFILE); 17710 if (nonRequiredApps.isEmpty()) { 17711 Slogf.i(LOG_TAG, "No disallowed packages for the managed profile."); 17712 } else { 17713 for (String packageName : nonRequiredApps) { 17714 Slogf.i(LOG_TAG, "Disallowed package [" + packageName + "]"); 17715 } 17716 } 17717 17718 userInfo = mUserManager.createProfileForUserEvenWhenDisallowed( 17719 provisioningParams.getProfileName(), 17720 UserManager.USER_TYPE_PROFILE_MANAGED, 17721 UserInfo.FLAG_DISABLED, 17722 caller.getUserId(), 17723 nonRequiredApps.toArray(new String[nonRequiredApps.size()])); 17724 if (userInfo == null) { 17725 throw new ServiceSpecificException( 17726 ERROR_PROFILE_CREATION_FAILED, 17727 "Error creating profile, createProfileForUserEvenWhenDisallowed " 17728 + "returned null."); 17729 } 17730 resetInteractAcrossProfilesAppOps(); 17731 logEventDuration( 17732 DevicePolicyEnums.PLATFORM_PROVISIONING_CREATE_PROFILE_MS, 17733 startTime, 17734 callerPackage); 17735 17736 maybeInstallDevicePolicyManagementRoleHolderInUser(userInfo.id); 17737 17738 installExistingAdminPackage(userInfo.id, admin.getPackageName()); 17739 if (!enableAdminAndSetProfileOwner( 17740 userInfo.id, caller.getUserId(), admin, provisioningParams.getOwnerName())) { 17741 throw new ServiceSpecificException( 17742 ERROR_SETTING_PROFILE_OWNER_FAILED, 17743 "Error setting profile owner."); 17744 } 17745 setUserSetupComplete(userInfo.id); 17746 17747 startUser(userInfo.id, callerPackage); 17748 maybeMigrateAccount( 17749 userInfo.id, caller.getUserId(), provisioningParams.getAccountToMigrate(), 17750 provisioningParams.isKeepingAccountOnMigration(), callerPackage); 17751 17752 if (provisioningParams.isOrganizationOwnedProvisioning()) { 17753 synchronized (getLockObject()) { 17754 setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(admin, userInfo.id, 17755 true); 17756 } 17757 } 17758 17759 onCreateAndProvisionManagedProfileCompleted(provisioningParams); 17760 17761 sendProvisioningCompletedBroadcast( 17762 userInfo.id, 17763 ACTION_PROVISION_MANAGED_PROFILE, 17764 provisioningParams.isLeaveAllSystemAppsEnabled()); 17765 17766 return userInfo.getUserHandle(); 17767 } catch (Exception e) { 17768 DevicePolicyEventLogger 17769 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR) 17770 .setStrings(callerPackage) 17771 .write(); 17772 // In case of any errors during provisioning, remove the newly created profile. 17773 if (userInfo != null) { 17774 mUserManager.removeUserEvenWhenDisallowed(userInfo.id); 17775 } 17776 throw e; 17777 } finally { 17778 Binder.restoreCallingIdentity(identity); 17779 } 17780 } 17781 17782 @Override 17783 public void finalizeWorkProfileProvisioning(UserHandle managedProfileUser, 17784 Account migratedAccount) { 17785 Preconditions.checkCallAuthorization( 17786 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 17787 17788 if (!isManagedProfile(managedProfileUser.getIdentifier())) { 17789 throw new IllegalStateException("Given user is not a managed profile"); 17790 } 17791 ComponentName profileOwnerComponent = 17792 mOwners.getProfileOwnerComponent(managedProfileUser.getIdentifier()); 17793 if (profileOwnerComponent == null) { 17794 throw new IllegalStateException("There is no profile owner on the given profile"); 17795 } 17796 Intent primaryProfileSuccessIntent = new Intent(ACTION_MANAGED_PROFILE_PROVISIONED); 17797 primaryProfileSuccessIntent.setPackage(profileOwnerComponent.getPackageName()); 17798 primaryProfileSuccessIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES 17799 | Intent.FLAG_RECEIVER_FOREGROUND); 17800 primaryProfileSuccessIntent.putExtra(Intent.EXTRA_USER, managedProfileUser); 17801 17802 if (migratedAccount != null) { 17803 primaryProfileSuccessIntent.putExtra(EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE, 17804 migratedAccount); 17805 } 17806 17807 mContext.sendBroadcastAsUser(primaryProfileSuccessIntent, 17808 UserHandle.of(getProfileParentId(managedProfileUser.getIdentifier()))); 17809 } 17810 17811 /** 17812 * Callback called at the beginning of {@link #createAndProvisionManagedProfile( 17813 * ManagedProfileProvisioningParams, String)} after the relevant prechecks have passed. 17814 * 17815 * <p>The logic in this method blocks provisioning. 17816 * 17817 * <p>This method is meant to be overridden by OEMs. 17818 */ 17819 private void onCreateAndProvisionManagedProfileStarted( 17820 ManagedProfileProvisioningParams provisioningParams) {} 17821 17822 /** 17823 * Callback called at the end of {@link #createAndProvisionManagedProfile( 17824 * ManagedProfileProvisioningParams, String)} after all the other provisioning tasks 17825 * have completed successfully. 17826 * 17827 * <p>The logic in this method blocks provisioning. 17828 * 17829 * <p>This method is meant to be overridden by OEMs. 17830 */ 17831 private void onCreateAndProvisionManagedProfileCompleted( 17832 ManagedProfileProvisioningParams provisioningParams) {} 17833 17834 private void maybeInstallDevicePolicyManagementRoleHolderInUser(int targetUserId) { 17835 String devicePolicyManagerRoleHolderPackageName = 17836 getDevicePolicyManagementRoleHolderPackageName(mContext); 17837 if (devicePolicyManagerRoleHolderPackageName == null) { 17838 Slogf.d(LOG_TAG, "No device policy management role holder specified."); 17839 return; 17840 } 17841 try { 17842 if (mIPackageManager.isPackageAvailable( 17843 devicePolicyManagerRoleHolderPackageName, targetUserId)) { 17844 Slogf.d(LOG_TAG, "The device policy management role holder " 17845 + devicePolicyManagerRoleHolderPackageName + " is already installed in " 17846 + "user " + targetUserId); 17847 return; 17848 } 17849 Slogf.d(LOG_TAG, "Installing the device policy management role holder " 17850 + devicePolicyManagerRoleHolderPackageName + " in user " + targetUserId); 17851 mIPackageManager.installExistingPackageAsUser( 17852 devicePolicyManagerRoleHolderPackageName, 17853 targetUserId, 17854 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 17855 PackageManager.INSTALL_REASON_POLICY, 17856 /* whiteListedPermissions= */ null); 17857 } catch (RemoteException e) { 17858 // Does not happen, same process 17859 } 17860 } 17861 17862 private String getDevicePolicyManagementRoleHolderPackageName(Context context) { 17863 RoleManager roleManager = context.getSystemService(RoleManager.class); 17864 List<String> roleHolders = 17865 roleManager.getRoleHolders(RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT); 17866 if (roleHolders.isEmpty()) { 17867 return null; 17868 } 17869 return roleHolders.get(0); 17870 } 17871 17872 private void resetInteractAcrossProfilesAppOps() { 17873 mInjector.getCrossProfileApps().clearInteractAcrossProfilesAppOps(); 17874 pregrantDefaultInteractAcrossProfilesAppOps(); 17875 } 17876 17877 private void pregrantDefaultInteractAcrossProfilesAppOps() { 17878 final String op = 17879 AppOpsManager.permissionToOp(Manifest.permission.INTERACT_ACROSS_PROFILES); 17880 for (String packageName : getConfigurableDefaultCrossProfilePackages()) { 17881 if (appOpIsChangedFromDefault(op, packageName)) { 17882 continue; 17883 } 17884 mInjector.getCrossProfileApps().setInteractAcrossProfilesAppOp( 17885 packageName, MODE_ALLOWED); 17886 } 17887 } 17888 17889 private Set<String> getConfigurableDefaultCrossProfilePackages() { 17890 List<String> defaultPackages = getDefaultCrossProfilePackages(); 17891 return defaultPackages.stream().filter( 17892 mInjector.getCrossProfileApps()::canConfigureInteractAcrossProfiles).collect( 17893 Collectors.toSet()); 17894 } 17895 17896 private boolean appOpIsChangedFromDefault(String op, String packageName) { 17897 try { 17898 final int uid = mContext.getPackageManager().getPackageUid( 17899 packageName, /* flags= */ 0); 17900 return mInjector.getAppOpsManager().unsafeCheckOpNoThrow( 17901 op, uid, packageName) 17902 != AppOpsManager.MODE_DEFAULT; 17903 } catch (NameNotFoundException e) { 17904 return false; 17905 } 17906 } 17907 17908 private void installExistingAdminPackage(int userId, String packageName) { 17909 try { 17910 final int status = mContext.getPackageManager().installExistingPackageAsUser( 17911 packageName, 17912 userId); 17913 if (status != PackageManager.INSTALL_SUCCEEDED) { 17914 throw new ServiceSpecificException( 17915 ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED, 17916 String.format("Failed to install existing package %s for user %d with " 17917 + "result code %d", 17918 packageName, userId, status)); 17919 } 17920 } catch (NameNotFoundException e) { 17921 throw new ServiceSpecificException( 17922 ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED, 17923 String.format("Failed to install existing package %s for user %d: %s", 17924 packageName, userId, e.getMessage())); 17925 } 17926 } 17927 17928 private boolean enableAdminAndSetProfileOwner( 17929 @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent, 17930 String ownerName) { 17931 enableAndSetActiveAdmin(userId, callingUserId, adminComponent); 17932 return setProfileOwner(adminComponent, ownerName, userId); 17933 } 17934 17935 private void enableAndSetActiveAdmin( 17936 @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) { 17937 final String adminPackage = adminComponent.getPackageName(); 17938 enablePackage(adminPackage, callingUserId); 17939 setActiveAdmin(adminComponent, /* refreshing= */ true, userId); 17940 } 17941 17942 private void enablePackage(String packageName, @UserIdInt int userId) { 17943 try { 17944 final int enabledSetting = mIPackageManager.getApplicationEnabledSetting( 17945 packageName, userId); 17946 if (enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17947 && enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17948 mIPackageManager.setApplicationEnabledSetting( 17949 packageName, 17950 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 17951 // Device policy app may have launched ManagedProvisioning, play nice and 17952 // don't kill it as a side-effect of this call. 17953 PackageManager.DONT_KILL_APP, 17954 userId, 17955 mContext.getOpPackageName()); 17956 } 17957 } catch (RemoteException e) { 17958 // Shouldn't happen. 17959 } 17960 } 17961 17962 private void setUserSetupComplete(@UserIdInt int userId) { 17963 Settings.Secure.putIntForUser( 17964 mContext.getContentResolver(), USER_SETUP_COMPLETE, 1, userId); 17965 } 17966 17967 private void startUser(@UserIdInt int userId, String callerPackage) 17968 throws IllegalStateException { 17969 final long startTime = SystemClock.elapsedRealtime(); 17970 final UserUnlockedBlockingReceiver unlockedReceiver = new UserUnlockedBlockingReceiver( 17971 userId); 17972 mContext.registerReceiverAsUser( 17973 unlockedReceiver, 17974 new UserHandle(userId), 17975 new IntentFilter(Intent.ACTION_USER_UNLOCKED), 17976 /* broadcastPermission = */ null, 17977 /* scheduler= */ null); 17978 try { 17979 if (!mInjector.getIActivityManager().startUserInBackground(userId)) { 17980 throw new ServiceSpecificException(ERROR_STARTING_PROFILE_FAILED, 17981 String.format("Unable to start user %d in background", userId)); 17982 } 17983 17984 if (!unlockedReceiver.waitForUserUnlocked()) { 17985 throw new ServiceSpecificException(ERROR_STARTING_PROFILE_FAILED, 17986 String.format("Timeout whilst waiting for unlock of user %d.", userId)); 17987 } 17988 logEventDuration( 17989 DevicePolicyEnums.PLATFORM_PROVISIONING_START_PROFILE_MS, 17990 startTime, 17991 callerPackage); 17992 } catch (RemoteException e) { 17993 // Shouldn't happen. 17994 } finally { 17995 mContext.unregisterReceiver(unlockedReceiver); 17996 } 17997 } 17998 17999 private void maybeMigrateAccount( 18000 @UserIdInt int targetUserId, @UserIdInt int sourceUserId, Account accountToMigrate, 18001 boolean keepAccountMigrated, String callerPackage) { 18002 final UserHandle sourceUser = UserHandle.of(sourceUserId); 18003 final UserHandle targetUser = UserHandle.of(targetUserId); 18004 if (accountToMigrate == null) { 18005 Slogf.d(LOG_TAG, "No account to migrate."); 18006 return; 18007 } 18008 if (sourceUser.equals(targetUser)) { 18009 Slogf.w(LOG_TAG, "sourceUser and targetUser are the same, won't migrate account."); 18010 return; 18011 } 18012 copyAccount(targetUser, sourceUser, accountToMigrate, callerPackage); 18013 if (!keepAccountMigrated) { 18014 removeAccount(accountToMigrate); 18015 } 18016 } 18017 18018 private void copyAccount( 18019 UserHandle targetUser, UserHandle sourceUser, Account accountToMigrate, 18020 String callerPackage) { 18021 final long startTime = SystemClock.elapsedRealtime(); 18022 try { 18023 final AccountManager accountManager = mContext.getSystemService(AccountManager.class); 18024 final boolean copySucceeded = accountManager.copyAccountToUser( 18025 accountToMigrate, 18026 sourceUser, 18027 targetUser, 18028 /* callback= */ null, /* handler= */ null) 18029 .getResult(60 * 3, TimeUnit.SECONDS); 18030 if (copySucceeded) { 18031 logCopyAccountStatus(COPY_ACCOUNT_SUCCEEDED, callerPackage); 18032 logEventDuration( 18033 DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_MS, 18034 startTime, 18035 callerPackage); 18036 } else { 18037 logCopyAccountStatus(COPY_ACCOUNT_FAILED, callerPackage); 18038 Slogf.e(LOG_TAG, "Failed to copy account to " + targetUser); 18039 } 18040 } catch (OperationCanceledException e) { 18041 // Account migration is not considered a critical operation. 18042 logCopyAccountStatus(COPY_ACCOUNT_TIMED_OUT, callerPackage); 18043 Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e); 18044 } catch (AuthenticatorException | IOException e) { 18045 logCopyAccountStatus(COPY_ACCOUNT_EXCEPTION, callerPackage); 18046 Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e); 18047 } 18048 } 18049 18050 private static void logCopyAccountStatus(@CopyAccountStatus int status, String callerPackage) { 18051 DevicePolicyEventLogger 18052 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_STATUS) 18053 .setInt(status) 18054 .setStrings(callerPackage) 18055 .write(); 18056 } 18057 18058 private void removeAccount(Account account) { 18059 final AccountManager accountManager = 18060 mContext.getSystemService(AccountManager.class); 18061 final AccountManagerFuture<Bundle> bundle = accountManager.removeAccount(account, 18062 null, null /* callback */, null /* handler */); 18063 try { 18064 final Bundle result = bundle.getResult(); 18065 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, /* default */ false)) { 18066 Slogf.i(LOG_TAG, "Account removed from the primary user."); 18067 } else { 18068 // TODO(174768447): Revisit start activity logic. 18069 final Intent removeIntent = result.getParcelable(AccountManager.KEY_INTENT); 18070 removeIntent.addFlags(FLAG_ACTIVITY_NEW_TASK); 18071 if (removeIntent != null) { 18072 Slogf.i(LOG_TAG, "Starting activity to remove account"); 18073 new Handler(Looper.getMainLooper()).post(() -> { 18074 mContext.startActivity(removeIntent); 18075 }); 18076 } else { 18077 Slogf.e(LOG_TAG, "Could not remove account from the primary user."); 18078 } 18079 } 18080 } catch (OperationCanceledException | AuthenticatorException | IOException e) { 18081 Slogf.e(LOG_TAG, "Exception removing account from the primary user.", e); 18082 } 18083 } 18084 18085 @Override 18086 public void provisionFullyManagedDevice( 18087 @NonNull FullyManagedDeviceProvisioningParams provisioningParams, 18088 @NonNull String callerPackage) { 18089 Objects.requireNonNull(provisioningParams, "provisioningParams is null."); 18090 Objects.requireNonNull(callerPackage, "callerPackage is null."); 18091 18092 ComponentName deviceAdmin = provisioningParams.getDeviceAdminComponentName(); 18093 Objects.requireNonNull(deviceAdmin, "admin is null."); 18094 Objects.requireNonNull(provisioningParams.getOwnerName(), "owner name is null."); 18095 18096 final CallerIdentity caller = getCallerIdentity(); 18097 Preconditions.checkCallAuthorization( 18098 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS) 18099 || (hasCallingOrSelfPermission(permission.PROVISION_DEMO_DEVICE) 18100 && provisioningParams.isDemoDevice())); 18101 18102 provisioningParams.logParams(callerPackage); 18103 18104 final long identity = Binder.clearCallingIdentity(); 18105 try { 18106 int result = checkProvisioningPreconditionSkipPermission( 18107 ACTION_PROVISION_MANAGED_DEVICE, deviceAdmin.getPackageName()); 18108 if (result != STATUS_OK) { 18109 throw new ServiceSpecificException( 18110 ERROR_PRE_CONDITION_FAILED, 18111 "Provisioning preconditions failed with result: " + result); 18112 } 18113 onProvisionFullyManagedDeviceStarted(provisioningParams); 18114 setTimeAndTimezone(provisioningParams.getTimeZone(), provisioningParams.getLocalTime()); 18115 setLocale(provisioningParams.getLocale()); 18116 18117 final int deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode() 18118 ? UserHandle.USER_SYSTEM : caller.getUserId(); 18119 if (!removeNonRequiredAppsForManagedDevice( 18120 deviceOwnerUserId, 18121 provisioningParams.isLeaveAllSystemAppsEnabled(), 18122 deviceAdmin)) { 18123 throw new ServiceSpecificException( 18124 ERROR_REMOVE_NON_REQUIRED_APPS_FAILED, 18125 "PackageManager failed to remove non required apps."); 18126 } 18127 18128 18129 if (!setActiveAdminAndDeviceOwner( 18130 deviceOwnerUserId, deviceAdmin, provisioningParams.getOwnerName())) { 18131 throw new ServiceSpecificException( 18132 ERROR_SET_DEVICE_OWNER_FAILED, 18133 "Failed to set device owner."); 18134 } 18135 18136 disallowAddUser(); 18137 setAdminCanGrantSensorsPermissionForUserUnchecked( 18138 deviceOwnerUserId, provisioningParams.canDeviceOwnerGrantSensorsPermissions()); 18139 setDemoDeviceStateUnchecked(deviceOwnerUserId, provisioningParams.isDemoDevice()); 18140 onProvisionFullyManagedDeviceCompleted(provisioningParams); 18141 sendProvisioningCompletedBroadcast( 18142 deviceOwnerUserId, 18143 ACTION_PROVISION_MANAGED_DEVICE, 18144 provisioningParams.isLeaveAllSystemAppsEnabled()); 18145 } catch (Exception e) { 18146 DevicePolicyEventLogger 18147 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR) 18148 .setStrings(callerPackage) 18149 .write(); 18150 throw e; 18151 } finally { 18152 Binder.restoreCallingIdentity(identity); 18153 } 18154 } 18155 18156 /** 18157 * Callback called at the beginning of {@link #provisionFullyManagedDevice( 18158 * FullyManagedDeviceProvisioningParams, String)} after the relevant prechecks have passed. 18159 * 18160 * <p>The logic in this method blocks provisioning. 18161 * 18162 * <p>This method is meant to be overridden by OEMs. 18163 */ 18164 private void onProvisionFullyManagedDeviceStarted( 18165 FullyManagedDeviceProvisioningParams provisioningParams) {} 18166 18167 /** 18168 * Callback called at the end of {@link #provisionFullyManagedDevice( 18169 * FullyManagedDeviceProvisioningParams, String)} after all the other provisioning tasks 18170 * have completed successfully. 18171 * 18172 * <p>The logic in this method blocks provisioning. 18173 * 18174 * <p>This method is meant to be overridden by OEMs. 18175 */ 18176 private void onProvisionFullyManagedDeviceCompleted( 18177 FullyManagedDeviceProvisioningParams provisioningParams) {} 18178 18179 private void setTimeAndTimezone(String timeZone, long localTime) { 18180 try { 18181 final AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class); 18182 if (timeZone != null) { 18183 alarmManager.setTimeZone(timeZone); 18184 } 18185 if (localTime > 0) { 18186 alarmManager.setTime(localTime); 18187 } 18188 } catch (Exception e) { 18189 // Do not stop provisioning and ignore this error. 18190 Slogf.e(LOG_TAG, "Alarm manager failed to set the system time/timezone.", e); 18191 } 18192 } 18193 18194 private void setLocale(Locale locale) { 18195 if (locale == null || locale.equals(Locale.getDefault())) { 18196 return; 18197 } 18198 try { 18199 // If locale is different from current locale this results in a configuration change, 18200 // which will trigger the restarting of the activity. 18201 LocalePicker.updateLocale(locale); 18202 } catch (Exception e) { 18203 // Do not stop provisioning and ignore this error. 18204 Slogf.e(LOG_TAG, "Failed to set the system locale.", e); 18205 } 18206 } 18207 18208 private boolean removeNonRequiredAppsForManagedDevice( 18209 @UserIdInt int userId, boolean leaveAllSystemAppsEnabled, ComponentName admin) { 18210 Set<String> packagesToDelete = leaveAllSystemAppsEnabled 18211 ? Collections.emptySet() 18212 : mOverlayPackagesProvider.getNonRequiredApps( 18213 admin, userId, ACTION_PROVISION_MANAGED_DEVICE); 18214 18215 removeNonInstalledPackages(packagesToDelete, userId); 18216 if (packagesToDelete.isEmpty()) { 18217 Slogf.i(LOG_TAG, "No packages to delete on user " + userId); 18218 return true; 18219 } 18220 18221 NonRequiredPackageDeleteObserver packageDeleteObserver = 18222 new NonRequiredPackageDeleteObserver(packagesToDelete.size()); 18223 for (String packageName : packagesToDelete) { 18224 Slogf.i(LOG_TAG, "Deleting package [" + packageName + "] as user " + userId); 18225 mContext.getPackageManager().deletePackageAsUser( 18226 packageName, 18227 packageDeleteObserver, 18228 PackageManager.DELETE_SYSTEM_APP, 18229 userId); 18230 } 18231 Slogf.i(LOG_TAG, "Waiting for non required apps to be deleted"); 18232 return packageDeleteObserver.awaitPackagesDeletion(); 18233 } 18234 18235 private void removeNonInstalledPackages(Set<String> packages, @UserIdInt int userId) { 18236 final Set<String> toBeRemoved = new HashSet<>(); 18237 for (String packageName : packages) { 18238 if (!isPackageInstalledForUser(packageName, userId)) { 18239 toBeRemoved.add(packageName); 18240 } 18241 } 18242 packages.removeAll(toBeRemoved); 18243 } 18244 18245 private void disallowAddUser() { 18246 if (mInjector.userManagerIsHeadlessSystemUserMode()) { 18247 Slogf.i(LOG_TAG, "Not setting DISALLOW_ADD_USER on headless system user mode."); 18248 return; 18249 } 18250 for (UserInfo userInfo : mUserManager.getUsers()) { 18251 UserHandle userHandle = userInfo.getUserHandle(); 18252 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) { 18253 mUserManager.setUserRestriction( 18254 UserManager.DISALLOW_ADD_USER, /* value= */ true, userHandle); 18255 } 18256 } 18257 } 18258 18259 private boolean setActiveAdminAndDeviceOwner( 18260 @UserIdInt int userId, ComponentName adminComponent, String name) { 18261 enableAndSetActiveAdmin(userId, userId, adminComponent); 18262 // TODO(b/178187130): Directly set DO and remove the check once silent provisioning is no 18263 // longer used. 18264 if (getDeviceOwnerComponent(/* callingUserOnly= */ true) == null) { 18265 return setDeviceOwner(adminComponent, name, userId, 18266 /* setProfileOwnerOnCurrentUserIfNecessary= */ true); 18267 } 18268 return true; 18269 } 18270 18271 private static void logEventDuration(int eventId, long startTime, String callerPackage) { 18272 final long duration = SystemClock.elapsedRealtime() - startTime; 18273 DevicePolicyEventLogger 18274 .createEvent(eventId) 18275 .setTimePeriod(duration) 18276 .setStrings(callerPackage) 18277 .write(); 18278 } 18279 18280 @Override 18281 public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) { 18282 Preconditions.checkCallAuthorization( 18283 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 18284 18285 mInjector.binderWithCleanCallingIdentity(() -> { 18286 try { 18287 final List<UserInfo> profiles = mUserManager.getProfiles(userId); 18288 final int numOfProfiles = profiles.size(); 18289 if (numOfProfiles <= 1) { 18290 return; 18291 } 18292 18293 final String managedProvisioningPackageName = getManagedProvisioningPackage( 18294 mContext); 18295 // Removes cross profile intent filters from the parent to all the profiles. 18296 mIPackageManager.clearCrossProfileIntentFilters( 18297 userId, mContext.getOpPackageName()); 18298 // Setting and resetting default cross profile intent filters was previously handled 18299 // by Managed Provisioning. For backwards compatibility, clear any intent filters 18300 // that were set by ManagedProvisioning. 18301 mIPackageManager.clearCrossProfileIntentFilters( 18302 userId, managedProvisioningPackageName); 18303 18304 // For each profile reset cross profile intent filters 18305 for (int i = 0; i < numOfProfiles; i++) { 18306 UserInfo profile = profiles.get(i); 18307 mIPackageManager.clearCrossProfileIntentFilters( 18308 profile.id, mContext.getOpPackageName()); 18309 // Clear any intent filters that were set by ManagedProvisioning. 18310 mIPackageManager.clearCrossProfileIntentFilters( 18311 profile.id, managedProvisioningPackageName); 18312 18313 mUserManagerInternal.setDefaultCrossProfileIntentFilters(userId, profile.id); 18314 } 18315 } catch (RemoteException e) { 18316 // Shouldn't happen. 18317 } 18318 }); 18319 } 18320 18321 private void setAdminCanGrantSensorsPermissionForUserUnchecked(@UserIdInt int userId, 18322 boolean canGrant) { 18323 Slogf.d(LOG_TAG, "setAdminCanGrantSensorsPermissionForUserUnchecked(%d, %b)", 18324 userId, canGrant); 18325 synchronized (getLockObject()) { 18326 ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId); 18327 18328 Preconditions.checkState( 18329 isDeviceOwner(owner) && owner.getUserHandle().getIdentifier() == userId, 18330 "May only be set on a the user of a device owner."); 18331 18332 owner.mAdminCanGrantSensorsPermissions = canGrant; 18333 mPolicyCache.setAdminCanGrantSensorsPermissions(userId, canGrant); 18334 saveSettingsLocked(userId); 18335 } 18336 } 18337 18338 private void setDemoDeviceStateUnchecked(@UserIdInt int userId, boolean isDemoDevice) { 18339 Slogf.d(LOG_TAG, "setDemoDeviceStateUnchecked(%d, %b)", 18340 userId, isDemoDevice); 18341 if (!isDemoDevice) { 18342 return; 18343 } 18344 synchronized (getLockObject()) { 18345 mInjector.settingsGlobalPutStringForUser( 18346 Settings.Global.DEVICE_DEMO_MODE, Integer.toString(/* value= */ 1), userId); 18347 } 18348 setUserProvisioningState(STATE_USER_SETUP_FINALIZED, userId); 18349 } 18350 18351 private void updateAdminCanGrantSensorsPermissionCache(@UserIdInt int userId) { 18352 synchronized (getLockObject()) { 18353 18354 ActiveAdmin owner; 18355 // If the user is affiliated the device (either a DO itself, or an affiliated PO), 18356 // use mAdminCanGrantSensorsPermissions from the DO 18357 if (isUserAffiliatedWithDeviceLocked(userId)) { 18358 owner = getDeviceOwnerAdminLocked(); 18359 } else { 18360 owner = getDeviceOrProfileOwnerAdminLocked(userId); 18361 } 18362 boolean canGrant = owner != null ? owner.mAdminCanGrantSensorsPermissions : false; 18363 mPolicyCache.setAdminCanGrantSensorsPermissions(userId, canGrant); 18364 } 18365 } 18366 18367 private void updateNetworkPreferenceForUser(int userId, 18368 List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) { 18369 if (!isManagedProfile(userId) && !isDeviceOwnerUserId(userId)) { 18370 return; 18371 } 18372 List<ProfileNetworkPreference> preferences = new ArrayList<>(); 18373 for (PreferentialNetworkServiceConfig preferentialNetworkServiceConfig : 18374 preferentialNetworkServiceConfigs) { 18375 ProfileNetworkPreference.Builder preferenceBuilder = 18376 new ProfileNetworkPreference.Builder(); 18377 if (preferentialNetworkServiceConfig.isEnabled()) { 18378 if (preferentialNetworkServiceConfig.isFallbackToDefaultConnectionAllowed()) { 18379 preferenceBuilder.setPreference(PROFILE_NETWORK_PREFERENCE_ENTERPRISE); 18380 } else { 18381 preferenceBuilder.setPreference( 18382 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK); 18383 } 18384 preferenceBuilder.setIncludedUids( 18385 preferentialNetworkServiceConfig.getIncludedUids()); 18386 preferenceBuilder.setExcludedUids( 18387 preferentialNetworkServiceConfig.getExcludedUids()); 18388 preferenceBuilder.setPreferenceEnterpriseId( 18389 preferentialNetworkServiceConfig.getNetworkId()); 18390 } else { 18391 preferenceBuilder.setPreference(PROFILE_NETWORK_PREFERENCE_DEFAULT); 18392 } 18393 18394 18395 preferences.add(preferenceBuilder.build()); 18396 } 18397 Slogf.d(LOG_TAG, "updateNetworkPreferenceForUser to " + preferences); 18398 mInjector.binderWithCleanCallingIdentity(() -> 18399 mInjector.getConnectivityManager().setProfileNetworkPreferences( 18400 UserHandle.of(userId), preferences, 18401 null /* executor */, null /* listener */)); 18402 } 18403 18404 @Override 18405 public boolean canAdminGrantSensorsPermissionsForUser(int userId) { 18406 if (!mHasFeature) { 18407 return false; 18408 } 18409 18410 return mPolicyCache.canAdminGrantSensorsPermissionsForUser(userId); 18411 } 18412 18413 @Override 18414 public void setDeviceOwnerType(@NonNull ComponentName admin, 18415 @DeviceOwnerType int deviceOwnerType) { 18416 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18417 permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 18418 18419 synchronized (getLockObject()) { 18420 setDeviceOwnerTypeLocked(admin, deviceOwnerType); 18421 } 18422 } 18423 18424 private void setDeviceOwnerTypeLocked(ComponentName admin, 18425 @DeviceOwnerType int deviceOwnerType) { 18426 String packageName = admin.getPackageName(); 18427 boolean isAdminTestOnly; 18428 18429 verifyDeviceOwnerTypePreconditionsLocked(admin); 18430 18431 isAdminTestOnly = isAdminTestOnlyLocked(admin, mOwners.getDeviceOwnerUserId()); 18432 Preconditions.checkState(isAdminTestOnly 18433 || !mOwners.isDeviceOwnerTypeSetForDeviceOwner(packageName), 18434 "Test only admins can only set the device owner type more than once"); 18435 18436 mOwners.setDeviceOwnerType(packageName, deviceOwnerType, isAdminTestOnly); 18437 setGlobalSettingDeviceOwnerType(deviceOwnerType); 18438 } 18439 18440 // TODO(b/237065504): Allow mainline modules to get the device owner type. This is a workaround 18441 // to get the device owner type in PermissionController. See HibernationPolicy.kt. 18442 private void setGlobalSettingDeviceOwnerType(int deviceOwnerType) { 18443 mInjector.binderWithCleanCallingIdentity( 18444 () -> mInjector.settingsGlobalPutInt("device_owner_type", deviceOwnerType)); 18445 } 18446 18447 @Override 18448 @DeviceOwnerType 18449 public int getDeviceOwnerType(@NonNull ComponentName admin) { 18450 synchronized (getLockObject()) { 18451 verifyDeviceOwnerTypePreconditionsLocked(admin); 18452 return getDeviceOwnerTypeLocked(admin.getPackageName()); 18453 } 18454 } 18455 18456 @DeviceOwnerType 18457 private int getDeviceOwnerTypeLocked(String packageName) { 18458 return mOwners.getDeviceOwnerType(packageName); 18459 } 18460 18461 /** 18462 * {@code true} is returned <b>only if</b> the caller is the device owner and the device owner 18463 * type is {@link DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}. {@code false} is returned for 18464 * the case where the caller is not the device owner, there is no device owner, or the device 18465 * owner type is not {@link DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}. 18466 */ 18467 private boolean isFinancedDeviceOwner(CallerIdentity caller) { 18468 synchronized (getLockObject()) { 18469 return isDeviceOwnerLocked(caller) && getDeviceOwnerTypeLocked( 18470 mOwners.getDeviceOwnerPackageName()) == DEVICE_OWNER_TYPE_FINANCED; 18471 } 18472 } 18473 18474 private void verifyDeviceOwnerTypePreconditionsLocked(@NonNull ComponentName admin) { 18475 Preconditions.checkState(mOwners.hasDeviceOwner(), "there is no device owner"); 18476 Preconditions.checkState(mOwners.getDeviceOwnerComponent().equals(admin), 18477 "admin is not the device owner"); 18478 } 18479 18480 @Override 18481 public void setUsbDataSignalingEnabled(String packageName, boolean enabled) { 18482 Objects.requireNonNull(packageName, "Admin package name must be provided"); 18483 final CallerIdentity caller = getCallerIdentity(packageName); 18484 Preconditions.checkCallAuthorization( 18485 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller), 18486 "USB data signaling can only be controlled by a device owner or " 18487 + "a profile owner on an organization-owned device."); 18488 Preconditions.checkState(canUsbDataSignalingBeDisabled(), 18489 "USB data signaling cannot be disabled."); 18490 18491 synchronized (getLockObject()) { 18492 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 18493 if (admin.mUsbDataSignalingEnabled != enabled) { 18494 admin.mUsbDataSignalingEnabled = enabled; 18495 saveSettingsLocked(caller.getUserId()); 18496 updateUsbDataSignal(); 18497 } 18498 } 18499 DevicePolicyEventLogger 18500 .createEvent(DevicePolicyEnums.SET_USB_DATA_SIGNALING) 18501 .setAdmin(packageName) 18502 .setBoolean(enabled) 18503 .write(); 18504 } 18505 18506 private void updateUsbDataSignal() { 18507 if (!canUsbDataSignalingBeDisabled()) { 18508 return; 18509 } 18510 final boolean usbEnabled; 18511 synchronized (getLockObject()) { 18512 usbEnabled = isUsbDataSignalingEnabledInternalLocked(); 18513 } 18514 if (!mInjector.binderWithCleanCallingIdentity( 18515 () -> mInjector.getUsbManager().enableUsbDataSignal(usbEnabled))) { 18516 Slogf.w(LOG_TAG, "Failed to set usb data signaling state"); 18517 } 18518 } 18519 18520 @Override 18521 public boolean isUsbDataSignalingEnabled(String packageName) { 18522 final CallerIdentity caller = getCallerIdentity(packageName); 18523 synchronized (getLockObject()) { 18524 // If the caller is an admin, return the policy set by itself. Otherwise 18525 // return the device-wide policy. 18526 if (isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)) { 18527 return getProfileOwnerOrDeviceOwnerLocked(caller).mUsbDataSignalingEnabled; 18528 } else { 18529 return isUsbDataSignalingEnabledInternalLocked(); 18530 } 18531 } 18532 } 18533 18534 @Override 18535 public boolean isUsbDataSignalingEnabledForUser(int userId) { 18536 final CallerIdentity caller = getCallerIdentity(); 18537 Preconditions.checkCallAuthorization(isSystemUid(caller)); 18538 18539 synchronized (getLockObject()) { 18540 return isUsbDataSignalingEnabledInternalLocked(); 18541 } 18542 } 18543 18544 private boolean isUsbDataSignalingEnabledInternalLocked() { 18545 final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 18546 UserHandle.USER_SYSTEM); 18547 return admin == null || admin.mUsbDataSignalingEnabled; 18548 } 18549 18550 @Override 18551 public boolean canUsbDataSignalingBeDisabled() { 18552 return mInjector.binderWithCleanCallingIdentity(() -> 18553 mInjector.getUsbManager() != null 18554 && mInjector.getUsbManager().getUsbHalVersion() >= UsbManager.USB_HAL_V1_3 18555 ); 18556 } 18557 18558 private void notifyMinimumRequiredWifiSecurityLevelChanged(int level) { 18559 mInjector.binderWithCleanCallingIdentity( 18560 () -> mInjector.getWifiManager() 18561 .notifyMinimumRequiredWifiSecurityLevelChanged(level)); 18562 } 18563 18564 private void notifyWifiSsidPolicyChanged(WifiSsidPolicy policy) { 18565 if (policy == null) { 18566 // If policy doesn't limit SSIDs, no need to disconnect anything. 18567 return; 18568 } 18569 mInjector.binderWithCleanCallingIdentity( 18570 () -> mInjector.getWifiManager().notifyWifiSsidPolicyChanged(policy)); 18571 } 18572 18573 @Override 18574 public void setMinimumRequiredWifiSecurityLevel(int level) { 18575 final CallerIdentity caller = getCallerIdentity(); 18576 Preconditions.checkCallAuthorization( 18577 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller), 18578 "Wi-Fi minimum security level can only be controlled by a device owner or " 18579 + "a profile owner on an organization-owned device."); 18580 18581 boolean valueChanged = false; 18582 synchronized (getLockObject()) { 18583 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 18584 if (admin.mWifiMinimumSecurityLevel != level) { 18585 admin.mWifiMinimumSecurityLevel = level; 18586 saveSettingsLocked(caller.getUserId()); 18587 valueChanged = true; 18588 } 18589 } 18590 if (valueChanged) notifyMinimumRequiredWifiSecurityLevelChanged(level); 18591 } 18592 18593 @Override 18594 public int getMinimumRequiredWifiSecurityLevel() { 18595 synchronized (getLockObject()) { 18596 final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 18597 UserHandle.USER_SYSTEM); 18598 return (admin == null) ? DevicePolicyManager.WIFI_SECURITY_OPEN 18599 : admin.mWifiMinimumSecurityLevel; 18600 } 18601 } 18602 18603 @Override 18604 public WifiSsidPolicy getWifiSsidPolicy() { 18605 final CallerIdentity caller = getCallerIdentity(); 18606 Preconditions.checkCallAuthorization( 18607 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller) 18608 || canQueryAdminPolicy(caller), 18609 "SSID policy can only be retrieved by a device owner or " 18610 + "a profile owner on an organization-owned device or " 18611 + "an app with the QUERY_ADMIN_POLICY permission."); 18612 synchronized (getLockObject()) { 18613 final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked( 18614 UserHandle.USER_SYSTEM); 18615 return admin != null ? admin.mWifiSsidPolicy : null; 18616 } 18617 } 18618 18619 @Override 18620 public void setWifiSsidPolicy(WifiSsidPolicy policy) { 18621 final CallerIdentity caller = getCallerIdentity(); 18622 Preconditions.checkCallAuthorization( 18623 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller), 18624 "SSID denylist can only be controlled by a device owner or " 18625 + "a profile owner on an organization-owned device."); 18626 18627 boolean changed = false; 18628 synchronized (getLockObject()) { 18629 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller); 18630 if (!Objects.equals(policy, admin.mWifiSsidPolicy)) { 18631 admin.mWifiSsidPolicy = policy; 18632 changed = true; 18633 } 18634 if (changed) saveSettingsLocked(caller.getUserId()); 18635 } 18636 if (changed) { 18637 notifyWifiSsidPolicyChanged(policy); 18638 } 18639 } 18640 18641 @Override 18642 public void setDrawables(@NonNull List<DevicePolicyDrawableResource> drawables) { 18643 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18644 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES)); 18645 18646 Objects.requireNonNull(drawables, "drawables must be provided."); 18647 18648 mInjector.binderWithCleanCallingIdentity(() -> { 18649 if (mDeviceManagementResourcesProvider.updateDrawables(drawables)) { 18650 sendDrawableUpdatedBroadcast( 18651 drawables.stream().map(s -> s.getDrawableId()).collect( 18652 Collectors.toList())); 18653 } 18654 }); 18655 } 18656 18657 @Override 18658 public void resetDrawables(@NonNull List<String> drawableIds) { 18659 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18660 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES)); 18661 18662 Objects.requireNonNull(drawableIds, "drawableIds must be provided."); 18663 18664 mInjector.binderWithCleanCallingIdentity(() -> { 18665 if (mDeviceManagementResourcesProvider.removeDrawables(drawableIds)) { 18666 sendDrawableUpdatedBroadcast(drawableIds); 18667 } 18668 }); 18669 } 18670 18671 @Override 18672 public ParcelableResource getDrawable( 18673 String drawableId, String drawableStyle, String drawableSource) { 18674 return mInjector.binderWithCleanCallingIdentity(() -> 18675 mDeviceManagementResourcesProvider.getDrawable( 18676 drawableId, drawableStyle, drawableSource)); 18677 } 18678 18679 private void sendDrawableUpdatedBroadcast(List<String> drawableIds) { 18680 sendResourceUpdatedBroadcast(EXTRA_RESOURCE_TYPE_DRAWABLE, drawableIds); 18681 } 18682 18683 @Override 18684 public void setStrings(@NonNull List<DevicePolicyStringResource> strings) { 18685 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18686 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES)); 18687 18688 Objects.requireNonNull(strings, "strings must be provided."); 18689 18690 mInjector.binderWithCleanCallingIdentity(() -> { 18691 if (mDeviceManagementResourcesProvider.updateStrings(strings)) 18692 sendStringsUpdatedBroadcast( 18693 strings.stream().map(s -> s.getStringId()).collect(Collectors.toList())); 18694 }); 18695 } 18696 18697 @Override 18698 public void resetStrings(@NonNull List<String> stringIds) { 18699 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18700 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES)); 18701 18702 mInjector.binderWithCleanCallingIdentity(() -> { 18703 if (mDeviceManagementResourcesProvider.removeStrings(stringIds)) { 18704 sendStringsUpdatedBroadcast(stringIds); 18705 } 18706 }); 18707 } 18708 18709 @Override 18710 public ParcelableResource getString(String stringId) { 18711 return mInjector.binderWithCleanCallingIdentity(() -> 18712 mDeviceManagementResourcesProvider.getString(stringId)); 18713 } 18714 18715 private void sendStringsUpdatedBroadcast(List<String> stringIds) { 18716 sendResourceUpdatedBroadcast(EXTRA_RESOURCE_TYPE_STRING, stringIds); 18717 } 18718 18719 private void sendResourceUpdatedBroadcast(int resourceType, List<String> resourceIds) { 18720 final Intent intent = new Intent(ACTION_DEVICE_POLICY_RESOURCE_UPDATED); 18721 intent.putExtra(EXTRA_RESOURCE_IDS, resourceIds.toArray(String[]::new)); 18722 intent.putExtra(EXTRA_RESOURCE_TYPE, resourceType); 18723 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 18724 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 18725 18726 List<UserInfo> users = mUserManager.getAliveUsers(); 18727 for (int i = 0; i < users.size(); i++) { 18728 UserHandle user = users.get(i).getUserHandle(); 18729 mContext.sendBroadcastAsUser(intent, user); 18730 } 18731 } 18732 18733 private String getUpdatableString( 18734 String updatableStringId, int defaultStringId, Object... formatArgs) { 18735 ParcelableResource resource = mDeviceManagementResourcesProvider.getString( 18736 updatableStringId); 18737 if (resource == null) { 18738 return ParcelableResource.loadDefaultString(() -> 18739 mContext.getString(defaultStringId, formatArgs)); 18740 } 18741 return resource.getString( 18742 mContext, () -> mContext.getString(defaultStringId, formatArgs), formatArgs); 18743 } 18744 18745 public boolean isDpcDownloaded() { 18746 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18747 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 18748 18749 ContentResolver cr = mContext.getContentResolver(); 18750 18751 return mInjector.binderWithCleanCallingIdentity(() -> Settings.Secure.getIntForUser( 18752 cr, MANAGED_PROVISIONING_DPC_DOWNLOADED, 18753 /* def= */ 0, /* userHandle= */ cr.getUserId()) 18754 == 1); 18755 } 18756 18757 public void setDpcDownloaded(boolean downloaded) { 18758 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18759 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 18760 18761 int setTo = downloaded ? 1 : 0; 18762 18763 mInjector.binderWithCleanCallingIdentity(() -> Settings.Secure.putInt( 18764 mContext.getContentResolver(), MANAGED_PROVISIONING_DPC_DOWNLOADED, setTo)); 18765 } 18766 18767 @Override 18768 public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() { 18769 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18770 android.Manifest.permission.MANAGE_ROLE_HOLDERS)); 18771 return mInjector.binderWithCleanCallingIdentity(() -> { 18772 if (getUserData( 18773 UserHandle.USER_SYSTEM).mBypassDevicePolicyManagementRoleQualifications) { 18774 return true; 18775 } 18776 return shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal(); 18777 }); 18778 } 18779 18780 private boolean shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal() { 18781 if (mUserManager.getUserCount() > 1) { 18782 return false; 18783 } 18784 AccountManager am = AccountManager.get(mContext); 18785 Account[] accounts = am.getAccounts(); 18786 return accounts.length == 0; 18787 } 18788 18789 private void setBypassDevicePolicyManagementRoleQualificationStateInternal( 18790 String currentRoleHolder, boolean allowBypass) { 18791 boolean stateChanged = false; 18792 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 18793 if (policy.mBypassDevicePolicyManagementRoleQualifications != allowBypass) { 18794 policy.mBypassDevicePolicyManagementRoleQualifications = allowBypass; 18795 stateChanged = true; 18796 } 18797 if (!Objects.equals(currentRoleHolder, policy.mCurrentRoleHolder)) { 18798 policy.mCurrentRoleHolder = currentRoleHolder; 18799 stateChanged = true; 18800 } 18801 if (stateChanged) { 18802 synchronized (getLockObject()) { 18803 saveSettingsLocked(UserHandle.USER_SYSTEM); 18804 } 18805 } 18806 } 18807 18808 private final class DevicePolicyManagementRoleObserver implements OnRoleHoldersChangedListener { 18809 private RoleManager mRm; 18810 private final Executor mExecutor; 18811 private final Context mContext; 18812 18813 DevicePolicyManagementRoleObserver(@NonNull Context context) { 18814 mContext = context; 18815 mExecutor = mContext.getMainExecutor(); 18816 mRm = mContext.getSystemService(RoleManager.class); 18817 } 18818 18819 public void register() { 18820 mRm.addOnRoleHoldersChangedListenerAsUser(mExecutor, this, UserHandle.SYSTEM); 18821 } 18822 18823 @Override 18824 public void onRoleHoldersChanged(@NonNull String roleName, @NonNull UserHandle user) { 18825 if (!RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT.equals(roleName)) { 18826 return; 18827 } 18828 String newRoleHolder = getRoleHolder(); 18829 if (isDefaultRoleHolder(newRoleHolder)) { 18830 Slogf.i(LOG_TAG, 18831 "onRoleHoldersChanged: Default role holder is set, returning early"); 18832 return; 18833 } 18834 if (newRoleHolder == null) { 18835 Slogf.i(LOG_TAG, 18836 "onRoleHoldersChanged: New role holder is null, returning early"); 18837 return; 18838 } 18839 if (shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal()) { 18840 Slogf.w(LOG_TAG, 18841 "onRoleHoldersChanged: Updating current role holder to " + newRoleHolder); 18842 setBypassDevicePolicyManagementRoleQualificationStateInternal( 18843 newRoleHolder, /* allowBypass= */ true); 18844 return; 18845 } 18846 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 18847 if (!newRoleHolder.equals(policy.mCurrentRoleHolder)) { 18848 Slogf.w(LOG_TAG, 18849 "onRoleHoldersChanged: You can't set a different role holder, role " 18850 + "is getting revoked from " + newRoleHolder); 18851 setBypassDevicePolicyManagementRoleQualificationStateInternal( 18852 /* currentRoleHolder= */ null, /* allowBypass= */ false); 18853 mRm.removeRoleHolderAsUser( 18854 RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, 18855 newRoleHolder, 18856 /* flags= */ 0, 18857 user, 18858 mExecutor, 18859 successful -> {}); 18860 } 18861 } 18862 18863 private String getRoleHolder() { 18864 return DevicePolicyManagerService.this.getDevicePolicyManagementRoleHolderPackageName( 18865 mContext); 18866 } 18867 18868 private boolean isDefaultRoleHolder(String packageName) { 18869 String defaultRoleHolder = getDefaultRoleHolderPackageName(); 18870 if (packageName == null || defaultRoleHolder == null) { 18871 return false; 18872 } 18873 if (!defaultRoleHolder.equals(packageName)) { 18874 return false; 18875 } 18876 return hasSigningCertificate( 18877 packageName, getDefaultRoleHolderPackageSignature()); 18878 } 18879 18880 private boolean hasSigningCertificate(String packageName, String certificateString) { 18881 if (packageName == null || certificateString == null) { 18882 return false; 18883 } 18884 byte[] certificate; 18885 try { 18886 certificate = new Signature(certificateString).toByteArray(); 18887 } catch (IllegalArgumentException e) { 18888 Slogf.w(LOG_TAG, "Cannot parse signing certificate: " + certificateString, e); 18889 return false; 18890 } 18891 PackageManager pm = mInjector.getPackageManager(); 18892 return pm.hasSigningCertificate( 18893 packageName, certificate, PackageManager.CERT_INPUT_SHA256); 18894 } 18895 18896 private String getDefaultRoleHolderPackageName() { 18897 String[] info = getDefaultRoleHolderPackageNameAndSignature(); 18898 if (info == null) { 18899 return null; 18900 } 18901 return info[0]; 18902 } 18903 18904 private String getDefaultRoleHolderPackageSignature() { 18905 String[] info = getDefaultRoleHolderPackageNameAndSignature(); 18906 if (info == null || info.length < 2) { 18907 return null; 18908 } 18909 return info[1]; 18910 } 18911 18912 private String[] getDefaultRoleHolderPackageNameAndSignature() { 18913 String packageNameAndSignature = mContext.getString( 18914 com.android.internal.R.string.config_devicePolicyManagement); 18915 if (TextUtils.isEmpty(packageNameAndSignature)) { 18916 return null; 18917 } 18918 if (packageNameAndSignature.contains(":")) { 18919 return packageNameAndSignature.split(":"); 18920 } 18921 return new String[]{packageNameAndSignature}; 18922 } 18923 } 18924 18925 @Override 18926 public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) { 18927 Preconditions.checkCallAuthorization(hasCallingOrSelfPermission( 18928 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)); 18929 int userId = user.getIdentifier(); 18930 return mInjector.binderWithCleanCallingIdentity(() -> { 18931 List<UserInfo> userProfiles = mUserManager.getProfiles(userId); 18932 List<UserHandle> result = new ArrayList<>(); 18933 for (int i = 0; i < userProfiles.size(); i++) { 18934 UserInfo userInfo = userProfiles.get(i); 18935 if (userInfo.isManagedProfile() && hasProfileOwner(userInfo.id)) { 18936 result.add(new UserHandle(userInfo.id)); 18937 } 18938 } 18939 return result; 18940 }); 18941 } 18942 18943 /** 18944 * Truncates char sequence to maximum length, nulls are ignored. 18945 */ 18946 private static CharSequence truncateIfLonger(CharSequence input, int maxLength) { 18947 return input == null || input.length() <= maxLength 18948 ? input 18949 : input.subSequence(0, maxLength); 18950 } 18951 18952 /** 18953 * Throw if string argument is too long to be serialized. 18954 */ 18955 private static void enforceMaxStringLength(String str, String argName) { 18956 Preconditions.checkArgument( 18957 str.length() <= MAX_POLICY_STRING_LENGTH, argName + " loo long"); 18958 } 18959 18960 private static void enforceMaxPackageNameLength(String pkg) { 18961 Preconditions.checkArgument( 18962 pkg.length() <= MAX_PACKAGE_NAME_LENGTH, "Package name too long"); 18963 } 18964 18965 /** 18966 * Throw if persistable bundle contains any string that we can't serialize. 18967 */ 18968 private static void enforceMaxStringLength(PersistableBundle bundle, String argName) { 18969 // Persistable bundles can have other persistable bundles as values, traverse with a queue. 18970 Queue<PersistableBundle> queue = new ArrayDeque<>(); 18971 queue.add(bundle); 18972 while (!queue.isEmpty()) { 18973 PersistableBundle current = queue.remove(); 18974 for (String key : current.keySet()) { 18975 enforceMaxStringLength(key, "key in " + argName); 18976 Object value = current.get(key); 18977 if (value instanceof String) { 18978 enforceMaxStringLength((String) value, "string value in " + argName); 18979 } else if (value instanceof String[]) { 18980 for (String str : (String[]) value) { 18981 enforceMaxStringLength(str, "string value in " + argName); 18982 } 18983 } else if (value instanceof PersistableBundle) { 18984 queue.add((PersistableBundle) value); 18985 } 18986 } 18987 } 18988 } 18989 } 18990