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.app.ActivityManager.LOCK_TASK_MODE_NONE; 23 import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE; 24 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER; 25 import static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY; 26 import static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED; 27 import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE; 28 import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED; 29 import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER; 30 import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED; 31 import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED; 32 import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS; 33 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER; 34 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT; 35 import static android.app.admin.DevicePolicyManager.CODE_OK; 36 import static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 37 import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER; 38 import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER; 39 import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING; 40 import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED; 41 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS; 42 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL; 43 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL; 44 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_SELECTION; 45 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP; 46 import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE; 47 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES; 48 import static android.app.admin.DevicePolicyManager.DELEGATION_NETWORK_LOGGING; 49 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS; 50 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT; 51 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO; 52 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI; 53 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID; 54 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL; 55 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED; 56 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME; 57 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS; 58 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW; 59 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE; 60 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC; 61 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC; 62 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK; 63 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 64 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED; 65 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC; 66 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX; 67 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; 68 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 69 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OFF; 70 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OPPORTUNISTIC; 71 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME; 72 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_UNKNOWN; 73 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_ERROR_FAILURE_SETTING; 74 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR; 75 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 76 import static android.app.admin.DevicePolicyManager.WIPE_EUICC; 77 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE; 78 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA; 79 import static android.app.admin.DevicePolicyManager.WIPE_SILENTLY; 80 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 81 import static android.provider.Settings.Global.PRIVATE_DNS_MODE; 82 import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER; 83 import static android.provider.Telephony.Carriers.DPC_URI; 84 import static android.provider.Telephony.Carriers.ENFORCE_KEY; 85 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI; 86 87 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB; 88 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW; 89 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER; 90 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER; 91 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; 92 93 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 94 import static org.xmlpull.v1.XmlPullParser.END_TAG; 95 import static org.xmlpull.v1.XmlPullParser.TEXT; 96 97 import android.Manifest.permission; 98 import android.accessibilityservice.AccessibilityServiceInfo; 99 import android.accounts.Account; 100 import android.accounts.AccountManager; 101 import android.annotation.NonNull; 102 import android.annotation.Nullable; 103 import android.annotation.UserIdInt; 104 import android.app.Activity; 105 import android.app.ActivityManager; 106 import android.app.ActivityManagerInternal; 107 import android.app.ActivityTaskManager; 108 import android.app.ActivityThread; 109 import android.app.AlarmManager; 110 import android.app.AppGlobals; 111 import android.app.AppOpsManager; 112 import android.app.BroadcastOptions; 113 import android.app.IActivityManager; 114 import android.app.IActivityTaskManager; 115 import android.app.IApplicationThread; 116 import android.app.IServiceConnection; 117 import android.app.Notification; 118 import android.app.NotificationManager; 119 import android.app.PendingIntent; 120 import android.app.StatusBarManager; 121 import android.app.admin.DeviceAdminInfo; 122 import android.app.admin.DeviceAdminReceiver; 123 import android.app.admin.DevicePolicyCache; 124 import android.app.admin.DevicePolicyEventLogger; 125 import android.app.admin.DevicePolicyManager; 126 import android.app.admin.DevicePolicyManager.PasswordComplexity; 127 import android.app.admin.DevicePolicyManagerInternal; 128 import android.app.admin.NetworkEvent; 129 import android.app.admin.PasswordMetrics; 130 import android.app.admin.SecurityLog; 131 import android.app.admin.SecurityLog.SecurityEvent; 132 import android.app.admin.StartInstallingUpdateCallback; 133 import android.app.admin.SystemUpdateInfo; 134 import android.app.admin.SystemUpdatePolicy; 135 import android.app.backup.IBackupManager; 136 import android.app.trust.TrustManager; 137 import android.app.usage.UsageStatsManagerInternal; 138 import android.content.ActivityNotFoundException; 139 import android.content.BroadcastReceiver; 140 import android.content.ComponentName; 141 import android.content.ContentValues; 142 import android.content.Context; 143 import android.content.Intent; 144 import android.content.IntentFilter; 145 import android.content.PermissionChecker; 146 import android.content.pm.ActivityInfo; 147 import android.content.pm.ApplicationInfo; 148 import android.content.pm.IPackageDataObserver; 149 import android.content.pm.IPackageManager; 150 import android.content.pm.PackageInfo; 151 import android.content.pm.PackageManager; 152 import android.content.pm.PackageManager.NameNotFoundException; 153 import android.content.pm.PackageManagerInternal; 154 import android.content.pm.ParceledListSlice; 155 import android.content.pm.PermissionInfo; 156 import android.content.pm.ResolveInfo; 157 import android.content.pm.ServiceInfo; 158 import android.content.pm.StringParceledListSlice; 159 import android.content.pm.UserInfo; 160 import android.content.res.Resources; 161 import android.database.ContentObserver; 162 import android.database.Cursor; 163 import android.graphics.Bitmap; 164 import android.graphics.Color; 165 import android.media.AudioManager; 166 import android.media.IAudioService; 167 import android.net.ConnectivityManager; 168 import android.net.IIpConnectivityMetrics; 169 import android.net.NetworkUtils; 170 import android.net.ProxyInfo; 171 import android.net.Uri; 172 import android.net.metrics.IpConnectivityLog; 173 import android.net.wifi.WifiManager; 174 import android.os.Binder; 175 import android.os.Build; 176 import android.os.Bundle; 177 import android.os.Environment; 178 import android.os.FileUtils; 179 import android.os.Handler; 180 import android.os.IBinder; 181 import android.os.Looper; 182 import android.os.ParcelFileDescriptor; 183 import android.os.PersistableBundle; 184 import android.os.PowerManager; 185 import android.os.PowerManagerInternal; 186 import android.os.Process; 187 import android.os.RecoverySystem; 188 import android.os.RemoteCallback; 189 import android.os.RemoteException; 190 import android.os.ServiceManager; 191 import android.os.ServiceSpecificException; 192 import android.os.SystemClock; 193 import android.os.SystemProperties; 194 import android.os.UserHandle; 195 import android.os.UserManager; 196 import android.os.UserManagerInternal; 197 import android.os.UserManagerInternal.UserRestrictionsListener; 198 import android.os.storage.StorageManager; 199 import android.permission.PermissionControllerManager; 200 import android.provider.CalendarContract; 201 import android.provider.ContactsContract.QuickContact; 202 import android.provider.ContactsInternal; 203 import android.provider.Settings; 204 import android.provider.Settings.Global; 205 import android.security.IKeyChainAliasCallback; 206 import android.security.IKeyChainService; 207 import android.security.KeyChain; 208 import android.security.KeyChain.KeyChainConnection; 209 import android.security.KeyStore; 210 import android.security.keymaster.KeymasterCertificateChain; 211 import android.security.keystore.AttestationUtils; 212 import android.security.keystore.KeyGenParameterSpec; 213 import android.security.keystore.ParcelableKeyGenParameterSpec; 214 import android.service.persistentdata.PersistentDataBlockManager; 215 import android.stats.devicepolicy.DevicePolicyEnums; 216 import android.telephony.TelephonyManager; 217 import android.telephony.data.ApnSetting; 218 import android.text.TextUtils; 219 import android.util.ArrayMap; 220 import android.util.ArraySet; 221 import android.util.AtomicFile; 222 import android.util.Log; 223 import android.util.Pair; 224 import android.util.Slog; 225 import android.util.SparseArray; 226 import android.util.Xml; 227 import android.view.IWindowManager; 228 import android.view.accessibility.AccessibilityManager; 229 import android.view.accessibility.IAccessibilityManager; 230 import android.view.inputmethod.InputMethodInfo; 231 import android.view.inputmethod.InputMethodSystemProperty; 232 233 import com.android.internal.R; 234 import com.android.internal.annotations.GuardedBy; 235 import com.android.internal.annotations.VisibleForTesting; 236 import com.android.internal.logging.MetricsLogger; 237 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 238 import com.android.internal.notification.SystemNotificationChannels; 239 import com.android.internal.os.BackgroundThread; 240 import com.android.internal.statusbar.IStatusBarService; 241 import com.android.internal.telephony.SmsApplication; 242 import com.android.internal.util.DumpUtils; 243 import com.android.internal.util.FastXmlSerializer; 244 import com.android.internal.util.FunctionalUtils.ThrowingRunnable; 245 import com.android.internal.util.JournaledFile; 246 import com.android.internal.util.Preconditions; 247 import com.android.internal.util.StatLogger; 248 import com.android.internal.util.XmlUtils; 249 import com.android.internal.widget.LockPatternUtils; 250 import com.android.server.LocalServices; 251 import com.android.server.LockGuard; 252 import com.android.server.SystemServerInitThreadPool; 253 import com.android.server.SystemService; 254 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo; 255 import com.android.server.inputmethod.InputMethodManagerInternal; 256 import com.android.server.net.NetworkPolicyManagerInternal; 257 import com.android.server.pm.UserRestrictionsUtils; 258 import com.android.server.storage.DeviceStorageMonitorInternal; 259 import com.android.server.uri.UriGrantsManagerInternal; 260 import com.android.server.wm.ActivityTaskManagerInternal; 261 262 import com.google.android.collect.Sets; 263 264 import org.xmlpull.v1.XmlPullParser; 265 import org.xmlpull.v1.XmlPullParserException; 266 import org.xmlpull.v1.XmlSerializer; 267 268 import java.io.File; 269 import java.io.FileDescriptor; 270 import java.io.FileInputStream; 271 import java.io.FileNotFoundException; 272 import java.io.FileOutputStream; 273 import java.io.IOException; 274 import java.io.PrintWriter; 275 import java.lang.reflect.Constructor; 276 import java.nio.charset.StandardCharsets; 277 import java.text.DateFormat; 278 import java.time.LocalDate; 279 import java.util.ArrayList; 280 import java.util.Arrays; 281 import java.util.Collection; 282 import java.util.Collections; 283 import java.util.Date; 284 import java.util.HashMap; 285 import java.util.List; 286 import java.util.Map; 287 import java.util.Map.Entry; 288 import java.util.Set; 289 import java.util.concurrent.TimeUnit; 290 import java.util.concurrent.atomic.AtomicBoolean; 291 import java.util.function.Function; 292 293 /** 294 * Implementation of the device policy APIs. 295 */ 296 public class DevicePolicyManagerService extends BaseIDevicePolicyManager { 297 298 protected static final String LOG_TAG = "DevicePolicyManager"; 299 300 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE 301 302 private static final String DEVICE_POLICIES_XML = "device_policies.xml"; 303 304 private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML = 305 "transfer-ownership-parameters.xml"; 306 307 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate"; 308 309 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component"; 310 311 private static final String TAG_LOCK_TASK_FEATURES = "lock-task-features"; 312 313 private static final String TAG_STATUS_BAR = "statusbar"; 314 315 private static final String ATTR_DISABLED = "disabled"; 316 317 private static final String ATTR_NAME = "name"; 318 319 private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML = 320 "do-not-ask-credentials-on-boot"; 321 322 private static final String TAG_AFFILIATION_ID = "affiliation-id"; 323 324 private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval"; 325 326 private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request"; 327 328 private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval"; 329 330 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending"; 331 332 private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set"; 333 334 private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert"; 335 336 private static final String ATTR_ID = "id"; 337 338 private static final String ATTR_VALUE = "value"; 339 340 private static final String ATTR_ALIAS = "alias"; 341 342 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle"; 343 344 private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token"; 345 346 private static final String TAG_PASSWORD_VALIDITY = "password-validity"; 347 348 private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle"; 349 350 private static final int REQUEST_EXPIRE_PASSWORD = 5571; 351 352 private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1); 353 354 private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms 355 356 private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION 357 = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION"; 358 359 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider"; 360 private static final String ATTR_SETUP_COMPLETE = "setup-complete"; 361 private static final String ATTR_PROVISIONING_STATE = "provisioning-state"; 362 private static final String ATTR_PERMISSION_POLICY = "permission-policy"; 363 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED = 364 "device-provisioning-config-applied"; 365 private static final String ATTR_DEVICE_PAIRED = "device-paired"; 366 private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer"; 367 private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER 368 = "application-restrictions-manager"; 369 370 // Comprehensive list of delegations. 371 private static final String DELEGATIONS[] = { 372 DELEGATION_CERT_INSTALL, 373 DELEGATION_APP_RESTRICTIONS, 374 DELEGATION_BLOCK_UNINSTALL, 375 DELEGATION_ENABLE_SYSTEM_APP, 376 DELEGATION_KEEP_UNINSTALLED_PACKAGES, 377 DELEGATION_PACKAGE_ACCESS, 378 DELEGATION_PERMISSION_GRANT, 379 DELEGATION_INSTALL_EXISTING_PACKAGE, 380 DELEGATION_KEEP_UNINSTALLED_PACKAGES, 381 DELEGATION_NETWORK_LOGGING, 382 DELEGATION_CERT_SELECTION, 383 }; 384 385 // Subset of delegations that can only be delegated by Device Owner. 386 private static final List<String> DEVICE_OWNER_DELEGATIONS = Arrays.asList(new String[] { 387 DELEGATION_NETWORK_LOGGING, 388 }); 389 390 // Subset of delegations that only one single package within a given user can hold 391 private static final List<String> EXCLUSIVE_DELEGATIONS = Arrays.asList(new String[] { 392 DELEGATION_NETWORK_LOGGING, 393 DELEGATION_CERT_SELECTION, 394 }); 395 396 /** 397 * System property whose value is either "true" or "false", indicating whether 398 * device owner is present. 399 */ 400 private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner"; 401 402 private static final int STATUS_BAR_DISABLE_MASK = 403 StatusBarManager.DISABLE_EXPAND | 404 StatusBarManager.DISABLE_NOTIFICATION_ICONS | 405 StatusBarManager.DISABLE_NOTIFICATION_ALERTS | 406 StatusBarManager.DISABLE_SEARCH; 407 408 private static final int STATUS_BAR_DISABLE2_MASK = 409 StatusBarManager.DISABLE2_QUICK_SETTINGS; 410 411 private static final Set<String> SECURE_SETTINGS_WHITELIST; 412 private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST; 413 private static final Set<String> GLOBAL_SETTINGS_WHITELIST; 414 private static final Set<String> GLOBAL_SETTINGS_DEPRECATED; 415 private static final Set<String> SYSTEM_SETTINGS_WHITELIST; 416 private static final Set<Integer> DA_DISALLOWED_POLICIES; 417 private static final String AB_DEVICE_KEY = "ro.build.ab_update"; 418 419 static { 420 SECURE_SETTINGS_WHITELIST = new ArraySet<>(); 421 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD); 422 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS); 423 SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS); 424 425 SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>(); 426 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST); 427 SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE); 428 429 GLOBAL_SETTINGS_WHITELIST = new ArraySet<>(); 430 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED); 431 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME); 432 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE); 433 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING); 434 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED); 435 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY); 436 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN); 437 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN); 438 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.PRIVATE_DNS_MODE); 439 GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER); 440 441 GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>(); 442 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON); 443 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); 444 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER); 445 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE); 446 GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON); 447 448 SYSTEM_SETTINGS_WHITELIST = new ArraySet<>(); 449 SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS); 450 SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE); 451 SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_OFF_TIMEOUT); 452 453 DA_DISALLOWED_POLICIES = new ArraySet<>(); 454 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 455 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES); 456 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD); 457 DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 458 } 459 460 /** 461 * Keyguard features that when set on a profile affect the profile content or challenge only. 462 * These cannot be set on the managed profile's parent DPM instance 463 */ 464 private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY = 465 DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS; 466 467 /** Keyguard features that are allowed to be set on a managed profile */ 468 private static final int PROFILE_KEYGUARD_FEATURES = 469 PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY; 470 471 private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000; 472 473 /** 474 * Minimum timeout in milliseconds after which unlocking with weak auth times out, 475 * i.e. the user has to use a strong authentication method like password, PIN or pattern. 476 */ 477 private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1); 478 479 /** 480 * The amount of ms that a managed kiosk must go without user interaction to be considered 481 * unattended. 482 */ 483 private static final int UNATTENDED_MANAGED_KIOSK_MS = 30000; 484 485 /** 486 * Strings logged with {@link 487 * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB} 488 * and {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB}. 489 */ 490 private static final String LOG_TAG_PROFILE_OWNER = "profile-owner"; 491 private static final String LOG_TAG_DEVICE_OWNER = "device-owner"; 492 493 final Context mContext; 494 final Injector mInjector; 495 final IPackageManager mIPackageManager; 496 final UserManager mUserManager; 497 final UserManagerInternal mUserManagerInternal; 498 final UsageStatsManagerInternal mUsageStatsManagerInternal; 499 final TelephonyManager mTelephonyManager; 500 private final LockPatternUtils mLockPatternUtils; 501 private final DeviceAdminServiceController mDeviceAdminServiceController; 502 private final OverlayPackagesProvider mOverlayPackagesProvider; 503 504 private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl(); 505 506 /** 507 * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p 508 * is requested for user u. 509 */ 510 private final Set<Pair<String, Integer>> mPackagesToRemove = 511 new ArraySet<Pair<String, Integer>>(); 512 513 final LocalService mLocalService; 514 515 // Stores and loads state on device and profile owners. 516 @VisibleForTesting 517 final Owners mOwners; 518 519 private final Binder mToken = new Binder(); 520 521 /** 522 * Whether or not device admin feature is supported. If it isn't return defaults for all 523 * public methods. 524 */ 525 final boolean mHasFeature; 526 527 /** 528 * Whether or not this device is a watch. 529 */ 530 final boolean mIsWatch; 531 532 /** 533 * Whether this device has the telephony feature. 534 */ 535 final boolean mHasTelephonyFeature; 536 537 private final CertificateMonitor mCertificateMonitor; 538 private final SecurityLogMonitor mSecurityLogMonitor; 539 540 @GuardedBy("getLockObject()") 541 private NetworkLogger mNetworkLogger; 542 543 private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean(); 544 private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean(); 545 546 private final SetupContentObserver mSetupContentObserver; 547 private final DevicePolicyConstantsObserver mConstantsObserver; 548 549 private DevicePolicyConstants mConstants; 550 551 private static final boolean ENABLE_LOCK_GUARD = true; 552 553 interface Stats { 554 int LOCK_GUARD_GUARD = 0; 555 556 int COUNT = LOCK_GUARD_GUARD + 1; 557 } 558 559 private final StatLogger mStatLogger = new StatLogger(new String[] { 560 "LockGuard.guard()", 561 }); 562 563 private final Object mLockDoNoUseDirectly = LockGuard.installNewLock( 564 LockGuard.INDEX_DPMS, /* doWtf=*/ true); 565 getLockObject()566 final Object getLockObject() { 567 if (ENABLE_LOCK_GUARD) { 568 final long start = mStatLogger.getTime(); 569 LockGuard.guard(LockGuard.INDEX_DPMS); 570 mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start); 571 } 572 return mLockDoNoUseDirectly; 573 } 574 575 /** 576 * Check if the current thread holds the DPMS lock, and if not, do a WTF. 577 * 578 * (Doing this check too much may be costly, so don't call it in a hot path.) 579 */ ensureLocked()580 final void ensureLocked() { 581 if (Thread.holdsLock(mLockDoNoUseDirectly)) { 582 return; 583 } 584 Slog.wtfStack(LOG_TAG, "Not holding DPMS lock."); 585 } 586 587 @VisibleForTesting 588 final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager; 589 590 private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() { 591 @Override 592 public void run() { 593 if(mRemoteBugreportServiceIsActive.get()) { 594 onBugreportFailed(); 595 } 596 } 597 }; 598 599 /** Listens only if mHasFeature == true. */ 600 private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() { 601 602 @Override 603 public void onReceive(Context context, Intent intent) { 604 if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction()) 605 && mRemoteBugreportServiceIsActive.get()) { 606 onBugreportFinished(intent); 607 } 608 } 609 }; 610 611 /** Listens only if mHasFeature == true. */ 612 private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() { 613 614 @Override 615 public void onReceive(Context context, Intent intent) { 616 String action = intent.getAction(); 617 mInjector.getNotificationManager().cancel(LOG_TAG, 618 RemoteBugreportUtils.NOTIFICATION_ID); 619 if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) { 620 onBugreportSharingAccepted(); 621 } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) { 622 onBugreportSharingDeclined(); 623 } 624 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 625 } 626 }; 627 628 public static final class Lifecycle extends SystemService { 629 private BaseIDevicePolicyManager mService; 630 Lifecycle(Context context)631 public Lifecycle(Context context) { 632 super(context); 633 String dpmsClassName = context.getResources() 634 .getString(R.string.config_deviceSpecificDevicePolicyManagerService); 635 if (TextUtils.isEmpty(dpmsClassName)) { 636 dpmsClassName = DevicePolicyManagerService.class.getName(); 637 } 638 try { 639 Class serviceClass = Class.forName(dpmsClassName); 640 Constructor constructor = serviceClass.getConstructor(Context.class); 641 mService = (BaseIDevicePolicyManager) constructor.newInstance(context); 642 } catch (Exception e) { 643 throw new IllegalStateException( 644 "Failed to instantiate DevicePolicyManagerService with class name: " 645 + dpmsClassName, e); 646 } 647 } 648 649 @Override onStart()650 public void onStart() { 651 publishBinderService(Context.DEVICE_POLICY_SERVICE, mService); 652 } 653 654 @Override onBootPhase(int phase)655 public void onBootPhase(int phase) { 656 mService.systemReady(phase); 657 } 658 659 @Override onStartUser(int userHandle)660 public void onStartUser(int userHandle) { 661 mService.handleStartUser(userHandle); 662 } 663 664 @Override onUnlockUser(int userHandle)665 public void onUnlockUser(int userHandle) { 666 mService.handleUnlockUser(userHandle); 667 } 668 669 @Override onStopUser(int userHandle)670 public void onStopUser(int userHandle) { 671 mService.handleStopUser(userHandle); 672 } 673 } 674 675 public static class DevicePolicyData { 676 int mFailedPasswordAttempts = 0; 677 boolean mPasswordValidAtLastCheckpoint = true; 678 679 int mUserHandle; 680 int mPasswordOwner = -1; 681 long mLastMaximumTimeToLock = -1; 682 boolean mUserSetupComplete = false; 683 boolean mPaired = false; 684 int mUserProvisioningState; 685 int mPermissionPolicy; 686 687 boolean mDeviceProvisioningConfigApplied = false; 688 689 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>(); 690 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>(); 691 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>(); 692 693 // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead. 694 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>(); 695 696 // This is the list of component allowed to start lock task mode. 697 List<String> mLockTaskPackages = new ArrayList<>(); 698 699 // Bitfield of feature flags to be enabled during LockTask mode. 700 // We default on the power button menu, in order to be consistent with pre-P behaviour. 701 int mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS; 702 703 boolean mStatusBarDisabled = false; 704 705 ComponentName mRestrictionsProvider; 706 707 // Map of delegate package to delegation scopes 708 final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>(); 709 710 boolean doNotAskCredentialsOnBoot = false; 711 712 Set<String> mAffiliationIds = new ArraySet<>(); 713 714 long mLastSecurityLogRetrievalTime = -1; 715 716 long mLastBugReportRequestTime = -1; 717 718 long mLastNetworkLogsRetrievalTime = -1; 719 720 boolean mCurrentInputMethodSet = false; 721 722 // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead. 723 Set<String> mOwnerInstalledCaCerts = new ArraySet<>(); 724 725 // Used for initialization of users created by createAndManageUser. 726 boolean mAdminBroadcastPending = false; 727 PersistableBundle mInitBundle = null; 728 729 long mPasswordTokenHandle = 0; 730 DevicePolicyData(int userHandle)731 public DevicePolicyData(int userHandle) { 732 mUserHandle = userHandle; 733 } 734 } 735 736 @GuardedBy("getLockObject()") 737 final SparseArray<DevicePolicyData> mUserData = new SparseArray<>(); 738 739 @GuardedBy("getLockObject()") 740 final SparseArray<PasswordMetrics> mUserPasswordMetrics = new SparseArray<>(); 741 742 final Handler mHandler; 743 final Handler mBackgroundHandler; 744 745 /** Listens only if mHasFeature == true. */ 746 final BroadcastReceiver mReceiver = new BroadcastReceiver() { 747 @Override 748 public void onReceive(Context context, Intent intent) { 749 final String action = intent.getAction(); 750 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 751 getSendingUserId()); 752 753 /* 754 * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(), 755 * however it's too early in the boot process to register with IIpConnectivityMetrics 756 * to listen for events. 757 */ 758 if (Intent.ACTION_USER_STARTED.equals(action) 759 && userHandle == mOwners.getDeviceOwnerUserId()) { 760 synchronized (getLockObject()) { 761 if (isNetworkLoggingEnabledInternalLocked()) { 762 setNetworkLoggingActiveInternal(true); 763 } 764 } 765 } 766 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 767 && userHandle == mOwners.getDeviceOwnerUserId() 768 && getDeviceOwnerRemoteBugreportUri() != null) { 769 IntentFilter filterConsent = new IntentFilter(); 770 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 771 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 772 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 773 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, 774 RemoteBugreportUtils.NOTIFICATION_ID, 775 RemoteBugreportUtils.buildNotification(mContext, 776 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 777 UserHandle.ALL); 778 } 779 if (Intent.ACTION_BOOT_COMPLETED.equals(action) 780 || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) { 781 if (VERBOSE_LOG) { 782 Slog.v(LOG_TAG, "Sending password expiration notifications for action " 783 + action + " for user " + userHandle); 784 } 785 mHandler.post(new Runnable() { 786 @Override 787 public void run() { 788 handlePasswordExpirationNotification(userHandle); 789 } 790 }); 791 } 792 793 if (Intent.ACTION_USER_ADDED.equals(action)) { 794 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle); 795 synchronized (getLockObject()) { 796 // It might take a while for the user to become affiliated. Make security 797 // and network logging unavailable in the meantime. 798 maybePauseDeviceWideLoggingLocked(); 799 } 800 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 801 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle); 802 synchronized (getLockObject()) { 803 // Check whether the user is affiliated, *before* removing its data. 804 boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle); 805 removeUserData(userHandle); 806 if (!isRemovedUserAffiliated) { 807 // We discard the logs when unaffiliated users are deleted (so that the 808 // device owner cannot retrieve data about that user after it's gone). 809 discardDeviceWideLogsLocked(); 810 // Resume logging if all remaining users are affiliated. 811 maybeResumeDeviceWideLoggingLocked(); 812 } 813 } 814 } else if (Intent.ACTION_USER_STARTED.equals(action)) { 815 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle); 816 synchronized (getLockObject()) { 817 maybeSendAdminEnabledBroadcastLocked(userHandle); 818 // Reset the policy data 819 mUserData.remove(userHandle); 820 } 821 handlePackagesChanged(null /* check all admins */, userHandle); 822 } else if (Intent.ACTION_USER_STOPPED.equals(action)) { 823 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle); 824 } else if (Intent.ACTION_USER_SWITCHED.equals(action)) { 825 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle); 826 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) { 827 synchronized (getLockObject()) { 828 maybeSendAdminEnabledBroadcastLocked(userHandle); 829 } 830 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { 831 handlePackagesChanged(null /* check all admins */, userHandle); 832 } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action) 833 || (Intent.ACTION_PACKAGE_ADDED.equals(action) 834 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) { 835 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 836 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action) 837 && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 838 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 839 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) { 840 clearWipeProfileNotification(); 841 } else if (Intent.ACTION_DATE_CHANGED.equals(action) 842 || Intent.ACTION_TIME_CHANGED.equals(action)) { 843 // Update freeze period record when clock naturally progresses to the next day 844 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made 845 // (ACTION_TIME_CHANGED) 846 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true); 847 } 848 849 } 850 851 private void sendDeviceOwnerUserCommand(String action, int userHandle) { 852 synchronized (getLockObject()) { 853 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 854 if (deviceOwner != null) { 855 Bundle extras = new Bundle(); 856 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 857 sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null, 858 /* inForeground */ true); 859 } 860 } 861 } 862 }; 863 864 protected static class RestrictionsListener implements UserRestrictionsListener { 865 private Context mContext; 866 RestrictionsListener(Context context)867 public RestrictionsListener(Context context) { 868 mContext = context; 869 } 870 onUserRestrictionsChanged(int userId, Bundle newRestrictions, Bundle prevRestrictions)871 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions, 872 Bundle prevRestrictions) { 873 final boolean newlyDisallowed = 874 newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE); 875 final boolean previouslyDisallowed = 876 prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE); 877 final boolean restrictionChanged = (newlyDisallowed != previouslyDisallowed); 878 879 if (restrictionChanged) { 880 // Notify ManagedProvisioning to update the built-in cross profile intent filters. 881 Intent intent = new Intent( 882 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED); 883 intent.setPackage(getManagedProvisioningPackage(mContext)); 884 intent.putExtra(Intent.EXTRA_USER_ID, userId); 885 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 886 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM); 887 } 888 } 889 } 890 891 static class ActiveAdmin { 892 private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features"; 893 private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin"; 894 private static final String TAG_DISABLE_CAMERA = "disable-camera"; 895 private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id"; 896 private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search"; 897 private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING 898 = "disable-bt-contacts-sharing"; 899 private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture"; 900 private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management"; 901 private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time"; 902 private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users"; 903 private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled"; 904 private static final String TAG_ACCOUNT_TYPE = "account-type"; 905 private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES 906 = "permitted-accessiblity-services"; 907 private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested"; 908 private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features"; 909 private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options"; 910 private static final String TAG_TRUST_AGENT_COMPONENT = "component"; 911 private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date"; 912 private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout"; 913 private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list"; 914 private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec"; 915 private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy"; 916 private static final String TAG_PERMITTED_IMES = "permitted-imes"; 917 private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS = 918 "permitted-notification-listeners"; 919 private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe"; 920 private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock"; 921 private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout"; 922 private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter"; 923 private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols"; 924 private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric"; 925 private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters"; 926 private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase"; 927 private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase"; 928 private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length"; 929 private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length"; 930 private static final String ATTR_VALUE = "value"; 931 private static final String TAG_PASSWORD_QUALITY = "password-quality"; 932 private static final String TAG_POLICIES = "policies"; 933 private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS = 934 "cross-profile-widget-providers"; 935 private static final String TAG_PROVIDER = "provider"; 936 private static final String TAG_PACKAGE_LIST_ITEM = "item"; 937 private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages"; 938 private static final String TAG_USER_RESTRICTIONS = "user-restrictions"; 939 private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS = 940 "default-enabled-user-restrictions"; 941 private static final String TAG_RESTRICTION = "restriction"; 942 private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message"; 943 private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message"; 944 private static final String TAG_PARENT_ADMIN = "parent-admin"; 945 private static final String TAG_ORGANIZATION_COLOR = "organization-color"; 946 private static final String TAG_ORGANIZATION_NAME = "organization-name"; 947 private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification"; 948 private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications"; 949 private static final String TAG_IS_LOGOUT_ENABLED = "is_logout_enabled"; 950 private static final String TAG_START_USER_SESSION_MESSAGE = "start_user_session_message"; 951 private static final String TAG_END_USER_SESSION_MESSAGE = "end_user_session_message"; 952 private static final String TAG_METERED_DATA_DISABLED_PACKAGES = 953 "metered_data_disabled_packages"; 954 private static final String TAG_CROSS_PROFILE_CALENDAR_PACKAGES = 955 "cross-profile-calendar-packages"; 956 private static final String TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL = 957 "cross-profile-calendar-packages-null"; 958 959 DeviceAdminInfo info; 960 961 962 static final int DEF_PASSWORD_HISTORY_LENGTH = 0; 963 int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH; 964 965 static final int DEF_MINIMUM_PASSWORD_LENGTH = 0; 966 static final int DEF_MINIMUM_PASSWORD_LETTERS = 1; 967 static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0; 968 static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0; 969 static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1; 970 static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1; 971 static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0; 972 @NonNull 973 PasswordMetrics minimumPasswordMetrics = new PasswordMetrics( 974 PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH, 975 DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE, 976 DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC, 977 DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER); 978 979 static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0; 980 long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK; 981 982 long strongAuthUnlockTimeout = 0; // admin doesn't participate by default 983 984 static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0; 985 int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE; 986 987 static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0; 988 long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT; 989 990 static final long DEF_PASSWORD_EXPIRATION_DATE = 0; 991 long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE; 992 993 static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none 994 995 int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED; 996 997 boolean encryptionRequested = false; 998 boolean testOnlyAdmin = false; 999 boolean disableCamera = false; 1000 boolean disableCallerId = false; 1001 boolean disableContactsSearch = false; 1002 boolean disableBluetoothContactSharing = true; 1003 boolean disableScreenCapture = false; // Can only be set by a device/profile owner. 1004 boolean requireAutoTime = false; // Can only be set by a device owner. 1005 boolean forceEphemeralUsers = false; // Can only be set by a device owner. 1006 boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner. 1007 boolean isLogoutEnabled = false; // Can only be set by a device owner. 1008 1009 // one notification after enabling + one more after reboots 1010 static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2; 1011 int numNetworkLoggingNotifications = 0; 1012 long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch 1013 1014 ActiveAdmin parentAdmin; 1015 final boolean isParent; 1016 1017 static class TrustAgentInfo { 1018 public PersistableBundle options; TrustAgentInfo(PersistableBundle bundle)1019 TrustAgentInfo(PersistableBundle bundle) { 1020 options = bundle; 1021 } 1022 } 1023 1024 // The list of packages which are not allowed to use metered data. 1025 List<String> meteredDisabledPackages; 1026 1027 final Set<String> accountTypesWithManagementDisabled = new ArraySet<>(); 1028 1029 // The list of permitted accessibility services package namesas set by a profile 1030 // or device owner. Null means all accessibility services are allowed, empty means 1031 // none except system services are allowed. 1032 List<String> permittedAccessiblityServices; 1033 1034 // The list of permitted input methods package names as set by a profile or device owner. 1035 // Null means all input methods are allowed, empty means none except system imes are 1036 // allowed. 1037 List<String> permittedInputMethods; 1038 1039 // The list of packages allowed to use a NotificationListenerService to receive events for 1040 // notifications from this user. Null means that all packages are allowed. Empty list means 1041 // that only packages from the system are allowed. 1042 List<String> permittedNotificationListeners; 1043 1044 // List of package names to keep cached. 1045 List<String> keepUninstalledPackages; 1046 1047 // TODO: review implementation decisions with frameworks team 1048 boolean specifiesGlobalProxy = false; 1049 String globalProxySpec = null; 1050 String globalProxyExclusionList = null; 1051 1052 ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>(); 1053 1054 List<String> crossProfileWidgetProviders; 1055 1056 Bundle userRestrictions; 1057 1058 // User restrictions that have already been enabled by default for this admin (either when 1059 // setting the device or profile owner, or during a system update if one of those "enabled 1060 // by default" restrictions is newly added). 1061 final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>(); 1062 1063 // Support text provided by the admin to display to the user. 1064 CharSequence shortSupportMessage = null; 1065 CharSequence longSupportMessage = null; 1066 1067 // Background color of confirm credentials screen. Default: teal. 1068 static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B"); 1069 int organizationColor = DEF_ORGANIZATION_COLOR; 1070 1071 // Default title of confirm credentials screen 1072 String organizationName = null; 1073 1074 // Message for user switcher 1075 String startUserSessionMessage = null; 1076 String endUserSessionMessage = null; 1077 1078 // The whitelist of packages that can access cross profile calendar APIs. 1079 // This whitelist should be in default an empty list, which indicates that no package 1080 // is whitelisted. 1081 List<String> mCrossProfileCalendarPackages = Collections.emptyList(); 1082 ActiveAdmin(DeviceAdminInfo _info, boolean parent)1083 ActiveAdmin(DeviceAdminInfo _info, boolean parent) { 1084 info = _info; 1085 isParent = parent; 1086 } 1087 getParentActiveAdmin()1088 ActiveAdmin getParentActiveAdmin() { 1089 Preconditions.checkState(!isParent); 1090 1091 if (parentAdmin == null) { 1092 parentAdmin = new ActiveAdmin(info, /* parent */ true); 1093 } 1094 return parentAdmin; 1095 } 1096 hasParentActiveAdmin()1097 boolean hasParentActiveAdmin() { 1098 return parentAdmin != null; 1099 } 1100 getUid()1101 int getUid() { return info.getActivityInfo().applicationInfo.uid; } 1102 getUserHandle()1103 public UserHandle getUserHandle() { 1104 return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid)); 1105 } 1106 writeToXml(XmlSerializer out)1107 void writeToXml(XmlSerializer out) 1108 throws IllegalArgumentException, IllegalStateException, IOException { 1109 out.startTag(null, TAG_POLICIES); 1110 info.writePoliciesToXml(out); 1111 out.endTag(null, TAG_POLICIES); 1112 if (minimumPasswordMetrics.quality != PASSWORD_QUALITY_UNSPECIFIED) { 1113 out.startTag(null, TAG_PASSWORD_QUALITY); 1114 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality)); 1115 out.endTag(null, TAG_PASSWORD_QUALITY); 1116 if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) { 1117 out.startTag(null, TAG_MIN_PASSWORD_LENGTH); 1118 out.attribute( 1119 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length)); 1120 out.endTag(null, TAG_MIN_PASSWORD_LENGTH); 1121 } 1122 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) { 1123 out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH); 1124 out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength)); 1125 out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH); 1126 } 1127 if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) { 1128 out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE); 1129 out.attribute( 1130 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase)); 1131 out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE); 1132 } 1133 if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) { 1134 out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE); 1135 out.attribute( 1136 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase)); 1137 out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE); 1138 } 1139 if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) { 1140 out.startTag(null, TAG_MIN_PASSWORD_LETTERS); 1141 out.attribute( 1142 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters)); 1143 out.endTag(null, TAG_MIN_PASSWORD_LETTERS); 1144 } 1145 if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) { 1146 out.startTag(null, TAG_MIN_PASSWORD_NUMERIC); 1147 out.attribute( 1148 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric)); 1149 out.endTag(null, TAG_MIN_PASSWORD_NUMERIC); 1150 } 1151 if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) { 1152 out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS); 1153 out.attribute( 1154 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols)); 1155 out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS); 1156 } 1157 if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) { 1158 out.startTag(null, TAG_MIN_PASSWORD_NONLETTER); 1159 out.attribute( 1160 null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter)); 1161 out.endTag(null, TAG_MIN_PASSWORD_NONLETTER); 1162 } 1163 } 1164 if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) { 1165 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK); 1166 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock)); 1167 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK); 1168 } 1169 if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 1170 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT); 1171 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout)); 1172 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT); 1173 } 1174 if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 1175 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE); 1176 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe)); 1177 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE); 1178 } 1179 if (specifiesGlobalProxy) { 1180 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY); 1181 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy)); 1182 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY); 1183 if (globalProxySpec != null) { 1184 out.startTag(null, TAG_GLOBAL_PROXY_SPEC); 1185 out.attribute(null, ATTR_VALUE, globalProxySpec); 1186 out.endTag(null, TAG_GLOBAL_PROXY_SPEC); 1187 } 1188 if (globalProxyExclusionList != null) { 1189 out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST); 1190 out.attribute(null, ATTR_VALUE, globalProxyExclusionList); 1191 out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST); 1192 } 1193 } 1194 if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) { 1195 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT); 1196 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout)); 1197 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT); 1198 } 1199 if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) { 1200 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE); 1201 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate)); 1202 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE); 1203 } 1204 if (encryptionRequested) { 1205 out.startTag(null, TAG_ENCRYPTION_REQUESTED); 1206 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested)); 1207 out.endTag(null, TAG_ENCRYPTION_REQUESTED); 1208 } 1209 if (testOnlyAdmin) { 1210 out.startTag(null, TAG_TEST_ONLY_ADMIN); 1211 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin)); 1212 out.endTag(null, TAG_TEST_ONLY_ADMIN); 1213 } 1214 if (disableCamera) { 1215 out.startTag(null, TAG_DISABLE_CAMERA); 1216 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera)); 1217 out.endTag(null, TAG_DISABLE_CAMERA); 1218 } 1219 if (disableCallerId) { 1220 out.startTag(null, TAG_DISABLE_CALLER_ID); 1221 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId)); 1222 out.endTag(null, TAG_DISABLE_CALLER_ID); 1223 } 1224 if (disableContactsSearch) { 1225 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH); 1226 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch)); 1227 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH); 1228 } 1229 if (!disableBluetoothContactSharing) { 1230 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING); 1231 out.attribute(null, ATTR_VALUE, 1232 Boolean.toString(disableBluetoothContactSharing)); 1233 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING); 1234 } 1235 if (disableScreenCapture) { 1236 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE); 1237 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture)); 1238 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE); 1239 } 1240 if (requireAutoTime) { 1241 out.startTag(null, TAG_REQUIRE_AUTO_TIME); 1242 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime)); 1243 out.endTag(null, TAG_REQUIRE_AUTO_TIME); 1244 } 1245 if (forceEphemeralUsers) { 1246 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS); 1247 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers)); 1248 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS); 1249 } 1250 if (isNetworkLoggingEnabled) { 1251 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED); 1252 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled)); 1253 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS, 1254 Integer.toString(numNetworkLoggingNotifications)); 1255 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION, 1256 Long.toString(lastNetworkLoggingNotificationTimeMs)); 1257 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED); 1258 } 1259 if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) { 1260 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES); 1261 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures)); 1262 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES); 1263 } 1264 if (!accountTypesWithManagementDisabled.isEmpty()) { 1265 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT); 1266 writeAttributeValuesToXml( 1267 out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled); 1268 out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT); 1269 } 1270 if (!trustAgentInfos.isEmpty()) { 1271 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet(); 1272 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES); 1273 for (Entry<String, TrustAgentInfo> entry : set) { 1274 TrustAgentInfo trustAgentInfo = entry.getValue(); 1275 out.startTag(null, TAG_TRUST_AGENT_COMPONENT); 1276 out.attribute(null, ATTR_VALUE, entry.getKey()); 1277 if (trustAgentInfo.options != null) { 1278 out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS); 1279 try { 1280 trustAgentInfo.options.saveToXml(out); 1281 } catch (XmlPullParserException e) { 1282 Log.e(LOG_TAG, "Failed to save TrustAgent options", e); 1283 } 1284 out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS); 1285 } 1286 out.endTag(null, TAG_TRUST_AGENT_COMPONENT); 1287 } 1288 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES); 1289 } 1290 if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) { 1291 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS); 1292 writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders); 1293 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS); 1294 } 1295 writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES, 1296 permittedAccessiblityServices); 1297 writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods); 1298 writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS, 1299 permittedNotificationListeners); 1300 writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages); 1301 writePackageListToXml(out, TAG_METERED_DATA_DISABLED_PACKAGES, meteredDisabledPackages); 1302 if (hasUserRestrictions()) { 1303 UserRestrictionsUtils.writeRestrictions( 1304 out, userRestrictions, TAG_USER_RESTRICTIONS); 1305 } 1306 if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) { 1307 out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS); 1308 writeAttributeValuesToXml( 1309 out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet); 1310 out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS); 1311 } 1312 if (!TextUtils.isEmpty(shortSupportMessage)) { 1313 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE); 1314 out.text(shortSupportMessage.toString()); 1315 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE); 1316 } 1317 if (!TextUtils.isEmpty(longSupportMessage)) { 1318 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE); 1319 out.text(longSupportMessage.toString()); 1320 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE); 1321 } 1322 if (parentAdmin != null) { 1323 out.startTag(null, TAG_PARENT_ADMIN); 1324 parentAdmin.writeToXml(out); 1325 out.endTag(null, TAG_PARENT_ADMIN); 1326 } 1327 if (organizationColor != DEF_ORGANIZATION_COLOR) { 1328 out.startTag(null, TAG_ORGANIZATION_COLOR); 1329 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor)); 1330 out.endTag(null, TAG_ORGANIZATION_COLOR); 1331 } 1332 if (organizationName != null) { 1333 out.startTag(null, TAG_ORGANIZATION_NAME); 1334 out.text(organizationName); 1335 out.endTag(null, TAG_ORGANIZATION_NAME); 1336 } 1337 if (isLogoutEnabled) { 1338 out.startTag(null, TAG_IS_LOGOUT_ENABLED); 1339 out.attribute(null, ATTR_VALUE, Boolean.toString(isLogoutEnabled)); 1340 out.endTag(null, TAG_IS_LOGOUT_ENABLED); 1341 } 1342 if (startUserSessionMessage != null) { 1343 out.startTag(null, TAG_START_USER_SESSION_MESSAGE); 1344 out.text(startUserSessionMessage); 1345 out.endTag(null, TAG_START_USER_SESSION_MESSAGE); 1346 } 1347 if (endUserSessionMessage != null) { 1348 out.startTag(null, TAG_END_USER_SESSION_MESSAGE); 1349 out.text(endUserSessionMessage); 1350 out.endTag(null, TAG_END_USER_SESSION_MESSAGE); 1351 } 1352 if (mCrossProfileCalendarPackages == null) { 1353 out.startTag(null, TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL); 1354 out.endTag(null, TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL); 1355 } else { 1356 writePackageListToXml(out, TAG_CROSS_PROFILE_CALENDAR_PACKAGES, 1357 mCrossProfileCalendarPackages); 1358 } 1359 } 1360 writePackageListToXml(XmlSerializer out, String outerTag, List<String> packageList)1361 void writePackageListToXml(XmlSerializer out, String outerTag, 1362 List<String> packageList) 1363 throws IllegalArgumentException, IllegalStateException, IOException { 1364 if (packageList == null) { 1365 return; 1366 } 1367 1368 out.startTag(null, outerTag); 1369 writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList); 1370 out.endTag(null, outerTag); 1371 } 1372 writeAttributeValuesToXml(XmlSerializer out, String tag, @NonNull Collection<String> values)1373 void writeAttributeValuesToXml(XmlSerializer out, String tag, 1374 @NonNull Collection<String> values) throws IOException { 1375 for (String value : values) { 1376 out.startTag(null, tag); 1377 out.attribute(null, ATTR_VALUE, value); 1378 out.endTag(null, tag); 1379 } 1380 } 1381 readFromXml(XmlPullParser parser, boolean shouldOverridePolicies)1382 void readFromXml(XmlPullParser parser, boolean shouldOverridePolicies) 1383 throws XmlPullParserException, IOException { 1384 int outerDepth = parser.getDepth(); 1385 int type; 1386 while ((type=parser.next()) != END_DOCUMENT 1387 && (type != END_TAG || parser.getDepth() > outerDepth)) { 1388 if (type == END_TAG || type == TEXT) { 1389 continue; 1390 } 1391 String tag = parser.getName(); 1392 if (TAG_POLICIES.equals(tag)) { 1393 if (shouldOverridePolicies) { 1394 Log.d(LOG_TAG, "Overriding device admin policies from XML."); 1395 info.readPoliciesFromXml(parser); 1396 } 1397 } else if (TAG_PASSWORD_QUALITY.equals(tag)) { 1398 minimumPasswordMetrics.quality = Integer.parseInt( 1399 parser.getAttributeValue(null, ATTR_VALUE)); 1400 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) { 1401 minimumPasswordMetrics.length = Integer.parseInt( 1402 parser.getAttributeValue(null, ATTR_VALUE)); 1403 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) { 1404 passwordHistoryLength = Integer.parseInt( 1405 parser.getAttributeValue(null, ATTR_VALUE)); 1406 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) { 1407 minimumPasswordMetrics.upperCase = Integer.parseInt( 1408 parser.getAttributeValue(null, ATTR_VALUE)); 1409 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) { 1410 minimumPasswordMetrics.lowerCase = Integer.parseInt( 1411 parser.getAttributeValue(null, ATTR_VALUE)); 1412 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) { 1413 minimumPasswordMetrics.letters = Integer.parseInt( 1414 parser.getAttributeValue(null, ATTR_VALUE)); 1415 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) { 1416 minimumPasswordMetrics.numeric = Integer.parseInt( 1417 parser.getAttributeValue(null, ATTR_VALUE)); 1418 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) { 1419 minimumPasswordMetrics.symbols = Integer.parseInt( 1420 parser.getAttributeValue(null, ATTR_VALUE)); 1421 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) { 1422 minimumPasswordMetrics.nonLetter = Integer.parseInt( 1423 parser.getAttributeValue(null, ATTR_VALUE)); 1424 }else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) { 1425 maximumTimeToUnlock = Long.parseLong( 1426 parser.getAttributeValue(null, ATTR_VALUE)); 1427 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) { 1428 strongAuthUnlockTimeout = Long.parseLong( 1429 parser.getAttributeValue(null, ATTR_VALUE)); 1430 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) { 1431 maximumFailedPasswordsForWipe = Integer.parseInt( 1432 parser.getAttributeValue(null, ATTR_VALUE)); 1433 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) { 1434 specifiesGlobalProxy = Boolean.parseBoolean( 1435 parser.getAttributeValue(null, ATTR_VALUE)); 1436 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) { 1437 globalProxySpec = 1438 parser.getAttributeValue(null, ATTR_VALUE); 1439 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) { 1440 globalProxyExclusionList = 1441 parser.getAttributeValue(null, ATTR_VALUE); 1442 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) { 1443 passwordExpirationTimeout = Long.parseLong( 1444 parser.getAttributeValue(null, ATTR_VALUE)); 1445 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) { 1446 passwordExpirationDate = Long.parseLong( 1447 parser.getAttributeValue(null, ATTR_VALUE)); 1448 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) { 1449 encryptionRequested = Boolean.parseBoolean( 1450 parser.getAttributeValue(null, ATTR_VALUE)); 1451 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) { 1452 testOnlyAdmin = Boolean.parseBoolean( 1453 parser.getAttributeValue(null, ATTR_VALUE)); 1454 } else if (TAG_DISABLE_CAMERA.equals(tag)) { 1455 disableCamera = Boolean.parseBoolean( 1456 parser.getAttributeValue(null, ATTR_VALUE)); 1457 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) { 1458 disableCallerId = Boolean.parseBoolean( 1459 parser.getAttributeValue(null, ATTR_VALUE)); 1460 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) { 1461 disableContactsSearch = Boolean.parseBoolean( 1462 parser.getAttributeValue(null, ATTR_VALUE)); 1463 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) { 1464 disableBluetoothContactSharing = Boolean.parseBoolean(parser 1465 .getAttributeValue(null, ATTR_VALUE)); 1466 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) { 1467 disableScreenCapture = Boolean.parseBoolean( 1468 parser.getAttributeValue(null, ATTR_VALUE)); 1469 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) { 1470 requireAutoTime = Boolean.parseBoolean( 1471 parser.getAttributeValue(null, ATTR_VALUE)); 1472 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) { 1473 forceEphemeralUsers = Boolean.parseBoolean( 1474 parser.getAttributeValue(null, ATTR_VALUE)); 1475 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) { 1476 isNetworkLoggingEnabled = Boolean.parseBoolean( 1477 parser.getAttributeValue(null, ATTR_VALUE)); 1478 lastNetworkLoggingNotificationTimeMs = Long.parseLong( 1479 parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION)); 1480 numNetworkLoggingNotifications = Integer.parseInt( 1481 parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS)); 1482 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) { 1483 disabledKeyguardFeatures = Integer.parseInt( 1484 parser.getAttributeValue(null, ATTR_VALUE)); 1485 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) { 1486 readAttributeValues( 1487 parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled); 1488 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) { 1489 trustAgentInfos = getAllTrustAgentInfos(parser, tag); 1490 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) { 1491 crossProfileWidgetProviders = new ArrayList<>(); 1492 readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders); 1493 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) { 1494 permittedAccessiblityServices = readPackageList(parser, tag); 1495 } else if (TAG_PERMITTED_IMES.equals(tag)) { 1496 permittedInputMethods = readPackageList(parser, tag); 1497 } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) { 1498 permittedNotificationListeners = readPackageList(parser, tag); 1499 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) { 1500 keepUninstalledPackages = readPackageList(parser, tag); 1501 } else if (TAG_METERED_DATA_DISABLED_PACKAGES.equals(tag)) { 1502 meteredDisabledPackages = readPackageList(parser, tag); 1503 } else if (TAG_USER_RESTRICTIONS.equals(tag)) { 1504 userRestrictions = UserRestrictionsUtils.readRestrictions(parser); 1505 } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) { 1506 readAttributeValues( 1507 parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet); 1508 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) { 1509 type = parser.next(); 1510 if (type == XmlPullParser.TEXT) { 1511 shortSupportMessage = parser.getText(); 1512 } else { 1513 Log.w(LOG_TAG, "Missing text when loading short support message"); 1514 } 1515 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) { 1516 type = parser.next(); 1517 if (type == XmlPullParser.TEXT) { 1518 longSupportMessage = parser.getText(); 1519 } else { 1520 Log.w(LOG_TAG, "Missing text when loading long support message"); 1521 } 1522 } else if (TAG_PARENT_ADMIN.equals(tag)) { 1523 Preconditions.checkState(!isParent); 1524 parentAdmin = new ActiveAdmin(info, /* parent */ true); 1525 parentAdmin.readFromXml(parser, shouldOverridePolicies); 1526 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) { 1527 organizationColor = Integer.parseInt( 1528 parser.getAttributeValue(null, ATTR_VALUE)); 1529 } else if (TAG_ORGANIZATION_NAME.equals(tag)) { 1530 type = parser.next(); 1531 if (type == XmlPullParser.TEXT) { 1532 organizationName = parser.getText(); 1533 } else { 1534 Log.w(LOG_TAG, "Missing text when loading organization name"); 1535 } 1536 } else if (TAG_IS_LOGOUT_ENABLED.equals(tag)) { 1537 isLogoutEnabled = Boolean.parseBoolean( 1538 parser.getAttributeValue(null, ATTR_VALUE)); 1539 } else if (TAG_START_USER_SESSION_MESSAGE.equals(tag)) { 1540 type = parser.next(); 1541 if (type == XmlPullParser.TEXT) { 1542 startUserSessionMessage = parser.getText(); 1543 } else { 1544 Log.w(LOG_TAG, "Missing text when loading start session message"); 1545 } 1546 } else if (TAG_END_USER_SESSION_MESSAGE.equals(tag)) { 1547 type = parser.next(); 1548 if (type == XmlPullParser.TEXT) { 1549 endUserSessionMessage = parser.getText(); 1550 } else { 1551 Log.w(LOG_TAG, "Missing text when loading end session message"); 1552 } 1553 } else if (TAG_CROSS_PROFILE_CALENDAR_PACKAGES.equals(tag)) { 1554 mCrossProfileCalendarPackages = readPackageList(parser, tag); 1555 } else if (TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL.equals(tag)) { 1556 mCrossProfileCalendarPackages = null; 1557 } else { 1558 Slog.w(LOG_TAG, "Unknown admin tag: " + tag); 1559 XmlUtils.skipCurrentTag(parser); 1560 } 1561 } 1562 } 1563 readPackageList(XmlPullParser parser, String tag)1564 private List<String> readPackageList(XmlPullParser parser, 1565 String tag) throws XmlPullParserException, IOException { 1566 List<String> result = new ArrayList<String>(); 1567 int outerDepth = parser.getDepth(); 1568 int outerType; 1569 while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT 1570 && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1571 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) { 1572 continue; 1573 } 1574 String outerTag = parser.getName(); 1575 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) { 1576 String packageName = parser.getAttributeValue(null, ATTR_VALUE); 1577 if (packageName != null) { 1578 result.add(packageName); 1579 } else { 1580 Slog.w(LOG_TAG, "Package name missing under " + outerTag); 1581 } 1582 } else { 1583 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag); 1584 } 1585 } 1586 return result; 1587 } 1588 readAttributeValues( XmlPullParser parser, String tag, Collection<String> result)1589 private void readAttributeValues( 1590 XmlPullParser parser, String tag, Collection<String> result) 1591 throws XmlPullParserException, IOException { 1592 result.clear(); 1593 int outerDepthDAM = parser.getDepth(); 1594 int typeDAM; 1595 while ((typeDAM=parser.next()) != END_DOCUMENT 1596 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1597 if (typeDAM == END_TAG || typeDAM == TEXT) { 1598 continue; 1599 } 1600 String tagDAM = parser.getName(); 1601 if (tag.equals(tagDAM)) { 1602 result.add(parser.getAttributeValue(null, ATTR_VALUE)); 1603 } else { 1604 Slog.e(LOG_TAG, "Expected tag " + tag + " but found " + tagDAM); 1605 } 1606 } 1607 } 1608 getAllTrustAgentInfos( XmlPullParser parser, String tag)1609 private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos( 1610 XmlPullParser parser, String tag) throws XmlPullParserException, IOException { 1611 int outerDepthDAM = parser.getDepth(); 1612 int typeDAM; 1613 final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>(); 1614 while ((typeDAM=parser.next()) != END_DOCUMENT 1615 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1616 if (typeDAM == END_TAG || typeDAM == TEXT) { 1617 continue; 1618 } 1619 String tagDAM = parser.getName(); 1620 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) { 1621 final String component = parser.getAttributeValue(null, ATTR_VALUE); 1622 final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag); 1623 result.put(component, trustAgentInfo); 1624 } else { 1625 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 1626 } 1627 } 1628 return result; 1629 } 1630 getTrustAgentInfo(XmlPullParser parser, String tag)1631 private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag) 1632 throws XmlPullParserException, IOException { 1633 int outerDepthDAM = parser.getDepth(); 1634 int typeDAM; 1635 TrustAgentInfo result = new TrustAgentInfo(null); 1636 while ((typeDAM=parser.next()) != END_DOCUMENT 1637 && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1638 if (typeDAM == END_TAG || typeDAM == TEXT) { 1639 continue; 1640 } 1641 String tagDAM = parser.getName(); 1642 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) { 1643 result.options = PersistableBundle.restoreFromXml(parser); 1644 } else { 1645 Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 1646 } 1647 } 1648 return result; 1649 } 1650 hasUserRestrictions()1651 boolean hasUserRestrictions() { 1652 return userRestrictions != null && userRestrictions.size() > 0; 1653 } 1654 ensureUserRestrictions()1655 Bundle ensureUserRestrictions() { 1656 if (userRestrictions == null) { 1657 userRestrictions = new Bundle(); 1658 } 1659 return userRestrictions; 1660 } 1661 transfer(DeviceAdminInfo deviceAdminInfo)1662 public void transfer(DeviceAdminInfo deviceAdminInfo) { 1663 if (hasParentActiveAdmin()) { 1664 parentAdmin.info = deviceAdminInfo; 1665 } 1666 info = deviceAdminInfo; 1667 } 1668 dump(String prefix, PrintWriter pw)1669 void dump(String prefix, PrintWriter pw) { 1670 pw.print(prefix); pw.print("uid="); pw.println(getUid()); 1671 pw.print(prefix); pw.print("testOnlyAdmin="); 1672 pw.println(testOnlyAdmin); 1673 pw.print(prefix); pw.println("policies:"); 1674 ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies(); 1675 if (pols != null) { 1676 for (int i=0; i<pols.size(); i++) { 1677 pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag); 1678 } 1679 } 1680 pw.print(prefix); pw.print("passwordQuality=0x"); 1681 pw.println(Integer.toHexString(minimumPasswordMetrics.quality)); 1682 pw.print(prefix); pw.print("minimumPasswordLength="); 1683 pw.println(minimumPasswordMetrics.length); 1684 pw.print(prefix); pw.print("passwordHistoryLength="); 1685 pw.println(passwordHistoryLength); 1686 pw.print(prefix); pw.print("minimumPasswordUpperCase="); 1687 pw.println(minimumPasswordMetrics.upperCase); 1688 pw.print(prefix); pw.print("minimumPasswordLowerCase="); 1689 pw.println(minimumPasswordMetrics.lowerCase); 1690 pw.print(prefix); pw.print("minimumPasswordLetters="); 1691 pw.println(minimumPasswordMetrics.letters); 1692 pw.print(prefix); pw.print("minimumPasswordNumeric="); 1693 pw.println(minimumPasswordMetrics.numeric); 1694 pw.print(prefix); pw.print("minimumPasswordSymbols="); 1695 pw.println(minimumPasswordMetrics.symbols); 1696 pw.print(prefix); pw.print("minimumPasswordNonLetter="); 1697 pw.println(minimumPasswordMetrics.nonLetter); 1698 pw.print(prefix); pw.print("maximumTimeToUnlock="); 1699 pw.println(maximumTimeToUnlock); 1700 pw.print(prefix); pw.print("strongAuthUnlockTimeout="); 1701 pw.println(strongAuthUnlockTimeout); 1702 pw.print(prefix); pw.print("maximumFailedPasswordsForWipe="); 1703 pw.println(maximumFailedPasswordsForWipe); 1704 pw.print(prefix); pw.print("specifiesGlobalProxy="); 1705 pw.println(specifiesGlobalProxy); 1706 pw.print(prefix); pw.print("passwordExpirationTimeout="); 1707 pw.println(passwordExpirationTimeout); 1708 pw.print(prefix); pw.print("passwordExpirationDate="); 1709 pw.println(passwordExpirationDate); 1710 if (globalProxySpec != null) { 1711 pw.print(prefix); pw.print("globalProxySpec="); 1712 pw.println(globalProxySpec); 1713 } 1714 if (globalProxyExclusionList != null) { 1715 pw.print(prefix); pw.print("globalProxyEclusionList="); 1716 pw.println(globalProxyExclusionList); 1717 } 1718 pw.print(prefix); pw.print("encryptionRequested="); 1719 pw.println(encryptionRequested); 1720 pw.print(prefix); pw.print("disableCamera="); 1721 pw.println(disableCamera); 1722 pw.print(prefix); pw.print("disableCallerId="); 1723 pw.println(disableCallerId); 1724 pw.print(prefix); pw.print("disableContactsSearch="); 1725 pw.println(disableContactsSearch); 1726 pw.print(prefix); pw.print("disableBluetoothContactSharing="); 1727 pw.println(disableBluetoothContactSharing); 1728 pw.print(prefix); pw.print("disableScreenCapture="); 1729 pw.println(disableScreenCapture); 1730 pw.print(prefix); pw.print("requireAutoTime="); 1731 pw.println(requireAutoTime); 1732 pw.print(prefix); pw.print("forceEphemeralUsers="); 1733 pw.println(forceEphemeralUsers); 1734 pw.print(prefix); pw.print("isNetworkLoggingEnabled="); 1735 pw.println(isNetworkLoggingEnabled); 1736 pw.print(prefix); pw.print("disabledKeyguardFeatures="); 1737 pw.println(disabledKeyguardFeatures); 1738 pw.print(prefix); pw.print("crossProfileWidgetProviders="); 1739 pw.println(crossProfileWidgetProviders); 1740 if (permittedAccessiblityServices != null) { 1741 pw.print(prefix); pw.print("permittedAccessibilityServices="); 1742 pw.println(permittedAccessiblityServices); 1743 } 1744 if (permittedInputMethods != null) { 1745 pw.print(prefix); pw.print("permittedInputMethods="); 1746 pw.println(permittedInputMethods); 1747 } 1748 if (permittedNotificationListeners != null) { 1749 pw.print(prefix); pw.print("permittedNotificationListeners="); 1750 pw.println(permittedNotificationListeners); 1751 } 1752 if (keepUninstalledPackages != null) { 1753 pw.print(prefix); pw.print("keepUninstalledPackages="); 1754 pw.println(keepUninstalledPackages); 1755 } 1756 pw.print(prefix); pw.print("organizationColor="); 1757 pw.println(organizationColor); 1758 if (organizationName != null) { 1759 pw.print(prefix); pw.print("organizationName="); 1760 pw.println(organizationName); 1761 } 1762 pw.print(prefix); pw.println("userRestrictions:"); 1763 UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions); 1764 pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet="); 1765 pw.println(defaultEnabledRestrictionsAlreadySet); 1766 pw.print(prefix); pw.print("isParent="); 1767 pw.println(isParent); 1768 if (parentAdmin != null) { 1769 pw.print(prefix); pw.println("parentAdmin:"); 1770 parentAdmin.dump(prefix + " ", pw); 1771 } 1772 if (mCrossProfileCalendarPackages != null) { 1773 pw.print(prefix); pw.print("mCrossProfileCalendarPackages="); 1774 pw.println(mCrossProfileCalendarPackages); 1775 } 1776 } 1777 } 1778 handlePackagesChanged(@ullable String packageName, int userHandle)1779 private void handlePackagesChanged(@Nullable String packageName, int userHandle) { 1780 boolean removedAdmin = false; 1781 if (VERBOSE_LOG) { 1782 Slog.d(LOG_TAG, "Handling package changes package " + packageName 1783 + " for user " + userHandle); 1784 } 1785 DevicePolicyData policy = getUserData(userHandle); 1786 synchronized (getLockObject()) { 1787 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 1788 ActiveAdmin aa = policy.mAdminList.get(i); 1789 try { 1790 // If we're checking all packages or if the specific one we're checking matches, 1791 // then check if the package and receiver still exist. 1792 final String adminPackage = aa.info.getPackageName(); 1793 if (packageName == null || packageName.equals(adminPackage)) { 1794 if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null 1795 || mIPackageManager.getReceiverInfo(aa.info.getComponent(), 1796 PackageManager.MATCH_DIRECT_BOOT_AWARE 1797 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 1798 userHandle) == null) { 1799 removedAdmin = true; 1800 policy.mAdminList.remove(i); 1801 policy.mAdminMap.remove(aa.info.getComponent()); 1802 pushActiveAdminPackagesLocked(userHandle); 1803 pushMeteredDisabledPackagesLocked(userHandle); 1804 } 1805 } 1806 } catch (RemoteException re) { 1807 // Shouldn't happen. 1808 } 1809 } 1810 if (removedAdmin) { 1811 validatePasswordOwnerLocked(policy); 1812 } 1813 1814 boolean removedDelegate = false; 1815 1816 // Check if a delegate was removed. 1817 for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) { 1818 final String delegatePackage = policy.mDelegationMap.keyAt(i); 1819 if (isRemovedPackage(packageName, delegatePackage, userHandle)) { 1820 policy.mDelegationMap.removeAt(i); 1821 removedDelegate = true; 1822 } 1823 } 1824 1825 // If it's an owner package, we may need to refresh the bound connection. 1826 final ComponentName owner = getOwnerComponent(userHandle); 1827 if ((packageName != null) && (owner != null) 1828 && (owner.getPackageName().equals(packageName))) { 1829 startOwnerService(userHandle, "package-broadcast"); 1830 } 1831 1832 // Persist updates if the removed package was an admin or delegate. 1833 if (removedAdmin || removedDelegate) { 1834 saveSettingsLocked(policy.mUserHandle); 1835 } 1836 } 1837 if (removedAdmin) { 1838 // The removed admin might have disabled camera, so update user restrictions. 1839 pushUserRestrictions(userHandle); 1840 } 1841 } 1842 isRemovedPackage(String changedPackage, String targetPackage, int userHandle)1843 private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) { 1844 try { 1845 return targetPackage != null 1846 && (changedPackage == null || changedPackage.equals(targetPackage)) 1847 && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null; 1848 } catch (RemoteException e) { 1849 // Shouldn't happen 1850 } 1851 1852 return false; 1853 } 1854 1855 /** 1856 * Unit test will subclass it to inject mocks. 1857 */ 1858 @VisibleForTesting 1859 static class Injector { 1860 1861 public final Context mContext; 1862 Injector(Context context)1863 Injector(Context context) { 1864 mContext = context; 1865 } 1866 hasFeature()1867 public boolean hasFeature() { 1868 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN); 1869 } 1870 createContextAsUser(UserHandle user)1871 Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException { 1872 final String packageName = mContext.getPackageName(); 1873 return mContext.createPackageContextAsUser(packageName, 0, user); 1874 } 1875 getResources()1876 Resources getResources() { 1877 return mContext.getResources(); 1878 } 1879 newOwners()1880 Owners newOwners() { 1881 return new Owners(getUserManager(), getUserManagerInternal(), 1882 getPackageManagerInternal(), getActivityTaskManagerInternal()); 1883 } 1884 getUserManager()1885 UserManager getUserManager() { 1886 return UserManager.get(mContext); 1887 } 1888 getUserManagerInternal()1889 UserManagerInternal getUserManagerInternal() { 1890 return LocalServices.getService(UserManagerInternal.class); 1891 } 1892 getPackageManagerInternal()1893 PackageManagerInternal getPackageManagerInternal() { 1894 return LocalServices.getService(PackageManagerInternal.class); 1895 } 1896 getActivityTaskManagerInternal()1897 ActivityTaskManagerInternal getActivityTaskManagerInternal() { 1898 return LocalServices.getService(ActivityTaskManagerInternal.class); 1899 } 1900 getPermissionControllerManager( @onNull UserHandle user)1901 @NonNull PermissionControllerManager getPermissionControllerManager( 1902 @NonNull UserHandle user) { 1903 if (user.equals(mContext.getUser())) { 1904 return mContext.getSystemService(PermissionControllerManager.class); 1905 } else { 1906 try { 1907 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, 1908 user).getSystemService(PermissionControllerManager.class); 1909 } catch (NameNotFoundException notPossible) { 1910 // not possible 1911 throw new IllegalStateException(notPossible); 1912 } 1913 } 1914 } 1915 getUsageStatsManagerInternal()1916 UsageStatsManagerInternal getUsageStatsManagerInternal() { 1917 return LocalServices.getService(UsageStatsManagerInternal.class); 1918 } 1919 getNetworkPolicyManagerInternal()1920 NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() { 1921 return LocalServices.getService(NetworkPolicyManagerInternal.class); 1922 } 1923 getNotificationManager()1924 NotificationManager getNotificationManager() { 1925 return mContext.getSystemService(NotificationManager.class); 1926 } 1927 getIIpConnectivityMetrics()1928 IIpConnectivityMetrics getIIpConnectivityMetrics() { 1929 return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface( 1930 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME)); 1931 } 1932 getPackageManager()1933 PackageManager getPackageManager() { 1934 return mContext.getPackageManager(); 1935 } 1936 getPowerManagerInternal()1937 PowerManagerInternal getPowerManagerInternal() { 1938 return LocalServices.getService(PowerManagerInternal.class); 1939 } 1940 getTelephonyManager()1941 TelephonyManager getTelephonyManager() { 1942 return TelephonyManager.from(mContext); 1943 } 1944 getTrustManager()1945 TrustManager getTrustManager() { 1946 return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE); 1947 } 1948 getAlarmManager()1949 AlarmManager getAlarmManager() { 1950 return mContext.getSystemService(AlarmManager.class); 1951 } 1952 getConnectivityManager()1953 ConnectivityManager getConnectivityManager() { 1954 return mContext.getSystemService(ConnectivityManager.class); 1955 } 1956 getIWindowManager()1957 IWindowManager getIWindowManager() { 1958 return IWindowManager.Stub 1959 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)); 1960 } 1961 getIActivityManager()1962 IActivityManager getIActivityManager() { 1963 return ActivityManager.getService(); 1964 } 1965 getIActivityTaskManager()1966 IActivityTaskManager getIActivityTaskManager() { 1967 return ActivityTaskManager.getService(); 1968 } 1969 getActivityManagerInternal()1970 ActivityManagerInternal getActivityManagerInternal() { 1971 return LocalServices.getService(ActivityManagerInternal.class); 1972 } 1973 getIPackageManager()1974 IPackageManager getIPackageManager() { 1975 return AppGlobals.getPackageManager(); 1976 } 1977 getIBackupManager()1978 IBackupManager getIBackupManager() { 1979 return IBackupManager.Stub.asInterface( 1980 ServiceManager.getService(Context.BACKUP_SERVICE)); 1981 } 1982 getIAudioService()1983 IAudioService getIAudioService() { 1984 return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE)); 1985 } 1986 isBuildDebuggable()1987 boolean isBuildDebuggable() { 1988 return Build.IS_DEBUGGABLE; 1989 } 1990 newLockPatternUtils()1991 LockPatternUtils newLockPatternUtils() { 1992 return new LockPatternUtils(mContext); 1993 } 1994 storageManagerIsFileBasedEncryptionEnabled()1995 boolean storageManagerIsFileBasedEncryptionEnabled() { 1996 return StorageManager.isFileEncryptedNativeOnly(); 1997 } 1998 storageManagerIsNonDefaultBlockEncrypted()1999 boolean storageManagerIsNonDefaultBlockEncrypted() { 2000 long identity = Binder.clearCallingIdentity(); 2001 try { 2002 return StorageManager.isNonDefaultBlockEncrypted(); 2003 } finally { 2004 Binder.restoreCallingIdentity(identity); 2005 } 2006 } 2007 storageManagerIsEncrypted()2008 boolean storageManagerIsEncrypted() { 2009 return StorageManager.isEncrypted(); 2010 } 2011 storageManagerIsEncryptable()2012 boolean storageManagerIsEncryptable() { 2013 return StorageManager.isEncryptable(); 2014 } 2015 getMyLooper()2016 Looper getMyLooper() { 2017 return Looper.myLooper(); 2018 } 2019 getWifiManager()2020 WifiManager getWifiManager() { 2021 return mContext.getSystemService(WifiManager.class); 2022 } 2023 binderClearCallingIdentity()2024 long binderClearCallingIdentity() { 2025 return Binder.clearCallingIdentity(); 2026 } 2027 binderRestoreCallingIdentity(long token)2028 void binderRestoreCallingIdentity(long token) { 2029 Binder.restoreCallingIdentity(token); 2030 } 2031 binderGetCallingUid()2032 int binderGetCallingUid() { 2033 return Binder.getCallingUid(); 2034 } 2035 binderGetCallingPid()2036 int binderGetCallingPid() { 2037 return Binder.getCallingPid(); 2038 } 2039 binderGetCallingUserHandle()2040 UserHandle binderGetCallingUserHandle() { 2041 return Binder.getCallingUserHandle(); 2042 } 2043 binderIsCallingUidMyUid()2044 boolean binderIsCallingUidMyUid() { 2045 return getCallingUid() == Process.myUid(); 2046 } 2047 binderWithCleanCallingIdentity(@onNull ThrowingRunnable action)2048 void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) { 2049 Binder.withCleanCallingIdentity(action); 2050 } 2051 userHandleGetCallingUserId()2052 final int userHandleGetCallingUserId() { 2053 return UserHandle.getUserId(binderGetCallingUid()); 2054 } 2055 environmentGetUserSystemDirectory(int userId)2056 File environmentGetUserSystemDirectory(int userId) { 2057 return Environment.getUserSystemDirectory(userId); 2058 } 2059 powerManagerGoToSleep(long time, int reason, int flags)2060 void powerManagerGoToSleep(long time, int reason, int flags) { 2061 mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags); 2062 } 2063 powerManagerReboot(String reason)2064 void powerManagerReboot(String reason) { 2065 mContext.getSystemService(PowerManager.class).reboot(reason); 2066 } 2067 recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, boolean wipeEuicc)2068 void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, 2069 boolean wipeEuicc) throws IOException { 2070 RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc); 2071 } 2072 systemPropertiesGetBoolean(String key, boolean def)2073 boolean systemPropertiesGetBoolean(String key, boolean def) { 2074 return SystemProperties.getBoolean(key, def); 2075 } 2076 systemPropertiesGetLong(String key, long def)2077 long systemPropertiesGetLong(String key, long def) { 2078 return SystemProperties.getLong(key, def); 2079 } 2080 systemPropertiesGet(String key, String def)2081 String systemPropertiesGet(String key, String def) { 2082 return SystemProperties.get(key, def); 2083 } 2084 systemPropertiesGet(String key)2085 String systemPropertiesGet(String key) { 2086 return SystemProperties.get(key); 2087 } 2088 systemPropertiesSet(String key, String value)2089 void systemPropertiesSet(String key, String value) { 2090 SystemProperties.set(key, value); 2091 } 2092 userManagerIsSplitSystemUser()2093 boolean userManagerIsSplitSystemUser() { 2094 return UserManager.isSplitSystemUser(); 2095 } 2096 getDevicePolicyFilePathForSystemUser()2097 String getDevicePolicyFilePathForSystemUser() { 2098 return "/data/system/"; 2099 } 2100 pendingIntentGetActivityAsUser(Context context, int requestCode, @NonNull Intent intent, int flags, Bundle options, UserHandle user)2101 PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode, 2102 @NonNull Intent intent, int flags, Bundle options, UserHandle user) { 2103 return PendingIntent.getActivityAsUser( 2104 context, requestCode, intent, flags, options, user); 2105 } 2106 registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer, int userHandle)2107 void registerContentObserver(Uri uri, boolean notifyForDescendents, 2108 ContentObserver observer, int userHandle) { 2109 mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents, 2110 observer, userHandle); 2111 } 2112 settingsSecureGetIntForUser(String name, int def, int userHandle)2113 int settingsSecureGetIntForUser(String name, int def, int userHandle) { 2114 return Settings.Secure.getIntForUser(mContext.getContentResolver(), 2115 name, def, userHandle); 2116 } 2117 settingsSecureGetStringForUser(String name, int userHandle)2118 String settingsSecureGetStringForUser(String name, int userHandle) { 2119 return Settings.Secure.getStringForUser(mContext.getContentResolver(), name, 2120 userHandle); 2121 } 2122 settingsSecurePutIntForUser(String name, int value, int userHandle)2123 void settingsSecurePutIntForUser(String name, int value, int userHandle) { 2124 Settings.Secure.putIntForUser(mContext.getContentResolver(), 2125 name, value, userHandle); 2126 } 2127 settingsSecurePutStringForUser(String name, String value, int userHandle)2128 void settingsSecurePutStringForUser(String name, String value, int userHandle) { 2129 Settings.Secure.putStringForUser(mContext.getContentResolver(), 2130 name, value, userHandle); 2131 } 2132 settingsGlobalPutStringForUser(String name, String value, int userHandle)2133 void settingsGlobalPutStringForUser(String name, String value, int userHandle) { 2134 Settings.Global.putStringForUser(mContext.getContentResolver(), 2135 name, value, userHandle); 2136 } 2137 settingsSecurePutInt(String name, int value)2138 void settingsSecurePutInt(String name, int value) { 2139 Settings.Secure.putInt(mContext.getContentResolver(), name, value); 2140 } 2141 settingsGlobalGetInt(String name, int def)2142 int settingsGlobalGetInt(String name, int def) { 2143 return Settings.Global.getInt(mContext.getContentResolver(), name, def); 2144 } 2145 2146 @Nullable settingsGlobalGetString(String name)2147 String settingsGlobalGetString(String name) { 2148 return Settings.Global.getString(mContext.getContentResolver(), name); 2149 } 2150 settingsGlobalPutInt(String name, int value)2151 void settingsGlobalPutInt(String name, int value) { 2152 Settings.Global.putInt(mContext.getContentResolver(), name, value); 2153 } 2154 settingsSecurePutString(String name, String value)2155 void settingsSecurePutString(String name, String value) { 2156 Settings.Secure.putString(mContext.getContentResolver(), name, value); 2157 } 2158 settingsGlobalPutString(String name, String value)2159 void settingsGlobalPutString(String name, String value) { 2160 Settings.Global.putString(mContext.getContentResolver(), name, value); 2161 } 2162 settingsSystemPutStringForUser(String name, String value, int userId)2163 void settingsSystemPutStringForUser(String name, String value, int userId) { 2164 Settings.System.putStringForUser( 2165 mContext.getContentResolver(), name, value, userId); 2166 } 2167 securityLogSetLoggingEnabledProperty(boolean enabled)2168 void securityLogSetLoggingEnabledProperty(boolean enabled) { 2169 SecurityLog.setLoggingEnabledProperty(enabled); 2170 } 2171 securityLogGetLoggingEnabledProperty()2172 boolean securityLogGetLoggingEnabledProperty() { 2173 return SecurityLog.getLoggingEnabledProperty(); 2174 } 2175 securityLogIsLoggingEnabled()2176 boolean securityLogIsLoggingEnabled() { 2177 return SecurityLog.isLoggingEnabled(); 2178 } 2179 keyChainBindAsUser(UserHandle user)2180 KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException { 2181 return KeyChain.bindAsUser(mContext, user); 2182 } 2183 postOnSystemServerInitThreadPool(Runnable runnable)2184 void postOnSystemServerInitThreadPool(Runnable runnable) { 2185 SystemServerInitThreadPool.get().submit(runnable, LOG_TAG); 2186 } 2187 newTransferOwnershipMetadataManager()2188 public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() { 2189 return new TransferOwnershipMetadataManager(); 2190 } 2191 runCryptoSelfTest()2192 public void runCryptoSelfTest() { 2193 CryptoTestHelper.runAndLogSelfTest(); 2194 } 2195 } 2196 2197 /** 2198 * Instantiates the service. 2199 */ DevicePolicyManagerService(Context context)2200 public DevicePolicyManagerService(Context context) { 2201 this(new Injector(context)); 2202 } 2203 2204 @VisibleForTesting DevicePolicyManagerService(Injector injector)2205 DevicePolicyManagerService(Injector injector) { 2206 mInjector = injector; 2207 mContext = Preconditions.checkNotNull(injector.mContext); 2208 mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper())); 2209 2210 mConstantsObserver = new DevicePolicyConstantsObserver(mHandler); 2211 mConstantsObserver.register(); 2212 mConstants = loadConstants(); 2213 2214 mOwners = Preconditions.checkNotNull(injector.newOwners()); 2215 2216 mUserManager = Preconditions.checkNotNull(injector.getUserManager()); 2217 mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal()); 2218 mUsageStatsManagerInternal = Preconditions.checkNotNull( 2219 injector.getUsageStatsManagerInternal()); 2220 mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager()); 2221 mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager()); 2222 2223 mLocalService = new LocalService(); 2224 mLockPatternUtils = injector.newLockPatternUtils(); 2225 2226 // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false? 2227 mSecurityLogMonitor = new SecurityLogMonitor(this); 2228 2229 mHasFeature = mInjector.hasFeature(); 2230 mIsWatch = mInjector.getPackageManager() 2231 .hasSystemFeature(PackageManager.FEATURE_WATCH); 2232 mHasTelephonyFeature = mInjector.getPackageManager() 2233 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY); 2234 mBackgroundHandler = BackgroundThread.getHandler(); 2235 2236 // Needed when mHasFeature == false, because it controls the certificate warning text. 2237 mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler); 2238 2239 mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants); 2240 2241 mOverlayPackagesProvider = new OverlayPackagesProvider(mContext); 2242 2243 mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager(); 2244 2245 if (!mHasFeature) { 2246 // Skip the rest of the initialization 2247 mSetupContentObserver = null; 2248 return; 2249 } 2250 2251 IntentFilter filter = new IntentFilter(); 2252 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 2253 filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION); 2254 filter.addAction(Intent.ACTION_USER_ADDED); 2255 filter.addAction(Intent.ACTION_USER_REMOVED); 2256 filter.addAction(Intent.ACTION_USER_STARTED); 2257 filter.addAction(Intent.ACTION_USER_STOPPED); 2258 filter.addAction(Intent.ACTION_USER_SWITCHED); 2259 filter.addAction(Intent.ACTION_USER_UNLOCKED); 2260 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 2261 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 2262 filter = new IntentFilter(); 2263 filter.addAction(Intent.ACTION_PACKAGE_CHANGED); 2264 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 2265 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 2266 filter.addAction(Intent.ACTION_PACKAGE_ADDED); 2267 filter.addDataScheme("package"); 2268 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 2269 filter = new IntentFilter(); 2270 filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED); 2271 filter.addAction(Intent.ACTION_TIME_CHANGED); 2272 filter.addAction(Intent.ACTION_DATE_CHANGED); 2273 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 2274 2275 LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService); 2276 2277 mSetupContentObserver = new SetupContentObserver(mHandler); 2278 2279 mUserManagerInternal.addUserRestrictionsListener(new RestrictionsListener(mContext)); 2280 } 2281 2282 /** 2283 * Creates and loads the policy data from xml. 2284 * @param userHandle the user for whom to load the policy data 2285 * @return 2286 */ 2287 @NonNull getUserData(int userHandle)2288 DevicePolicyData getUserData(int userHandle) { 2289 synchronized (getLockObject()) { 2290 DevicePolicyData policy = mUserData.get(userHandle); 2291 if (policy == null) { 2292 policy = new DevicePolicyData(userHandle); 2293 mUserData.append(userHandle, policy); 2294 loadSettingsLocked(policy, userHandle); 2295 } 2296 return policy; 2297 } 2298 } 2299 2300 /** 2301 * Provides PasswordMetrics object corresponding to the given user. 2302 * @param userHandle the user for whom to provide metrics. 2303 * @return the user password metrics, or {@code null} if none have been associated with 2304 * the user yet (for example, if the device has booted but not been unlocked). 2305 */ 2306 @GuardedBy("getLockObject()") getUserPasswordMetricsLocked(int userHandle)2307 PasswordMetrics getUserPasswordMetricsLocked(int userHandle) { 2308 return mUserPasswordMetrics.get(userHandle); 2309 } 2310 2311 /** 2312 * Creates and loads the policy data from xml for data that is shared between 2313 * various profiles of a user. In contrast to {@link #getUserData(int)} 2314 * it allows access to data of users other than the calling user. 2315 * 2316 * This function should only be used for shared data, e.g. everything regarding 2317 * passwords and should be removed once multiple screen locks are present. 2318 * @param userHandle the user for whom to load the policy data 2319 * @return 2320 */ getUserDataUnchecked(int userHandle)2321 DevicePolicyData getUserDataUnchecked(int userHandle) { 2322 long ident = mInjector.binderClearCallingIdentity(); 2323 try { 2324 return getUserData(userHandle); 2325 } finally { 2326 mInjector.binderRestoreCallingIdentity(ident); 2327 } 2328 } 2329 removeUserData(int userHandle)2330 void removeUserData(int userHandle) { 2331 synchronized (getLockObject()) { 2332 if (userHandle == UserHandle.USER_SYSTEM) { 2333 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring."); 2334 return; 2335 } 2336 updatePasswordQualityCacheForUserGroup(userHandle); 2337 mPolicyCache.onUserRemoved(userHandle); 2338 mOwners.removeProfileOwner(userHandle); 2339 mOwners.writeProfileOwner(userHandle); 2340 2341 DevicePolicyData policy = mUserData.get(userHandle); 2342 if (policy != null) { 2343 mUserData.remove(userHandle); 2344 } 2345 if (mUserPasswordMetrics.get(userHandle) != null) { 2346 mUserPasswordMetrics.remove(userHandle); 2347 } 2348 2349 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle), 2350 DEVICE_POLICIES_XML); 2351 policyFile.delete(); 2352 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath()); 2353 } 2354 } 2355 loadOwners()2356 void loadOwners() { 2357 synchronized (getLockObject()) { 2358 mOwners.load(); 2359 setDeviceOwnerSystemPropertyLocked(); 2360 findOwnerComponentIfNecessaryLocked(); 2361 migrateUserRestrictionsIfNecessaryLocked(); 2362 maybeSetDefaultDeviceOwnerUserRestrictionsLocked(); 2363 2364 // TODO PO may not have a class name either due to b/17652534. Address that too. 2365 2366 updateDeviceOwnerLocked(); 2367 } 2368 } 2369 2370 /** Apply default restrictions that haven't been applied to device owners yet. */ maybeSetDefaultDeviceOwnerUserRestrictionsLocked()2371 private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() { 2372 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 2373 if (deviceOwner != null) { 2374 maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(), 2375 deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner()); 2376 } 2377 } 2378 2379 /** Apply default restrictions that haven't been applied to profile owners yet. */ maybeSetDefaultProfileOwnerUserRestrictions()2380 private void maybeSetDefaultProfileOwnerUserRestrictions() { 2381 synchronized (getLockObject()) { 2382 for (final int userId : mOwners.getProfileOwnerKeys()) { 2383 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 2384 // The following restrictions used to be applied to managed profiles by different 2385 // means (via Settings or by disabling components). Now they are proper user 2386 // restrictions so we apply them to managed profile owners. Non-managed secondary 2387 // users didn't have those restrictions so we skip them to keep existing behavior. 2388 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) { 2389 continue; 2390 } 2391 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner, 2392 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 2393 ensureUnknownSourcesRestrictionForProfileOwnerLocked( 2394 userId, profileOwner, false /* newOwner */); 2395 } 2396 } 2397 } 2398 2399 /** 2400 * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the 2401 * set of restrictions for this profile owner. 2402 */ ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, ActiveAdmin profileOwner, boolean newOwner)2403 private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, 2404 ActiveAdmin profileOwner, boolean newOwner) { 2405 if (newOwner || mInjector.settingsSecureGetIntForUser( 2406 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) { 2407 profileOwner.ensureUserRestrictions().putBoolean( 2408 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true); 2409 saveUserRestrictionsLocked(userId); 2410 mInjector.settingsSecurePutIntForUser( 2411 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId); 2412 } 2413 } 2414 2415 /** 2416 * Apply default restrictions that haven't been applied to a given admin yet. 2417 */ maybeSetDefaultRestrictionsForAdminLocked( int userId, ActiveAdmin admin, Set<String> defaultRestrictions)2418 private void maybeSetDefaultRestrictionsForAdminLocked( 2419 int userId, ActiveAdmin admin, Set<String> defaultRestrictions) { 2420 if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) { 2421 return; // The same set of default restrictions has been already applied. 2422 } 2423 Slog.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId); 2424 2425 if (VERBOSE_LOG) { 2426 Slog.d(LOG_TAG,"Default enabled restrictions: " 2427 + defaultRestrictions 2428 + ". Restrictions already enabled: " 2429 + admin.defaultEnabledRestrictionsAlreadySet); 2430 } 2431 2432 final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions); 2433 restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet); 2434 if (!restrictionsToSet.isEmpty()) { 2435 for (final String restriction : restrictionsToSet) { 2436 admin.ensureUserRestrictions().putBoolean(restriction, true); 2437 } 2438 admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet); 2439 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet); 2440 saveUserRestrictionsLocked(userId); 2441 } 2442 } 2443 setDeviceOwnerSystemPropertyLocked()2444 private void setDeviceOwnerSystemPropertyLocked() { 2445 final boolean deviceProvisioned = 2446 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0; 2447 final boolean hasDeviceOwner = mOwners.hasDeviceOwner(); 2448 // If the device is not provisioned and there is currently no device owner, do not set the 2449 // read-only system property yet, since Device owner may still be provisioned. 2450 if (!hasDeviceOwner && !deviceProvisioned) { 2451 return; 2452 } 2453 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is 2454 // always false at this point. 2455 if (StorageManager.inCryptKeeperBounce()) { 2456 return; 2457 } 2458 2459 if (!mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT, "").isEmpty()) { 2460 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?"); 2461 } else { 2462 final String value = Boolean.toString(hasDeviceOwner); 2463 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, value); 2464 Slog.i(LOG_TAG, "Set ro.device_owner property to " + value); 2465 } 2466 } 2467 maybeStartSecurityLogMonitorOnActivityManagerReady()2468 private void maybeStartSecurityLogMonitorOnActivityManagerReady() { 2469 synchronized (getLockObject()) { 2470 if (mInjector.securityLogIsLoggingEnabled()) { 2471 mSecurityLogMonitor.start(); 2472 mInjector.runCryptoSelfTest(); 2473 maybePauseDeviceWideLoggingLocked(); 2474 } 2475 } 2476 } 2477 findOwnerComponentIfNecessaryLocked()2478 private void findOwnerComponentIfNecessaryLocked() { 2479 if (!mOwners.hasDeviceOwner()) { 2480 return; 2481 } 2482 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent(); 2483 2484 if (!TextUtils.isEmpty(doComponentName.getClassName())) { 2485 return; // Already a full component name. 2486 } 2487 2488 final ComponentName doComponent = findAdminComponentWithPackageLocked( 2489 doComponentName.getPackageName(), 2490 mOwners.getDeviceOwnerUserId()); 2491 if (doComponent == null) { 2492 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin"); 2493 } else { 2494 mOwners.setDeviceOwnerWithRestrictionsMigrated( 2495 doComponent, 2496 mOwners.getDeviceOwnerName(), 2497 mOwners.getDeviceOwnerUserId(), 2498 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()); 2499 mOwners.writeDeviceOwner(); 2500 if (VERBOSE_LOG) { 2501 Log.v(LOG_TAG, "Device owner component filled in"); 2502 } 2503 } 2504 } 2505 2506 /** 2507 * We didn't use to persist user restrictions for each owners but only persisted in user 2508 * manager. 2509 */ migrateUserRestrictionsIfNecessaryLocked()2510 private void migrateUserRestrictionsIfNecessaryLocked() { 2511 boolean migrated = false; 2512 // Migrate for the DO. Basically all restrictions should be considered to be set by DO, 2513 // except for the "system controlled" ones. 2514 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) { 2515 if (VERBOSE_LOG) { 2516 Log.v(LOG_TAG, "Migrating DO user restrictions"); 2517 } 2518 migrated = true; 2519 2520 // Migrate user 0 restrictions to DO. 2521 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 2522 2523 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin, 2524 /* exceptionList =*/ null, /* isDeviceOwner =*/ true); 2525 2526 // Push DO user restrictions to user manager. 2527 pushUserRestrictions(UserHandle.USER_SYSTEM); 2528 2529 mOwners.setDeviceOwnerUserRestrictionsMigrated(); 2530 } 2531 2532 // Migrate for POs. 2533 2534 // The following restrictions can be set on secondary users by the device owner, so we 2535 // assume they're not from the PO. 2536 final Set<String> secondaryUserExceptionList = Sets.newArraySet( 2537 UserManager.DISALLOW_OUTGOING_CALLS, 2538 UserManager.DISALLOW_SMS); 2539 2540 for (UserInfo ui : mUserManager.getUsers()) { 2541 final int userId = ui.id; 2542 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) { 2543 if (VERBOSE_LOG) { 2544 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId); 2545 } 2546 migrated = true; 2547 2548 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId); 2549 2550 final Set<String> exceptionList = 2551 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList; 2552 2553 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin, 2554 exceptionList, /* isDeviceOwner =*/ false); 2555 2556 // Note if a secondary user has no PO but has a DA that disables camera, we 2557 // don't get here and won't push the camera user restriction to UserManager 2558 // here. That's okay because we'll push user restrictions anyway when a user 2559 // starts. But we still do it because we want to let user manager persist 2560 // upon migration. 2561 pushUserRestrictions(userId); 2562 2563 mOwners.setProfileOwnerUserRestrictionsMigrated(userId); 2564 } 2565 } 2566 if (VERBOSE_LOG && migrated) { 2567 Log.v(LOG_TAG, "User restrictions migrated."); 2568 } 2569 } 2570 migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, Set<String> exceptionList, boolean isDeviceOwner)2571 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, 2572 Set<String> exceptionList, boolean isDeviceOwner) { 2573 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions( 2574 user.getIdentifier()); 2575 2576 final Bundle newBaseRestrictions = new Bundle(); 2577 final Bundle newOwnerRestrictions = new Bundle(); 2578 2579 for (String key : origRestrictions.keySet()) { 2580 if (!origRestrictions.getBoolean(key)) { 2581 continue; 2582 } 2583 final boolean canOwnerChange = isDeviceOwner 2584 ? UserRestrictionsUtils.canDeviceOwnerChange(key) 2585 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier()); 2586 2587 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) { 2588 newBaseRestrictions.putBoolean(key, true); 2589 } else { 2590 newOwnerRestrictions.putBoolean(key, true); 2591 } 2592 } 2593 2594 if (VERBOSE_LOG) { 2595 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions); 2596 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions); 2597 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions); 2598 } 2599 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(), 2600 newBaseRestrictions); 2601 2602 if (admin != null) { 2603 admin.ensureUserRestrictions().clear(); 2604 admin.ensureUserRestrictions().putAll(newOwnerRestrictions); 2605 } else { 2606 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier()); 2607 } 2608 saveSettingsLocked(user.getIdentifier()); 2609 } 2610 findAdminComponentWithPackageLocked(String packageName, int userId)2611 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) { 2612 final DevicePolicyData policy = getUserData(userId); 2613 final int n = policy.mAdminList.size(); 2614 ComponentName found = null; 2615 int nFound = 0; 2616 for (int i = 0; i < n; i++) { 2617 final ActiveAdmin admin = policy.mAdminList.get(i); 2618 if (packageName.equals(admin.info.getPackageName())) { 2619 // Found! 2620 if (nFound == 0) { 2621 found = admin.info.getComponent(); 2622 } 2623 nFound++; 2624 } 2625 } 2626 if (nFound > 1) { 2627 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO."); 2628 } 2629 return found; 2630 } 2631 2632 /** 2633 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration 2634 * reminders. Clears alarm if no expirations are configured. 2635 */ setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent)2636 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) { 2637 final long expiration = getPasswordExpirationLocked(null, userHandle, parent); 2638 final long now = System.currentTimeMillis(); 2639 final long timeToExpire = expiration - now; 2640 final long alarmTime; 2641 if (expiration == 0) { 2642 // No expirations are currently configured: Cancel alarm. 2643 alarmTime = 0; 2644 } else if (timeToExpire <= 0) { 2645 // The password has already expired: Repeat every 24 hours. 2646 alarmTime = now + MS_PER_DAY; 2647 } else { 2648 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before 2649 // the expiration time. 2650 long alarmInterval = timeToExpire % MS_PER_DAY; 2651 if (alarmInterval == 0) { 2652 alarmInterval = MS_PER_DAY; 2653 } 2654 alarmTime = now + alarmInterval; 2655 } 2656 2657 long token = mInjector.binderClearCallingIdentity(); 2658 try { 2659 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle; 2660 AlarmManager am = mInjector.getAlarmManager(); 2661 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD, 2662 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION), 2663 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT, 2664 UserHandle.of(affectedUserHandle)); 2665 am.cancel(pi); 2666 if (alarmTime != 0) { 2667 am.set(AlarmManager.RTC, alarmTime, pi); 2668 } 2669 } finally { 2670 mInjector.binderRestoreCallingIdentity(token); 2671 } 2672 } 2673 getActiveAdminUncheckedLocked(ComponentName who, int userHandle)2674 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) { 2675 ensureLocked(); 2676 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who); 2677 if (admin != null 2678 && who.getPackageName().equals(admin.info.getActivityInfo().packageName) 2679 && who.getClassName().equals(admin.info.getActivityInfo().name)) { 2680 return admin; 2681 } 2682 return null; 2683 } 2684 getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent)2685 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) { 2686 ensureLocked(); 2687 if (parent) { 2688 enforceManagedProfile(userHandle, "call APIs on the parent profile"); 2689 } 2690 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2691 if (admin != null && parent) { 2692 admin = admin.getParentActiveAdmin(); 2693 } 2694 return admin; 2695 } 2696 getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)2697 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy) 2698 throws SecurityException { 2699 return getActiveAdminOrCheckPermissionForCallerLocked(who, 2700 reqPolicy, /* permission= */ null); 2701 } 2702 2703 /** 2704 * Finds an active admin for the caller then checks {@code permission} if admin check failed. 2705 * 2706 * @return an active admin or {@code null} if there is no active admin but 2707 * {@code permission} is granted 2708 * @throws SecurityException if caller neither has an active admin nor {@code permission} 2709 */ 2710 @Nullable getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, @Nullable String permission)2711 ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked( 2712 ComponentName who, 2713 int reqPolicy, 2714 @Nullable String permission) throws SecurityException { 2715 ensureLocked(); 2716 final int callingUid = mInjector.binderGetCallingUid(); 2717 2718 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid); 2719 if (result != null) { 2720 return result; 2721 } else if (permission != null 2722 && (mContext.checkCallingPermission(permission) 2723 == PackageManager.PERMISSION_GRANTED)) { 2724 return null; 2725 } 2726 2727 if (who != null) { 2728 final int userId = UserHandle.getUserId(callingUid); 2729 final DevicePolicyData policy = getUserData(userId); 2730 ActiveAdmin admin = policy.mAdminMap.get(who); 2731 final boolean isDeviceOwner = isDeviceOwner(admin.info.getComponent(), userId); 2732 final boolean isProfileOwner = isProfileOwner(admin.info.getComponent(), userId); 2733 2734 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) { 2735 throw new SecurityException("Admin " + admin.info.getComponent() 2736 + " does not own the device"); 2737 } 2738 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) { 2739 throw new SecurityException("Admin " + admin.info.getComponent() 2740 + " does not own the profile"); 2741 } 2742 if (DA_DISALLOWED_POLICIES.contains(reqPolicy) && !isDeviceOwner && !isProfileOwner) { 2743 throw new SecurityException("Admin " + admin.info.getComponent() 2744 + " is not a device owner or profile owner, so may not use policy: " 2745 + admin.info.getTagForPolicy(reqPolicy)); 2746 } 2747 throw new SecurityException("Admin " + admin.info.getComponent() 2748 + " did not specify uses-policy for: " 2749 + admin.info.getTagForPolicy(reqPolicy)); 2750 } else { 2751 throw new SecurityException("No active admin owned by uid " 2752 + callingUid + " for policy #" + reqPolicy); 2753 } 2754 } 2755 getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)2756 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent) 2757 throws SecurityException { 2758 return getActiveAdminOrCheckPermissionForCallerLocked( 2759 who, reqPolicy, parent, /* permission= */ null); 2760 } 2761 2762 /** 2763 * Finds an active admin for the caller then checks {@code permission} if admin check failed. 2764 * 2765 * @return an active admin or {@code null} if there is no active admin but 2766 * {@code permission} is granted 2767 * @throws SecurityException if caller neither has an active admin nor {@code permission} 2768 */ 2769 @Nullable getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, boolean parent, @Nullable String permission)2770 ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked( 2771 ComponentName who, 2772 int reqPolicy, 2773 boolean parent, 2774 @Nullable String permission) throws SecurityException { 2775 ensureLocked(); 2776 if (parent) { 2777 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), 2778 "call APIs on the parent profile"); 2779 } 2780 ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked( 2781 who, reqPolicy, permission); 2782 return parent ? admin.getParentActiveAdmin() : admin; 2783 } 2784 2785 /** 2786 * Find the admin for the component and userId bit of the uid, then check 2787 * the admin's uid matches the uid. 2788 */ getActiveAdminForUidLocked(ComponentName who, int uid)2789 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) { 2790 ensureLocked(); 2791 final int userId = UserHandle.getUserId(uid); 2792 final DevicePolicyData policy = getUserData(userId); 2793 ActiveAdmin admin = policy.mAdminMap.get(who); 2794 if (admin == null) { 2795 throw new SecurityException("No active admin " + who + " for UID " + uid); 2796 } 2797 if (admin.getUid() != uid) { 2798 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2799 } 2800 return admin; 2801 } 2802 2803 /** 2804 * Returns the active admin for the user of the caller as denoted by uid, which implements 2805 * the {@code reqPolicy}. 2806 * 2807 * The {@code who} parameter is used as a hint: 2808 * If provided, it must be the component name of the active admin for that user and the caller 2809 * uid must match the uid of the admin. 2810 * If not provided, iterate over all of the active admins in the DevicePolicyData for that user 2811 * and return the one with the uid specified as parameter, and has the policy specified. 2812 */ getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, int uid)2813 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, 2814 int uid) { 2815 ensureLocked(); 2816 // Try to find an admin which can use reqPolicy 2817 final int userId = UserHandle.getUserId(uid); 2818 final DevicePolicyData policy = getUserData(userId); 2819 if (who != null) { 2820 ActiveAdmin admin = policy.mAdminMap.get(who); 2821 if (admin == null) { 2822 throw new SecurityException("No active admin " + who); 2823 } 2824 if (admin.getUid() != uid) { 2825 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2826 } 2827 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) { 2828 return admin; 2829 } 2830 } else { 2831 for (ActiveAdmin admin : policy.mAdminList) { 2832 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, 2833 userId)) { 2834 return admin; 2835 } 2836 } 2837 } 2838 2839 return null; 2840 } 2841 2842 @VisibleForTesting isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, int userId)2843 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, 2844 int userId) { 2845 ensureLocked(); 2846 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId); 2847 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId); 2848 2849 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) { 2850 return ownsDevice; 2851 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) { 2852 // DO always has the PO power. 2853 return ownsDevice || ownsProfile; 2854 } else { 2855 boolean allowedToUsePolicy = ownsDevice || ownsProfile 2856 || !DA_DISALLOWED_POLICIES.contains(reqPolicy) 2857 || getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.Q; 2858 return allowedToUsePolicy && admin.info.usesPolicy(reqPolicy); 2859 } 2860 } 2861 2862 void sendAdminCommandLocked(ActiveAdmin admin, String action) { 2863 sendAdminCommandLocked(admin, action, null); 2864 } 2865 2866 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) { 2867 sendAdminCommandLocked(admin, action, null, result); 2868 } 2869 2870 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2871 BroadcastReceiver result) { 2872 sendAdminCommandLocked(admin, action, adminExtras, result, false); 2873 } 2874 2875 /** 2876 * Send an update to one specific admin, get notified when that admin returns a result. 2877 * 2878 * @return whether the broadcast was successfully sent 2879 */ 2880 boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2881 BroadcastReceiver result, boolean inForeground) { 2882 Intent intent = new Intent(action); 2883 intent.setComponent(admin.info.getComponent()); 2884 if (UserManager.isDeviceInDemoMode(mContext)) { 2885 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2886 } 2887 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) { 2888 intent.putExtra("expiration", admin.passwordExpirationDate); 2889 } 2890 if (inForeground) { 2891 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 2892 } 2893 if (adminExtras != null) { 2894 intent.putExtras(adminExtras); 2895 } 2896 if (mInjector.getPackageManager().queryBroadcastReceiversAsUser( 2897 intent, 2898 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, 2899 admin.getUserHandle()).isEmpty()) { 2900 return false; 2901 } 2902 2903 final BroadcastOptions options = BroadcastOptions.makeBasic(); 2904 options.setBackgroundActivityStartsAllowed(true); 2905 2906 if (result != null) { 2907 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(), 2908 null, AppOpsManager.OP_NONE, options.toBundle(), 2909 result, mHandler, Activity.RESULT_OK, null, null); 2910 } else { 2911 mContext.sendBroadcastAsUser(intent, admin.getUserHandle(), null, options.toBundle()); 2912 } 2913 2914 return true; 2915 } 2916 2917 /** 2918 * Send an update to all admins of a user that enforce a specified policy. 2919 */ 2920 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) { 2921 final DevicePolicyData policy = getUserData(userHandle); 2922 final int count = policy.mAdminList.size(); 2923 for (int i = 0; i < count; i++) { 2924 final ActiveAdmin admin = policy.mAdminList.get(i); 2925 if (admin.info.usesPolicy(reqPolicy)) { 2926 sendAdminCommandLocked(admin, action, adminExtras, null); 2927 } 2928 } 2929 } 2930 2931 /** 2932 * Send an update intent to all admins of a user and its profiles. Only send to admins that 2933 * enforce a specified policy. 2934 */ 2935 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy, 2936 int userHandle, Bundle adminExtras) { 2937 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle); 2938 for (int profileId : profileIds) { 2939 sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras); 2940 } 2941 } 2942 2943 /** 2944 * Sends a broadcast to each profile that share the password unlock with the given user id. 2945 */ 2946 private void sendAdminCommandForLockscreenPoliciesLocked( 2947 String action, int reqPolicy, int userHandle) { 2948 final Bundle extras = new Bundle(); 2949 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 2950 if (isSeparateProfileChallengeEnabled(userHandle)) { 2951 sendAdminCommandLocked(action, reqPolicy, userHandle, extras); 2952 } else { 2953 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras); 2954 } 2955 } 2956 2957 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) { 2958 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 2959 DevicePolicyData policy = getUserData(userHandle); 2960 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) { 2961 policy.mRemovingAdmins.add(adminReceiver); 2962 sendAdminCommandLocked(admin, 2963 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED, 2964 new BroadcastReceiver() { 2965 @Override 2966 public void onReceive(Context context, Intent intent) { 2967 removeAdminArtifacts(adminReceiver, userHandle); 2968 removePackageIfRequired(adminReceiver.getPackageName(), userHandle); 2969 } 2970 }); 2971 } 2972 } 2973 2974 2975 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle, 2976 boolean throwForMissingPermission) { 2977 if (!mHasFeature) { 2978 return null; 2979 } 2980 enforceFullCrossUsersPermission(userHandle); 2981 ActivityInfo ai = null; 2982 try { 2983 ai = mIPackageManager.getReceiverInfo(adminName, 2984 PackageManager.GET_META_DATA | 2985 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS | 2986 PackageManager.MATCH_DIRECT_BOOT_AWARE | 2987 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle); 2988 } catch (RemoteException e) { 2989 // shouldn't happen. 2990 } 2991 if (ai == null) { 2992 throw new IllegalArgumentException("Unknown admin: " + adminName); 2993 } 2994 2995 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) { 2996 final String message = "DeviceAdminReceiver " + adminName + " must be protected with " 2997 + permission.BIND_DEVICE_ADMIN; 2998 Slog.w(LOG_TAG, message); 2999 if (throwForMissingPermission && 3000 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) { 3001 throw new IllegalArgumentException(message); 3002 } 3003 } 3004 3005 try { 3006 return new DeviceAdminInfo(mContext, ai); 3007 } catch (XmlPullParserException | IOException e) { 3008 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName, 3009 e); 3010 return null; 3011 } 3012 } 3013 3014 private File getPolicyFileDirectory(@UserIdInt int userId) { 3015 return userId == UserHandle.USER_SYSTEM 3016 ? new File(mInjector.getDevicePolicyFilePathForSystemUser()) 3017 : mInjector.environmentGetUserSystemDirectory(userId); 3018 } 3019 3020 private JournaledFile makeJournaledFile(@UserIdInt int userId) { 3021 final String base = new File(getPolicyFileDirectory(userId), DEVICE_POLICIES_XML) 3022 .getAbsolutePath(); 3023 if (VERBOSE_LOG) { 3024 Log.v(LOG_TAG, "Opening " + base); 3025 } 3026 return new JournaledFile(new File(base), new File(base + ".tmp")); 3027 } 3028 3029 private void saveSettingsLocked(int userHandle) { 3030 DevicePolicyData policy = getUserData(userHandle); 3031 JournaledFile journal = makeJournaledFile(userHandle); 3032 FileOutputStream stream = null; 3033 try { 3034 stream = new FileOutputStream(journal.chooseForWrite(), false); 3035 XmlSerializer out = new FastXmlSerializer(); 3036 out.setOutput(stream, StandardCharsets.UTF_8.name()); 3037 out.startDocument(null, true); 3038 3039 out.startTag(null, "policies"); 3040 if (policy.mRestrictionsProvider != null) { 3041 out.attribute(null, ATTR_PERMISSION_PROVIDER, 3042 policy.mRestrictionsProvider.flattenToString()); 3043 } 3044 if (policy.mUserSetupComplete) { 3045 out.attribute(null, ATTR_SETUP_COMPLETE, 3046 Boolean.toString(true)); 3047 } 3048 if (policy.mPaired) { 3049 out.attribute(null, ATTR_DEVICE_PAIRED, 3050 Boolean.toString(true)); 3051 } 3052 if (policy.mDeviceProvisioningConfigApplied) { 3053 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED, 3054 Boolean.toString(true)); 3055 } 3056 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) { 3057 out.attribute(null, ATTR_PROVISIONING_STATE, 3058 Integer.toString(policy.mUserProvisioningState)); 3059 } 3060 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) { 3061 out.attribute(null, ATTR_PERMISSION_POLICY, 3062 Integer.toString(policy.mPermissionPolicy)); 3063 } 3064 3065 // Serialize delegations. 3066 for (int i = 0; i < policy.mDelegationMap.size(); ++i) { 3067 final String delegatePackage = policy.mDelegationMap.keyAt(i); 3068 final List<String> scopes = policy.mDelegationMap.valueAt(i); 3069 3070 // Every "delegation" tag serializes the information of one delegate-scope pair. 3071 for (String scope : scopes) { 3072 out.startTag(null, "delegation"); 3073 out.attribute(null, "delegatePackage", delegatePackage); 3074 out.attribute(null, "scope", scope); 3075 out.endTag(null, "delegation"); 3076 } 3077 } 3078 3079 final int N = policy.mAdminList.size(); 3080 for (int i=0; i<N; i++) { 3081 ActiveAdmin ap = policy.mAdminList.get(i); 3082 if (ap != null) { 3083 out.startTag(null, "admin"); 3084 out.attribute(null, "name", ap.info.getComponent().flattenToString()); 3085 ap.writeToXml(out); 3086 out.endTag(null, "admin"); 3087 } 3088 } 3089 3090 if (policy.mPasswordOwner >= 0) { 3091 out.startTag(null, "password-owner"); 3092 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner)); 3093 out.endTag(null, "password-owner"); 3094 } 3095 3096 if (policy.mFailedPasswordAttempts != 0) { 3097 out.startTag(null, "failed-password-attempts"); 3098 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts)); 3099 out.endTag(null, "failed-password-attempts"); 3100 } 3101 3102 // For FDE devices only, we save this flag so we can report on password sufficiency 3103 // before the user enters their password for the first time after a reboot. For 3104 // security reasons, we don't want to store the full set of active password metrics. 3105 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 3106 out.startTag(null, TAG_PASSWORD_VALIDITY); 3107 out.attribute(null, ATTR_VALUE, 3108 Boolean.toString(policy.mPasswordValidAtLastCheckpoint)); 3109 out.endTag(null, TAG_PASSWORD_VALIDITY); 3110 } 3111 3112 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) { 3113 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 3114 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i)); 3115 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 3116 } 3117 3118 for (int i=0; i<policy.mLockTaskPackages.size(); i++) { 3119 String component = policy.mLockTaskPackages.get(i); 3120 out.startTag(null, TAG_LOCK_TASK_COMPONENTS); 3121 out.attribute(null, "name", component); 3122 out.endTag(null, TAG_LOCK_TASK_COMPONENTS); 3123 } 3124 3125 if (policy.mLockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) { 3126 out.startTag(null, TAG_LOCK_TASK_FEATURES); 3127 out.attribute(null, ATTR_VALUE, Integer.toString(policy.mLockTaskFeatures)); 3128 out.endTag(null, TAG_LOCK_TASK_FEATURES); 3129 } 3130 3131 if (policy.mStatusBarDisabled) { 3132 out.startTag(null, TAG_STATUS_BAR); 3133 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled)); 3134 out.endTag(null, TAG_STATUS_BAR); 3135 } 3136 3137 if (policy.doNotAskCredentialsOnBoot) { 3138 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 3139 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 3140 } 3141 3142 for (String id : policy.mAffiliationIds) { 3143 out.startTag(null, TAG_AFFILIATION_ID); 3144 out.attribute(null, ATTR_ID, id); 3145 out.endTag(null, TAG_AFFILIATION_ID); 3146 } 3147 3148 if (policy.mLastSecurityLogRetrievalTime >= 0) { 3149 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 3150 out.attribute(null, ATTR_VALUE, 3151 Long.toString(policy.mLastSecurityLogRetrievalTime)); 3152 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 3153 } 3154 3155 if (policy.mLastBugReportRequestTime >= 0) { 3156 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST); 3157 out.attribute(null, ATTR_VALUE, 3158 Long.toString(policy.mLastBugReportRequestTime)); 3159 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST); 3160 } 3161 3162 if (policy.mLastNetworkLogsRetrievalTime >= 0) { 3163 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 3164 out.attribute(null, ATTR_VALUE, 3165 Long.toString(policy.mLastNetworkLogsRetrievalTime)); 3166 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 3167 } 3168 3169 if (policy.mAdminBroadcastPending) { 3170 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING); 3171 out.attribute(null, ATTR_VALUE, 3172 Boolean.toString(policy.mAdminBroadcastPending)); 3173 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING); 3174 } 3175 3176 if (policy.mInitBundle != null) { 3177 out.startTag(null, TAG_INITIALIZATION_BUNDLE); 3178 policy.mInitBundle.saveToXml(out); 3179 out.endTag(null, TAG_INITIALIZATION_BUNDLE); 3180 } 3181 3182 if (policy.mPasswordTokenHandle != 0) { 3183 out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE); 3184 out.attribute(null, ATTR_VALUE, 3185 Long.toString(policy.mPasswordTokenHandle)); 3186 out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE); 3187 } 3188 3189 if (policy.mCurrentInputMethodSet) { 3190 out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET); 3191 out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET); 3192 } 3193 3194 for (final String cert : policy.mOwnerInstalledCaCerts) { 3195 out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT); 3196 out.attribute(null, ATTR_ALIAS, cert); 3197 out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT); 3198 } 3199 3200 out.endTag(null, "policies"); 3201 3202 out.endDocument(); 3203 stream.flush(); 3204 FileUtils.sync(stream); 3205 stream.close(); 3206 journal.commit(); 3207 sendChangedNotification(userHandle); 3208 } catch (XmlPullParserException | IOException e) { 3209 Slog.w(LOG_TAG, "failed writing file", e); 3210 try { 3211 if (stream != null) { 3212 stream.close(); 3213 } 3214 } catch (IOException ex) { 3215 // Ignore 3216 } 3217 journal.rollback(); 3218 } 3219 } 3220 3221 private void sendChangedNotification(int userHandle) { 3222 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 3223 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 3224 long ident = mInjector.binderClearCallingIdentity(); 3225 try { 3226 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle)); 3227 } finally { 3228 mInjector.binderRestoreCallingIdentity(ident); 3229 } 3230 } 3231 3232 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) { 3233 JournaledFile journal = makeJournaledFile(userHandle); 3234 FileInputStream stream = null; 3235 File file = journal.chooseForRead(); 3236 boolean needsRewrite = false; 3237 try { 3238 stream = new FileInputStream(file); 3239 XmlPullParser parser = Xml.newPullParser(); 3240 parser.setInput(stream, StandardCharsets.UTF_8.name()); 3241 3242 int type; 3243 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 3244 && type != XmlPullParser.START_TAG) { 3245 } 3246 String tag = parser.getName(); 3247 if (!"policies".equals(tag)) { 3248 throw new XmlPullParserException( 3249 "Settings do not start with policies tag: found " + tag); 3250 } 3251 3252 // Extract the permission provider component name if available 3253 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER); 3254 if (permissionProvider != null) { 3255 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider); 3256 } 3257 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE); 3258 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) { 3259 policy.mUserSetupComplete = true; 3260 } 3261 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED); 3262 if (paired != null && Boolean.toString(true).equals(paired)) { 3263 policy.mPaired = true; 3264 } 3265 String deviceProvisioningConfigApplied = parser.getAttributeValue(null, 3266 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED); 3267 if (deviceProvisioningConfigApplied != null 3268 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) { 3269 policy.mDeviceProvisioningConfigApplied = true; 3270 } 3271 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE); 3272 if (!TextUtils.isEmpty(provisioningState)) { 3273 policy.mUserProvisioningState = Integer.parseInt(provisioningState); 3274 } 3275 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY); 3276 if (!TextUtils.isEmpty(permissionPolicy)) { 3277 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy); 3278 } 3279 // Check for delegation compatibility with pre-O. 3280 // TODO(edmanp) remove in P. 3281 { 3282 final String certDelegate = parser.getAttributeValue(null, 3283 ATTR_DELEGATED_CERT_INSTALLER); 3284 if (certDelegate != null) { 3285 List<String> scopes = policy.mDelegationMap.get(certDelegate); 3286 if (scopes == null) { 3287 scopes = new ArrayList<>(); 3288 policy.mDelegationMap.put(certDelegate, scopes); 3289 } 3290 if (!scopes.contains(DELEGATION_CERT_INSTALL)) { 3291 scopes.add(DELEGATION_CERT_INSTALL); 3292 needsRewrite = true; 3293 } 3294 } 3295 final String appRestrictionsDelegate = parser.getAttributeValue(null, 3296 ATTR_APPLICATION_RESTRICTIONS_MANAGER); 3297 if (appRestrictionsDelegate != null) { 3298 List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate); 3299 if (scopes == null) { 3300 scopes = new ArrayList<>(); 3301 policy.mDelegationMap.put(appRestrictionsDelegate, scopes); 3302 } 3303 if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) { 3304 scopes.add(DELEGATION_APP_RESTRICTIONS); 3305 needsRewrite = true; 3306 } 3307 } 3308 } 3309 3310 type = parser.next(); 3311 int outerDepth = parser.getDepth(); 3312 policy.mLockTaskPackages.clear(); 3313 policy.mAdminList.clear(); 3314 policy.mAdminMap.clear(); 3315 policy.mAffiliationIds.clear(); 3316 policy.mOwnerInstalledCaCerts.clear(); 3317 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 3318 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 3319 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 3320 continue; 3321 } 3322 tag = parser.getName(); 3323 if ("admin".equals(tag)) { 3324 String name = parser.getAttributeValue(null, "name"); 3325 try { 3326 DeviceAdminInfo dai = findAdmin( 3327 ComponentName.unflattenFromString(name), userHandle, 3328 /* throwForMissingPermission= */ false); 3329 if (VERBOSE_LOG 3330 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid) 3331 != userHandle)) { 3332 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid " 3333 + dai.getActivityInfo().applicationInfo.uid + " for user " 3334 + userHandle); 3335 } 3336 if (dai != null) { 3337 boolean shouldOverwritePolicies = 3338 shouldOverwritePoliciesFromXml(dai.getComponent(), userHandle); 3339 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false); 3340 ap.readFromXml(parser, shouldOverwritePolicies); 3341 policy.mAdminMap.put(ap.info.getComponent(), ap); 3342 } 3343 } catch (RuntimeException e) { 3344 Slog.w(LOG_TAG, "Failed loading admin " + name, e); 3345 } 3346 } else if ("delegation".equals(tag)) { 3347 // Parse delegation info. 3348 final String delegatePackage = parser.getAttributeValue(null, 3349 "delegatePackage"); 3350 final String scope = parser.getAttributeValue(null, "scope"); 3351 3352 // Get a reference to the scopes list for the delegatePackage. 3353 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 3354 // Or make a new list if none was found. 3355 if (scopes == null) { 3356 scopes = new ArrayList<>(); 3357 policy.mDelegationMap.put(delegatePackage, scopes); 3358 } 3359 // Add the new scope to the list of delegatePackage if it's not already there. 3360 if (!scopes.contains(scope)) { 3361 scopes.add(scope); 3362 } 3363 } else if ("failed-password-attempts".equals(tag)) { 3364 policy.mFailedPasswordAttempts = Integer.parseInt( 3365 parser.getAttributeValue(null, "value")); 3366 } else if ("password-owner".equals(tag)) { 3367 policy.mPasswordOwner = Integer.parseInt( 3368 parser.getAttributeValue(null, "value")); 3369 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) { 3370 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME)); 3371 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) { 3372 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name")); 3373 } else if (TAG_LOCK_TASK_FEATURES.equals(tag)) { 3374 policy.mLockTaskFeatures = Integer.parseInt( 3375 parser.getAttributeValue(null, ATTR_VALUE)); 3376 } else if (TAG_STATUS_BAR.equals(tag)) { 3377 policy.mStatusBarDisabled = Boolean.parseBoolean( 3378 parser.getAttributeValue(null, ATTR_DISABLED)); 3379 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) { 3380 policy.doNotAskCredentialsOnBoot = true; 3381 } else if (TAG_AFFILIATION_ID.equals(tag)) { 3382 policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID)); 3383 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) { 3384 policy.mLastSecurityLogRetrievalTime = Long.parseLong( 3385 parser.getAttributeValue(null, ATTR_VALUE)); 3386 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) { 3387 policy.mLastBugReportRequestTime = Long.parseLong( 3388 parser.getAttributeValue(null, ATTR_VALUE)); 3389 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) { 3390 policy.mLastNetworkLogsRetrievalTime = Long.parseLong( 3391 parser.getAttributeValue(null, ATTR_VALUE)); 3392 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) { 3393 String pending = parser.getAttributeValue(null, ATTR_VALUE); 3394 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending); 3395 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) { 3396 policy.mInitBundle = PersistableBundle.restoreFromXml(parser); 3397 } else if ("active-password".equals(tag)) { 3398 // Remove password metrics from saved settings, as we no longer wish to store 3399 // these on disk 3400 needsRewrite = true; 3401 } else if (TAG_PASSWORD_VALIDITY.equals(tag)) { 3402 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 3403 // This flag is only used for FDE devices 3404 policy.mPasswordValidAtLastCheckpoint = Boolean.parseBoolean( 3405 parser.getAttributeValue(null, ATTR_VALUE)); 3406 } 3407 } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) { 3408 policy.mPasswordTokenHandle = Long.parseLong( 3409 parser.getAttributeValue(null, ATTR_VALUE)); 3410 } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) { 3411 policy.mCurrentInputMethodSet = true; 3412 } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) { 3413 policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS)); 3414 } else { 3415 Slog.w(LOG_TAG, "Unknown tag: " + tag); 3416 XmlUtils.skipCurrentTag(parser); 3417 } 3418 } 3419 } catch (FileNotFoundException e) { 3420 // Don't be noisy, this is normal if we haven't defined any policies. 3421 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException 3422 | IndexOutOfBoundsException e) { 3423 Slog.w(LOG_TAG, "failed parsing " + file, e); 3424 } 3425 try { 3426 if (stream != null) { 3427 stream.close(); 3428 } 3429 } catch (IOException e) { 3430 // Ignore 3431 } 3432 3433 // Generate a list of admins from the admin map 3434 policy.mAdminList.addAll(policy.mAdminMap.values()); 3435 3436 // Might need to upgrade the file by rewriting it 3437 if (needsRewrite) { 3438 saveSettingsLocked(userHandle); 3439 } 3440 3441 validatePasswordOwnerLocked(policy); 3442 updateMaximumTimeToLockLocked(userHandle); 3443 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle); 3444 updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle); 3445 if (policy.mStatusBarDisabled) { 3446 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle); 3447 } 3448 } 3449 shouldOverwritePoliciesFromXml( ComponentName deviceAdminComponent, int userHandle)3450 private boolean shouldOverwritePoliciesFromXml( 3451 ComponentName deviceAdminComponent, int userHandle) { 3452 // http://b/123415062: If DA, overwrite with the stored policies that were agreed by the 3453 // user to prevent apps from sneaking additional policies into updates. 3454 return !isProfileOwner(deviceAdminComponent, userHandle) 3455 && !isDeviceOwner(deviceAdminComponent, userHandle); 3456 } 3457 updateLockTaskPackagesLocked(List<String> packages, int userId)3458 private void updateLockTaskPackagesLocked(List<String> packages, int userId) { 3459 long ident = mInjector.binderClearCallingIdentity(); 3460 try { 3461 mInjector.getIActivityManager() 3462 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()])); 3463 } catch (RemoteException e) { 3464 // Not gonna happen. 3465 } finally { 3466 mInjector.binderRestoreCallingIdentity(ident); 3467 } 3468 } 3469 updateLockTaskFeaturesLocked(int flags, int userId)3470 private void updateLockTaskFeaturesLocked(int flags, int userId) { 3471 long ident = mInjector.binderClearCallingIdentity(); 3472 try { 3473 mInjector.getIActivityTaskManager().updateLockTaskFeatures(userId, flags); 3474 } catch (RemoteException e) { 3475 // Not gonna happen. 3476 } finally { 3477 mInjector.binderRestoreCallingIdentity(ident); 3478 } 3479 } 3480 updateDeviceOwnerLocked()3481 private void updateDeviceOwnerLocked() { 3482 long ident = mInjector.binderClearCallingIdentity(); 3483 try { 3484 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the 3485 // user id and also protect all other DAs too. 3486 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 3487 if (deviceOwnerComponent != null) { 3488 mInjector.getIActivityManager() 3489 .updateDeviceOwner(deviceOwnerComponent.getPackageName()); 3490 } 3491 } catch (RemoteException e) { 3492 // Not gonna happen. 3493 } finally { 3494 mInjector.binderRestoreCallingIdentity(ident); 3495 } 3496 } 3497 validateQualityConstant(int quality)3498 static void validateQualityConstant(int quality) { 3499 switch (quality) { 3500 case PASSWORD_QUALITY_UNSPECIFIED: 3501 case PASSWORD_QUALITY_BIOMETRIC_WEAK: 3502 case PASSWORD_QUALITY_SOMETHING: 3503 case PASSWORD_QUALITY_NUMERIC: 3504 case PASSWORD_QUALITY_NUMERIC_COMPLEX: 3505 case PASSWORD_QUALITY_ALPHABETIC: 3506 case PASSWORD_QUALITY_ALPHANUMERIC: 3507 case PASSWORD_QUALITY_COMPLEX: 3508 case PASSWORD_QUALITY_MANAGED: 3509 return; 3510 } 3511 throw new IllegalArgumentException("Invalid quality constant: 0x" 3512 + Integer.toHexString(quality)); 3513 } 3514 validatePasswordOwnerLocked(DevicePolicyData policy)3515 void validatePasswordOwnerLocked(DevicePolicyData policy) { 3516 if (policy.mPasswordOwner >= 0) { 3517 boolean haveOwner = false; 3518 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 3519 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) { 3520 haveOwner = true; 3521 break; 3522 } 3523 } 3524 if (!haveOwner) { 3525 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner 3526 + " no longer active; disabling"); 3527 policy.mPasswordOwner = -1; 3528 } 3529 } 3530 } 3531 3532 @VisibleForTesting 3533 @Override systemReady(int phase)3534 void systemReady(int phase) { 3535 if (!mHasFeature) { 3536 return; 3537 } 3538 switch (phase) { 3539 case SystemService.PHASE_LOCK_SETTINGS_READY: 3540 onLockSettingsReady(); 3541 loadAdminDataAsync(); 3542 mOwners.systemReady(); 3543 break; 3544 case SystemService.PHASE_ACTIVITY_MANAGER_READY: 3545 maybeStartSecurityLogMonitorOnActivityManagerReady(); 3546 break; 3547 case SystemService.PHASE_BOOT_COMPLETED: 3548 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this. 3549 break; 3550 } 3551 } 3552 onLockSettingsReady()3553 private void onLockSettingsReady() { 3554 getUserData(UserHandle.USER_SYSTEM); 3555 loadOwners(); 3556 cleanUpOldUsers(); 3557 maybeSetDefaultProfileOwnerUserRestrictions(); 3558 handleStartUser(UserHandle.USER_SYSTEM); 3559 maybeLogStart(); 3560 3561 // Register an observer for watching for user setup complete and settings changes. 3562 mSetupContentObserver.register(); 3563 // Initialize the user setup state, to handle the upgrade case. 3564 updateUserSetupCompleteAndPaired(); 3565 3566 List<String> packageList; 3567 synchronized (getLockObject()) { 3568 packageList = getKeepUninstalledPackagesLocked(); 3569 } 3570 if (packageList != null) { 3571 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 3572 } 3573 3574 synchronized (getLockObject()) { 3575 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 3576 if (deviceOwner != null) { 3577 // Push the force-ephemeral-users policy to the user manager. 3578 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers); 3579 3580 // Update user switcher message to activity manager. 3581 ActivityManagerInternal activityManagerInternal = 3582 mInjector.getActivityManagerInternal(); 3583 activityManagerInternal.setSwitchingFromSystemUserMessage( 3584 deviceOwner.startUserSessionMessage); 3585 activityManagerInternal.setSwitchingToSystemUserMessage( 3586 deviceOwner.endUserSessionMessage); 3587 } 3588 3589 revertTransferOwnershipIfNecessaryLocked(); 3590 } 3591 } 3592 revertTransferOwnershipIfNecessaryLocked()3593 private void revertTransferOwnershipIfNecessaryLocked() { 3594 if (!mTransferOwnershipMetadataManager.metadataFileExists()) { 3595 return; 3596 } 3597 Slog.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer."); 3598 final TransferOwnershipMetadataManager.Metadata metadata = 3599 mTransferOwnershipMetadataManager.loadMetadataFile(); 3600 // Revert transfer 3601 if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) { 3602 transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent, 3603 metadata.userId); 3604 deleteTransferOwnershipMetadataFileLocked(); 3605 deleteTransferOwnershipBundleLocked(metadata.userId); 3606 } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) { 3607 transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent, 3608 metadata.userId); 3609 deleteTransferOwnershipMetadataFileLocked(); 3610 deleteTransferOwnershipBundleLocked(metadata.userId); 3611 } 3612 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true); 3613 } 3614 maybeLogStart()3615 private void maybeLogStart() { 3616 if (!SecurityLog.isLoggingEnabled()) { 3617 return; 3618 } 3619 final String verifiedBootState = 3620 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate"); 3621 final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode"); 3622 SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode); 3623 } 3624 ensureDeviceOwnerUserStarted()3625 private void ensureDeviceOwnerUserStarted() { 3626 final int userId; 3627 synchronized (getLockObject()) { 3628 if (!mOwners.hasDeviceOwner()) { 3629 return; 3630 } 3631 userId = mOwners.getDeviceOwnerUserId(); 3632 } 3633 if (VERBOSE_LOG) { 3634 Log.v(LOG_TAG, "Starting non-system DO user: " + userId); 3635 } 3636 if (userId != UserHandle.USER_SYSTEM) { 3637 try { 3638 mInjector.getIActivityManager().startUserInBackground(userId); 3639 3640 // STOPSHIP Prevent the DO user from being killed. 3641 3642 } catch (RemoteException e) { 3643 Slog.w(LOG_TAG, "Exception starting user", e); 3644 } 3645 } 3646 } 3647 3648 @Override handleStartUser(int userId)3649 void handleStartUser(int userId) { 3650 updateScreenCaptureDisabled(userId, 3651 getScreenCaptureDisabled(null, userId)); 3652 pushUserRestrictions(userId); 3653 // When system user is started (device boot), load cache for all users. 3654 // This is to mitigate the potential race between loading the cache and keyguard 3655 // reading the value during user switch, due to onStartUser() being asynchronous. 3656 updatePasswordQualityCacheForUserGroup( 3657 userId == UserHandle.USER_SYSTEM ? UserHandle.USER_ALL : userId); 3658 3659 startOwnerService(userId, "start-user"); 3660 } 3661 3662 @Override handleUnlockUser(int userId)3663 void handleUnlockUser(int userId) { 3664 startOwnerService(userId, "unlock-user"); 3665 } 3666 3667 @Override handleStopUser(int userId)3668 void handleStopUser(int userId) { 3669 stopOwnerService(userId, "stop-user"); 3670 } 3671 startOwnerService(int userId, String actionForLog)3672 private void startOwnerService(int userId, String actionForLog) { 3673 final ComponentName owner = getOwnerComponent(userId); 3674 if (owner != null) { 3675 mDeviceAdminServiceController.startServiceForOwner( 3676 owner.getPackageName(), userId, actionForLog); 3677 } 3678 } 3679 stopOwnerService(int userId, String actionForLog)3680 private void stopOwnerService(int userId, String actionForLog) { 3681 mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog); 3682 } 3683 cleanUpOldUsers()3684 private void cleanUpOldUsers() { 3685 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled 3686 // before reboot 3687 Set<Integer> usersWithProfileOwners; 3688 Set<Integer> usersWithData; 3689 synchronized (getLockObject()) { 3690 usersWithProfileOwners = mOwners.getProfileOwnerKeys(); 3691 usersWithData = new ArraySet<>(); 3692 for (int i = 0; i < mUserData.size(); i++) { 3693 usersWithData.add(mUserData.keyAt(i)); 3694 } 3695 } 3696 List<UserInfo> allUsers = mUserManager.getUsers(); 3697 3698 Set<Integer> deletedUsers = new ArraySet<>(); 3699 deletedUsers.addAll(usersWithProfileOwners); 3700 deletedUsers.addAll(usersWithData); 3701 for (UserInfo userInfo : allUsers) { 3702 deletedUsers.remove(userInfo.id); 3703 } 3704 for (Integer userId : deletedUsers) { 3705 removeUserData(userId); 3706 } 3707 } 3708 handlePasswordExpirationNotification(int userHandle)3709 private void handlePasswordExpirationNotification(int userHandle) { 3710 final Bundle adminExtras = new Bundle(); 3711 adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 3712 3713 synchronized (getLockObject()) { 3714 final long now = System.currentTimeMillis(); 3715 3716 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 3717 userHandle, /* parent */ false); 3718 final int N = admins.size(); 3719 for (int i = 0; i < N; i++) { 3720 ActiveAdmin admin = admins.get(i); 3721 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD) 3722 && admin.passwordExpirationTimeout > 0L 3723 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS 3724 && admin.passwordExpirationDate > 0L) { 3725 sendAdminCommandLocked(admin, 3726 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null); 3727 } 3728 } 3729 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false); 3730 } 3731 } 3732 3733 /** 3734 * Clean up internal state when the set of installed trusted CA certificates changes. 3735 * 3736 * @param userHandle user to check for. This must be a real user and not, for example, 3737 * {@link UserHandle#ALL}. 3738 * @param installedCertificates the full set of certificate authorities currently installed for 3739 * {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will 3740 * correspond to some subset of this. 3741 */ onInstalledCertificatesChanged(final UserHandle userHandle, final @NonNull Collection<String> installedCertificates)3742 protected void onInstalledCertificatesChanged(final UserHandle userHandle, 3743 final @NonNull Collection<String> installedCertificates) { 3744 if (!mHasFeature) { 3745 return; 3746 } 3747 enforceManageUsers(); 3748 3749 synchronized (getLockObject()) { 3750 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3751 3752 boolean changed = false; 3753 changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates); 3754 changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates); 3755 if (changed) { 3756 saveSettingsLocked(userHandle.getIdentifier()); 3757 } 3758 } 3759 } 3760 3761 /** 3762 * Internal method used by {@link CertificateMonitor}. 3763 */ getAcceptedCaCertificates(final UserHandle userHandle)3764 protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) { 3765 if (!mHasFeature) { 3766 return Collections.<String> emptySet(); 3767 } 3768 synchronized (getLockObject()) { 3769 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3770 return policy.mAcceptedCaCertificates; 3771 } 3772 } 3773 3774 /** 3775 * @param adminReceiver The admin to add 3776 * @param refreshing true = update an active admin, no error 3777 */ 3778 @Override setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle)3779 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) { 3780 if (!mHasFeature) { 3781 return; 3782 } 3783 setActiveAdmin(adminReceiver, refreshing, userHandle, null); 3784 } 3785 setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, Bundle onEnableData)3786 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, 3787 Bundle onEnableData) { 3788 mContext.enforceCallingOrSelfPermission( 3789 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 3790 enforceFullCrossUsersPermission(userHandle); 3791 3792 DevicePolicyData policy = getUserData(userHandle); 3793 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle, 3794 /* throwForMissingPermission= */ true); 3795 synchronized (getLockObject()) { 3796 checkActiveAdminPrecondition(adminReceiver, info, policy); 3797 long ident = mInjector.binderClearCallingIdentity(); 3798 try { 3799 final ActiveAdmin existingAdmin 3800 = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3801 if (!refreshing && existingAdmin != null) { 3802 throw new IllegalArgumentException("Admin is already added"); 3803 } 3804 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false); 3805 newAdmin.testOnlyAdmin = 3806 (existingAdmin != null) ? existingAdmin.testOnlyAdmin 3807 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle); 3808 policy.mAdminMap.put(adminReceiver, newAdmin); 3809 int replaceIndex = -1; 3810 final int N = policy.mAdminList.size(); 3811 for (int i=0; i < N; i++) { 3812 ActiveAdmin oldAdmin = policy.mAdminList.get(i); 3813 if (oldAdmin.info.getComponent().equals(adminReceiver)) { 3814 replaceIndex = i; 3815 break; 3816 } 3817 } 3818 if (replaceIndex == -1) { 3819 policy.mAdminList.add(newAdmin); 3820 enableIfNecessary(info.getPackageName(), userHandle); 3821 mUsageStatsManagerInternal.onActiveAdminAdded( 3822 adminReceiver.getPackageName(), userHandle); 3823 } else { 3824 policy.mAdminList.set(replaceIndex, newAdmin); 3825 } 3826 saveSettingsLocked(userHandle); 3827 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3828 onEnableData, null); 3829 } finally { 3830 mInjector.binderRestoreCallingIdentity(ident); 3831 } 3832 } 3833 } 3834 loadAdminDataAsync()3835 private void loadAdminDataAsync() { 3836 mInjector.postOnSystemServerInitThreadPool(() -> { 3837 pushActiveAdminPackages(); 3838 mUsageStatsManagerInternal.onAdminDataAvailable(); 3839 pushAllMeteredRestrictedPackages(); 3840 mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable(); 3841 }); 3842 } 3843 pushActiveAdminPackages()3844 private void pushActiveAdminPackages() { 3845 synchronized (getLockObject()) { 3846 final List<UserInfo> users = mUserManager.getUsers(); 3847 for (int i = users.size() - 1; i >= 0; --i) { 3848 final int userId = users.get(i).id; 3849 mUsageStatsManagerInternal.setActiveAdminApps( 3850 getActiveAdminPackagesLocked(userId), userId); 3851 } 3852 } 3853 } 3854 pushAllMeteredRestrictedPackages()3855 private void pushAllMeteredRestrictedPackages() { 3856 synchronized (getLockObject()) { 3857 final List<UserInfo> users = mUserManager.getUsers(); 3858 for (int i = users.size() - 1; i >= 0; --i) { 3859 final int userId = users.get(i).id; 3860 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync( 3861 getMeteredDisabledPackagesLocked(userId), userId); 3862 } 3863 } 3864 } 3865 pushActiveAdminPackagesLocked(int userId)3866 private void pushActiveAdminPackagesLocked(int userId) { 3867 mUsageStatsManagerInternal.setActiveAdminApps( 3868 getActiveAdminPackagesLocked(userId), userId); 3869 } 3870 getActiveAdminPackagesLocked(int userId)3871 private Set<String> getActiveAdminPackagesLocked(int userId) { 3872 final DevicePolicyData policy = getUserData(userId); 3873 Set<String> adminPkgs = null; 3874 for (int i = policy.mAdminList.size() - 1; i >= 0; --i) { 3875 final String pkgName = policy.mAdminList.get(i).info.getPackageName(); 3876 if (adminPkgs == null) { 3877 adminPkgs = new ArraySet<>(); 3878 } 3879 adminPkgs.add(pkgName); 3880 } 3881 return adminPkgs; 3882 } 3883 transferActiveAdminUncheckedLocked(ComponentName incomingReceiver, ComponentName outgoingReceiver, int userHandle)3884 private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver, 3885 ComponentName outgoingReceiver, int userHandle) { 3886 final DevicePolicyData policy = getUserData(userHandle); 3887 if (!policy.mAdminMap.containsKey(outgoingReceiver) 3888 && policy.mAdminMap.containsKey(incomingReceiver)) { 3889 // Nothing to transfer - the incoming receiver is already the active admin. 3890 return; 3891 } 3892 final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle, 3893 /* throwForMissingPermission= */ true); 3894 final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver); 3895 final int oldAdminUid = adminToTransfer.getUid(); 3896 3897 adminToTransfer.transfer(incomingDeviceInfo); 3898 policy.mAdminMap.remove(outgoingReceiver); 3899 policy.mAdminMap.put(incomingReceiver, adminToTransfer); 3900 if (policy.mPasswordOwner == oldAdminUid) { 3901 policy.mPasswordOwner = adminToTransfer.getUid(); 3902 } 3903 3904 saveSettingsLocked(userHandle); 3905 sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3906 null, null); 3907 } 3908 checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info, DevicePolicyData policy)3909 private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info, 3910 DevicePolicyData policy) { 3911 if (info == null) { 3912 throw new IllegalArgumentException("Bad admin: " + adminReceiver); 3913 } 3914 if (!info.getActivityInfo().applicationInfo.isInternal()) { 3915 throw new IllegalArgumentException("Only apps in internal storage can be active admin: " 3916 + adminReceiver); 3917 } 3918 if (info.getActivityInfo().applicationInfo.isInstantApp()) { 3919 throw new IllegalArgumentException("Instant apps cannot be device admins: " 3920 + adminReceiver); 3921 } 3922 if (policy.mRemovingAdmins.contains(adminReceiver)) { 3923 throw new IllegalArgumentException( 3924 "Trying to set an admin which is being removed"); 3925 } 3926 } 3927 3928 @Override isAdminActive(ComponentName adminReceiver, int userHandle)3929 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) { 3930 if (!mHasFeature) { 3931 return false; 3932 } 3933 enforceFullCrossUsersPermission(userHandle); 3934 synchronized (getLockObject()) { 3935 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null; 3936 } 3937 } 3938 3939 @Override isRemovingAdmin(ComponentName adminReceiver, int userHandle)3940 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) { 3941 if (!mHasFeature) { 3942 return false; 3943 } 3944 enforceFullCrossUsersPermission(userHandle); 3945 synchronized (getLockObject()) { 3946 DevicePolicyData policyData = getUserData(userHandle); 3947 return policyData.mRemovingAdmins.contains(adminReceiver); 3948 } 3949 } 3950 3951 @Override hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle)3952 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) { 3953 if (!mHasFeature) { 3954 return false; 3955 } 3956 enforceFullCrossUsersPermission(userHandle); 3957 synchronized (getLockObject()) { 3958 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3959 if (administrator == null) { 3960 throw new SecurityException("No active admin " + adminReceiver); 3961 } 3962 return administrator.info.usesPolicy(policyId); 3963 } 3964 } 3965 3966 @Override 3967 @SuppressWarnings("unchecked") getActiveAdmins(int userHandle)3968 public List<ComponentName> getActiveAdmins(int userHandle) { 3969 if (!mHasFeature) { 3970 return Collections.EMPTY_LIST; 3971 } 3972 3973 enforceFullCrossUsersPermission(userHandle); 3974 synchronized (getLockObject()) { 3975 DevicePolicyData policy = getUserData(userHandle); 3976 final int N = policy.mAdminList.size(); 3977 if (N <= 0) { 3978 return null; 3979 } 3980 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N); 3981 for (int i=0; i<N; i++) { 3982 res.add(policy.mAdminList.get(i).info.getComponent()); 3983 } 3984 return res; 3985 } 3986 } 3987 3988 @Override packageHasActiveAdmins(String packageName, int userHandle)3989 public boolean packageHasActiveAdmins(String packageName, int userHandle) { 3990 if (!mHasFeature) { 3991 return false; 3992 } 3993 enforceFullCrossUsersPermission(userHandle); 3994 synchronized (getLockObject()) { 3995 DevicePolicyData policy = getUserData(userHandle); 3996 final int N = policy.mAdminList.size(); 3997 for (int i=0; i<N; i++) { 3998 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) { 3999 return true; 4000 } 4001 } 4002 return false; 4003 } 4004 } 4005 4006 @Override forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle)4007 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) { 4008 if (!mHasFeature) { 4009 return; 4010 } 4011 Preconditions.checkNotNull(adminReceiver, "ComponentName is null"); 4012 enforceShell("forceRemoveActiveAdmin"); 4013 long ident = mInjector.binderClearCallingIdentity(); 4014 try { 4015 synchronized (getLockObject()) { 4016 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) { 4017 throw new SecurityException("Attempt to remove non-test admin " 4018 + adminReceiver + " " + userHandle); 4019 } 4020 4021 // If admin is a device or profile owner tidy that up first. 4022 if (isDeviceOwner(adminReceiver, userHandle)) { 4023 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle); 4024 } 4025 if (isProfileOwner(adminReceiver, userHandle)) { 4026 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, 4027 userHandle, /* parent */ false); 4028 clearProfileOwnerLocked(admin, userHandle); 4029 } 4030 } 4031 // Remove the admin skipping sending the broadcast. 4032 removeAdminArtifacts(adminReceiver, userHandle); 4033 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle); 4034 } finally { 4035 mInjector.binderRestoreCallingIdentity(ident); 4036 } 4037 } 4038 clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle)4039 private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) { 4040 // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state 4041 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) { 4042 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle); 4043 } 4044 } 4045 4046 /** 4047 * Return if a given package has testOnly="true", in which case we'll relax certain rules 4048 * for CTS. 4049 * 4050 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked} 4051 * to check wehter an active admin is test-only or not. 4052 * 4053 * The system allows this flag to be changed when an app is updated, which is not good 4054 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed, 4055 * and used the persisted version in actual checks. (See b/31382361 and b/28928996) 4056 */ isPackageTestOnly(String packageName, int userHandle)4057 private boolean isPackageTestOnly(String packageName, int userHandle) { 4058 final ApplicationInfo ai; 4059 try { 4060 ai = mInjector.getIPackageManager().getApplicationInfo(packageName, 4061 (PackageManager.MATCH_DIRECT_BOOT_AWARE 4062 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle); 4063 } catch (RemoteException e) { 4064 throw new IllegalStateException(e); 4065 } 4066 if (ai == null) { 4067 throw new IllegalStateException("Couldn't find package: " 4068 + packageName + " on user " + userHandle); 4069 } 4070 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0; 4071 } 4072 4073 /** 4074 * See {@link #isPackageTestOnly}. 4075 */ isAdminTestOnlyLocked(ComponentName who, int userHandle)4076 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) { 4077 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 4078 return (admin != null) && admin.testOnlyAdmin; 4079 } 4080 enforceShell(String method)4081 private void enforceShell(String method) { 4082 final int callingUid = mInjector.binderGetCallingUid(); 4083 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) { 4084 throw new SecurityException("Non-shell user attempted to call " + method); 4085 } 4086 } 4087 4088 @Override removeActiveAdmin(ComponentName adminReceiver, int userHandle)4089 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) { 4090 if (!mHasFeature) { 4091 return; 4092 } 4093 enforceFullCrossUsersPermission(userHandle); 4094 enforceUserUnlocked(userHandle); 4095 synchronized (getLockObject()) { 4096 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 4097 if (admin == null) { 4098 return; 4099 } 4100 // Active device/profile owners must remain active admins. 4101 if (isDeviceOwner(adminReceiver, userHandle) 4102 || isProfileOwner(adminReceiver, userHandle)) { 4103 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" + 4104 adminReceiver); 4105 return; 4106 } 4107 if (admin.getUid() != mInjector.binderGetCallingUid()) { 4108 mContext.enforceCallingOrSelfPermission( 4109 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 4110 } 4111 long ident = mInjector.binderClearCallingIdentity(); 4112 try { 4113 removeActiveAdminLocked(adminReceiver, userHandle); 4114 } finally { 4115 mInjector.binderRestoreCallingIdentity(ident); 4116 } 4117 } 4118 } 4119 4120 @Override isSeparateProfileChallengeAllowed(int userHandle)4121 public boolean isSeparateProfileChallengeAllowed(int userHandle) { 4122 if (!isCallerWithSystemUid()) { 4123 throw new SecurityException("Caller must be system"); 4124 } 4125 ComponentName profileOwner = getProfileOwner(userHandle); 4126 // Profile challenge is supported on N or newer release. 4127 return profileOwner != null && 4128 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M; 4129 } 4130 4131 @Override setPasswordQuality(ComponentName who, int quality, boolean parent)4132 public void setPasswordQuality(ComponentName who, int quality, boolean parent) { 4133 if (!mHasFeature) { 4134 return; 4135 } 4136 Preconditions.checkNotNull(who, "ComponentName is null"); 4137 validateQualityConstant(quality); 4138 4139 final int userId = mInjector.userHandleGetCallingUserId(); 4140 synchronized (getLockObject()) { 4141 ActiveAdmin ap = getActiveAdminForCallerLocked( 4142 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4143 final long ident = mInjector.binderClearCallingIdentity(); 4144 try { 4145 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4146 if (metrics.quality != quality) { 4147 metrics.quality = quality; 4148 updatePasswordValidityCheckpointLocked(userId, parent); 4149 updatePasswordQualityCacheForUserGroup(userId); 4150 saveSettingsLocked(userId); 4151 } 4152 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4153 } finally { 4154 mInjector.binderRestoreCallingIdentity(ident); 4155 } 4156 } 4157 DevicePolicyEventLogger 4158 .createEvent(DevicePolicyEnums.SET_PASSWORD_QUALITY) 4159 .setAdmin(who) 4160 .setInt(quality) 4161 .setBoolean(parent) 4162 .write(); 4163 } 4164 4165 /** 4166 * Updates a flag that tells us whether the user's password currently satisfies the 4167 * requirements set by all of the user's active admins. The flag is updated both in memory 4168 * and persisted to disk by calling {@link #saveSettingsLocked}, for the value of the flag 4169 * be the correct one upon boot. 4170 * This should be called whenever the password or the admin policies have changed. 4171 */ 4172 @GuardedBy("getLockObject()") updatePasswordValidityCheckpointLocked(int userHandle, boolean parent)4173 private void updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) { 4174 final int credentialOwner = getCredentialOwner(userHandle, parent); 4175 DevicePolicyData policy = getUserData(credentialOwner); 4176 PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner); 4177 if (metrics == null) { 4178 metrics = new PasswordMetrics(); 4179 } 4180 policy.mPasswordValidAtLastCheckpoint = 4181 isPasswordSufficientForUserWithoutCheckpointLocked( 4182 metrics, userHandle, parent); 4183 4184 saveSettingsLocked(credentialOwner); 4185 } 4186 4187 /** 4188 * Update password quality values in policy cache for all users in the same user group as 4189 * the given user. The cached password quality for user X is the aggregated quality among all 4190 * admins who have influence of user X's screenlock, i.e. it's equivalent to the return value of 4191 * getPasswordQuality(null, user X, false). 4192 * 4193 * Caches for all users in the same user group often need to be updated alltogether because a 4194 * user's admin policy can affect another's aggregated password quality in some situation. 4195 * For example a managed profile's policy will affect the parent user if the profile has unified 4196 * challenge. A profile can also explicitly set a parent password quality which will affect the 4197 * aggregated password quality of the parent user. 4198 */ updatePasswordQualityCacheForUserGroup(@serIdInt int userId)4199 private void updatePasswordQualityCacheForUserGroup(@UserIdInt int userId) { 4200 final List<UserInfo> users; 4201 if (userId == UserHandle.USER_ALL) { 4202 users = mUserManager.getUsers(); 4203 } else { 4204 users = mUserManager.getProfiles(userId); 4205 } 4206 for (UserInfo userInfo : users) { 4207 final int currentUserId = userInfo.id; 4208 mPolicyCache.setPasswordQuality(currentUserId, 4209 getPasswordQuality(null, currentUserId, false)); 4210 } 4211 } 4212 4213 @Override getPasswordQuality(ComponentName who, int userHandle, boolean parent)4214 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) { 4215 if (!mHasFeature) { 4216 return PASSWORD_QUALITY_UNSPECIFIED; 4217 } 4218 enforceFullCrossUsersPermission(userHandle); 4219 synchronized (getLockObject()) { 4220 int mode = PASSWORD_QUALITY_UNSPECIFIED; 4221 4222 if (who != null) { 4223 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4224 return admin != null ? admin.minimumPasswordMetrics.quality : mode; 4225 } 4226 4227 // Return the strictest policy across all participating admins. 4228 List<ActiveAdmin> admins = 4229 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4230 final int N = admins.size(); 4231 for (int i = 0; i < N; i++) { 4232 ActiveAdmin admin = admins.get(i); 4233 if (mode < admin.minimumPasswordMetrics.quality) { 4234 mode = admin.minimumPasswordMetrics.quality; 4235 } 4236 } 4237 return mode; 4238 } 4239 } 4240 getActiveAdminsForLockscreenPoliciesLocked( int userHandle, boolean parent)4241 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked( 4242 int userHandle, boolean parent) { 4243 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) { 4244 // If this user has a separate challenge, only return its restrictions. 4245 return getUserDataUnchecked(userHandle).mAdminList; 4246 } else { 4247 // Return all admins for this user and the profiles that are visible from this 4248 // user that do not use a separate work challenge. 4249 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>(); 4250 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4251 DevicePolicyData policy = getUserData(userInfo.id); 4252 if (!userInfo.isManagedProfile()) { 4253 admins.addAll(policy.mAdminList); 4254 } else { 4255 // For managed profiles, we always include the policies set on the parent 4256 // profile. Additionally, we include the ones set on the managed profile 4257 // if no separate challenge is in place. 4258 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id); 4259 final int N = policy.mAdminList.size(); 4260 for (int i = 0; i < N; i++) { 4261 ActiveAdmin admin = policy.mAdminList.get(i); 4262 if (admin.hasParentActiveAdmin()) { 4263 admins.add(admin.getParentActiveAdmin()); 4264 } 4265 if (!hasSeparateChallenge) { 4266 admins.add(admin); 4267 } 4268 } 4269 } 4270 } 4271 return admins; 4272 } 4273 } 4274 isSeparateProfileChallengeEnabled(int userHandle)4275 private boolean isSeparateProfileChallengeEnabled(int userHandle) { 4276 long ident = mInjector.binderClearCallingIdentity(); 4277 try { 4278 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle); 4279 } finally { 4280 mInjector.binderRestoreCallingIdentity(ident); 4281 } 4282 } 4283 4284 @Override setPasswordMinimumLength(ComponentName who, int length, boolean parent)4285 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) { 4286 if (!mHasFeature) { 4287 return; 4288 } 4289 Preconditions.checkNotNull(who, "ComponentName is null"); 4290 final int userId = mInjector.userHandleGetCallingUserId(); 4291 synchronized (getLockObject()) { 4292 ActiveAdmin ap = getActiveAdminForCallerLocked( 4293 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4294 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4295 if (metrics.length != length) { 4296 metrics.length = length; 4297 updatePasswordValidityCheckpointLocked(userId, parent); 4298 saveSettingsLocked(userId); 4299 } 4300 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4301 } 4302 DevicePolicyEventLogger 4303 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LENGTH) 4304 .setAdmin(who) 4305 .setInt(length) 4306 .write(); 4307 } 4308 4309 @Override getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent)4310 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) { 4311 return getStrictestPasswordRequirement(who, userHandle, parent, 4312 admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_UNSPECIFIED); 4313 } 4314 4315 @Override setPasswordHistoryLength(ComponentName who, int length, boolean parent)4316 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) { 4317 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4318 return; 4319 } 4320 Preconditions.checkNotNull(who, "ComponentName is null"); 4321 final int userId = mInjector.userHandleGetCallingUserId(); 4322 synchronized (getLockObject()) { 4323 ActiveAdmin ap = getActiveAdminForCallerLocked( 4324 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4325 if (ap.passwordHistoryLength != length) { 4326 ap.passwordHistoryLength = length; 4327 updatePasswordValidityCheckpointLocked(userId, parent); 4328 saveSettingsLocked(userId); 4329 } 4330 } 4331 if (SecurityLog.isLoggingEnabled()) { 4332 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4333 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET, 4334 who.getPackageName(), userId, affectedUserId, length); 4335 } 4336 } 4337 4338 @Override getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent)4339 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) { 4340 if (!mLockPatternUtils.hasSecureLockScreen()) { 4341 return 0; 4342 } 4343 return getStrictestPasswordRequirement(who, userHandle, parent, 4344 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED); 4345 } 4346 4347 @Override setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent)4348 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) { 4349 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4350 return; 4351 } 4352 Preconditions.checkNotNull(who, "ComponentName is null"); 4353 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms"); 4354 final int userHandle = mInjector.userHandleGetCallingUserId(); 4355 synchronized (getLockObject()) { 4356 ActiveAdmin ap = getActiveAdminForCallerLocked( 4357 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent); 4358 // Calling this API automatically bumps the expiration date 4359 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 4360 ap.passwordExpirationDate = expiration; 4361 ap.passwordExpirationTimeout = timeout; 4362 if (timeout > 0L) { 4363 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 4364 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 4365 .format(new Date(expiration))); 4366 } 4367 saveSettingsLocked(userHandle); 4368 4369 // in case this is the first one, set the alarm on the appropriate user. 4370 setExpirationAlarmCheckLocked(mContext, userHandle, parent); 4371 } 4372 if (SecurityLog.isLoggingEnabled()) { 4373 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 4374 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(), 4375 userHandle, affectedUserId, timeout); 4376 } 4377 } 4378 4379 /** 4380 * Return a single admin's expiration cycle time, or the min of all cycle times. 4381 * Returns 0 if not configured. 4382 */ 4383 @Override getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent)4384 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) { 4385 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4386 return 0L; 4387 } 4388 enforceFullCrossUsersPermission(userHandle); 4389 synchronized (getLockObject()) { 4390 long timeout = 0L; 4391 4392 if (who != null) { 4393 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4394 return admin != null ? admin.passwordExpirationTimeout : timeout; 4395 } 4396 4397 // Return the strictest policy across all participating admins. 4398 List<ActiveAdmin> admins = 4399 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4400 final int N = admins.size(); 4401 for (int i = 0; i < N; i++) { 4402 ActiveAdmin admin = admins.get(i); 4403 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 4404 && timeout > admin.passwordExpirationTimeout)) { 4405 timeout = admin.passwordExpirationTimeout; 4406 } 4407 } 4408 return timeout; 4409 } 4410 } 4411 4412 @Override addCrossProfileWidgetProvider(ComponentName admin, String packageName)4413 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4414 final int userId = UserHandle.getCallingUserId(); 4415 List<String> changedProviders = null; 4416 4417 synchronized (getLockObject()) { 4418 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4419 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4420 if (activeAdmin.crossProfileWidgetProviders == null) { 4421 activeAdmin.crossProfileWidgetProviders = new ArrayList<>(); 4422 } 4423 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4424 if (!providers.contains(packageName)) { 4425 providers.add(packageName); 4426 changedProviders = new ArrayList<>(providers); 4427 saveSettingsLocked(userId); 4428 } 4429 } 4430 4431 DevicePolicyEventLogger 4432 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_WIDGET_PROVIDER) 4433 .setAdmin(admin) 4434 .write(); 4435 4436 if (changedProviders != null) { 4437 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 4438 return true; 4439 } 4440 4441 return false; 4442 } 4443 4444 @Override removeCrossProfileWidgetProvider(ComponentName admin, String packageName)4445 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { 4446 final int userId = UserHandle.getCallingUserId(); 4447 List<String> changedProviders = null; 4448 4449 synchronized (getLockObject()) { 4450 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4451 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4452 if (activeAdmin.crossProfileWidgetProviders == null 4453 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4454 return false; 4455 } 4456 List<String> providers = activeAdmin.crossProfileWidgetProviders; 4457 if (providers.remove(packageName)) { 4458 changedProviders = new ArrayList<>(providers); 4459 saveSettingsLocked(userId); 4460 } 4461 } 4462 4463 DevicePolicyEventLogger 4464 .createEvent(DevicePolicyEnums.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER) 4465 .setAdmin(admin) 4466 .write(); 4467 4468 if (changedProviders != null) { 4469 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 4470 return true; 4471 } 4472 4473 return false; 4474 } 4475 4476 @Override getCrossProfileWidgetProviders(ComponentName admin)4477 public List<String> getCrossProfileWidgetProviders(ComponentName admin) { 4478 synchronized (getLockObject()) { 4479 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 4480 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4481 if (activeAdmin.crossProfileWidgetProviders == null 4482 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 4483 return null; 4484 } 4485 if (mInjector.binderIsCallingUidMyUid()) { 4486 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders); 4487 } else { 4488 return activeAdmin.crossProfileWidgetProviders; 4489 } 4490 } 4491 } 4492 4493 /** 4494 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 4495 * Returns 0 if not configured. 4496 */ getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent)4497 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) { 4498 long timeout = 0L; 4499 4500 if (who != null) { 4501 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4502 return admin != null ? admin.passwordExpirationDate : timeout; 4503 } 4504 4505 // Return the strictest policy across all participating admins. 4506 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4507 final int N = admins.size(); 4508 for (int i = 0; i < N; i++) { 4509 ActiveAdmin admin = admins.get(i); 4510 if (timeout == 0L || (admin.passwordExpirationDate != 0 4511 && timeout > admin.passwordExpirationDate)) { 4512 timeout = admin.passwordExpirationDate; 4513 } 4514 } 4515 return timeout; 4516 } 4517 4518 @Override getPasswordExpiration(ComponentName who, int userHandle, boolean parent)4519 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) { 4520 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4521 return 0L; 4522 } 4523 enforceFullCrossUsersPermission(userHandle); 4524 synchronized (getLockObject()) { 4525 return getPasswordExpirationLocked(who, userHandle, parent); 4526 } 4527 } 4528 4529 @Override setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent)4530 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) { 4531 if (!mHasFeature) { 4532 return; 4533 } 4534 Preconditions.checkNotNull(who, "ComponentName is null"); 4535 final int userId = mInjector.userHandleGetCallingUserId(); 4536 synchronized (getLockObject()) { 4537 final ActiveAdmin ap = getActiveAdminForCallerLocked( 4538 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4539 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4540 if (metrics.upperCase != length) { 4541 metrics.upperCase = length; 4542 updatePasswordValidityCheckpointLocked(userId, parent); 4543 saveSettingsLocked(userId); 4544 } 4545 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4546 } 4547 DevicePolicyEventLogger 4548 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_UPPER_CASE) 4549 .setAdmin(who) 4550 .setInt(length) 4551 .write(); 4552 } 4553 4554 @Override getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent)4555 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) { 4556 return getStrictestPasswordRequirement(who, userHandle, parent, 4557 admin -> admin.minimumPasswordMetrics.upperCase, PASSWORD_QUALITY_COMPLEX); 4558 } 4559 4560 @Override setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent)4561 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) { 4562 Preconditions.checkNotNull(who, "ComponentName is null"); 4563 final int userId = mInjector.userHandleGetCallingUserId(); 4564 synchronized (getLockObject()) { 4565 ActiveAdmin ap = getActiveAdminForCallerLocked( 4566 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4567 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4568 if (metrics.lowerCase != length) { 4569 metrics.lowerCase = length; 4570 updatePasswordValidityCheckpointLocked(userId, parent); 4571 saveSettingsLocked(userId); 4572 } 4573 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4574 } 4575 DevicePolicyEventLogger 4576 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LOWER_CASE) 4577 .setAdmin(who) 4578 .setInt(length) 4579 .write(); 4580 } 4581 4582 @Override getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent)4583 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) { 4584 return getStrictestPasswordRequirement(who, userHandle, parent, 4585 admin -> admin.minimumPasswordMetrics.lowerCase, PASSWORD_QUALITY_COMPLEX); 4586 } 4587 4588 @Override setPasswordMinimumLetters(ComponentName who, int length, boolean parent)4589 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) { 4590 if (!mHasFeature) { 4591 return; 4592 } 4593 Preconditions.checkNotNull(who, "ComponentName is null"); 4594 final int userId = mInjector.userHandleGetCallingUserId(); 4595 synchronized (getLockObject()) { 4596 ActiveAdmin ap = getActiveAdminForCallerLocked( 4597 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4598 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4599 if (metrics.letters != length) { 4600 metrics.letters = length; 4601 updatePasswordValidityCheckpointLocked(userId, parent); 4602 saveSettingsLocked(userId); 4603 } 4604 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4605 } 4606 DevicePolicyEventLogger 4607 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LETTERS) 4608 .setAdmin(who) 4609 .setInt(length) 4610 .write(); 4611 } 4612 4613 @Override getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent)4614 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) { 4615 return getStrictestPasswordRequirement(who, userHandle, parent, 4616 admin -> admin.minimumPasswordMetrics.letters, PASSWORD_QUALITY_COMPLEX); 4617 } 4618 4619 @Override setPasswordMinimumNumeric(ComponentName who, int length, boolean parent)4620 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) { 4621 if (!mHasFeature) { 4622 return; 4623 } 4624 Preconditions.checkNotNull(who, "ComponentName is null"); 4625 final int userId = mInjector.userHandleGetCallingUserId(); 4626 synchronized (getLockObject()) { 4627 ActiveAdmin ap = getActiveAdminForCallerLocked( 4628 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4629 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4630 if (metrics.numeric != length) { 4631 metrics.numeric = length; 4632 updatePasswordValidityCheckpointLocked(userId, parent); 4633 saveSettingsLocked(userId); 4634 } 4635 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4636 } 4637 DevicePolicyEventLogger 4638 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NUMERIC) 4639 .setAdmin(who) 4640 .setInt(length) 4641 .write(); 4642 } 4643 4644 @Override getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent)4645 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) { 4646 return getStrictestPasswordRequirement(who, userHandle, parent, 4647 admin -> admin.minimumPasswordMetrics.numeric, PASSWORD_QUALITY_COMPLEX); 4648 } 4649 4650 @Override setPasswordMinimumSymbols(ComponentName who, int length, boolean parent)4651 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) { 4652 if (!mHasFeature) { 4653 return; 4654 } 4655 Preconditions.checkNotNull(who, "ComponentName is null"); 4656 final int userId = mInjector.userHandleGetCallingUserId(); 4657 synchronized (getLockObject()) { 4658 ActiveAdmin ap = getActiveAdminForCallerLocked( 4659 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4660 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4661 if (metrics.symbols != length) { 4662 ap.minimumPasswordMetrics.symbols = length; 4663 updatePasswordValidityCheckpointLocked(userId, parent); 4664 saveSettingsLocked(userId); 4665 } 4666 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4667 } 4668 DevicePolicyEventLogger 4669 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_SYMBOLS) 4670 .setAdmin(who) 4671 .setInt(length) 4672 .write(); 4673 } 4674 4675 @Override getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent)4676 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) { 4677 return getStrictestPasswordRequirement(who, userHandle, parent, 4678 admin -> admin.minimumPasswordMetrics.symbols, PASSWORD_QUALITY_COMPLEX); 4679 } 4680 4681 @Override setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent)4682 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) { 4683 if (!mHasFeature) { 4684 return; 4685 } 4686 Preconditions.checkNotNull(who, "ComponentName is null"); 4687 final int userId = mInjector.userHandleGetCallingUserId(); 4688 synchronized (getLockObject()) { 4689 ActiveAdmin ap = getActiveAdminForCallerLocked( 4690 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4691 final PasswordMetrics metrics = ap.minimumPasswordMetrics; 4692 if (metrics.nonLetter != length) { 4693 ap.minimumPasswordMetrics.nonLetter = length; 4694 updatePasswordValidityCheckpointLocked(userId, parent); 4695 saveSettingsLocked(userId); 4696 } 4697 maybeLogPasswordComplexitySet(who, userId, parent, metrics); 4698 } 4699 DevicePolicyEventLogger 4700 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NON_LETTER) 4701 .setAdmin(who) 4702 .setInt(length) 4703 .write(); 4704 } 4705 4706 @Override getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent)4707 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) { 4708 return getStrictestPasswordRequirement(who, userHandle, parent, 4709 admin -> admin.minimumPasswordMetrics.nonLetter, PASSWORD_QUALITY_COMPLEX); 4710 } 4711 4712 /** 4713 * Calculates strictest (maximum) value for a given password property enforced by admin[s]. 4714 */ getStrictestPasswordRequirement(ComponentName who, int userHandle, boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality)4715 private int getStrictestPasswordRequirement(ComponentName who, int userHandle, 4716 boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) { 4717 if (!mHasFeature) { 4718 return 0; 4719 } 4720 enforceFullCrossUsersPermission(userHandle); 4721 synchronized (getLockObject()) { 4722 if (who != null) { 4723 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4724 return admin != null ? getter.apply(admin) : 0; 4725 } 4726 4727 int maxValue = 0; 4728 final List<ActiveAdmin> admins = 4729 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4730 final int N = admins.size(); 4731 for (int i = 0; i < N; i++) { 4732 final ActiveAdmin admin = admins.get(i); 4733 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) { 4734 continue; 4735 } 4736 final Integer adminValue = getter.apply(admin); 4737 if (adminValue > maxValue) { 4738 maxValue = adminValue; 4739 } 4740 } 4741 return maxValue; 4742 } 4743 } 4744 4745 @Override isActivePasswordSufficient(int userHandle, boolean parent)4746 public boolean isActivePasswordSufficient(int userHandle, boolean parent) { 4747 if (!mHasFeature) { 4748 return true; 4749 } 4750 enforceFullCrossUsersPermission(userHandle); 4751 enforceUserUnlocked(userHandle, parent); 4752 4753 synchronized (getLockObject()) { 4754 // This API can only be called by an active device admin, 4755 // so try to retrieve it to check that the caller is one. 4756 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4757 int credentialOwner = getCredentialOwner(userHandle, parent); 4758 DevicePolicyData policy = getUserDataUnchecked(credentialOwner); 4759 PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner); 4760 return isActivePasswordSufficientForUserLocked( 4761 policy.mPasswordValidAtLastCheckpoint, metrics, userHandle, parent); 4762 } 4763 } 4764 4765 @Override isUsingUnifiedPassword(ComponentName admin)4766 public boolean isUsingUnifiedPassword(ComponentName admin) { 4767 if (!mHasFeature) { 4768 return true; 4769 } 4770 final int userId = mInjector.userHandleGetCallingUserId(); 4771 enforceProfileOrDeviceOwner(admin); 4772 enforceManagedProfile(userId, "query unified challenge status"); 4773 return !isSeparateProfileChallengeEnabled(userId); 4774 } 4775 4776 @Override isProfileActivePasswordSufficientForParent(int userHandle)4777 public boolean isProfileActivePasswordSufficientForParent(int userHandle) { 4778 if (!mHasFeature) { 4779 return true; 4780 } 4781 enforceFullCrossUsersPermission(userHandle); 4782 enforceManagedProfile(userHandle, "call APIs refering to the parent profile"); 4783 4784 synchronized (getLockObject()) { 4785 final int targetUser = getProfileParentId(userHandle); 4786 enforceUserUnlocked(targetUser, false); 4787 int credentialOwner = getCredentialOwner(userHandle, false); 4788 DevicePolicyData policy = getUserDataUnchecked(credentialOwner); 4789 PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner); 4790 return isActivePasswordSufficientForUserLocked( 4791 policy.mPasswordValidAtLastCheckpoint, metrics, targetUser, false); 4792 } 4793 } 4794 isActivePasswordSufficientForUserLocked( boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle, boolean parent)4795 private boolean isActivePasswordSufficientForUserLocked( 4796 boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle, 4797 boolean parent) { 4798 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) { 4799 // Before user enters their password for the first time after a reboot, return the 4800 // value of this flag, which tells us whether the password was valid the last time 4801 // settings were saved. If DPC changes password requirements on boot so that the 4802 // current password no longer meets the requirements, this value will be stale until 4803 // the next time the password is entered. 4804 return passwordValidAtLastCheckpoint; 4805 } 4806 4807 if (metrics == null) { 4808 // This could happen if the user never had a password set, for example, so 4809 // setActivePasswordState has never been called for it. 4810 metrics = new PasswordMetrics(); 4811 } 4812 4813 return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle, parent); 4814 } 4815 4816 /** 4817 * Returns {@code true} if the password represented by the {@code metrics} argument 4818 * sufficiently fulfills the password requirements for the user corresponding to 4819 * {@code userId} (or its parent, if {@code parent} is set to {@code true}). 4820 */ isPasswordSufficientForUserWithoutCheckpointLocked( PasswordMetrics metrics, @UserIdInt int userId, boolean parent)4821 private boolean isPasswordSufficientForUserWithoutCheckpointLocked( 4822 PasswordMetrics metrics, @UserIdInt int userId, boolean parent) { 4823 final int requiredQuality = getPasswordQuality(null, userId, parent); 4824 4825 if (requiredQuality >= PASSWORD_QUALITY_NUMERIC 4826 && metrics.length < getPasswordMinimumLength(null, userId, parent)) { 4827 return false; 4828 } 4829 4830 // PASSWORD_QUALITY_COMPLEX doesn't represent actual password quality, it means that number 4831 // of characters of each class should be checked instead of quality itself. 4832 if (requiredQuality == PASSWORD_QUALITY_COMPLEX) { 4833 return metrics.upperCase >= getPasswordMinimumUpperCase(null, userId, parent) 4834 && metrics.lowerCase >= getPasswordMinimumLowerCase(null, userId, parent) 4835 && metrics.letters >= getPasswordMinimumLetters(null, userId, parent) 4836 && metrics.numeric >= getPasswordMinimumNumeric(null, userId, parent) 4837 && metrics.symbols >= getPasswordMinimumSymbols(null, userId, parent) 4838 && metrics.nonLetter >= getPasswordMinimumNonLetter(null, userId, parent); 4839 } else { 4840 return metrics.quality >= requiredQuality; 4841 } 4842 } 4843 4844 @Override 4845 @PasswordComplexity getPasswordComplexity()4846 public int getPasswordComplexity() { 4847 DevicePolicyEventLogger 4848 .createEvent(DevicePolicyEnums.GET_USER_PASSWORD_COMPLEXITY_LEVEL) 4849 .setStrings(mInjector.getPackageManager() 4850 .getPackagesForUid(mInjector.binderGetCallingUid())) 4851 .write(); 4852 final int callingUserId = mInjector.userHandleGetCallingUserId(); 4853 enforceUserUnlocked(callingUserId); 4854 mContext.enforceCallingOrSelfPermission( 4855 REQUEST_PASSWORD_COMPLEXITY, 4856 "Must have " + REQUEST_PASSWORD_COMPLEXITY + " permission."); 4857 4858 synchronized (getLockObject()) { 4859 int targetUserId = getCredentialOwner(callingUserId, /* parent= */ false); 4860 PasswordMetrics metrics = getUserPasswordMetricsLocked(targetUserId); 4861 return metrics == null ? PASSWORD_COMPLEXITY_NONE : metrics.determineComplexity(); 4862 } 4863 } 4864 4865 @Override getCurrentFailedPasswordAttempts(int userHandle, boolean parent)4866 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) { 4867 if (!mLockPatternUtils.hasSecureLockScreen()) { 4868 return 0; 4869 } 4870 enforceFullCrossUsersPermission(userHandle); 4871 synchronized (getLockObject()) { 4872 if (!isCallerWithSystemUid()) { 4873 // This API can be called by an active device admin or by keyguard code. 4874 if (mContext.checkCallingPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE) 4875 != PackageManager.PERMISSION_GRANTED) { 4876 getActiveAdminForCallerLocked( 4877 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4878 } 4879 } 4880 4881 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4882 4883 return policy.mFailedPasswordAttempts; 4884 } 4885 } 4886 4887 @Override setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent)4888 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) { 4889 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4890 return; 4891 } 4892 Preconditions.checkNotNull(who, "ComponentName is null"); 4893 final int userId = mInjector.userHandleGetCallingUserId(); 4894 synchronized (getLockObject()) { 4895 // This API can only be called by an active device admin, 4896 // so try to retrieve it to check that the caller is one. 4897 getActiveAdminForCallerLocked( 4898 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent); 4899 ActiveAdmin ap = getActiveAdminForCallerLocked( 4900 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4901 if (ap.maximumFailedPasswordsForWipe != num) { 4902 ap.maximumFailedPasswordsForWipe = num; 4903 saveSettingsLocked(userId); 4904 } 4905 } 4906 if (SecurityLog.isLoggingEnabled()) { 4907 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 4908 SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(), 4909 userId, affectedUserId, num); 4910 } 4911 } 4912 4913 @Override getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent)4914 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) { 4915 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4916 return 0; 4917 } 4918 enforceFullCrossUsersPermission(userHandle); 4919 synchronized (getLockObject()) { 4920 ActiveAdmin admin = (who != null) 4921 ? getActiveAdminUncheckedLocked(who, userHandle, parent) 4922 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent); 4923 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 4924 } 4925 } 4926 4927 @Override getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent)4928 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) { 4929 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 4930 return UserHandle.USER_NULL; 4931 } 4932 enforceFullCrossUsersPermission(userHandle); 4933 synchronized (getLockObject()) { 4934 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked( 4935 userHandle, parent); 4936 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL; 4937 } 4938 } 4939 4940 /** 4941 * Returns the admin with the strictest policy on maximum failed passwords for: 4942 * <ul> 4943 * <li>this user if it has a separate profile challenge, or 4944 * <li>this user and all profiles that don't have their own challenge otherwise. 4945 * </ul> 4946 * <p>If the policy for the primary and any other profile are equal, it returns the admin for 4947 * the primary profile. 4948 * Returns {@code null} if no participating admin has that policy set. 4949 */ getAdminWithMinimumFailedPasswordsForWipeLocked( int userHandle, boolean parent)4950 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked( 4951 int userHandle, boolean parent) { 4952 int count = 0; 4953 ActiveAdmin strictestAdmin = null; 4954 4955 // Return the strictest policy across all participating admins. 4956 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4957 final int N = admins.size(); 4958 for (int i = 0; i < N; i++) { 4959 ActiveAdmin admin = admins.get(i); 4960 if (admin.maximumFailedPasswordsForWipe == 4961 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 4962 continue; // No max number of failed passwords policy set for this profile. 4963 } 4964 4965 // We always favor the primary profile if several profiles have the same value set. 4966 int userId = admin.getUserHandle().getIdentifier(); 4967 if (count == 0 || 4968 count > admin.maximumFailedPasswordsForWipe || 4969 (count == admin.maximumFailedPasswordsForWipe && 4970 getUserInfo(userId).isPrimary())) { 4971 count = admin.maximumFailedPasswordsForWipe; 4972 strictestAdmin = admin; 4973 } 4974 } 4975 return strictestAdmin; 4976 } 4977 getUserInfo(@serIdInt int userId)4978 private UserInfo getUserInfo(@UserIdInt int userId) { 4979 final long token = mInjector.binderClearCallingIdentity(); 4980 try { 4981 return mUserManager.getUserInfo(userId); 4982 } finally { 4983 mInjector.binderRestoreCallingIdentity(token); 4984 } 4985 } 4986 canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId)4987 private boolean canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId) { 4988 // Only if the admins targets a pre-O SDK 4989 return getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.O; 4990 } 4991 4992 /* PO or DO could do an untrusted reset in certain conditions. */ canUserHaveUntrustedCredentialReset(@serIdInt int userId)4993 private boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) { 4994 synchronized (getLockObject()) { 4995 // An active DO or PO might be able to fo an untrusted credential reset 4996 for (final ActiveAdmin admin : getUserData(userId).mAdminList) { 4997 if (!isActiveAdminWithPolicyForUserLocked(admin, 4998 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, userId)) { 4999 continue; 5000 } 5001 if (canPOorDOCallResetPassword(admin, userId)) { 5002 return true; 5003 } 5004 } 5005 return false; 5006 } 5007 } 5008 @Override resetPassword(String passwordOrNull, int flags)5009 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException { 5010 if (!mLockPatternUtils.hasSecureLockScreen()) { 5011 Slog.w(LOG_TAG, "Cannot reset password when the device has no lock screen"); 5012 return false; 5013 } 5014 5015 final int callingUid = mInjector.binderGetCallingUid(); 5016 final int userHandle = mInjector.userHandleGetCallingUserId(); 5017 5018 String password = passwordOrNull != null ? passwordOrNull : ""; 5019 5020 // Password resetting to empty/null is not allowed for managed profiles. 5021 if (TextUtils.isEmpty(password)) { 5022 enforceNotManagedProfile(userHandle, "clear the active password"); 5023 } 5024 5025 synchronized (getLockObject()) { 5026 // If caller has PO (or DO) it can change the password, so see if that's the case first. 5027 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked( 5028 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid); 5029 final boolean preN; 5030 if (admin != null) { 5031 if (!canPOorDOCallResetPassword(admin, userHandle)) { 5032 throw new SecurityException("resetPassword() is deprecated for DPC targeting O" 5033 + " or later"); 5034 } 5035 preN = getTargetSdk(admin.info.getPackageName(), 5036 userHandle) <= android.os.Build.VERSION_CODES.M; 5037 } else { 5038 // Otherwise, make sure the caller has any active admin with the right policy or 5039 // the required permission. 5040 admin = getActiveAdminOrCheckPermissionForCallerLocked( 5041 null, 5042 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD, 5043 android.Manifest.permission.RESET_PASSWORD); 5044 // Cannot be preN if admin is null because an exception would have been 5045 // thrown before getting here 5046 preN = admin == null ? false : getTargetSdk(admin.info.getPackageName(), 5047 userHandle) <= android.os.Build.VERSION_CODES.M; 5048 5049 // As of N, password resetting to empty/null is not allowed anymore. 5050 // TODO Should we allow DO/PO to set an empty password? 5051 if (TextUtils.isEmpty(password)) { 5052 if (!preN) { 5053 throw new SecurityException("Cannot call with null password"); 5054 } else { 5055 Slog.e(LOG_TAG, "Cannot call with null password"); 5056 return false; 5057 } 5058 } 5059 // As of N, password cannot be changed by the admin if it is already set. 5060 if (isLockScreenSecureUnchecked(userHandle)) { 5061 if (!preN) { 5062 throw new SecurityException("Cannot change current password"); 5063 } else { 5064 Slog.e(LOG_TAG, "Cannot change current password"); 5065 return false; 5066 } 5067 } 5068 } 5069 // Do not allow to reset password when current user has a managed profile 5070 if (!isManagedProfile(userHandle)) { 5071 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 5072 if (userInfo.isManagedProfile()) { 5073 if (!preN) { 5074 throw new IllegalStateException( 5075 "Cannot reset password on user has managed profile"); 5076 } else { 5077 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile"); 5078 return false; 5079 } 5080 } 5081 } 5082 } 5083 // Do not allow to reset password when user is locked 5084 if (!mUserManager.isUserUnlocked(userHandle)) { 5085 if (!preN) { 5086 throw new IllegalStateException("Cannot reset password when user is locked"); 5087 } else { 5088 Slog.e(LOG_TAG, "Cannot reset password when user is locked"); 5089 return false; 5090 } 5091 } 5092 } 5093 5094 return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle); 5095 } 5096 resetPasswordInternal(String password, long tokenHandle, byte[] token, int flags, int callingUid, int userHandle)5097 private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token, 5098 int flags, int callingUid, int userHandle) { 5099 int quality; 5100 synchronized (getLockObject()) { 5101 quality = getPasswordQuality(null, userHandle, /* parent */ false); 5102 if (quality == PASSWORD_QUALITY_MANAGED) { 5103 quality = PASSWORD_QUALITY_UNSPECIFIED; 5104 } 5105 // TODO(b/120484642): remove getBytes() below 5106 final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password.getBytes()); 5107 final int realQuality = metrics.quality; 5108 if (realQuality < quality && quality != PASSWORD_QUALITY_COMPLEX) { 5109 Slog.w(LOG_TAG, "resetPassword: password quality 0x" 5110 + Integer.toHexString(realQuality) 5111 + " does not meet required quality 0x" 5112 + Integer.toHexString(quality)); 5113 return false; 5114 } 5115 quality = Math.max(realQuality, quality); 5116 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false); 5117 if (password.length() < length) { 5118 Slog.w(LOG_TAG, "resetPassword: password length " + password.length() 5119 + " does not meet required length " + length); 5120 return false; 5121 } 5122 if (quality == PASSWORD_QUALITY_COMPLEX) { 5123 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false); 5124 if(metrics.letters < neededLetters) { 5125 Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters 5126 + " does not meet required number of letters " + neededLetters); 5127 return false; 5128 } 5129 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false); 5130 if (metrics.numeric < neededNumeric) { 5131 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric 5132 + " does not meet required number of numerical digits " 5133 + neededNumeric); 5134 return false; 5135 } 5136 int neededLowerCase = getPasswordMinimumLowerCase( 5137 null, userHandle, /* parent */ false); 5138 if (metrics.lowerCase < neededLowerCase) { 5139 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " 5140 + metrics.lowerCase 5141 + " does not meet required number of lowercase letters " 5142 + neededLowerCase); 5143 return false; 5144 } 5145 int neededUpperCase = getPasswordMinimumUpperCase( 5146 null, userHandle, /* parent */ false); 5147 if (metrics.upperCase < neededUpperCase) { 5148 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " 5149 + metrics.upperCase 5150 + " does not meet required number of uppercase letters " 5151 + neededUpperCase); 5152 return false; 5153 } 5154 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false); 5155 if (metrics.symbols < neededSymbols) { 5156 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols 5157 + " does not meet required number of special symbols " + neededSymbols); 5158 return false; 5159 } 5160 int neededNonLetter = getPasswordMinimumNonLetter( 5161 null, userHandle, /* parent */ false); 5162 if (metrics.nonLetter < neededNonLetter) { 5163 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " 5164 + metrics.nonLetter 5165 + " does not meet required number of non-letter characters " 5166 + neededNonLetter); 5167 return false; 5168 } 5169 } 5170 } 5171 5172 DevicePolicyData policy = getUserData(userHandle); 5173 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 5174 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 5175 return false; 5176 } 5177 5178 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid); 5179 boolean doNotAskCredentialsOnBoot = 5180 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 5181 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 5182 setDoNotAskCredentialsOnBoot(); 5183 } 5184 5185 // Don't do this with the lock held, because it is going to call 5186 // back in to the service. 5187 final long ident = mInjector.binderClearCallingIdentity(); 5188 final boolean result; 5189 try { 5190 if (token == null) { 5191 // This is the legacy reset password for DPM. Here we want to be able to override 5192 // the old device password without necessarily knowing it. 5193 if (!TextUtils.isEmpty(password)) { 5194 mLockPatternUtils.saveLockPassword(password.getBytes(), null, quality, 5195 userHandle, /*allowUntrustedChange */true); 5196 } else { 5197 mLockPatternUtils.clearLock(null, userHandle, 5198 /*allowUntrustedChange */ true); 5199 } 5200 result = true; 5201 } else { 5202 if (!TextUtils.isEmpty(password)) { 5203 result = mLockPatternUtils.setLockCredentialWithToken(password.getBytes(), 5204 LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 5205 quality, tokenHandle, token, userHandle); 5206 } else { 5207 result = mLockPatternUtils.setLockCredentialWithToken(null, 5208 LockPatternUtils.CREDENTIAL_TYPE_NONE, 5209 quality, tokenHandle, token, userHandle); 5210 } 5211 } 5212 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 5213 if (requireEntry) { 5214 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, 5215 UserHandle.USER_ALL); 5216 } 5217 synchronized (getLockObject()) { 5218 int newOwner = requireEntry ? callingUid : -1; 5219 if (policy.mPasswordOwner != newOwner) { 5220 policy.mPasswordOwner = newOwner; 5221 saveSettingsLocked(userHandle); 5222 } 5223 } 5224 } finally { 5225 mInjector.binderRestoreCallingIdentity(ident); 5226 } 5227 return result; 5228 } 5229 isLockScreenSecureUnchecked(int userId)5230 private boolean isLockScreenSecureUnchecked(int userId) { 5231 long ident = mInjector.binderClearCallingIdentity(); 5232 try { 5233 return mLockPatternUtils.isSecure(userId); 5234 } finally { 5235 mInjector.binderRestoreCallingIdentity(ident); 5236 } 5237 } 5238 setDoNotAskCredentialsOnBoot()5239 private void setDoNotAskCredentialsOnBoot() { 5240 synchronized (getLockObject()) { 5241 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 5242 if (!policyData.doNotAskCredentialsOnBoot) { 5243 policyData.doNotAskCredentialsOnBoot = true; 5244 saveSettingsLocked(UserHandle.USER_SYSTEM); 5245 } 5246 } 5247 } 5248 5249 @Override getDoNotAskCredentialsOnBoot()5250 public boolean getDoNotAskCredentialsOnBoot() { 5251 mContext.enforceCallingOrSelfPermission( 5252 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null); 5253 synchronized (getLockObject()) { 5254 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 5255 return policyData.doNotAskCredentialsOnBoot; 5256 } 5257 } 5258 5259 @Override setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent)5260 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) { 5261 if (!mHasFeature) { 5262 return; 5263 } 5264 Preconditions.checkNotNull(who, "ComponentName is null"); 5265 final int userHandle = mInjector.userHandleGetCallingUserId(); 5266 synchronized (getLockObject()) { 5267 final ActiveAdmin ap = getActiveAdminForCallerLocked( 5268 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 5269 if (ap.maximumTimeToUnlock != timeMs) { 5270 ap.maximumTimeToUnlock = timeMs; 5271 saveSettingsLocked(userHandle); 5272 updateMaximumTimeToLockLocked(userHandle); 5273 } 5274 } 5275 if (SecurityLog.isLoggingEnabled()) { 5276 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 5277 SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET, 5278 who.getPackageName(), userHandle, affectedUserId, timeMs); 5279 } 5280 } 5281 updateMaximumTimeToLockLocked(@serIdInt int userId)5282 private void updateMaximumTimeToLockLocked(@UserIdInt int userId) { 5283 // Update the profile's timeout 5284 if (isManagedProfile(userId)) { 5285 updateProfileLockTimeoutLocked(userId); 5286 } 5287 5288 final long timeMs; 5289 final long ident = mInjector.binderClearCallingIdentity(); 5290 try { 5291 // Update the device timeout 5292 final int parentId = getProfileParentId(userId); 5293 timeMs = getMaximumTimeToLockPolicyFromAdmins( 5294 getActiveAdminsForLockscreenPoliciesLocked(parentId, false)); 5295 5296 final DevicePolicyData policy = getUserDataUnchecked(parentId); 5297 if (policy.mLastMaximumTimeToLock == timeMs) { 5298 return; 5299 } 5300 policy.mLastMaximumTimeToLock = timeMs; 5301 5302 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) { 5303 // Make sure KEEP_SCREEN_ON is disabled, since that 5304 // would allow bypassing of the maximum time to lock. 5305 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 5306 } 5307 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5308 UserHandle.USER_SYSTEM, timeMs); 5309 } finally { 5310 mInjector.binderRestoreCallingIdentity(ident); 5311 } 5312 } 5313 updateProfileLockTimeoutLocked(@serIdInt int userId)5314 private void updateProfileLockTimeoutLocked(@UserIdInt int userId) { 5315 final long timeMs; 5316 if (isSeparateProfileChallengeEnabled(userId)) { 5317 timeMs = getMaximumTimeToLockPolicyFromAdmins( 5318 getActiveAdminsForLockscreenPoliciesLocked(userId, false /* parent */)); 5319 } else { 5320 timeMs = Long.MAX_VALUE; 5321 } 5322 5323 final DevicePolicyData policy = getUserDataUnchecked(userId); 5324 if (policy.mLastMaximumTimeToLock == timeMs) { 5325 return; 5326 } 5327 policy.mLastMaximumTimeToLock = timeMs; 5328 5329 final long ident = mInjector.binderClearCallingIdentity(); 5330 try { 5331 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 5332 userId, policy.mLastMaximumTimeToLock); 5333 } finally { 5334 mInjector.binderRestoreCallingIdentity(ident); 5335 } 5336 } 5337 5338 @Override getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent)5339 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) { 5340 if (!mHasFeature) { 5341 return 0; 5342 } 5343 enforceFullCrossUsersPermission(userHandle); 5344 synchronized (getLockObject()) { 5345 if (who != null) { 5346 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 5347 return admin != null ? admin.maximumTimeToUnlock : 0; 5348 } 5349 // Return the strictest policy across all participating admins. 5350 final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5351 userHandle, parent); 5352 final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins); 5353 return timeMs == Long.MAX_VALUE ? 0 : timeMs; 5354 } 5355 } 5356 getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins)5357 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) { 5358 long time = Long.MAX_VALUE; 5359 for (final ActiveAdmin admin : admins) { 5360 if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) { 5361 time = admin.maximumTimeToUnlock; 5362 } 5363 } 5364 return time; 5365 } 5366 5367 @Override setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, boolean parent)5368 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, 5369 boolean parent) { 5370 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 5371 return; 5372 } 5373 Preconditions.checkNotNull(who, "ComponentName is null"); 5374 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number."); 5375 // timeoutMs with value 0 means that the admin doesn't participate 5376 // timeoutMs is clamped to the interval in case the internal constants change in the future 5377 final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs(); 5378 if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) { 5379 timeoutMs = minimumStrongAuthTimeout; 5380 } 5381 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 5382 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5383 } 5384 5385 final int userHandle = mInjector.userHandleGetCallingUserId(); 5386 synchronized (getLockObject()) { 5387 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5388 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent); 5389 if (ap.strongAuthUnlockTimeout != timeoutMs) { 5390 ap.strongAuthUnlockTimeout = timeoutMs; 5391 saveSettingsLocked(userHandle); 5392 } 5393 } 5394 } 5395 5396 /** 5397 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all 5398 * admins if who is null. 5399 * Returns 0 if not configured for the provided admin. 5400 */ 5401 @Override getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent)5402 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) { 5403 if (!mHasFeature) { 5404 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5405 } 5406 if (!mLockPatternUtils.hasSecureLockScreen()) { 5407 // No strong auth timeout on devices not supporting the 5408 // {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature 5409 return 0; 5410 } 5411 enforceFullCrossUsersPermission(userId); 5412 synchronized (getLockObject()) { 5413 if (who != null) { 5414 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent); 5415 return admin != null ? admin.strongAuthUnlockTimeout : 0; 5416 } 5417 5418 // Return the strictest policy across all participating admins. 5419 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent); 5420 5421 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 5422 for (int i = 0; i < admins.size(); i++) { 5423 final long timeout = admins.get(i).strongAuthUnlockTimeout; 5424 if (timeout != 0) { // take only participating admins into account 5425 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout); 5426 } 5427 } 5428 return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs()); 5429 } 5430 } 5431 getMinimumStrongAuthTimeoutMs()5432 private long getMinimumStrongAuthTimeoutMs() { 5433 if (!mInjector.isBuildDebuggable()) { 5434 return MINIMUM_STRONG_AUTH_TIMEOUT_MS; 5435 } 5436 // ideally the property was named persist.sys.min_strong_auth_timeout, but system property 5437 // name cannot be longer than 31 characters 5438 return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo", 5439 MINIMUM_STRONG_AUTH_TIMEOUT_MS), 5440 MINIMUM_STRONG_AUTH_TIMEOUT_MS); 5441 } 5442 5443 @Override lockNow(int flags, boolean parent)5444 public void lockNow(int flags, boolean parent) { 5445 if (!mHasFeature) { 5446 return; 5447 } 5448 5449 final int callingUserId = mInjector.userHandleGetCallingUserId(); 5450 ComponentName adminComponent = null; 5451 synchronized (getLockObject()) { 5452 // Make sure the caller has any active admin with the right policy or 5453 // the required permission. 5454 final ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked( 5455 null, 5456 DeviceAdminInfo.USES_POLICY_FORCE_LOCK, 5457 parent, 5458 android.Manifest.permission.LOCK_DEVICE); 5459 final long ident = mInjector.binderClearCallingIdentity(); 5460 try { 5461 adminComponent = admin == null ? null : admin.info.getComponent(); 5462 if (adminComponent != null) { 5463 // For Profile Owners only, callers with only permission not allowed. 5464 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) { 5465 // Evict key 5466 enforceManagedProfile( 5467 callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 5468 if (!isProfileOwner(adminComponent, callingUserId)) { 5469 throw new SecurityException("Only profile owner admins can set " 5470 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY"); 5471 } 5472 if (parent) { 5473 throw new IllegalArgumentException( 5474 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent"); 5475 } 5476 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5477 throw new UnsupportedOperationException( 5478 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices"); 5479 } 5480 mUserManager.evictCredentialEncryptionKey(callingUserId); 5481 } 5482 } 5483 5484 // Lock all users unless this is a managed profile with a separate challenge 5485 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId) 5486 ? UserHandle.USER_ALL : callingUserId); 5487 mLockPatternUtils.requireStrongAuth( 5488 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock); 5489 5490 // Require authentication for the device or profile 5491 if (userToLock == UserHandle.USER_ALL) { 5492 // Power off the display 5493 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(), 5494 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 5495 mInjector.getIWindowManager().lockNow(null); 5496 } else { 5497 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true); 5498 } 5499 5500 if (SecurityLog.isLoggingEnabled() && adminComponent != null) { 5501 final int affectedUserId = 5502 parent ? getProfileParentId(callingUserId) : callingUserId; 5503 SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK, 5504 adminComponent.getPackageName(), callingUserId, affectedUserId); 5505 } 5506 } catch (RemoteException e) { 5507 } finally { 5508 mInjector.binderRestoreCallingIdentity(ident); 5509 } 5510 } 5511 DevicePolicyEventLogger 5512 .createEvent(DevicePolicyEnums.LOCK_NOW) 5513 .setAdmin(adminComponent) 5514 .setInt(flags) 5515 .write(); 5516 } 5517 5518 @Override enforceCanManageCaCerts(ComponentName who, String callerPackage)5519 public void enforceCanManageCaCerts(ComponentName who, String callerPackage) { 5520 if (who == null) { 5521 if (!isCallerDelegate(callerPackage, mInjector.binderGetCallingUid(), 5522 DELEGATION_CERT_INSTALL)) { 5523 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 5524 } 5525 } else { 5526 enforceProfileOrDeviceOwner(who); 5527 } 5528 } 5529 enforceDeviceOwner(ComponentName who)5530 private void enforceDeviceOwner(ComponentName who) { 5531 synchronized (getLockObject()) { 5532 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5533 } 5534 } 5535 enforceProfileOrDeviceOwner(ComponentName who)5536 private void enforceProfileOrDeviceOwner(ComponentName who) { 5537 synchronized (getLockObject()) { 5538 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5539 } 5540 } 5541 5542 @Override approveCaCert(String alias, int userId, boolean approval)5543 public boolean approveCaCert(String alias, int userId, boolean approval) { 5544 enforceManageUsers(); 5545 synchronized (getLockObject()) { 5546 Set<String> certs = getUserData(userId).mAcceptedCaCertificates; 5547 boolean changed = (approval ? certs.add(alias) : certs.remove(alias)); 5548 if (!changed) { 5549 return false; 5550 } 5551 saveSettingsLocked(userId); 5552 } 5553 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5554 return true; 5555 } 5556 5557 @Override isCaCertApproved(String alias, int userId)5558 public boolean isCaCertApproved(String alias, int userId) { 5559 enforceManageUsers(); 5560 synchronized (getLockObject()) { 5561 return getUserData(userId).mAcceptedCaCertificates.contains(alias); 5562 } 5563 } 5564 removeCaApprovalsIfNeeded(int userId)5565 private void removeCaApprovalsIfNeeded(int userId) { 5566 for (UserInfo userInfo : mUserManager.getProfiles(userId)) { 5567 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id); 5568 if (userInfo.isManagedProfile()){ 5569 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id)); 5570 } 5571 if (!isSecure) { 5572 synchronized (getLockObject()) { 5573 getUserData(userInfo.id).mAcceptedCaCertificates.clear(); 5574 saveSettingsLocked(userInfo.id); 5575 } 5576 mCertificateMonitor.onCertificateApprovalsChanged(userId); 5577 } 5578 } 5579 } 5580 5581 @Override installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)5582 public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) 5583 throws RemoteException { 5584 if (!mHasFeature) { 5585 return false; 5586 } 5587 enforceCanManageCaCerts(admin, callerPackage); 5588 5589 final String alias; 5590 5591 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 5592 final long id = mInjector.binderClearCallingIdentity(); 5593 try { 5594 alias = mCertificateMonitor.installCaCert(userHandle, certBuffer); 5595 final boolean isDelegate = (admin == null); 5596 DevicePolicyEventLogger 5597 .createEvent(DevicePolicyEnums.INSTALL_CA_CERT) 5598 .setAdmin(callerPackage) 5599 .setBoolean(isDelegate) 5600 .write(); 5601 if (alias == null) { 5602 Log.w(LOG_TAG, "Problem installing cert"); 5603 return false; 5604 } 5605 } finally { 5606 mInjector.binderRestoreCallingIdentity(id); 5607 } 5608 5609 synchronized (getLockObject()) { 5610 getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias); 5611 saveSettingsLocked(userHandle.getIdentifier()); 5612 } 5613 return true; 5614 } 5615 5616 @Override uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases)5617 public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) { 5618 if (!mHasFeature) { 5619 return; 5620 } 5621 enforceCanManageCaCerts(admin, callerPackage); 5622 5623 final int userId = mInjector.userHandleGetCallingUserId(); 5624 final long id = mInjector.binderClearCallingIdentity(); 5625 try { 5626 mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases); 5627 final boolean isDelegate = (admin == null); 5628 DevicePolicyEventLogger 5629 .createEvent(DevicePolicyEnums.UNINSTALL_CA_CERTS) 5630 .setAdmin(callerPackage) 5631 .setBoolean(isDelegate) 5632 .write(); 5633 } finally { 5634 mInjector.binderRestoreCallingIdentity(id); 5635 } 5636 5637 synchronized (getLockObject()) { 5638 if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) { 5639 saveSettingsLocked(userId); 5640 } 5641 } 5642 } 5643 5644 @Override installKeyPair(ComponentName who, String callerPackage, byte[] privKey, byte[] cert, byte[] chain, String alias, boolean requestAccess, boolean isUserSelectable)5645 public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey, 5646 byte[] cert, byte[] chain, String alias, boolean requestAccess, 5647 boolean isUserSelectable) { 5648 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5649 DELEGATION_CERT_INSTALL); 5650 5651 5652 final int callingUid = mInjector.binderGetCallingUid(); 5653 final long id = mInjector.binderClearCallingIdentity(); 5654 try { 5655 final KeyChainConnection keyChainConnection = 5656 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid)); 5657 try { 5658 IKeyChainService keyChain = keyChainConnection.getService(); 5659 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) { 5660 return false; 5661 } 5662 if (requestAccess) { 5663 keyChain.setGrant(callingUid, alias, true); 5664 } 5665 keyChain.setUserSelectable(alias, isUserSelectable); 5666 final boolean isDelegate = (who == null); 5667 DevicePolicyEventLogger 5668 .createEvent(DevicePolicyEnums.INSTALL_KEY_PAIR) 5669 .setAdmin(callerPackage) 5670 .setBoolean(isDelegate) 5671 .write(); 5672 return true; 5673 } catch (RemoteException e) { 5674 Log.e(LOG_TAG, "Installing certificate", e); 5675 } finally { 5676 keyChainConnection.close(); 5677 } 5678 } catch (InterruptedException e) { 5679 Log.w(LOG_TAG, "Interrupted while installing certificate", e); 5680 Thread.currentThread().interrupt(); 5681 } finally { 5682 mInjector.binderRestoreCallingIdentity(id); 5683 } 5684 return false; 5685 } 5686 5687 @Override removeKeyPair(ComponentName who, String callerPackage, String alias)5688 public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) { 5689 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5690 DELEGATION_CERT_INSTALL); 5691 5692 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 5693 final long id = Binder.clearCallingIdentity(); 5694 try { 5695 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 5696 try { 5697 IKeyChainService keyChain = keyChainConnection.getService(); 5698 final boolean result = keyChain.removeKeyPair(alias); 5699 final boolean isDelegate = (who == null); 5700 DevicePolicyEventLogger 5701 .createEvent(DevicePolicyEnums.REMOVE_KEY_PAIR) 5702 .setAdmin(callerPackage) 5703 .setBoolean(isDelegate) 5704 .write(); 5705 return result; 5706 } catch (RemoteException e) { 5707 Log.e(LOG_TAG, "Removing keypair", e); 5708 } finally { 5709 keyChainConnection.close(); 5710 } 5711 } catch (InterruptedException e) { 5712 Log.w(LOG_TAG, "Interrupted while removing keypair", e); 5713 Thread.currentThread().interrupt(); 5714 } finally { 5715 Binder.restoreCallingIdentity(id); 5716 } 5717 return false; 5718 } 5719 5720 /** 5721 * Enforce one the following conditions are met: 5722 * (1) The device has a Device Owner, and one of the following holds: 5723 * (1.1) The caller is the Device Owner 5724 * (1.2) The caller is another app in the same user as the device owner, AND 5725 * The caller is the delegated certificate installer. 5726 * (2) The user has a profile owner, AND: 5727 * (2.1) The profile owner has been granted access to Device IDs and one of the following 5728 * holds: 5729 * (2.1.1) The caller is the profile owner. 5730 * (2.1.2) The caller is from another app in the same user as the profile owner, AND 5731 * (2.1.2.1) The caller is the delegated cert installer. 5732 * 5733 * For the device owner case, simply check that the caller is the device owner or the 5734 * delegated certificate installer. 5735 * 5736 * For the profile owner case, first check that the caller is the profile owner or can 5737 * manage the DELEGATION_CERT_INSTALL scope. 5738 * If that check succeeds, ensure the profile owner was granted access to device 5739 * identifiers. The grant is transitive: The delegated cert installer is implicitly allowed 5740 * access to device identifiers in this case as part of the delegation. 5741 */ 5742 @VisibleForTesting enforceCallerCanRequestDeviceIdAttestation( ComponentName who, String callerPackage, int callerUid)5743 public void enforceCallerCanRequestDeviceIdAttestation( 5744 ComponentName who, String callerPackage, int callerUid) throws SecurityException { 5745 final int userId = UserHandle.getUserId(callerUid); 5746 5747 /** 5748 * First check if there's a profile owner because the device could be in COMP mode (where 5749 * there's a device owner and profile owner on the same device). 5750 * If the caller is from the work profile, then it must be the PO or the delegate, and 5751 * it must have the right permission to access device identifiers. 5752 */ 5753 if (hasProfileOwner(userId)) { 5754 // Make sure that the caller is the profile owner or delegate. 5755 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5756 DELEGATION_CERT_INSTALL); 5757 // Verify that the profile owner was granted access to Device IDs. 5758 if (canProfileOwnerAccessDeviceIds(userId)) { 5759 return; 5760 } 5761 throw new SecurityException( 5762 "Profile Owner is not allowed to access Device IDs."); 5763 } 5764 5765 // If not, fall back to the device owner check. 5766 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 5767 DELEGATION_CERT_INSTALL); 5768 } 5769 5770 @VisibleForTesting translateIdAttestationFlags( int idAttestationFlags)5771 public static int[] translateIdAttestationFlags( 5772 int idAttestationFlags) { 5773 Map<Integer, Integer> idTypeToAttestationFlag = new HashMap(); 5774 idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL); 5775 idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI); 5776 idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID); 5777 5778 int numFlagsSet = Integer.bitCount(idAttestationFlags); 5779 // No flags are set - return null to indicate no device ID attestation information should 5780 // be included in the attestation record. 5781 if (numFlagsSet == 0) { 5782 return null; 5783 } 5784 5785 // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if 5786 // no other flag is set. That will lead to inclusion of general device make data in the 5787 // attestation record, but no specific device identifiers. 5788 if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) { 5789 numFlagsSet -= 1; 5790 idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO); 5791 } 5792 5793 int[] attestationUtilsFlags = new int[numFlagsSet]; 5794 int i = 0; 5795 for (Integer idType: idTypeToAttestationFlag.keySet()) { 5796 if ((idType & idAttestationFlags) != 0) { 5797 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType); 5798 } 5799 } 5800 5801 return attestationUtilsFlags; 5802 } 5803 5804 @Override generateKeyPair(ComponentName who, String callerPackage, String algorithm, ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags, KeymasterCertificateChain attestationChain)5805 public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm, 5806 ParcelableKeyGenParameterSpec parcelableKeySpec, 5807 int idAttestationFlags, 5808 KeymasterCertificateChain attestationChain) { 5809 // Get attestation flags, if any. 5810 final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags); 5811 final boolean deviceIdAttestationRequired = attestationUtilsFlags != null; 5812 final int callingUid = mInjector.binderGetCallingUid(); 5813 5814 if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) { 5815 enforceCallerCanRequestDeviceIdAttestation(who, callerPackage, callingUid); 5816 } else { 5817 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5818 DELEGATION_CERT_INSTALL); 5819 } 5820 final KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec(); 5821 final String alias = keySpec.getKeystoreAlias(); 5822 if (TextUtils.isEmpty(alias)) { 5823 throw new IllegalArgumentException("Empty alias provided."); 5824 } 5825 // As the caller will be granted access to the key, ensure no UID was specified, as 5826 // it will not have the desired effect. 5827 if (keySpec.getUid() != KeyStore.UID_SELF) { 5828 Log.e(LOG_TAG, "Only the caller can be granted access to the generated keypair."); 5829 return false; 5830 } 5831 5832 if (deviceIdAttestationRequired && (keySpec.getAttestationChallenge() == null)) { 5833 throw new IllegalArgumentException( 5834 "Requested Device ID attestation but challenge is empty."); 5835 } 5836 5837 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 5838 final long id = mInjector.binderClearCallingIdentity(); 5839 try { 5840 try (KeyChainConnection keyChainConnection = 5841 KeyChain.bindAsUser(mContext, userHandle)) { 5842 IKeyChainService keyChain = keyChainConnection.getService(); 5843 5844 // Copy the provided keySpec, excluding the attestation challenge, which will be 5845 // used later for requesting key attestation record. 5846 final KeyGenParameterSpec noAttestationSpec = 5847 new KeyGenParameterSpec.Builder(keySpec) 5848 .setAttestationChallenge(null) 5849 .build(); 5850 5851 final int generationResult = keyChain.generateKeyPair(algorithm, 5852 new ParcelableKeyGenParameterSpec(noAttestationSpec)); 5853 if (generationResult != KeyChain.KEY_GEN_SUCCESS) { 5854 Log.e(LOG_TAG, String.format( 5855 "KeyChain failed to generate a keypair, error %d.", generationResult)); 5856 switch (generationResult) { 5857 case KeyChain.KEY_GEN_STRONGBOX_UNAVAILABLE: 5858 throw new ServiceSpecificException( 5859 DevicePolicyManager.KEY_GEN_STRONGBOX_UNAVAILABLE, 5860 String.format("KeyChain error: %d", generationResult)); 5861 default: 5862 return false; 5863 } 5864 } 5865 5866 // Set a grant for the caller here so that when the client calls 5867 // requestPrivateKey, it will be able to get the key from Keystore. 5868 // Note the use of the calling UID, since the request for the private 5869 // key will come from the client's process, so the grant has to be for 5870 // that UID. 5871 keyChain.setGrant(callingUid, alias, true); 5872 5873 final byte[] attestationChallenge = keySpec.getAttestationChallenge(); 5874 if (attestationChallenge != null) { 5875 final int attestationResult = keyChain.attestKey( 5876 alias, attestationChallenge, attestationUtilsFlags, attestationChain); 5877 if (attestationResult != KeyChain.KEY_ATTESTATION_SUCCESS) { 5878 Log.e(LOG_TAG, String.format( 5879 "Attestation for %s failed (rc=%d), deleting key.", 5880 alias, attestationResult)); 5881 keyChain.removeKeyPair(alias); 5882 if (attestationResult == KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS) { 5883 throw new UnsupportedOperationException( 5884 "Device does not support Device ID attestation."); 5885 } 5886 return false; 5887 } 5888 } 5889 final boolean isDelegate = (who == null); 5890 DevicePolicyEventLogger 5891 .createEvent(DevicePolicyEnums.GENERATE_KEY_PAIR) 5892 .setAdmin(callerPackage) 5893 .setBoolean(isDelegate) 5894 .setInt(idAttestationFlags) 5895 .setStrings(algorithm) 5896 .write(); 5897 return true; 5898 } 5899 } catch (RemoteException e) { 5900 Log.e(LOG_TAG, "KeyChain error while generating a keypair", e); 5901 } catch (InterruptedException e) { 5902 Log.w(LOG_TAG, "Interrupted while generating keypair", e); 5903 Thread.currentThread().interrupt(); 5904 } finally { 5905 mInjector.binderRestoreCallingIdentity(id); 5906 } 5907 return false; 5908 } 5909 5910 @Override setKeyPairCertificate(ComponentName who, String callerPackage, String alias, byte[] cert, byte[] chain, boolean isUserSelectable)5911 public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias, 5912 byte[] cert, byte[] chain, boolean isUserSelectable) { 5913 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 5914 DELEGATION_CERT_INSTALL); 5915 5916 final int callingUid = mInjector.binderGetCallingUid(); 5917 final long id = mInjector.binderClearCallingIdentity(); 5918 try (final KeyChainConnection keyChainConnection = 5919 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid))) { 5920 IKeyChainService keyChain = keyChainConnection.getService(); 5921 if (!keyChain.setKeyPairCertificate(alias, cert, chain)) { 5922 return false; 5923 } 5924 keyChain.setUserSelectable(alias, isUserSelectable); 5925 final boolean isDelegate = (who == null); 5926 DevicePolicyEventLogger 5927 .createEvent(DevicePolicyEnums.SET_KEY_PAIR_CERTIFICATE) 5928 .setAdmin(callerPackage) 5929 .setBoolean(isDelegate) 5930 .write(); 5931 return true; 5932 } catch (InterruptedException e) { 5933 Log.w(LOG_TAG, "Interrupted while setting keypair certificate", e); 5934 Thread.currentThread().interrupt(); 5935 } catch (RemoteException e) { 5936 Log.e(LOG_TAG, "Failed setting keypair certificate", e); 5937 } finally { 5938 mInjector.binderRestoreCallingIdentity(id); 5939 } 5940 return false; 5941 } 5942 5943 @Override choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, final IBinder response)5944 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, 5945 final IBinder response) { 5946 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers. 5947 if (!isCallerWithSystemUid()) { 5948 return; 5949 } 5950 5951 final UserHandle caller = mInjector.binderGetCallingUserHandle(); 5952 // If there is a profile owner, redirect to that; otherwise query the device owner. 5953 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier()); 5954 if (aliasChooser == null && caller.isSystem()) { 5955 synchronized (getLockObject()) { 5956 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 5957 if (deviceOwnerAdmin != null) { 5958 aliasChooser = deviceOwnerAdmin.info.getComponent(); 5959 } 5960 } 5961 } 5962 if (aliasChooser == null) { 5963 sendPrivateKeyAliasResponse(null, response); 5964 return; 5965 } 5966 5967 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 5968 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 5969 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri); 5970 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 5971 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 5972 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 5973 5974 final ComponentName delegateReceiver; 5975 delegateReceiver = resolveDelegateReceiver(DELEGATION_CERT_SELECTION, 5976 DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS, caller.getIdentifier()); 5977 5978 final boolean isDelegate; 5979 if (delegateReceiver != null) { 5980 intent.setComponent(delegateReceiver); 5981 isDelegate = true; 5982 } else { 5983 intent.setComponent(aliasChooser); 5984 isDelegate = false; 5985 } 5986 5987 final long id = mInjector.binderClearCallingIdentity(); 5988 try { 5989 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() { 5990 @Override 5991 public void onReceive(Context context, Intent intent) { 5992 final String chosenAlias = getResultData(); 5993 sendPrivateKeyAliasResponse(chosenAlias, response); 5994 } 5995 }, null, Activity.RESULT_OK, null, null); 5996 DevicePolicyEventLogger 5997 .createEvent(DevicePolicyEnums.CHOOSE_PRIVATE_KEY_ALIAS) 5998 .setAdmin(intent.getComponent()) 5999 .setBoolean(isDelegate) 6000 .write(); 6001 } finally { 6002 mInjector.binderRestoreCallingIdentity(id); 6003 } 6004 } 6005 sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder)6006 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 6007 final IKeyChainAliasCallback keyChainAliasResponse = 6008 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 6009 // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback 6010 // is oneway, which means it won't block if the recipient lives in another process. 6011 try { 6012 keyChainAliasResponse.alias(alias); 6013 } catch (Exception e) { 6014 // Caller could throw RuntimeException or RemoteException back across processes. Catch 6015 // everything just to be sure. 6016 Log.e(LOG_TAG, "error while responding to callback", e); 6017 } 6018 } 6019 6020 /** 6021 * Determine whether DPMS should check if a delegate package is already installed before 6022 * granting it new delegations via {@link #setDelegatedScopes}. 6023 */ shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, int targetSdk, List<String> scopes)6024 private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, 6025 int targetSdk, List<String> scopes) { 6026 // 1) Never skip is installed check from N. 6027 if (targetSdk >= Build.VERSION_CODES.N) { 6028 return true; 6029 } 6030 // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given. 6031 if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) { 6032 return false; 6033 } 6034 // 3) Skip if all previously granted scopes are being cleared. 6035 if (scopes.isEmpty()) { 6036 return false; 6037 } 6038 // Otherwise it should check that delegatePackage is installed. 6039 return true; 6040 } 6041 6042 /** 6043 * Set the scopes of a device owner or profile owner delegate. 6044 * 6045 * @param who the device owner or profile owner. 6046 * @param delegatePackage the name of the delegate package. 6047 * @param scopes the list of delegation scopes to be given to the delegate package. 6048 */ 6049 @Override setDelegatedScopes(ComponentName who, String delegatePackage, List<String> scopeList)6050 public void setDelegatedScopes(ComponentName who, String delegatePackage, 6051 List<String> scopeList) throws SecurityException { 6052 Preconditions.checkNotNull(who, "ComponentName is null"); 6053 Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty"); 6054 Preconditions.checkCollectionElementsNotNull(scopeList, "Scopes"); 6055 // Remove possible duplicates. 6056 final ArrayList<String> scopes = new ArrayList(new ArraySet(scopeList)); 6057 // Ensure given scopes are valid. 6058 if (scopes.retainAll(Arrays.asList(DELEGATIONS))) { 6059 throw new IllegalArgumentException("Unexpected delegation scopes"); 6060 } 6061 final boolean hasDoDelegation = !Collections.disjoint(scopes, DEVICE_OWNER_DELEGATIONS); 6062 // Retrieve the user ID of the calling process. 6063 final int userId = mInjector.userHandleGetCallingUserId(); 6064 synchronized (getLockObject()) { 6065 // Ensure calling process is device/profile owner. 6066 if (hasDoDelegation) { 6067 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6068 } else { 6069 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6070 } 6071 // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N). 6072 if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage, 6073 getTargetSdk(who.getPackageName(), userId), scopes)) { 6074 // Throw when the delegate package is not installed. 6075 if (!isPackageInstalledForUser(delegatePackage, userId)) { 6076 throw new IllegalArgumentException("Package " + delegatePackage 6077 + " is not installed on the current user"); 6078 } 6079 } 6080 6081 // Set the new delegate in user policies. 6082 final DevicePolicyData policy = getUserData(userId); 6083 List<String> exclusiveScopes = null; 6084 if (!scopes.isEmpty()) { 6085 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes)); 6086 exclusiveScopes = new ArrayList<>(scopes); 6087 exclusiveScopes.retainAll(EXCLUSIVE_DELEGATIONS); 6088 } else { 6089 // Remove any delegation info if the given scopes list is empty. 6090 policy.mDelegationMap.remove(delegatePackage); 6091 } 6092 sendDelegationChangedBroadcast(delegatePackage, scopes, userId); 6093 6094 // If set, remove exclusive scopes from all other delegates 6095 if (exclusiveScopes != null && !exclusiveScopes.isEmpty()) { 6096 for (int i = policy.mDelegationMap.size() - 1; i >= 0; --i) { 6097 final String currentPackage = policy.mDelegationMap.keyAt(i); 6098 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 6099 6100 if (!currentPackage.equals(delegatePackage)) { 6101 // Iterate through all other delegates 6102 if (currentScopes.removeAll(exclusiveScopes)) { 6103 // And if this delegate had some exclusive scopes which are now moved 6104 // to the new delegate, notify about its delegation changes. 6105 if (currentScopes.isEmpty()) { 6106 policy.mDelegationMap.removeAt(i); 6107 } 6108 sendDelegationChangedBroadcast(currentPackage, 6109 new ArrayList<>(currentScopes), userId); 6110 } 6111 } 6112 } 6113 } 6114 // Persist updates. 6115 saveSettingsLocked(userId); 6116 } 6117 } 6118 sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes, int userId)6119 private void sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes, 6120 int userId) { 6121 // Notify delegate package of updates. 6122 final Intent intent = new Intent( 6123 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED); 6124 // Only call receivers registered with Context#registerReceiver (don’t wake delegate). 6125 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 6126 // Limit components this intent resolves to to the delegate package. 6127 intent.setPackage(delegatePackage); 6128 // Include the list of delegated scopes as an extra. 6129 intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes); 6130 // Send the broadcast. 6131 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 6132 } 6133 6134 /** 6135 * Get the delegation scopes given to a delegate package by a device owner or profile owner. 6136 * 6137 * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by 6138 * passing in {@code null} as the {@code who} parameter and its own name as the 6139 * {@code delegatepackage}. 6140 * 6141 * @param who the device owner or profile owner, or {@code null} if the caller is 6142 * {@code delegatePackage}. 6143 * @param delegatePackage the name of the delegate package whose scopes are to be retrieved. 6144 * @return a list of the delegation scopes currently given to {@code delegatePackage}. 6145 */ 6146 @Override 6147 @NonNull getDelegatedScopes(ComponentName who, String delegatePackage)6148 public List<String> getDelegatedScopes(ComponentName who, 6149 String delegatePackage) throws SecurityException { 6150 Preconditions.checkNotNull(delegatePackage, "Delegate package is null"); 6151 6152 // Retrieve the user ID of the calling process. 6153 final int callingUid = mInjector.binderGetCallingUid(); 6154 final int userId = UserHandle.getUserId(callingUid); 6155 synchronized (getLockObject()) { 6156 // Ensure calling process is device/profile owner. 6157 if (who != null) { 6158 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6159 // Or ensure calling process is delegatePackage itself. 6160 } else { 6161 int uid = 0; 6162 try { 6163 uid = mInjector.getPackageManager() 6164 .getPackageUidAsUser(delegatePackage, userId); 6165 } catch(NameNotFoundException e) { 6166 } 6167 if (uid != callingUid) { 6168 throw new SecurityException("Caller with uid " + callingUid + " is not " 6169 + delegatePackage); 6170 } 6171 } 6172 final DevicePolicyData policy = getUserData(userId); 6173 // Retrieve the scopes assigned to delegatePackage, or null if no scope was given. 6174 final List<String> scopes = policy.mDelegationMap.get(delegatePackage); 6175 return scopes == null ? Collections.EMPTY_LIST : scopes; 6176 } 6177 } 6178 6179 /** 6180 * Get a list of packages that were given a specific delegation scopes by a device owner or 6181 * profile owner. 6182 * 6183 * @param who the device owner or profile owner. 6184 * @param scope the scope whose delegates are to be retrieved. 6185 * @return a list of the delegate packages currently given the {@code scope} delegation. 6186 */ 6187 @NonNull getDelegatePackages(ComponentName who, String scope)6188 public List<String> getDelegatePackages(ComponentName who, String scope) 6189 throws SecurityException { 6190 Preconditions.checkNotNull(who, "ComponentName is null"); 6191 Preconditions.checkNotNull(scope, "Scope is null"); 6192 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 6193 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 6194 } 6195 6196 // Retrieve the user ID of the calling process. 6197 final int userId = mInjector.userHandleGetCallingUserId(); 6198 synchronized (getLockObject()) { 6199 // Ensure calling process is device/profile owner. 6200 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6201 return getDelegatePackagesInternalLocked(scope, userId); 6202 } 6203 } 6204 getDelegatePackagesInternalLocked(String scope, int userId)6205 private List<String> getDelegatePackagesInternalLocked(String scope, int userId) { 6206 final DevicePolicyData policy = getUserData(userId); 6207 6208 // Create a list to hold the resulting delegate packages. 6209 final List<String> delegatePackagesWithScope = new ArrayList<>(); 6210 // Add all delegations containing scope to the result list. 6211 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 6212 if (policy.mDelegationMap.valueAt(i).contains(scope)) { 6213 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i)); 6214 } 6215 } 6216 return delegatePackagesWithScope; 6217 } 6218 6219 /** 6220 * Return the ComponentName of the receiver that handles the given broadcast action, from 6221 * the app that holds the given delegation capability. If the app defines multiple receivers 6222 * with the same intent action filter, will return any one of them nondeterministically. 6223 * 6224 * @return ComponentName of the receiver or {@null} if none exists. 6225 */ resolveDelegateReceiver(String scope, String action, int userId)6226 private ComponentName resolveDelegateReceiver(String scope, String action, int userId) { 6227 6228 final List<String> delegates; 6229 synchronized (getLockObject()) { 6230 delegates = getDelegatePackagesInternalLocked(scope, userId); 6231 } 6232 if (delegates.size() == 0) { 6233 return null; 6234 } else if (delegates.size() > 1) { 6235 Slog.wtf(LOG_TAG, "More than one delegate holds " + scope); 6236 return null; 6237 } 6238 final String pkg = delegates.get(0); 6239 Intent intent = new Intent(action); 6240 intent.setPackage(pkg); 6241 final List<ResolveInfo> receivers; 6242 try { 6243 receivers = mIPackageManager.queryIntentReceivers( 6244 intent, null, 0, userId).getList(); 6245 } catch (RemoteException e) { 6246 return null; 6247 } 6248 final int count = receivers.size(); 6249 if (count >= 1) { 6250 if (count > 1) { 6251 Slog.w(LOG_TAG, pkg + " defines more than one delegate receiver for " + action); 6252 } 6253 return receivers.get(0).activityInfo.getComponentName(); 6254 } else { 6255 return null; 6256 } 6257 } 6258 6259 /** 6260 * Check whether a caller application has been delegated a given scope via 6261 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 6262 * device owner. 6263 * <p> 6264 * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and 6265 * then comparing the calling UID with the UID of {@code callerPackage} as reported by 6266 * {@link PackageManager#getPackageUidAsUser}. 6267 * 6268 * @param callerPackage the name of the package that is trying to invoke a function in the DPMS. 6269 * @param scope the delegation scope to be checked. 6270 * @return {@code true} if the calling process is a delegate of {@code scope}. 6271 */ isCallerDelegate(String callerPackage, int callerUid, String scope)6272 private boolean isCallerDelegate(String callerPackage, int callerUid, String scope) { 6273 Preconditions.checkNotNull(callerPackage, "callerPackage is null"); 6274 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 6275 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 6276 } 6277 6278 // Retrieve the UID and user ID of the calling process. 6279 final int userId = UserHandle.getUserId(callerUid); 6280 synchronized (getLockObject()) { 6281 // Retrieve user policy data. 6282 final DevicePolicyData policy = getUserData(userId); 6283 // Retrieve the list of delegation scopes granted to callerPackage. 6284 final List<String> scopes = policy.mDelegationMap.get(callerPackage); 6285 // Check callingUid only if callerPackage has the required scope delegation. 6286 if (scopes != null && scopes.contains(scope)) { 6287 try { 6288 // Retrieve the expected UID for callerPackage. 6289 final int uid = mInjector.getPackageManager() 6290 .getPackageUidAsUser(callerPackage, userId); 6291 // Return true if the caller is actually callerPackage. 6292 return uid == callerUid; 6293 } catch (NameNotFoundException e) { 6294 // Ignore. 6295 } 6296 } 6297 return false; 6298 } 6299 } 6300 6301 /** 6302 * Throw a security exception if a ComponentName is given and it is not a device/profile owner 6303 * or if the calling process is not a delegate of the given scope. 6304 * 6305 * @param who the device owner of profile owner, or null if {@code callerPackage} is a 6306 * {@code scope} delegate. 6307 * @param callerPackage the name of the calling package. Required if {@code who} is 6308 * {@code null}. 6309 * @param reqPolicy the policy used in the API whose access permission is being checked. 6310 * @param scope the delegation scope corresponding to the API being checked. 6311 * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy}; 6312 * or when {@code who} is {@code null} and {@code callerPackage} is not a delegate 6313 * of {@code scope}. 6314 */ enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, String scope)6315 private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, 6316 String scope) { 6317 enforceCanManageScopeOrCheckPermission(who, callerPackage, reqPolicy, scope, null); 6318 } 6319 6320 /** 6321 * Throw a security exception if a ComponentName is given and it is not a device/profile owner 6322 * OR if the calling process is not a delegate of the given scope and does not hold the 6323 * required permission. 6324 */ enforceCanManageScopeOrCheckPermission(@ullable ComponentName who, @NonNull String callerPackage, int reqPolicy, @NonNull String scope, @Nullable String permission)6325 private void enforceCanManageScopeOrCheckPermission(@Nullable ComponentName who, 6326 @NonNull String callerPackage, int reqPolicy, @NonNull String scope, 6327 @Nullable String permission) { 6328 // If a ComponentName is given ensure it is a device or profile owner according to policy. 6329 if (who != null) { 6330 synchronized (getLockObject()) { 6331 getActiveAdminForCallerLocked(who, reqPolicy); 6332 } 6333 } else { 6334 // If no ComponentName is given ensure calling process has scope delegation or required 6335 // permission 6336 if (isCallerDelegate(callerPackage, mInjector.binderGetCallingUid(), scope)) { 6337 return; 6338 } 6339 if (permission == null) { 6340 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() 6341 + " is not a delegate of scope " + scope + "."); 6342 } else { 6343 mContext.enforceCallingOrSelfPermission(permission, null); 6344 } 6345 } 6346 } 6347 6348 /** 6349 * Helper function to preserve delegation behavior pre-O when using the deprecated functions 6350 * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}. 6351 */ setDelegatedScopePreO(ComponentName who, String delegatePackage, String scope)6352 private void setDelegatedScopePreO(ComponentName who, 6353 String delegatePackage, String scope) { 6354 Preconditions.checkNotNull(who, "ComponentName is null"); 6355 6356 final int userId = mInjector.userHandleGetCallingUserId(); 6357 synchronized (getLockObject()) { 6358 // Ensure calling process is device/profile owner. 6359 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6360 final DevicePolicyData policy = getUserData(userId); 6361 6362 if (delegatePackage != null) { 6363 // Set package as a delegate for scope if it is not already one. 6364 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 6365 if (scopes == null) { 6366 scopes = new ArrayList<>(); 6367 } 6368 if (!scopes.contains(scope)) { 6369 scopes.add(scope); 6370 setDelegatedScopes(who, delegatePackage, scopes); 6371 } 6372 } 6373 6374 // Clear any existing scope delegates. 6375 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 6376 final String currentPackage = policy.mDelegationMap.keyAt(i); 6377 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 6378 6379 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) { 6380 final List<String> newScopes = new ArrayList(currentScopes); 6381 newScopes.remove(scope); 6382 setDelegatedScopes(who, currentPackage, newScopes); 6383 } 6384 } 6385 } 6386 } 6387 6388 @Override setCertInstallerPackage(ComponentName who, String installerPackage)6389 public void setCertInstallerPackage(ComponentName who, String installerPackage) 6390 throws SecurityException { 6391 setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL); 6392 DevicePolicyEventLogger 6393 .createEvent(DevicePolicyEnums.SET_CERT_INSTALLER_PACKAGE) 6394 .setAdmin(who) 6395 .setStrings(installerPackage) 6396 .write(); 6397 } 6398 6399 @Override getCertInstallerPackage(ComponentName who)6400 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 6401 final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL); 6402 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 6403 } 6404 6405 /** 6406 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is 6407 * not installed and therefore not available. 6408 * 6409 * @throws SecurityException if the caller is not a profile or device owner. 6410 * @throws UnsupportedOperationException if the package does not support being set as always-on. 6411 */ 6412 @Override setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown, List<String> lockdownWhitelist)6413 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown, 6414 List<String> lockdownWhitelist) 6415 throws SecurityException { 6416 enforceProfileOrDeviceOwner(admin); 6417 6418 final int userId = mInjector.userHandleGetCallingUserId(); 6419 final long token = mInjector.binderClearCallingIdentity(); 6420 try { 6421 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) { 6422 Slog.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage); 6423 throw new ServiceSpecificException( 6424 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage); 6425 } 6426 6427 if (vpnPackage != null && lockdown && lockdownWhitelist != null) { 6428 for (String packageName : lockdownWhitelist) { 6429 if (!isPackageInstalledForUser(packageName, userId)) { 6430 Slog.w(LOG_TAG, "Non-existent package in VPN whitelist: " + packageName); 6431 throw new ServiceSpecificException( 6432 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName); 6433 } 6434 } 6435 } 6436 // If some package is uninstalled after the check above, it will be ignored by CM. 6437 if (!mInjector.getConnectivityManager().setAlwaysOnVpnPackageForUser( 6438 userId, vpnPackage, lockdown, lockdownWhitelist)) { 6439 throw new UnsupportedOperationException(); 6440 } 6441 DevicePolicyEventLogger 6442 .createEvent(DevicePolicyEnums.SET_ALWAYS_ON_VPN_PACKAGE) 6443 .setAdmin(admin) 6444 .setStrings(vpnPackage) 6445 .setBoolean(lockdown) 6446 .setInt(lockdownWhitelist != null ? lockdownWhitelist.size() : 0) 6447 .write(); 6448 } finally { 6449 mInjector.binderRestoreCallingIdentity(token); 6450 } 6451 return true; 6452 } 6453 6454 @Override getAlwaysOnVpnPackage(ComponentName admin)6455 public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException { 6456 enforceProfileOrDeviceOwner(admin); 6457 6458 final int userId = mInjector.userHandleGetCallingUserId(); 6459 final long token = mInjector.binderClearCallingIdentity(); 6460 try { 6461 return mInjector.getConnectivityManager().getAlwaysOnVpnPackageForUser(userId); 6462 } finally { 6463 mInjector.binderRestoreCallingIdentity(token); 6464 } 6465 } 6466 6467 @Override isAlwaysOnVpnLockdownEnabled(ComponentName admin)6468 public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException { 6469 enforceProfileOrDeviceOwner(admin); 6470 6471 final int userId = mInjector.userHandleGetCallingUserId(); 6472 final long token = mInjector.binderClearCallingIdentity(); 6473 try { 6474 return mInjector.getConnectivityManager().isVpnLockdownEnabled(userId); 6475 } finally { 6476 mInjector.binderRestoreCallingIdentity(token); 6477 } 6478 } 6479 6480 @Override getAlwaysOnVpnLockdownWhitelist(ComponentName admin)6481 public List<String> getAlwaysOnVpnLockdownWhitelist(ComponentName admin) 6482 throws SecurityException { 6483 enforceProfileOrDeviceOwner(admin); 6484 6485 final int userId = mInjector.userHandleGetCallingUserId(); 6486 final long token = mInjector.binderClearCallingIdentity(); 6487 try { 6488 return mInjector.getConnectivityManager().getVpnLockdownWhitelist(userId); 6489 } finally { 6490 mInjector.binderRestoreCallingIdentity(token); 6491 } 6492 } 6493 forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc)6494 private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) { 6495 wtfIfInLock(); 6496 boolean success = false; 6497 try { 6498 if (wipeExtRequested) { 6499 StorageManager sm = (StorageManager) mContext.getSystemService( 6500 Context.STORAGE_SERVICE); 6501 sm.wipeAdoptableDisks(); 6502 } 6503 mInjector.recoverySystemRebootWipeUserData( 6504 /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc); 6505 success = true; 6506 } catch (IOException | SecurityException e) { 6507 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 6508 } finally { 6509 if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE); 6510 } 6511 } 6512 forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently)6513 private void forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently) { 6514 boolean success = false; 6515 try { 6516 IActivityManager am = mInjector.getIActivityManager(); 6517 if (am.getCurrentUser().id == userId) { 6518 am.switchUser(UserHandle.USER_SYSTEM); 6519 } 6520 6521 success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId); 6522 if (!success) { 6523 Slog.w(LOG_TAG, "Couldn't remove user " + userId); 6524 } else if (isManagedProfile(userId) && !wipeSilently) { 6525 sendWipeProfileNotification(wipeReasonForUser); 6526 } 6527 } catch (RemoteException re) { 6528 // Shouldn't happen 6529 } finally { 6530 if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE); 6531 } 6532 } 6533 6534 @Override wipeDataWithReason(int flags, String wipeReasonForUser)6535 public void wipeDataWithReason(int flags, String wipeReasonForUser) { 6536 if (!mHasFeature) { 6537 return; 6538 } 6539 Preconditions.checkStringNotEmpty(wipeReasonForUser, "wipeReasonForUser is null or empty"); 6540 enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId()); 6541 6542 final ActiveAdmin admin; 6543 synchronized (getLockObject()) { 6544 admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA); 6545 } 6546 DevicePolicyEventLogger 6547 .createEvent(DevicePolicyEnums.WIPE_DATA_WITH_REASON) 6548 .setAdmin(admin.info.getComponent()) 6549 .setInt(flags) 6550 .write(); 6551 String internalReason = "DevicePolicyManager.wipeDataWithReason() from " 6552 + admin.info.getComponent().flattenToShortString(); 6553 wipeDataNoLock( 6554 admin.info.getComponent(), flags, internalReason, wipeReasonForUser, 6555 admin.getUserHandle().getIdentifier()); 6556 } 6557 wipeDataNoLock(ComponentName admin, int flags, String internalReason, String wipeReasonForUser, int userId)6558 private void wipeDataNoLock(ComponentName admin, int flags, String internalReason, 6559 String wipeReasonForUser, int userId) { 6560 wtfIfInLock(); 6561 6562 long ident = mInjector.binderClearCallingIdentity(); 6563 try { 6564 // First check whether the admin is allowed to wipe the device/user/profile. 6565 final String restriction; 6566 if (userId == UserHandle.USER_SYSTEM) { 6567 restriction = UserManager.DISALLOW_FACTORY_RESET; 6568 } else if (isManagedProfile(userId)) { 6569 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 6570 } else { 6571 restriction = UserManager.DISALLOW_REMOVE_USER; 6572 } 6573 if (isAdminAffectedByRestriction(admin, restriction, userId)) { 6574 throw new SecurityException("Cannot wipe data. " + restriction 6575 + " restriction is set for user " + userId); 6576 } 6577 6578 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 6579 if (!isDeviceOwner(admin, userId)) { 6580 throw new SecurityException( 6581 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA"); 6582 } 6583 PersistentDataBlockManager manager = (PersistentDataBlockManager) 6584 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 6585 if (manager != null) { 6586 manager.wipe(); 6587 } 6588 } 6589 6590 // TODO If split user is enabled and the device owner is set in the primary user 6591 // (rather than system), we should probably trigger factory reset. Current code just 6592 // removes that user (but still clears FRP...) 6593 if (userId == UserHandle.USER_SYSTEM) { 6594 forceWipeDeviceNoLock(/*wipeExtRequested=*/ ( 6595 flags & WIPE_EXTERNAL_STORAGE) != 0, 6596 internalReason, 6597 /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0); 6598 } else { 6599 forceWipeUser(userId, wipeReasonForUser, (flags & WIPE_SILENTLY) != 0); 6600 } 6601 } finally { 6602 mInjector.binderRestoreCallingIdentity(ident); 6603 } 6604 } 6605 sendWipeProfileNotification(String wipeReasonForUser)6606 private void sendWipeProfileNotification(String wipeReasonForUser) { 6607 Notification notification = 6608 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 6609 .setSmallIcon(android.R.drawable.stat_sys_warning) 6610 .setContentTitle(mContext.getString(R.string.work_profile_deleted)) 6611 .setContentText(wipeReasonForUser) 6612 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 6613 .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser)) 6614 .build(); 6615 mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification); 6616 } 6617 clearWipeProfileNotification()6618 private void clearWipeProfileNotification() { 6619 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED); 6620 } 6621 6622 @Override getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle)6623 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 6624 if (!mHasFeature) { 6625 return; 6626 } 6627 enforceFullCrossUsersPermission(userHandle); 6628 mContext.enforceCallingOrSelfPermission( 6629 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6630 6631 synchronized (getLockObject()) { 6632 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 6633 if (admin == null) { 6634 result.sendResult(null); 6635 return; 6636 } 6637 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 6638 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 6639 intent.setComponent(admin.info.getComponent()); 6640 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 6641 null, new BroadcastReceiver() { 6642 @Override 6643 public void onReceive(Context context, Intent intent) { 6644 result.sendResult(getResultExtras(false)); 6645 } 6646 }, null, Activity.RESULT_OK, null, null); 6647 } 6648 } 6649 6650 /** 6651 * Notify DPMS regarding the metric of the current password. This happens when the user changes 6652 * the password, but also when the user just unlocks the keyguard. In comparison, 6653 * reportPasswordChanged() is only called when the user changes the password. 6654 */ 6655 @Override setActivePasswordState(PasswordMetrics metrics, int userHandle)6656 public void setActivePasswordState(PasswordMetrics metrics, int userHandle) { 6657 if (!mLockPatternUtils.hasSecureLockScreen()) { 6658 return; 6659 } 6660 enforceFullCrossUsersPermission(userHandle); 6661 mContext.enforceCallingOrSelfPermission( 6662 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6663 6664 // If the managed profile doesn't have a separate password, set the metrics to default 6665 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 6666 metrics = new PasswordMetrics(); 6667 } 6668 6669 validateQualityConstant(metrics.quality); 6670 synchronized (getLockObject()) { 6671 mUserPasswordMetrics.put(userHandle, metrics); 6672 } 6673 } 6674 6675 @Override reportPasswordChanged(@serIdInt int userId)6676 public void reportPasswordChanged(@UserIdInt int userId) { 6677 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 6678 return; 6679 } 6680 enforceFullCrossUsersPermission(userId); 6681 6682 // Managed Profile password can only be changed when it has a separate challenge. 6683 if (!isSeparateProfileChallengeEnabled(userId)) { 6684 enforceNotManagedProfile(userId, "set the active password"); 6685 } 6686 6687 mContext.enforceCallingOrSelfPermission( 6688 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6689 6690 DevicePolicyData policy = getUserData(userId); 6691 6692 long ident = mInjector.binderClearCallingIdentity(); 6693 try { 6694 synchronized (getLockObject()) { 6695 policy.mFailedPasswordAttempts = 0; 6696 updatePasswordValidityCheckpointLocked(userId, /* parent */ false); 6697 saveSettingsLocked(userId); 6698 updatePasswordExpirationsLocked(userId); 6699 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 6700 6701 // Send a broadcast to each profile using this password as its primary unlock. 6702 sendAdminCommandForLockscreenPoliciesLocked( 6703 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 6704 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 6705 } 6706 removeCaApprovalsIfNeeded(userId); 6707 } finally { 6708 mInjector.binderRestoreCallingIdentity(ident); 6709 } 6710 } 6711 6712 /** 6713 * Called any time the device password is updated. Resets all password expiration clocks. 6714 */ updatePasswordExpirationsLocked(int userHandle)6715 private void updatePasswordExpirationsLocked(int userHandle) { 6716 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>(); 6717 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 6718 userHandle, /* parent */ false); 6719 final int N = admins.size(); 6720 for (int i = 0; i < N; i++) { 6721 ActiveAdmin admin = admins.get(i); 6722 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 6723 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 6724 long timeout = admin.passwordExpirationTimeout; 6725 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 6726 admin.passwordExpirationDate = expiration; 6727 } 6728 } 6729 for (int affectedUserId : affectedUserIds) { 6730 saveSettingsLocked(affectedUserId); 6731 } 6732 } 6733 6734 @Override reportFailedPasswordAttempt(int userHandle)6735 public void reportFailedPasswordAttempt(int userHandle) { 6736 enforceFullCrossUsersPermission(userHandle); 6737 if (!isSeparateProfileChallengeEnabled(userHandle)) { 6738 enforceNotManagedProfile(userHandle, 6739 "report failed password attempt if separate profile challenge is not in place"); 6740 } 6741 mContext.enforceCallingOrSelfPermission( 6742 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6743 6744 boolean wipeData = false; 6745 ActiveAdmin strictestAdmin = null; 6746 final long ident = mInjector.binderClearCallingIdentity(); 6747 try { 6748 synchronized (getLockObject()) { 6749 DevicePolicyData policy = getUserData(userHandle); 6750 policy.mFailedPasswordAttempts++; 6751 saveSettingsLocked(userHandle); 6752 if (mHasFeature) { 6753 strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 6754 userHandle, /* parent */ false); 6755 int max = strictestAdmin != null 6756 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 6757 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 6758 wipeData = true; 6759 } 6760 6761 sendAdminCommandForLockscreenPoliciesLocked( 6762 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 6763 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 6764 } 6765 } 6766 } finally { 6767 mInjector.binderRestoreCallingIdentity(ident); 6768 } 6769 6770 if (wipeData && strictestAdmin != null) { 6771 final int userId = strictestAdmin.getUserHandle().getIdentifier(); 6772 Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: " 6773 + strictestAdmin.info.getComponent().flattenToShortString() 6774 + ". Calling wipeData for user " + userId); 6775 6776 // Attempt to wipe the device/user/profile associated with the admin, as if the 6777 // admin had called wipeData(). That way we can check whether the admin is actually 6778 // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the 6779 // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be 6780 // able to do so). 6781 // IMPORTANT: Call without holding the lock to prevent deadlock. 6782 try { 6783 String wipeReasonForUser = mContext.getString( 6784 R.string.work_profile_deleted_reason_maximum_password_failure); 6785 wipeDataNoLock(strictestAdmin.info.getComponent(), 6786 /*flags=*/ 0, 6787 /*reason=*/ "reportFailedPasswordAttempt()", 6788 wipeReasonForUser, 6789 userId); 6790 } catch (SecurityException e) { 6791 Slog.w(LOG_TAG, "Failed to wipe user " + userId 6792 + " after max failed password attempts reached.", e); 6793 } 6794 } 6795 6796 if (mInjector.securityLogIsLoggingEnabled()) { 6797 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, 6798 /*result*/ 0, /*method strength*/ 1); 6799 } 6800 } 6801 6802 @Override reportSuccessfulPasswordAttempt(int userHandle)6803 public void reportSuccessfulPasswordAttempt(int userHandle) { 6804 enforceFullCrossUsersPermission(userHandle); 6805 mContext.enforceCallingOrSelfPermission( 6806 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6807 6808 synchronized (getLockObject()) { 6809 DevicePolicyData policy = getUserData(userHandle); 6810 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 6811 long ident = mInjector.binderClearCallingIdentity(); 6812 try { 6813 policy.mFailedPasswordAttempts = 0; 6814 policy.mPasswordOwner = -1; 6815 saveSettingsLocked(userHandle); 6816 if (mHasFeature) { 6817 sendAdminCommandForLockscreenPoliciesLocked( 6818 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 6819 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 6820 } 6821 } finally { 6822 mInjector.binderRestoreCallingIdentity(ident); 6823 } 6824 } 6825 } 6826 6827 if (mInjector.securityLogIsLoggingEnabled()) { 6828 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 6829 /*method strength*/ 1); 6830 } 6831 } 6832 6833 @Override reportFailedBiometricAttempt(int userHandle)6834 public void reportFailedBiometricAttempt(int userHandle) { 6835 enforceFullCrossUsersPermission(userHandle); 6836 mContext.enforceCallingOrSelfPermission( 6837 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6838 if (mInjector.securityLogIsLoggingEnabled()) { 6839 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 6840 /*method strength*/ 0); 6841 } 6842 } 6843 6844 @Override reportSuccessfulBiometricAttempt(int userHandle)6845 public void reportSuccessfulBiometricAttempt(int userHandle) { 6846 enforceFullCrossUsersPermission(userHandle); 6847 mContext.enforceCallingOrSelfPermission( 6848 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6849 if (mInjector.securityLogIsLoggingEnabled()) { 6850 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 6851 /*method strength*/ 0); 6852 } 6853 } 6854 6855 @Override reportKeyguardDismissed(int userHandle)6856 public void reportKeyguardDismissed(int userHandle) { 6857 enforceFullCrossUsersPermission(userHandle); 6858 mContext.enforceCallingOrSelfPermission( 6859 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6860 6861 if (mInjector.securityLogIsLoggingEnabled()) { 6862 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 6863 } 6864 } 6865 6866 @Override reportKeyguardSecured(int userHandle)6867 public void reportKeyguardSecured(int userHandle) { 6868 enforceFullCrossUsersPermission(userHandle); 6869 mContext.enforceCallingOrSelfPermission( 6870 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 6871 6872 if (mInjector.securityLogIsLoggingEnabled()) { 6873 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 6874 } 6875 } 6876 6877 @Override setGlobalProxy(ComponentName who, String proxySpec, String exclusionList)6878 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 6879 String exclusionList) { 6880 if (!mHasFeature) { 6881 return null; 6882 } 6883 synchronized (getLockObject()) { 6884 Preconditions.checkNotNull(who, "ComponentName is null"); 6885 6886 // Only check if system user has set global proxy. We don't allow other users to set it. 6887 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6888 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 6889 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 6890 6891 // Scan through active admins and find if anyone has already 6892 // set the global proxy. 6893 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 6894 for (ComponentName component : compSet) { 6895 ActiveAdmin ap = policy.mAdminMap.get(component); 6896 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 6897 // Another admin already sets the global proxy 6898 // Return it to the caller. 6899 return component; 6900 } 6901 } 6902 6903 // If the user is not system, don't set the global proxy. Fail silently. 6904 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 6905 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 6906 + UserHandle.getCallingUserId() + " is not permitted."); 6907 return null; 6908 } 6909 if (proxySpec == null) { 6910 admin.specifiesGlobalProxy = false; 6911 admin.globalProxySpec = null; 6912 admin.globalProxyExclusionList = null; 6913 } else { 6914 6915 admin.specifiesGlobalProxy = true; 6916 admin.globalProxySpec = proxySpec; 6917 admin.globalProxyExclusionList = exclusionList; 6918 } 6919 6920 // Reset the global proxy accordingly 6921 // Do this using system permissions, as apps cannot write to secure settings 6922 long origId = mInjector.binderClearCallingIdentity(); 6923 try { 6924 resetGlobalProxyLocked(policy); 6925 } finally { 6926 mInjector.binderRestoreCallingIdentity(origId); 6927 } 6928 return null; 6929 } 6930 } 6931 6932 @Override getGlobalProxyAdmin(int userHandle)6933 public ComponentName getGlobalProxyAdmin(int userHandle) { 6934 if (!mHasFeature) { 6935 return null; 6936 } 6937 enforceFullCrossUsersPermission(userHandle); 6938 synchronized (getLockObject()) { 6939 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 6940 // Scan through active admins and find if anyone has already 6941 // set the global proxy. 6942 final int N = policy.mAdminList.size(); 6943 for (int i = 0; i < N; i++) { 6944 ActiveAdmin ap = policy.mAdminList.get(i); 6945 if (ap.specifiesGlobalProxy) { 6946 // Device admin sets the global proxy 6947 // Return it to the caller. 6948 return ap.info.getComponent(); 6949 } 6950 } 6951 } 6952 // No device admin sets the global proxy. 6953 return null; 6954 } 6955 6956 @Override setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo)6957 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 6958 enforceDeviceOwner(who); 6959 long token = mInjector.binderClearCallingIdentity(); 6960 try { 6961 mInjector.getConnectivityManager().setGlobalProxy(proxyInfo); 6962 } finally { 6963 mInjector.binderRestoreCallingIdentity(token); 6964 } 6965 } 6966 resetGlobalProxyLocked(DevicePolicyData policy)6967 private void resetGlobalProxyLocked(DevicePolicyData policy) { 6968 final int N = policy.mAdminList.size(); 6969 for (int i = 0; i < N; i++) { 6970 ActiveAdmin ap = policy.mAdminList.get(i); 6971 if (ap.specifiesGlobalProxy) { 6972 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 6973 return; 6974 } 6975 } 6976 // No device admins defining global proxies - reset global proxy settings to none 6977 saveGlobalProxyLocked(null, null); 6978 } 6979 saveGlobalProxyLocked(String proxySpec, String exclusionList)6980 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 6981 if (exclusionList == null) { 6982 exclusionList = ""; 6983 } 6984 if (proxySpec == null) { 6985 proxySpec = ""; 6986 } 6987 // Remove white spaces 6988 proxySpec = proxySpec.trim(); 6989 String data[] = proxySpec.split(":"); 6990 int proxyPort = 8080; 6991 if (data.length > 1) { 6992 try { 6993 proxyPort = Integer.parseInt(data[1]); 6994 } catch (NumberFormatException e) {} 6995 } 6996 exclusionList = exclusionList.trim(); 6997 6998 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 6999 if (!proxyProperties.isValid()) { 7000 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 7001 return; 7002 } 7003 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 7004 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 7005 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 7006 exclusionList); 7007 } 7008 7009 /** 7010 * Called by an application that is administering the device to request that the storage system 7011 * be encrypted. Does nothing if the caller is on a secondary user or a managed profile. 7012 * 7013 * @return the new total request status (for all admins), or {@link 7014 * DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user 7015 */ 7016 @Override setStorageEncryption(ComponentName who, boolean encrypt)7017 public int setStorageEncryption(ComponentName who, boolean encrypt) { 7018 if (!mHasFeature) { 7019 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7020 } 7021 Preconditions.checkNotNull(who, "ComponentName is null"); 7022 final int userHandle = UserHandle.getCallingUserId(); 7023 synchronized (getLockObject()) { 7024 // Check for permissions 7025 // Only system user can set storage encryption 7026 if (userHandle != UserHandle.USER_SYSTEM) { 7027 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User " 7028 + UserHandle.getCallingUserId() + " is not permitted."); 7029 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7030 } 7031 7032 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 7033 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 7034 7035 // Quick exit: If the filesystem does not support encryption, we can exit early. 7036 if (!isEncryptionSupported()) { 7037 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7038 } 7039 7040 // (1) Record the value for the admin so it's sticky 7041 if (ap.encryptionRequested != encrypt) { 7042 ap.encryptionRequested = encrypt; 7043 saveSettingsLocked(userHandle); 7044 } 7045 7046 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 7047 // (2) Compute "max" for all admins 7048 boolean newRequested = false; 7049 final int N = policy.mAdminList.size(); 7050 for (int i = 0; i < N; i++) { 7051 newRequested |= policy.mAdminList.get(i).encryptionRequested; 7052 } 7053 7054 // Notify OS of new request 7055 setEncryptionRequested(newRequested); 7056 7057 // Return the new global request status 7058 return newRequested 7059 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 7060 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 7061 } 7062 } 7063 7064 /** 7065 * Get the current storage encryption request status for a given admin, or aggregate of all 7066 * active admins. 7067 */ 7068 @Override getStorageEncryption(ComponentName who, int userHandle)7069 public boolean getStorageEncryption(ComponentName who, int userHandle) { 7070 if (!mHasFeature) { 7071 return false; 7072 } 7073 enforceFullCrossUsersPermission(userHandle); 7074 synchronized (getLockObject()) { 7075 // Check for permissions if a particular caller is specified 7076 if (who != null) { 7077 // When checking for a single caller, status is based on caller's request 7078 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 7079 return ap != null ? ap.encryptionRequested : false; 7080 } 7081 7082 // If no particular caller is specified, return the aggregate set of requests. 7083 // This is short circuited by returning true on the first hit. 7084 DevicePolicyData policy = getUserData(userHandle); 7085 final int N = policy.mAdminList.size(); 7086 for (int i = 0; i < N; i++) { 7087 if (policy.mAdminList.get(i).encryptionRequested) { 7088 return true; 7089 } 7090 } 7091 return false; 7092 } 7093 } 7094 7095 /** 7096 * Get the current encryption status of the device. 7097 */ 7098 @Override getStorageEncryptionStatus(@ullable String callerPackage, int userHandle)7099 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 7100 if (!mHasFeature) { 7101 // Ok to return current status. 7102 } 7103 enforceFullCrossUsersPermission(userHandle); 7104 7105 // It's not critical here, but let's make sure the package name is correct, in case 7106 // we start using it for different purposes. 7107 ensureCallerPackage(callerPackage); 7108 7109 final ApplicationInfo ai; 7110 try { 7111 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 7112 } catch (RemoteException e) { 7113 throw new SecurityException(e); 7114 } 7115 7116 boolean legacyApp = false; 7117 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 7118 legacyApp = true; 7119 } 7120 7121 final int rawStatus = getEncryptionStatus(); 7122 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 7123 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 7124 } 7125 return rawStatus; 7126 } 7127 7128 /** 7129 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 7130 */ isEncryptionSupported()7131 private boolean isEncryptionSupported() { 7132 // Note, this can be implemented as 7133 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7134 // But is provided as a separate internal method if there's a faster way to do a 7135 // simple check for supported-or-not. 7136 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7137 } 7138 7139 /** 7140 * Hook to low-levels: Reporting the current status of encryption. 7141 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 7142 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 7143 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 7144 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or 7145 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 7146 */ getEncryptionStatus()7147 private int getEncryptionStatus() { 7148 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 7149 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 7150 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) { 7151 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 7152 } else if (mInjector.storageManagerIsEncrypted()) { 7153 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 7154 } else if (mInjector.storageManagerIsEncryptable()) { 7155 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 7156 } else { 7157 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 7158 } 7159 } 7160 7161 /** 7162 * Hook to low-levels: If needed, record the new admin setting for encryption. 7163 */ setEncryptionRequested(boolean encrypt)7164 private void setEncryptionRequested(boolean encrypt) { 7165 } 7166 7167 /** 7168 * Set whether the screen capture is disabled for the user managed by the specified admin. 7169 */ 7170 @Override setScreenCaptureDisabled(ComponentName who, boolean disabled)7171 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) { 7172 if (!mHasFeature) { 7173 return; 7174 } 7175 Preconditions.checkNotNull(who, "ComponentName is null"); 7176 final int userHandle = UserHandle.getCallingUserId(); 7177 synchronized (getLockObject()) { 7178 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 7179 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7180 if (ap.disableScreenCapture != disabled) { 7181 ap.disableScreenCapture = disabled; 7182 saveSettingsLocked(userHandle); 7183 updateScreenCaptureDisabled(userHandle, disabled); 7184 } 7185 } 7186 DevicePolicyEventLogger 7187 .createEvent(DevicePolicyEnums.SET_SCREEN_CAPTURE_DISABLED) 7188 .setAdmin(who) 7189 .setBoolean(disabled) 7190 .write(); 7191 } 7192 7193 /** 7194 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 7195 * active admin (if given admin is null). 7196 */ 7197 @Override getScreenCaptureDisabled(ComponentName who, int userHandle)7198 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) { 7199 if (!mHasFeature) { 7200 return false; 7201 } 7202 synchronized (getLockObject()) { 7203 if (who != null) { 7204 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7205 return (admin != null) ? admin.disableScreenCapture : false; 7206 } 7207 7208 DevicePolicyData policy = getUserData(userHandle); 7209 final int N = policy.mAdminList.size(); 7210 for (int i = 0; i < N; i++) { 7211 ActiveAdmin admin = policy.mAdminList.get(i); 7212 if (admin.disableScreenCapture) { 7213 return true; 7214 } 7215 } 7216 return false; 7217 } 7218 } 7219 updateScreenCaptureDisabled(int userHandle, boolean disabled)7220 private void updateScreenCaptureDisabled(int userHandle, boolean disabled) { 7221 mPolicyCache.setScreenCaptureDisabled(userHandle, disabled); 7222 mHandler.post(new Runnable() { 7223 @Override 7224 public void run() { 7225 try { 7226 mInjector.getIWindowManager().refreshScreenCaptureDisabled(userHandle); 7227 } catch (RemoteException e) { 7228 Log.w(LOG_TAG, "Unable to notify WindowManager.", e); 7229 } 7230 } 7231 }); 7232 } 7233 7234 /** 7235 * Set whether auto time is required by the specified admin (must be device or profile owner). 7236 */ 7237 @Override setAutoTimeRequired(ComponentName who, boolean required)7238 public void setAutoTimeRequired(ComponentName who, boolean required) { 7239 if (!mHasFeature) { 7240 return; 7241 } 7242 Preconditions.checkNotNull(who, "ComponentName is null"); 7243 final int userHandle = UserHandle.getCallingUserId(); 7244 synchronized (getLockObject()) { 7245 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7246 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7247 if (admin.requireAutoTime != required) { 7248 admin.requireAutoTime = required; 7249 saveSettingsLocked(userHandle); 7250 } 7251 } 7252 7253 // Turn AUTO_TIME on in settings if it is required 7254 if (required) { 7255 long ident = mInjector.binderClearCallingIdentity(); 7256 try { 7257 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */); 7258 } finally { 7259 mInjector.binderRestoreCallingIdentity(ident); 7260 } 7261 } 7262 DevicePolicyEventLogger 7263 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_REQUIRED) 7264 .setAdmin(who) 7265 .setBoolean(required) 7266 .write(); 7267 } 7268 7269 /** 7270 * Returns whether or not auto time is required by the device owner or any profile owner. 7271 */ 7272 @Override getAutoTimeRequired()7273 public boolean getAutoTimeRequired() { 7274 if (!mHasFeature) { 7275 return false; 7276 } 7277 synchronized (getLockObject()) { 7278 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7279 if (deviceOwner != null && deviceOwner.requireAutoTime) { 7280 // If the device owner enforces auto time, we don't need to check the PO's 7281 return true; 7282 } 7283 7284 // Now check to see if any profile owner on any user enforces auto time 7285 for (Integer userId : mOwners.getProfileOwnerKeys()) { 7286 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 7287 if (profileOwner != null && profileOwner.requireAutoTime) { 7288 return true; 7289 } 7290 } 7291 7292 return false; 7293 } 7294 } 7295 7296 @Override setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers)7297 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 7298 if (!mHasFeature) { 7299 return; 7300 } 7301 Preconditions.checkNotNull(who, "ComponentName is null"); 7302 // Allow setting this policy to true only if there is a split system user. 7303 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) { 7304 throw new UnsupportedOperationException( 7305 "Cannot force ephemeral users on systems without split system user."); 7306 } 7307 boolean removeAllUsers = false; 7308 synchronized (getLockObject()) { 7309 final ActiveAdmin deviceOwner = 7310 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7311 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) { 7312 deviceOwner.forceEphemeralUsers = forceEphemeralUsers; 7313 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 7314 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers); 7315 removeAllUsers = forceEphemeralUsers; 7316 } 7317 } 7318 if (removeAllUsers) { 7319 long identitity = mInjector.binderClearCallingIdentity(); 7320 try { 7321 mUserManagerInternal.removeAllUsers(); 7322 } finally { 7323 mInjector.binderRestoreCallingIdentity(identitity); 7324 } 7325 } 7326 } 7327 7328 @Override getForceEphemeralUsers(ComponentName who)7329 public boolean getForceEphemeralUsers(ComponentName who) { 7330 if (!mHasFeature) { 7331 return false; 7332 } 7333 Preconditions.checkNotNull(who, "ComponentName is null"); 7334 synchronized (getLockObject()) { 7335 final ActiveAdmin deviceOwner = 7336 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7337 return deviceOwner.forceEphemeralUsers; 7338 } 7339 } 7340 ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who)7341 private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) 7342 throws SecurityException { 7343 synchronized (getLockObject()) { 7344 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 7345 } 7346 ensureAllUsersAffiliated(); 7347 } 7348 ensureAllUsersAffiliated()7349 private void ensureAllUsersAffiliated() throws SecurityException { 7350 synchronized (getLockObject()) { 7351 if (!areAllUsersAffiliatedWithDeviceLocked()) { 7352 throw new SecurityException("Not all users are affiliated."); 7353 } 7354 } 7355 } 7356 7357 @Override requestBugreport(ComponentName who)7358 public boolean requestBugreport(ComponentName who) { 7359 if (!mHasFeature) { 7360 return false; 7361 } 7362 Preconditions.checkNotNull(who, "ComponentName is null"); 7363 7364 // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport 7365 // which could still contain data related to that user. Should we disallow that, e.g. until 7366 // next boot? Might not be needed given that this still requires user consent. 7367 ensureDeviceOwnerAndAllUsersAffiliated(who); 7368 7369 if (mRemoteBugreportServiceIsActive.get() 7370 || (getDeviceOwnerRemoteBugreportUri() != null)) { 7371 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running."); 7372 return false; 7373 } 7374 7375 final long currentTime = System.currentTimeMillis(); 7376 synchronized (getLockObject()) { 7377 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 7378 if (currentTime > policyData.mLastBugReportRequestTime) { 7379 policyData.mLastBugReportRequestTime = currentTime; 7380 saveSettingsLocked(UserHandle.USER_SYSTEM); 7381 } 7382 } 7383 7384 final long callingIdentity = mInjector.binderClearCallingIdentity(); 7385 try { 7386 mInjector.getIActivityManager().requestBugReport( 7387 ActivityManager.BUGREPORT_OPTION_REMOTE); 7388 7389 mRemoteBugreportServiceIsActive.set(true); 7390 mRemoteBugreportSharingAccepted.set(false); 7391 registerRemoteBugreportReceivers(); 7392 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, 7393 RemoteBugreportUtils.NOTIFICATION_ID, 7394 RemoteBugreportUtils.buildNotification(mContext, 7395 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL); 7396 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable, 7397 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS); 7398 DevicePolicyEventLogger 7399 .createEvent(DevicePolicyEnums.REQUEST_BUGREPORT) 7400 .setAdmin(who) 7401 .write(); 7402 return true; 7403 } catch (RemoteException re) { 7404 // should never happen 7405 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re); 7406 return false; 7407 } finally { 7408 mInjector.binderRestoreCallingIdentity(callingIdentity); 7409 } 7410 } 7411 sendDeviceOwnerCommand(String action, Bundle extras)7412 void sendDeviceOwnerCommand(String action, Bundle extras) { 7413 final int deviceOwnerUserId; 7414 synchronized (getLockObject()) { 7415 deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 7416 } 7417 7418 ComponentName receiverComponent = null; 7419 if (action.equals(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE)) { 7420 receiverComponent = resolveDelegateReceiver(DELEGATION_NETWORK_LOGGING, action, 7421 deviceOwnerUserId); 7422 } 7423 if (receiverComponent == null) { 7424 synchronized (getLockObject()) { 7425 receiverComponent = mOwners.getDeviceOwnerComponent(); 7426 } 7427 } 7428 sendActiveAdminCommand(action, extras, deviceOwnerUserId, receiverComponent); 7429 } 7430 sendProfileOwnerCommand(String action, Bundle extras, int userHandle)7431 private void sendProfileOwnerCommand(String action, Bundle extras, int userHandle) { 7432 sendActiveAdminCommand(action, extras, userHandle, 7433 mOwners.getProfileOwnerComponent(userHandle)); 7434 } 7435 sendActiveAdminCommand(String action, Bundle extras, int userHandle, ComponentName receiverComponent)7436 private void sendActiveAdminCommand(String action, Bundle extras, 7437 int userHandle, ComponentName receiverComponent) { 7438 final Intent intent = new Intent(action); 7439 intent.setComponent(receiverComponent); 7440 if (extras != null) { 7441 intent.putExtras(extras); 7442 } 7443 mContext.sendBroadcastAsUser(intent, UserHandle.of(userHandle)); 7444 } 7445 sendOwnerChangedBroadcast(String broadcast, int userId)7446 private void sendOwnerChangedBroadcast(String broadcast, int userId) { 7447 final Intent intent = new Intent(broadcast) 7448 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 7449 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 7450 } 7451 getDeviceOwnerRemoteBugreportUri()7452 private String getDeviceOwnerRemoteBugreportUri() { 7453 synchronized (getLockObject()) { 7454 return mOwners.getDeviceOwnerRemoteBugreportUri(); 7455 } 7456 } 7457 setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash)7458 private void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, 7459 String bugreportHash) { 7460 synchronized (getLockObject()) { 7461 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 7462 } 7463 } 7464 registerRemoteBugreportReceivers()7465 private void registerRemoteBugreportReceivers() { 7466 try { 7467 IntentFilter filterFinished = new IntentFilter( 7468 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH, 7469 RemoteBugreportUtils.BUGREPORT_MIMETYPE); 7470 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished); 7471 } catch (IntentFilter.MalformedMimeTypeException e) { 7472 // should never happen, as setting a constant 7473 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e); 7474 } 7475 IntentFilter filterConsent = new IntentFilter(); 7476 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 7477 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 7478 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 7479 } 7480 onBugreportFinished(Intent intent)7481 private void onBugreportFinished(Intent intent) { 7482 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 7483 mRemoteBugreportServiceIsActive.set(false); 7484 Uri bugreportUri = intent.getData(); 7485 String bugreportUriString = null; 7486 if (bugreportUri != null) { 7487 bugreportUriString = bugreportUri.toString(); 7488 } 7489 String bugreportHash = intent.getStringExtra( 7490 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH); 7491 if (mRemoteBugreportSharingAccepted.get()) { 7492 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 7493 mInjector.getNotificationManager().cancel(LOG_TAG, 7494 RemoteBugreportUtils.NOTIFICATION_ID); 7495 } else { 7496 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash); 7497 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 7498 RemoteBugreportUtils.buildNotification(mContext, 7499 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 7500 UserHandle.ALL); 7501 } 7502 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 7503 } 7504 onBugreportFailed()7505 private void onBugreportFailed() { 7506 mRemoteBugreportServiceIsActive.set(false); 7507 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 7508 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 7509 mRemoteBugreportSharingAccepted.set(false); 7510 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 7511 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID); 7512 Bundle extras = new Bundle(); 7513 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 7514 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING); 7515 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 7516 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 7517 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 7518 } 7519 onBugreportSharingAccepted()7520 private void onBugreportSharingAccepted() { 7521 mRemoteBugreportSharingAccepted.set(true); 7522 String bugreportUriString = null; 7523 String bugreportHash = null; 7524 synchronized (getLockObject()) { 7525 bugreportUriString = getDeviceOwnerRemoteBugreportUri(); 7526 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash(); 7527 } 7528 if (bugreportUriString != null) { 7529 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 7530 } else if (mRemoteBugreportServiceIsActive.get()) { 7531 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 7532 RemoteBugreportUtils.buildNotification(mContext, 7533 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED), 7534 UserHandle.ALL); 7535 } 7536 } 7537 onBugreportSharingDeclined()7538 private void onBugreportSharingDeclined() { 7539 if (mRemoteBugreportServiceIsActive.get()) { 7540 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 7541 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 7542 mRemoteBugreportServiceIsActive.set(false); 7543 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 7544 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 7545 } 7546 mRemoteBugreportSharingAccepted.set(false); 7547 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 7548 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null); 7549 } 7550 shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, String bugreportHash)7551 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, 7552 String bugreportHash) { 7553 ParcelFileDescriptor pfd = null; 7554 try { 7555 if (bugreportUriString == null) { 7556 throw new FileNotFoundException(); 7557 } 7558 Uri bugreportUri = Uri.parse(bugreportUriString); 7559 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r"); 7560 7561 synchronized (getLockObject()) { 7562 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 7563 intent.setComponent(mOwners.getDeviceOwnerComponent()); 7564 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE); 7565 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 7566 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7567 7568 LocalServices.getService(UriGrantsManagerInternal.class) 7569 .grantUriPermissionFromIntent(Process.SHELL_UID, 7570 mOwners.getDeviceOwnerComponent().getPackageName(), 7571 intent, mOwners.getDeviceOwnerUserId()); 7572 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 7573 } 7574 } catch (FileNotFoundException e) { 7575 Bundle extras = new Bundle(); 7576 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 7577 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE); 7578 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 7579 } finally { 7580 try { 7581 if (pfd != null) { 7582 pfd.close(); 7583 } 7584 } catch (IOException ex) { 7585 // Ignore 7586 } 7587 mRemoteBugreportSharingAccepted.set(false); 7588 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 7589 } 7590 } 7591 7592 /** 7593 * Disables all device cameras according to the specified admin. 7594 */ 7595 @Override setCameraDisabled(ComponentName who, boolean disabled)7596 public void setCameraDisabled(ComponentName who, boolean disabled) { 7597 if (!mHasFeature) { 7598 return; 7599 } 7600 Preconditions.checkNotNull(who, "ComponentName is null"); 7601 final int userHandle = mInjector.userHandleGetCallingUserId(); 7602 synchronized (getLockObject()) { 7603 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 7604 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 7605 if (ap.disableCamera != disabled) { 7606 ap.disableCamera = disabled; 7607 saveSettingsLocked(userHandle); 7608 } 7609 } 7610 // Tell the user manager that the restrictions have changed. 7611 pushUserRestrictions(userHandle); 7612 DevicePolicyEventLogger 7613 .createEvent(DevicePolicyEnums.SET_CAMERA_DISABLED) 7614 .setAdmin(who) 7615 .setBoolean(disabled) 7616 .write(); 7617 } 7618 7619 /** 7620 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 7621 * active admins. 7622 */ 7623 @Override getCameraDisabled(ComponentName who, int userHandle)7624 public boolean getCameraDisabled(ComponentName who, int userHandle) { 7625 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true); 7626 } 7627 getCameraDisabled(ComponentName who, int userHandle, boolean mergeDeviceOwnerRestriction)7628 private boolean getCameraDisabled(ComponentName who, int userHandle, 7629 boolean mergeDeviceOwnerRestriction) { 7630 if (!mHasFeature) { 7631 return false; 7632 } 7633 synchronized (getLockObject()) { 7634 if (who != null) { 7635 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7636 return (admin != null) ? admin.disableCamera : false; 7637 } 7638 // First, see if DO has set it. If so, it's device-wide. 7639 if (mergeDeviceOwnerRestriction) { 7640 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7641 if (deviceOwner != null && deviceOwner.disableCamera) { 7642 return true; 7643 } 7644 } 7645 7646 // Then check each device admin on the user. 7647 DevicePolicyData policy = getUserData(userHandle); 7648 // Determine whether or not the device camera is disabled for any active admins. 7649 final int N = policy.mAdminList.size(); 7650 for (int i = 0; i < N; i++) { 7651 ActiveAdmin admin = policy.mAdminList.get(i); 7652 if (admin.disableCamera) { 7653 return true; 7654 } 7655 } 7656 return false; 7657 } 7658 } 7659 7660 @Override setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent)7661 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 7662 if (!mHasFeature) { 7663 return; 7664 } 7665 Preconditions.checkNotNull(who, "ComponentName is null"); 7666 final int userHandle = mInjector.userHandleGetCallingUserId(); 7667 if (isManagedProfile(userHandle)) { 7668 if (parent) { 7669 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 7670 } else { 7671 which = which & PROFILE_KEYGUARD_FEATURES; 7672 } 7673 } 7674 synchronized (getLockObject()) { 7675 ActiveAdmin ap = getActiveAdminForCallerLocked( 7676 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 7677 if (ap.disabledKeyguardFeatures != which) { 7678 ap.disabledKeyguardFeatures = which; 7679 saveSettingsLocked(userHandle); 7680 } 7681 } 7682 if (SecurityLog.isLoggingEnabled()) { 7683 final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle; 7684 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET, 7685 who.getPackageName(), userHandle, affectedUserId, which); 7686 } 7687 DevicePolicyEventLogger 7688 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED_FEATURES) 7689 .setAdmin(who) 7690 .setInt(which) 7691 .setBoolean(parent) 7692 .write(); 7693 } 7694 7695 /** 7696 * Gets the disabled state for features in keyguard for the given admin, 7697 * or the aggregate of all active admins if who is null. 7698 */ 7699 @Override getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent)7700 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 7701 if (!mHasFeature) { 7702 return 0; 7703 } 7704 enforceFullCrossUsersPermission(userHandle); 7705 final long ident = mInjector.binderClearCallingIdentity(); 7706 try { 7707 synchronized (getLockObject()) { 7708 if (who != null) { 7709 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 7710 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 7711 } 7712 7713 final List<ActiveAdmin> admins; 7714 if (!parent && isManagedProfile(userHandle)) { 7715 // If we are being asked about a managed profile, just return keyguard features 7716 // disabled by admins in the profile. 7717 admins = getUserDataUnchecked(userHandle).mAdminList; 7718 } else { 7719 // Otherwise return those set by admins in the user and its profiles. 7720 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 7721 } 7722 7723 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 7724 final int N = admins.size(); 7725 for (int i = 0; i < N; i++) { 7726 ActiveAdmin admin = admins.get(i); 7727 int userId = admin.getUserHandle().getIdentifier(); 7728 boolean isRequestedUser = !parent && (userId == userHandle); 7729 if (isRequestedUser || !isManagedProfile(userId)) { 7730 // If we are being asked explicitly about this user 7731 // return all disabled features even if its a managed profile. 7732 which |= admin.disabledKeyguardFeatures; 7733 } else { 7734 // Otherwise a managed profile is only allowed to disable 7735 // some features on the parent user. 7736 which |= (admin.disabledKeyguardFeatures 7737 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 7738 } 7739 } 7740 return which; 7741 } 7742 } finally { 7743 mInjector.binderRestoreCallingIdentity(ident); 7744 } 7745 } 7746 7747 @Override setKeepUninstalledPackages(ComponentName who, String callerPackage, List<String> packageList)7748 public void setKeepUninstalledPackages(ComponentName who, String callerPackage, 7749 List<String> packageList) { 7750 if (!mHasFeature) { 7751 return; 7752 } 7753 Preconditions.checkNotNull(packageList, "packageList is null"); 7754 final int userHandle = UserHandle.getCallingUserId(); 7755 synchronized (getLockObject()) { 7756 // Ensure the caller is a DO or a keep uninstalled packages delegate. 7757 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7758 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 7759 // Get the device owner 7760 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7761 // Set list of packages to be kept even if uninstalled. 7762 deviceOwner.keepUninstalledPackages = packageList; 7763 // Save settings. 7764 saveSettingsLocked(userHandle); 7765 // Notify package manager. 7766 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 7767 } 7768 final boolean isDelegate = (who == null); 7769 DevicePolicyEventLogger 7770 .createEvent(DevicePolicyEnums.SET_KEEP_UNINSTALLED_PACKAGES) 7771 .setAdmin(callerPackage) 7772 .setBoolean(isDelegate) 7773 .setStrings(packageList.toArray(new String[0])) 7774 .write(); 7775 } 7776 7777 @Override getKeepUninstalledPackages(ComponentName who, String callerPackage)7778 public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) { 7779 if (!mHasFeature) { 7780 return null; 7781 } 7782 // TODO In split system user mode, allow apps on user 0 to query the list 7783 synchronized (getLockObject()) { 7784 // Ensure the caller is a DO or a keep uninstalled packages delegate. 7785 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7786 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 7787 return getKeepUninstalledPackagesLocked(); 7788 } 7789 } 7790 getKeepUninstalledPackagesLocked()7791 private List<String> getKeepUninstalledPackagesLocked() { 7792 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 7793 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 7794 } 7795 7796 @Override setDeviceOwner(ComponentName admin, String ownerName, int userId)7797 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) { 7798 if (!mHasFeature) { 7799 return false; 7800 } 7801 if (admin == null 7802 || !isPackageInstalledForUser(admin.getPackageName(), userId)) { 7803 throw new IllegalArgumentException("Invalid component " + admin 7804 + " for device owner"); 7805 } 7806 final boolean hasIncompatibleAccountsOrNonAdb = 7807 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin); 7808 synchronized (getLockObject()) { 7809 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb); 7810 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 7811 if (activeAdmin == null 7812 || getUserData(userId).mRemovingAdmins.contains(admin)) { 7813 throw new IllegalArgumentException("Not active admin: " + admin); 7814 } 7815 7816 // Shutting down backup manager service permanently. 7817 toggleBackupServiceActive(UserHandle.USER_SYSTEM, /* makeActive= */ false); 7818 if (isAdb()) { 7819 // Log device owner provisioning was started using adb. 7820 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 7821 DevicePolicyEventLogger 7822 .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB) 7823 .setAdmin(admin) 7824 .setStrings(LOG_TAG_DEVICE_OWNER) 7825 .write(); 7826 } 7827 7828 mOwners.setDeviceOwner(admin, ownerName, userId); 7829 mOwners.writeDeviceOwner(); 7830 updateDeviceOwnerLocked(); 7831 setDeviceOwnerSystemPropertyLocked(); 7832 7833 final Set<String> restrictions = 7834 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner(); 7835 if (!restrictions.isEmpty()) { 7836 for (String restriction : restrictions) { 7837 activeAdmin.ensureUserRestrictions().putBoolean(restriction, true); 7838 } 7839 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions); 7840 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions); 7841 7842 saveUserRestrictionsLocked(userId); 7843 } 7844 7845 long ident = mInjector.binderClearCallingIdentity(); 7846 try { 7847 // TODO Send to system too? 7848 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId); 7849 } finally { 7850 mInjector.binderRestoreCallingIdentity(ident); 7851 } 7852 mDeviceAdminServiceController.startServiceForOwner( 7853 admin.getPackageName(), userId, "set-device-owner"); 7854 7855 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 7856 return true; 7857 } 7858 } 7859 7860 @Override hasDeviceOwner()7861 public boolean hasDeviceOwner() { 7862 enforceDeviceOwnerOrManageUsers(); 7863 return mOwners.hasDeviceOwner(); 7864 } 7865 isDeviceOwner(ActiveAdmin admin)7866 boolean isDeviceOwner(ActiveAdmin admin) { 7867 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 7868 } 7869 isDeviceOwner(ComponentName who, int userId)7870 public boolean isDeviceOwner(ComponentName who, int userId) { 7871 synchronized (getLockObject()) { 7872 return mOwners.hasDeviceOwner() 7873 && mOwners.getDeviceOwnerUserId() == userId 7874 && mOwners.getDeviceOwnerComponent().equals(who); 7875 } 7876 } 7877 isDeviceOwnerPackage(String packageName, int userId)7878 private boolean isDeviceOwnerPackage(String packageName, int userId) { 7879 synchronized (getLockObject()) { 7880 return mOwners.hasDeviceOwner() 7881 && mOwners.getDeviceOwnerUserId() == userId 7882 && mOwners.getDeviceOwnerPackageName().equals(packageName); 7883 } 7884 } 7885 isProfileOwnerPackage(String packageName, int userId)7886 private boolean isProfileOwnerPackage(String packageName, int userId) { 7887 synchronized (getLockObject()) { 7888 return mOwners.hasProfileOwner(userId) 7889 && mOwners.getProfileOwnerPackage(userId).equals(packageName); 7890 } 7891 } 7892 isProfileOwner(ComponentName who, int userId)7893 public boolean isProfileOwner(ComponentName who, int userId) { 7894 final ComponentName profileOwner = getProfileOwner(userId); 7895 return who != null && who.equals(profileOwner); 7896 } 7897 hasProfileOwner(int userId)7898 private boolean hasProfileOwner(int userId) { 7899 synchronized (getLockObject()) { 7900 return mOwners.hasProfileOwner(userId); 7901 } 7902 } 7903 canProfileOwnerAccessDeviceIds(int userId)7904 private boolean canProfileOwnerAccessDeviceIds(int userId) { 7905 synchronized (getLockObject()) { 7906 return mOwners.canProfileOwnerAccessDeviceIds(userId); 7907 } 7908 } 7909 7910 @Override getDeviceOwnerComponent(boolean callingUserOnly)7911 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 7912 if (!mHasFeature) { 7913 return null; 7914 } 7915 if (!callingUserOnly) { 7916 enforceManageUsers(); 7917 } 7918 synchronized (getLockObject()) { 7919 if (!mOwners.hasDeviceOwner()) { 7920 return null; 7921 } 7922 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 7923 mOwners.getDeviceOwnerUserId()) { 7924 return null; 7925 } 7926 return mOwners.getDeviceOwnerComponent(); 7927 } 7928 } 7929 7930 @Override getDeviceOwnerUserId()7931 public int getDeviceOwnerUserId() { 7932 if (!mHasFeature) { 7933 return UserHandle.USER_NULL; 7934 } 7935 enforceManageUsers(); 7936 synchronized (getLockObject()) { 7937 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 7938 } 7939 } 7940 7941 /** 7942 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 7943 * MANAGE_USERS. 7944 */ 7945 @Override getDeviceOwnerName()7946 public String getDeviceOwnerName() { 7947 if (!mHasFeature) { 7948 return null; 7949 } 7950 enforceManageUsers(); 7951 synchronized (getLockObject()) { 7952 if (!mOwners.hasDeviceOwner()) { 7953 return null; 7954 } 7955 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 7956 // Should setDeviceOwner/ProfileOwner still take a name? 7957 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 7958 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 7959 } 7960 } 7961 7962 /** Returns the active device owner or {@code null} if there is no device owner. */ 7963 @VisibleForTesting getDeviceOwnerAdminLocked()7964 ActiveAdmin getDeviceOwnerAdminLocked() { 7965 ensureLocked(); 7966 ComponentName component = mOwners.getDeviceOwnerComponent(); 7967 if (component == null) { 7968 return null; 7969 } 7970 7971 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 7972 final int n = policy.mAdminList.size(); 7973 for (int i = 0; i < n; i++) { 7974 ActiveAdmin admin = policy.mAdminList.get(i); 7975 if (component.equals(admin.info.getComponent())) { 7976 return admin; 7977 } 7978 } 7979 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 7980 return null; 7981 } 7982 7983 @Override clearDeviceOwner(String packageName)7984 public void clearDeviceOwner(String packageName) { 7985 Preconditions.checkNotNull(packageName, "packageName is null"); 7986 final int callingUid = mInjector.binderGetCallingUid(); 7987 try { 7988 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 7989 UserHandle.getUserId(callingUid)); 7990 if (uid != callingUid) { 7991 throw new SecurityException("Invalid packageName"); 7992 } 7993 } catch (NameNotFoundException e) { 7994 throw new SecurityException(e); 7995 } 7996 synchronized (getLockObject()) { 7997 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 7998 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 7999 if (!mOwners.hasDeviceOwner() 8000 || !deviceOwnerComponent.getPackageName().equals(packageName) 8001 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) { 8002 throw new SecurityException( 8003 "clearDeviceOwner can only be called by the device owner"); 8004 } 8005 enforceUserUnlocked(deviceOwnerUserId); 8006 8007 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 8008 long ident = mInjector.binderClearCallingIdentity(); 8009 try { 8010 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 8011 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 8012 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, 8013 deviceOwnerUserId); 8014 } finally { 8015 mInjector.binderRestoreCallingIdentity(ident); 8016 } 8017 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 8018 } 8019 } 8020 clearOverrideApnUnchecked()8021 private void clearOverrideApnUnchecked() { 8022 // Disable Override APNs and remove them from database. 8023 setOverrideApnsEnabledUnchecked(false); 8024 final List<ApnSetting> apns = getOverrideApnsUnchecked(); 8025 for (int i = 0; i < apns.size(); i ++) { 8026 removeOverrideApnUnchecked(apns.get(i).getId()); 8027 } 8028 } 8029 clearDeviceOwnerLocked(ActiveAdmin admin, int userId)8030 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 8031 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner"); 8032 8033 if (admin != null) { 8034 admin.disableCamera = false; 8035 admin.userRestrictions = null; 8036 admin.defaultEnabledRestrictionsAlreadySet.clear(); 8037 admin.forceEphemeralUsers = false; 8038 admin.isNetworkLoggingEnabled = false; 8039 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 8040 } 8041 final DevicePolicyData policyData = getUserData(userId); 8042 policyData.mCurrentInputMethodSet = false; 8043 saveSettingsLocked(userId); 8044 final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM); 8045 systemPolicyData.mLastSecurityLogRetrievalTime = -1; 8046 systemPolicyData.mLastBugReportRequestTime = -1; 8047 systemPolicyData.mLastNetworkLogsRetrievalTime = -1; 8048 saveSettingsLocked(UserHandle.USER_SYSTEM); 8049 clearUserPoliciesLocked(userId); 8050 clearOverrideApnUnchecked(); 8051 8052 mOwners.clearDeviceOwner(); 8053 mOwners.writeDeviceOwner(); 8054 updateDeviceOwnerLocked(); 8055 8056 clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId)); 8057 mInjector.securityLogSetLoggingEnabledProperty(false); 8058 mSecurityLogMonitor.stop(); 8059 setNetworkLoggingActiveInternal(false); 8060 deleteTransferOwnershipBundleLocked(userId); 8061 8062 try { 8063 if (mInjector.getIBackupManager() != null) { 8064 // Reactivate backup service. 8065 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true); 8066 } 8067 } catch (RemoteException e) { 8068 throw new IllegalStateException("Failed reactivating backup service.", e); 8069 } 8070 } 8071 8072 @Override setProfileOwner(ComponentName who, String ownerName, int userHandle)8073 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 8074 if (!mHasFeature) { 8075 return false; 8076 } 8077 if (who == null 8078 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) { 8079 throw new IllegalArgumentException("Component " + who 8080 + " not installed for userId:" + userHandle); 8081 } 8082 8083 final boolean hasIncompatibleAccountsOrNonAdb = 8084 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who); 8085 synchronized (getLockObject()) { 8086 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb); 8087 8088 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 8089 if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) { 8090 throw new IllegalArgumentException("Not active admin: " + who); 8091 } 8092 8093 if (isAdb()) { 8094 // Log profile owner provisioning was started using adb. 8095 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 8096 DevicePolicyEventLogger 8097 .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB) 8098 .setAdmin(who) 8099 .setStrings(LOG_TAG_PROFILE_OWNER) 8100 .write(); 8101 } 8102 8103 // Shutting down backup manager service permanently. 8104 toggleBackupServiceActive(userHandle, /* makeActive= */ false); 8105 8106 mOwners.setProfileOwner(who, ownerName, userHandle); 8107 mOwners.writeProfileOwner(userHandle); 8108 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 8109 8110 final long id = mInjector.binderClearCallingIdentity(); 8111 try { 8112 if (mUserManager.isManagedProfile(userHandle)) { 8113 maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin, 8114 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles()); 8115 ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin, 8116 true /* newOwner */); 8117 } 8118 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 8119 userHandle); 8120 } finally { 8121 mInjector.binderRestoreCallingIdentity(id); 8122 } 8123 mDeviceAdminServiceController.startServiceForOwner( 8124 who.getPackageName(), userHandle, "set-profile-owner"); 8125 return true; 8126 } 8127 } 8128 8129 toggleBackupServiceActive(int userId, boolean makeActive)8130 private void toggleBackupServiceActive(int userId, boolean makeActive) { 8131 long ident = mInjector.binderClearCallingIdentity(); 8132 try { 8133 if (mInjector.getIBackupManager() != null) { 8134 mInjector.getIBackupManager() 8135 .setBackupServiceActive(userId, makeActive); 8136 } 8137 } catch (RemoteException e) { 8138 throw new IllegalStateException("Failed deactivating backup service.", e); 8139 } finally { 8140 mInjector.binderRestoreCallingIdentity(ident); 8141 } 8142 8143 } 8144 8145 @Override clearProfileOwner(ComponentName who)8146 public void clearProfileOwner(ComponentName who) { 8147 if (!mHasFeature) { 8148 return; 8149 } 8150 Preconditions.checkNotNull(who, "ComponentName is null"); 8151 8152 final int userId = mInjector.userHandleGetCallingUserId(); 8153 enforceNotManagedProfile(userId, "clear profile owner"); 8154 enforceUserUnlocked(userId); 8155 synchronized (getLockObject()) { 8156 // Check if this is the profile owner who is calling 8157 final ActiveAdmin admin = 8158 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8159 8160 final long ident = mInjector.binderClearCallingIdentity(); 8161 try { 8162 clearProfileOwnerLocked(admin, userId); 8163 removeActiveAdminLocked(who, userId); 8164 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, 8165 userId); 8166 } finally { 8167 mInjector.binderRestoreCallingIdentity(ident); 8168 } 8169 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 8170 } 8171 } 8172 clearProfileOwnerLocked(ActiveAdmin admin, int userId)8173 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 8174 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner"); 8175 8176 if (admin != null) { 8177 admin.disableCamera = false; 8178 admin.userRestrictions = null; 8179 admin.defaultEnabledRestrictionsAlreadySet.clear(); 8180 } 8181 final DevicePolicyData policyData = getUserData(userId); 8182 policyData.mCurrentInputMethodSet = false; 8183 policyData.mOwnerInstalledCaCerts.clear(); 8184 saveSettingsLocked(userId); 8185 clearUserPoliciesLocked(userId); 8186 mOwners.removeProfileOwner(userId); 8187 mOwners.writeProfileOwner(userId); 8188 deleteTransferOwnershipBundleLocked(userId); 8189 } 8190 8191 @Override setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info)8192 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 8193 Preconditions.checkNotNull(who, "ComponentName is null"); 8194 if (!mHasFeature) { 8195 return; 8196 } 8197 8198 synchronized (getLockObject()) { 8199 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8200 long token = mInjector.binderClearCallingIdentity(); 8201 try { 8202 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null); 8203 } finally { 8204 mInjector.binderRestoreCallingIdentity(token); 8205 } 8206 } 8207 DevicePolicyEventLogger 8208 .createEvent(DevicePolicyEnums.SET_DEVICE_OWNER_LOCK_SCREEN_INFO) 8209 .setAdmin(who) 8210 .write(); 8211 } 8212 8213 @Override getDeviceOwnerLockScreenInfo()8214 public CharSequence getDeviceOwnerLockScreenInfo() { 8215 return mLockPatternUtils.getDeviceOwnerInfo(); 8216 } 8217 clearUserPoliciesLocked(int userId)8218 private void clearUserPoliciesLocked(int userId) { 8219 // Reset some of the user-specific policies. 8220 final DevicePolicyData policy = getUserData(userId); 8221 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 8222 // Clear delegations. 8223 policy.mDelegationMap.clear(); 8224 policy.mStatusBarDisabled = false; 8225 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 8226 policy.mAffiliationIds.clear(); 8227 policy.mLockTaskPackages.clear(); 8228 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId); 8229 policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE; 8230 saveSettingsLocked(userId); 8231 8232 try { 8233 mIPackageManager.updatePermissionFlagsForAllApps( 8234 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 8235 0 /* flagValues */, userId); 8236 pushUserRestrictions(userId); 8237 } catch (RemoteException re) { 8238 // Shouldn't happen. 8239 } 8240 } 8241 8242 @Override hasUserSetupCompleted()8243 public boolean hasUserSetupCompleted() { 8244 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 8245 } 8246 8247 // This checks only if the Setup Wizard has run. Since Wear devices pair before 8248 // completing Setup Wizard, and pairing involves transferring user data, calling 8249 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). hasUserSetupCompleted(int userHandle)8250 private boolean hasUserSetupCompleted(int userHandle) { 8251 if (!mHasFeature) { 8252 return true; 8253 } 8254 return getUserData(userHandle).mUserSetupComplete; 8255 } 8256 hasPaired(int userHandle)8257 private boolean hasPaired(int userHandle) { 8258 if (!mHasFeature) { 8259 return true; 8260 } 8261 return getUserData(userHandle).mPaired; 8262 } 8263 8264 @Override getUserProvisioningState()8265 public int getUserProvisioningState() { 8266 if (!mHasFeature) { 8267 return DevicePolicyManager.STATE_USER_UNMANAGED; 8268 } 8269 enforceManageUsers(); 8270 int userHandle = mInjector.userHandleGetCallingUserId(); 8271 return getUserProvisioningState(userHandle); 8272 } 8273 getUserProvisioningState(int userHandle)8274 private int getUserProvisioningState(int userHandle) { 8275 return getUserData(userHandle).mUserProvisioningState; 8276 } 8277 8278 @Override setUserProvisioningState(int newState, int userHandle)8279 public void setUserProvisioningState(int newState, int userHandle) { 8280 if (!mHasFeature) { 8281 return; 8282 } 8283 8284 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle) 8285 && getManagedUserId(userHandle) == -1) { 8286 // No managed device, user or profile, so setting provisioning state makes no sense. 8287 throw new IllegalStateException("Not allowed to change provisioning state unless a " 8288 + "device or profile owner is set."); 8289 } 8290 8291 synchronized (getLockObject()) { 8292 boolean transitionCheckNeeded = true; 8293 8294 // Calling identity/permission checks. 8295 if (isAdb()) { 8296 // ADB shell can only move directly from un-managed to finalized as part of directly 8297 // setting profile-owner or device-owner. 8298 if (getUserProvisioningState(userHandle) != 8299 DevicePolicyManager.STATE_USER_UNMANAGED 8300 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 8301 throw new IllegalStateException("Not allowed to change provisioning state " 8302 + "unless current provisioning state is unmanaged, and new state is " 8303 + "finalized."); 8304 } 8305 transitionCheckNeeded = false; 8306 } else { 8307 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS. 8308 enforceCanManageProfileAndDeviceOwners(); 8309 } 8310 8311 final DevicePolicyData policyData = getUserData(userHandle); 8312 if (transitionCheckNeeded) { 8313 // Optional state transition check for non-ADB case. 8314 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState); 8315 } 8316 policyData.mUserProvisioningState = newState; 8317 saveSettingsLocked(userHandle); 8318 } 8319 } 8320 checkUserProvisioningStateTransition(int currentState, int newState)8321 private void checkUserProvisioningStateTransition(int currentState, int newState) { 8322 // Valid transitions for normal use-cases. 8323 switch (currentState) { 8324 case DevicePolicyManager.STATE_USER_UNMANAGED: 8325 // Can move to any state from unmanaged (except itself as an edge case).. 8326 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 8327 return; 8328 } 8329 break; 8330 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 8331 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 8332 // Can only move to finalized from these states. 8333 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 8334 return; 8335 } 8336 break; 8337 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 8338 // Current user has a managed-profile, but current user is not managed, so 8339 // rather than moving to finalized state, go back to unmanaged once 8340 // profile provisioning is complete. 8341 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 8342 return; 8343 } 8344 break; 8345 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED: 8346 // Cannot transition out of finalized. 8347 break; 8348 } 8349 8350 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 8351 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 8352 + "from state [" + currentState + "]"); 8353 } 8354 8355 @Override setProfileEnabled(ComponentName who)8356 public void setProfileEnabled(ComponentName who) { 8357 if (!mHasFeature) { 8358 return; 8359 } 8360 Preconditions.checkNotNull(who, "ComponentName is null"); 8361 synchronized (getLockObject()) { 8362 // Check if this is the profile owner who is calling 8363 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8364 final int userId = UserHandle.getCallingUserId(); 8365 enforceManagedProfile(userId, "enable the profile"); 8366 // Check if the profile is already enabled. 8367 UserInfo managedProfile = getUserInfo(userId); 8368 if (managedProfile.isEnabled()) { 8369 Slog.e(LOG_TAG, 8370 "setProfileEnabled is called when the profile is already enabled"); 8371 return; 8372 } 8373 long id = mInjector.binderClearCallingIdentity(); 8374 try { 8375 mUserManager.setUserEnabled(userId); 8376 UserInfo parent = mUserManager.getProfileParent(userId); 8377 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 8378 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 8379 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 8380 Intent.FLAG_RECEIVER_FOREGROUND); 8381 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id)); 8382 } finally { 8383 mInjector.binderRestoreCallingIdentity(id); 8384 } 8385 } 8386 } 8387 8388 @Override setProfileName(ComponentName who, String profileName)8389 public void setProfileName(ComponentName who, String profileName) { 8390 Preconditions.checkNotNull(who, "ComponentName is null"); 8391 enforceProfileOrDeviceOwner(who); 8392 8393 final int userId = UserHandle.getCallingUserId(); 8394 final long id = mInjector.binderClearCallingIdentity(); 8395 try { 8396 mUserManager.setUserName(userId, profileName); 8397 DevicePolicyEventLogger 8398 .createEvent(DevicePolicyEnums.SET_PROFILE_NAME) 8399 .setAdmin(who) 8400 .write(); 8401 } finally { 8402 mInjector.binderRestoreCallingIdentity(id); 8403 } 8404 } 8405 8406 @Override getProfileOwnerAsUser(int userHandle)8407 public ComponentName getProfileOwnerAsUser(int userHandle) { 8408 enforceCrossUsersPermission(userHandle); 8409 8410 return getProfileOwner(userHandle); 8411 } 8412 8413 @Override getProfileOwner(int userHandle)8414 public ComponentName getProfileOwner(int userHandle) { 8415 if (!mHasFeature) { 8416 return null; 8417 } 8418 8419 synchronized (getLockObject()) { 8420 return mOwners.getProfileOwnerComponent(userHandle); 8421 } 8422 } 8423 8424 // Returns the active profile owner for this user or null if the current user has no 8425 // profile owner. 8426 @VisibleForTesting getProfileOwnerAdminLocked(int userHandle)8427 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 8428 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 8429 if (profileOwner == null) { 8430 return null; 8431 } 8432 DevicePolicyData policy = getUserData(userHandle); 8433 final int n = policy.mAdminList.size(); 8434 for (int i = 0; i < n; i++) { 8435 ActiveAdmin admin = policy.mAdminList.get(i); 8436 if (profileOwner.equals(admin.info.getComponent())) { 8437 return admin; 8438 } 8439 } 8440 return null; 8441 } 8442 8443 @Override getProfileOwnerName(int userHandle)8444 public String getProfileOwnerName(int userHandle) { 8445 if (!mHasFeature) { 8446 return null; 8447 } 8448 enforceManageUsers(); 8449 ComponentName profileOwner = getProfileOwner(userHandle); 8450 if (profileOwner == null) { 8451 return null; 8452 } 8453 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 8454 } 8455 8456 @Override checkDeviceIdentifierAccess(String packageName, int pid, int uid)8457 public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) { 8458 // If the caller is not a system app then it should only be able to check its own device 8459 // identifier access. 8460 int callingUid = mInjector.binderGetCallingUid(); 8461 int callingPid = mInjector.binderGetCallingPid(); 8462 if (UserHandle.getAppId(callingUid) >= Process.FIRST_APPLICATION_UID 8463 && (callingUid != uid || callingPid != pid)) { 8464 String message = String.format( 8465 "Calling uid %d, pid %d cannot check device identifier access for package %s " 8466 + "(uid=%d, pid=%d)", callingUid, callingPid, packageName, uid, pid); 8467 Log.w(LOG_TAG, message); 8468 throw new SecurityException(message); 8469 } 8470 // Verify that the specified packages matches the provided uid. 8471 int userId = UserHandle.getUserId(uid); 8472 try { 8473 ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(packageName, 0, userId); 8474 // Since this call goes directly to PackageManagerService a NameNotFoundException is not 8475 // thrown but null data can be returned; if the appInfo for the specified package cannot 8476 // be found then return false to prevent crashing the app. 8477 if (appInfo == null) { 8478 Log.w(LOG_TAG, 8479 String.format("appInfo could not be found for package %s", packageName)); 8480 return false; 8481 } else if (uid != appInfo.uid) { 8482 String message = String.format("Package %s (uid=%d) does not match provided uid %d", 8483 packageName, appInfo.uid, uid); 8484 Log.w(LOG_TAG, message); 8485 throw new SecurityException(message); 8486 } 8487 } catch (RemoteException e) { 8488 // If an exception is caught obtaining the appInfo just return false to prevent crashing 8489 // apps due to an internal error. 8490 Log.e(LOG_TAG, "Exception caught obtaining appInfo for package " + packageName, e); 8491 return false; 8492 } 8493 // A device or profile owner must also have the READ_PHONE_STATE permission to access device 8494 // identifiers. If the package being checked does not have this permission then deny access. 8495 if (mContext.checkPermission(android.Manifest.permission.READ_PHONE_STATE, pid, uid) 8496 != PackageManager.PERMISSION_GRANTED) { 8497 return false; 8498 } 8499 8500 // Allow access to the device owner or delegate cert installer. 8501 ComponentName deviceOwner = getDeviceOwnerComponent(true); 8502 if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName) 8503 || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) { 8504 return true; 8505 } 8506 // Allow access to the profile owner for the specified user, or delegate cert installer 8507 ComponentName profileOwner = getProfileOwnerAsUser(userId); 8508 if (profileOwner != null && (profileOwner.getPackageName().equals(packageName) 8509 || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) { 8510 return true; 8511 } 8512 8513 Log.w(LOG_TAG, String.format("Package %s (uid=%d, pid=%d) cannot access Device IDs", 8514 packageName, uid, pid)); 8515 return false; 8516 } 8517 8518 /** 8519 * Canonical name for a given package. 8520 */ getApplicationLabel(String packageName, int userHandle)8521 private String getApplicationLabel(String packageName, int userHandle) { 8522 long token = mInjector.binderClearCallingIdentity(); 8523 try { 8524 final Context userContext; 8525 try { 8526 UserHandle handle = new UserHandle(userHandle); 8527 userContext = mContext.createPackageContextAsUser(packageName, 0, handle); 8528 } catch (PackageManager.NameNotFoundException nnfe) { 8529 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe); 8530 return null; 8531 } 8532 ApplicationInfo appInfo = userContext.getApplicationInfo(); 8533 CharSequence result = null; 8534 if (appInfo != null) { 8535 result = appInfo.loadUnsafeLabel(userContext.getPackageManager()); 8536 } 8537 return result != null ? result.toString() : null; 8538 } finally { 8539 mInjector.binderRestoreCallingIdentity(token); 8540 } 8541 } 8542 8543 /** 8544 * Calls wtfStack() if called with the DPMS lock held. 8545 */ wtfIfInLock()8546 private void wtfIfInLock() { 8547 if (Thread.holdsLock(this)) { 8548 Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held"); 8549 } 8550 } 8551 8552 /** 8553 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 8554 * permission. 8555 * The profile owner can only be set before the user setup phase has completed, 8556 * except for: 8557 * - SYSTEM_UID 8558 * - adb unless hasIncompatibleAccountsOrNonAdb is true. 8559 */ enforceCanSetProfileOwnerLocked(@ullable ComponentName owner, int userHandle, boolean hasIncompatibleAccountsOrNonAdb)8560 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle, 8561 boolean hasIncompatibleAccountsOrNonAdb) { 8562 UserInfo info = getUserInfo(userHandle); 8563 if (info == null) { 8564 // User doesn't exist. 8565 throw new IllegalArgumentException( 8566 "Attempted to set profile owner for invalid userId: " + userHandle); 8567 } 8568 if (info.isGuest()) { 8569 throw new IllegalStateException("Cannot set a profile owner on a guest"); 8570 } 8571 if (mOwners.hasProfileOwner(userHandle)) { 8572 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 8573 + "is already set."); 8574 } 8575 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 8576 throw new IllegalStateException("Trying to set the profile owner, but the user " 8577 + "already has a device owner."); 8578 } 8579 if (isAdb()) { 8580 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 8581 && hasIncompatibleAccountsOrNonAdb) { 8582 throw new IllegalStateException("Not allowed to set the profile owner because " 8583 + "there are already some accounts on the profile"); 8584 } 8585 return; 8586 } 8587 enforceCanManageProfileAndDeviceOwners(); 8588 8589 if ((mIsWatch || hasUserSetupCompleted(userHandle))) { 8590 if (!isCallerWithSystemUid()) { 8591 throw new IllegalStateException("Cannot set the profile owner on a user which is " 8592 + "already set-up"); 8593 } 8594 8595 if (!mIsWatch) { 8596 // Only the default supervision profile owner can be set as profile owner after SUW 8597 final String supervisor = mContext.getResources().getString( 8598 com.android.internal.R.string 8599 .config_defaultSupervisionProfileOwnerComponent); 8600 if (supervisor == null) { 8601 throw new IllegalStateException("Unable to set profile owner post-setup, no" 8602 + "default supervisor profile owner defined"); 8603 } 8604 8605 final ComponentName supervisorComponent = ComponentName.unflattenFromString( 8606 supervisor); 8607 if (!owner.equals(supervisorComponent)) { 8608 throw new IllegalStateException("Unable to set non-default profile owner" 8609 + " post-setup " + owner); 8610 } 8611 } 8612 } 8613 } 8614 8615 /** 8616 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 8617 * permission. 8618 */ enforceCanSetDeviceOwnerLocked(@ullable ComponentName owner, int userId, boolean hasIncompatibleAccountsOrNonAdb)8619 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId, 8620 boolean hasIncompatibleAccountsOrNonAdb) { 8621 if (!isAdb()) { 8622 enforceCanManageProfileAndDeviceOwners(); 8623 } 8624 8625 final int code = checkDeviceOwnerProvisioningPreConditionLocked( 8626 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb); 8627 switch (code) { 8628 case CODE_OK: 8629 return; 8630 case CODE_HAS_DEVICE_OWNER: 8631 throw new IllegalStateException( 8632 "Trying to set the device owner, but device owner is already set."); 8633 case CODE_USER_HAS_PROFILE_OWNER: 8634 throw new IllegalStateException("Trying to set the device owner, but the user " 8635 + "already has a profile owner."); 8636 case CODE_USER_NOT_RUNNING: 8637 throw new IllegalStateException("User not running: " + userId); 8638 case CODE_NOT_SYSTEM_USER: 8639 throw new IllegalStateException("User is not system user"); 8640 case CODE_USER_SETUP_COMPLETED: 8641 throw new IllegalStateException( 8642 "Cannot set the device owner if the device is already set-up"); 8643 case CODE_NONSYSTEM_USER_EXISTS: 8644 throw new IllegalStateException("Not allowed to set the device owner because there " 8645 + "are already several users on the device"); 8646 case CODE_ACCOUNTS_NOT_EMPTY: 8647 throw new IllegalStateException("Not allowed to set the device owner because there " 8648 + "are already some accounts on the device"); 8649 case CODE_HAS_PAIRED: 8650 throw new IllegalStateException("Not allowed to set the device owner because this " 8651 + "device has already paired"); 8652 default: 8653 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code); 8654 } 8655 } 8656 enforceUserUnlocked(int userId)8657 private void enforceUserUnlocked(int userId) { 8658 // Since we're doing this operation on behalf of an app, we only 8659 // want to use the actual "unlocked" state. 8660 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 8661 "User must be running and unlocked"); 8662 } 8663 enforceUserUnlocked(@serIdInt int userId, boolean parent)8664 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 8665 if (parent) { 8666 enforceUserUnlocked(getProfileParentId(userId)); 8667 } else { 8668 enforceUserUnlocked(userId); 8669 } 8670 } 8671 enforceManageUsers()8672 private void enforceManageUsers() { 8673 final int callingUid = mInjector.binderGetCallingUid(); 8674 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 8675 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8676 } 8677 } 8678 enforceFullCrossUsersPermission(int userHandle)8679 private void enforceFullCrossUsersPermission(int userHandle) { 8680 enforceSystemUserOrPermissionIfCrossUser(userHandle, 8681 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 8682 } 8683 enforceCrossUsersPermission(int userHandle)8684 private void enforceCrossUsersPermission(int userHandle) { 8685 enforceSystemUserOrPermissionIfCrossUser(userHandle, 8686 android.Manifest.permission.INTERACT_ACROSS_USERS); 8687 } 8688 enforceSystemUserOrPermission(String permission)8689 private void enforceSystemUserOrPermission(String permission) { 8690 if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) { 8691 mContext.enforceCallingOrSelfPermission(permission, 8692 "Must be system or have " + permission + " permission"); 8693 } 8694 } 8695 enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission)8696 private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) { 8697 if (userHandle < 0) { 8698 throw new IllegalArgumentException("Invalid userId " + userHandle); 8699 } 8700 if (userHandle == mInjector.userHandleGetCallingUserId()) { 8701 return; 8702 } 8703 enforceSystemUserOrPermission(permission); 8704 } 8705 enforceManagedProfile(int userHandle, String message)8706 private void enforceManagedProfile(int userHandle, String message) { 8707 if(!isManagedProfile(userHandle)) { 8708 throw new SecurityException("You can not " + message + " outside a managed profile."); 8709 } 8710 } 8711 enforceNotManagedProfile(int userHandle, String message)8712 private void enforceNotManagedProfile(int userHandle, String message) { 8713 if(isManagedProfile(userHandle)) { 8714 throw new SecurityException("You can not " + message + " for a managed profile."); 8715 } 8716 } 8717 enforceDeviceOwnerOrManageUsers()8718 private void enforceDeviceOwnerOrManageUsers() { 8719 synchronized (getLockObject()) { 8720 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 8721 mInjector.binderGetCallingUid()) != null) { 8722 return; 8723 } 8724 } 8725 enforceManageUsers(); 8726 } 8727 enforceProfileOwnerOrSystemUser()8728 private void enforceProfileOwnerOrSystemUser() { 8729 synchronized (getLockObject()) { 8730 if (getActiveAdminWithPolicyForUidLocked(null, 8731 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 8732 != null) { 8733 return; 8734 } 8735 } 8736 Preconditions.checkState(isCallerWithSystemUid(), 8737 "Only profile owner, device owner and system may call this method."); 8738 } 8739 enforceProfileOwnerOrFullCrossUsersPermission(int userId)8740 private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) { 8741 if (userId == mInjector.userHandleGetCallingUserId()) { 8742 synchronized (getLockObject()) { 8743 if (getActiveAdminWithPolicyForUidLocked(null, 8744 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 8745 != null) { 8746 // Device Owner/Profile Owner may access the user it runs on. 8747 return; 8748 } 8749 } 8750 } 8751 // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required. 8752 enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 8753 } 8754 canUserUseLockTaskLocked(int userId)8755 private boolean canUserUseLockTaskLocked(int userId) { 8756 if (isUserAffiliatedWithDeviceLocked(userId)) { 8757 return true; 8758 } 8759 8760 // Unaffiliated profile owners are not allowed to use lock when there is a device owner. 8761 if (mOwners.hasDeviceOwner()) { 8762 return false; 8763 } 8764 8765 final ComponentName profileOwner = getProfileOwner(userId); 8766 if (profileOwner == null) { 8767 return false; 8768 } 8769 8770 // Managed profiles are not allowed to use lock task 8771 if (isManagedProfile(userId)) { 8772 return false; 8773 } 8774 8775 return true; 8776 } 8777 enforceCanCallLockTaskLocked(ComponentName who)8778 private void enforceCanCallLockTaskLocked(ComponentName who) { 8779 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8780 final int userId = mInjector.userHandleGetCallingUserId(); 8781 if (!canUserUseLockTaskLocked(userId)) { 8782 throw new SecurityException("User " + userId + " is not allowed to use lock task"); 8783 } 8784 } 8785 ensureCallerPackage(@ullable String packageName)8786 private void ensureCallerPackage(@Nullable String packageName) { 8787 if (packageName == null) { 8788 Preconditions.checkState(isCallerWithSystemUid(), 8789 "Only caller can omit package name"); 8790 } else { 8791 final int callingUid = mInjector.binderGetCallingUid(); 8792 final int userId = mInjector.userHandleGetCallingUserId(); 8793 try { 8794 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 8795 packageName, 0, userId); 8796 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name"); 8797 } catch (RemoteException e) { 8798 // Shouldn't happen 8799 } 8800 } 8801 } 8802 isCallerWithSystemUid()8803 private boolean isCallerWithSystemUid() { 8804 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID); 8805 } 8806 getProfileParentId(int userHandle)8807 protected int getProfileParentId(int userHandle) { 8808 final long ident = mInjector.binderClearCallingIdentity(); 8809 try { 8810 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 8811 return parentUser != null ? parentUser.id : userHandle; 8812 } finally { 8813 mInjector.binderRestoreCallingIdentity(ident); 8814 } 8815 } 8816 getCredentialOwner(int userHandle, boolean parent)8817 private int getCredentialOwner(int userHandle, boolean parent) { 8818 final long ident = mInjector.binderClearCallingIdentity(); 8819 try { 8820 if (parent) { 8821 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 8822 if (parentProfile != null) { 8823 userHandle = parentProfile.id; 8824 } 8825 } 8826 return mUserManager.getCredentialOwnerProfile(userHandle); 8827 } finally { 8828 mInjector.binderRestoreCallingIdentity(ident); 8829 } 8830 } 8831 isManagedProfile(int userHandle)8832 private boolean isManagedProfile(int userHandle) { 8833 final UserInfo user = getUserInfo(userHandle); 8834 return user != null && user.isManagedProfile(); 8835 } 8836 enableIfNecessary(String packageName, int userId)8837 private void enableIfNecessary(String packageName, int userId) { 8838 try { 8839 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 8840 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId); 8841 if (ai.enabledSetting 8842 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 8843 mIPackageManager.setApplicationEnabledSetting(packageName, 8844 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 8845 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 8846 } 8847 } catch (RemoteException e) { 8848 } 8849 } 8850 8851 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)8852 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 8853 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return; 8854 8855 synchronized (getLockObject()) { 8856 pw.println("Current Device Policy Manager state:"); 8857 8858 mOwners.dump(" ", pw); 8859 mDeviceAdminServiceController.dump(" ", pw); 8860 int userCount = mUserData.size(); 8861 for (int u = 0; u < userCount; u++) { 8862 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 8863 pw.println(); 8864 pw.println(" Enabled Device Admins (User " + policy.mUserHandle 8865 + ", provisioningState: " + policy.mUserProvisioningState + "):"); 8866 final int N = policy.mAdminList.size(); 8867 for (int i=0; i<N; i++) { 8868 ActiveAdmin ap = policy.mAdminList.get(i); 8869 if (ap != null) { 8870 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 8871 pw.println(":"); 8872 ap.dump(" ", pw); 8873 } 8874 } 8875 if (!policy.mRemovingAdmins.isEmpty()) { 8876 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 8877 + policy.mRemovingAdmins); 8878 } 8879 8880 pw.println(" "); 8881 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 8882 } 8883 pw.println(); 8884 mConstants.dump(" ", pw); 8885 pw.println(); 8886 mStatLogger.dump(pw, " "); 8887 pw.println(); 8888 pw.println(" Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 8889 pw.println(); 8890 mPolicyCache.dump(" ", pw); 8891 } 8892 } 8893 getEncryptionStatusName(int encryptionStatus)8894 private String getEncryptionStatusName(int encryptionStatus) { 8895 switch (encryptionStatus) { 8896 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 8897 return "inactive"; 8898 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 8899 return "block default key"; 8900 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 8901 return "block"; 8902 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 8903 return "per-user"; 8904 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 8905 return "unsupported"; 8906 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 8907 return "activating"; 8908 default: 8909 return "unknown"; 8910 } 8911 } 8912 8913 @Override addPersistentPreferredActivity(ComponentName who, IntentFilter filter, ComponentName activity)8914 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 8915 ComponentName activity) { 8916 Preconditions.checkNotNull(who, "ComponentName is null"); 8917 final int userHandle = UserHandle.getCallingUserId(); 8918 synchronized (getLockObject()) { 8919 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8920 8921 long id = mInjector.binderClearCallingIdentity(); 8922 try { 8923 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 8924 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 8925 } catch (RemoteException re) { 8926 // Shouldn't happen 8927 } finally { 8928 mInjector.binderRestoreCallingIdentity(id); 8929 } 8930 } 8931 final String activityPackage = 8932 (activity != null ? activity.getPackageName() : null); 8933 DevicePolicyEventLogger 8934 .createEvent(DevicePolicyEnums.ADD_PERSISTENT_PREFERRED_ACTIVITY) 8935 .setAdmin(who) 8936 .setStrings(activityPackage, getIntentFilterActions(filter)) 8937 .write(); 8938 } 8939 8940 @Override clearPackagePersistentPreferredActivities(ComponentName who, String packageName)8941 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 8942 Preconditions.checkNotNull(who, "ComponentName is null"); 8943 final int userHandle = UserHandle.getCallingUserId(); 8944 synchronized (getLockObject()) { 8945 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8946 8947 long id = mInjector.binderClearCallingIdentity(); 8948 try { 8949 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 8950 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 8951 } catch (RemoteException re) { 8952 // Shouldn't happen 8953 } finally { 8954 mInjector.binderRestoreCallingIdentity(id); 8955 } 8956 } 8957 } 8958 8959 @Override setDefaultSmsApplication(ComponentName admin, String packageName)8960 public void setDefaultSmsApplication(ComponentName admin, String packageName) { 8961 Preconditions.checkNotNull(admin, "ComponentName is null"); 8962 enforceDeviceOwner(admin); 8963 mInjector.binderWithCleanCallingIdentity(() -> 8964 SmsApplication.setDefaultApplication(packageName, mContext)); 8965 } 8966 8967 @Override setApplicationRestrictionsManagingPackage(ComponentName admin, String packageName)8968 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 8969 String packageName) { 8970 try { 8971 setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS); 8972 } catch (IllegalArgumentException e) { 8973 return false; 8974 } 8975 return true; 8976 } 8977 8978 @Override getApplicationRestrictionsManagingPackage(ComponentName admin)8979 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 8980 final List<String> delegatePackages = getDelegatePackages(admin, 8981 DELEGATION_APP_RESTRICTIONS); 8982 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 8983 } 8984 8985 @Override isCallerApplicationRestrictionsManagingPackage(String callerPackage)8986 public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) { 8987 return isCallerDelegate(callerPackage, mInjector.binderGetCallingUid(), 8988 DELEGATION_APP_RESTRICTIONS); 8989 } 8990 8991 @Override setApplicationRestrictions(ComponentName who, String callerPackage, String packageName, Bundle settings)8992 public void setApplicationRestrictions(ComponentName who, String callerPackage, 8993 String packageName, Bundle settings) { 8994 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8995 DELEGATION_APP_RESTRICTIONS); 8996 8997 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 8998 final long id = mInjector.binderClearCallingIdentity(); 8999 try { 9000 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 9001 final boolean isDelegate = (who == null); 9002 DevicePolicyEventLogger 9003 .createEvent(DevicePolicyEnums.SET_APPLICATION_RESTRICTIONS) 9004 .setAdmin(callerPackage) 9005 .setBoolean(isDelegate) 9006 .setStrings(packageName) 9007 .write(); 9008 } finally { 9009 mInjector.binderRestoreCallingIdentity(id); 9010 } 9011 } 9012 9013 @Override setTrustAgentConfiguration(ComponentName admin, ComponentName agent, PersistableBundle args, boolean parent)9014 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 9015 PersistableBundle args, boolean parent) { 9016 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 9017 return; 9018 } 9019 Preconditions.checkNotNull(admin, "admin is null"); 9020 Preconditions.checkNotNull(agent, "agent is null"); 9021 final int userHandle = UserHandle.getCallingUserId(); 9022 synchronized (getLockObject()) { 9023 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 9024 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 9025 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 9026 saveSettingsLocked(userHandle); 9027 } 9028 } 9029 9030 @Override getTrustAgentConfiguration(ComponentName admin, ComponentName agent, int userHandle, boolean parent)9031 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 9032 ComponentName agent, int userHandle, boolean parent) { 9033 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 9034 return null; 9035 } 9036 Preconditions.checkNotNull(agent, "agent null"); 9037 enforceFullCrossUsersPermission(userHandle); 9038 9039 synchronized (getLockObject()) { 9040 final String componentName = agent.flattenToString(); 9041 if (admin != null) { 9042 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 9043 if (ap == null) return null; 9044 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 9045 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 9046 List<PersistableBundle> result = new ArrayList<>(); 9047 result.add(trustAgentInfo.options); 9048 return result; 9049 } 9050 9051 // Return strictest policy for this user and profiles that are visible from this user. 9052 List<PersistableBundle> result = null; 9053 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 9054 // of the options. If any admin doesn't have options, discard options for the rest 9055 // and return null. 9056 List<ActiveAdmin> admins = 9057 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 9058 boolean allAdminsHaveOptions = true; 9059 final int N = admins.size(); 9060 for (int i = 0; i < N; i++) { 9061 final ActiveAdmin active = admins.get(i); 9062 9063 final boolean disablesTrust = (active.disabledKeyguardFeatures 9064 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 9065 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 9066 if (info != null && info.options != null && !info.options.isEmpty()) { 9067 if (disablesTrust) { 9068 if (result == null) { 9069 result = new ArrayList<>(); 9070 } 9071 result.add(info.options); 9072 } else { 9073 Log.w(LOG_TAG, "Ignoring admin " + active.info 9074 + " because it has trust options but doesn't declare " 9075 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 9076 } 9077 } else if (disablesTrust) { 9078 allAdminsHaveOptions = false; 9079 break; 9080 } 9081 } 9082 return allAdminsHaveOptions ? result : null; 9083 } 9084 } 9085 9086 @Override setRestrictionsProvider(ComponentName who, ComponentName permissionProvider)9087 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 9088 Preconditions.checkNotNull(who, "ComponentName is null"); 9089 synchronized (getLockObject()) { 9090 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9091 9092 int userHandle = UserHandle.getCallingUserId(); 9093 DevicePolicyData userData = getUserData(userHandle); 9094 userData.mRestrictionsProvider = permissionProvider; 9095 saveSettingsLocked(userHandle); 9096 } 9097 } 9098 9099 @Override getRestrictionsProvider(int userHandle)9100 public ComponentName getRestrictionsProvider(int userHandle) { 9101 synchronized (getLockObject()) { 9102 if (!isCallerWithSystemUid()) { 9103 throw new SecurityException("Only the system can query the permission provider"); 9104 } 9105 DevicePolicyData userData = getUserData(userHandle); 9106 return userData != null ? userData.mRestrictionsProvider : null; 9107 } 9108 } 9109 9110 @Override addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags)9111 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 9112 Preconditions.checkNotNull(who, "ComponentName is null"); 9113 int callingUserId = UserHandle.getCallingUserId(); 9114 synchronized (getLockObject()) { 9115 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9116 9117 long id = mInjector.binderClearCallingIdentity(); 9118 try { 9119 UserInfo parent = mUserManager.getProfileParent(callingUserId); 9120 if (parent == null) { 9121 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 9122 + "parent"); 9123 return; 9124 } 9125 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 9126 mIPackageManager.addCrossProfileIntentFilter( 9127 filter, who.getPackageName(), callingUserId, parent.id, 0); 9128 } 9129 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 9130 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 9131 parent.id, callingUserId, 0); 9132 } 9133 } catch (RemoteException re) { 9134 // Shouldn't happen 9135 } finally { 9136 mInjector.binderRestoreCallingIdentity(id); 9137 } 9138 } 9139 DevicePolicyEventLogger 9140 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_INTENT_FILTER) 9141 .setAdmin(who) 9142 .setStrings(getIntentFilterActions(filter)) 9143 .setInt(flags) 9144 .write(); 9145 } 9146 getIntentFilterActions(IntentFilter filter)9147 private static String[] getIntentFilterActions(IntentFilter filter) { 9148 if (filter == null) { 9149 return null; 9150 } 9151 final int actionsCount = filter.countActions(); 9152 final String[] actions = new String[actionsCount]; 9153 for (int i = 0; i < actionsCount; i++) { 9154 actions[i] = filter.getAction(i); 9155 } 9156 return actions; 9157 } 9158 9159 @Override clearCrossProfileIntentFilters(ComponentName who)9160 public void clearCrossProfileIntentFilters(ComponentName who) { 9161 Preconditions.checkNotNull(who, "ComponentName is null"); 9162 int callingUserId = UserHandle.getCallingUserId(); 9163 synchronized (getLockObject()) { 9164 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9165 long id = mInjector.binderClearCallingIdentity(); 9166 try { 9167 UserInfo parent = mUserManager.getProfileParent(callingUserId); 9168 if (parent == null) { 9169 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 9170 + "parent"); 9171 return; 9172 } 9173 // Removing those that go from the managed profile to the parent. 9174 mIPackageManager.clearCrossProfileIntentFilters( 9175 callingUserId, who.getPackageName()); 9176 // And those that go from the parent to the managed profile. 9177 // If we want to support multiple managed profiles, we will have to only remove 9178 // those that have callingUserId as their target. 9179 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 9180 } catch (RemoteException re) { 9181 // Shouldn't happen 9182 } finally { 9183 mInjector.binderRestoreCallingIdentity(id); 9184 } 9185 } 9186 } 9187 9188 /** 9189 * @return true if all packages in enabledPackages are either in the list 9190 * permittedList or are a system app. 9191 */ checkPackagesInPermittedListOrSystem(List<String> enabledPackages, List<String> permittedList, int userIdToCheck)9192 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 9193 List<String> permittedList, int userIdToCheck) { 9194 long id = mInjector.binderClearCallingIdentity(); 9195 try { 9196 // If we have an enabled packages list for a managed profile the packages 9197 // we should check are installed for the parent user. 9198 UserInfo user = getUserInfo(userIdToCheck); 9199 if (user.isManagedProfile()) { 9200 userIdToCheck = user.profileGroupId; 9201 } 9202 9203 for (String enabledPackage : enabledPackages) { 9204 boolean systemService = false; 9205 try { 9206 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 9207 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 9208 userIdToCheck); 9209 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9210 } catch (RemoteException e) { 9211 Log.i(LOG_TAG, "Can't talk to package managed", e); 9212 } 9213 if (!systemService && !permittedList.contains(enabledPackage)) { 9214 return false; 9215 } 9216 } 9217 } finally { 9218 mInjector.binderRestoreCallingIdentity(id); 9219 } 9220 return true; 9221 } 9222 getAccessibilityManagerForUser(int userId)9223 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 9224 // Not using AccessibilityManager.getInstance because that guesses 9225 // at the user you require based on callingUid and caches for a given 9226 // process. 9227 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 9228 IAccessibilityManager service = iBinder == null 9229 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 9230 return new AccessibilityManager(mContext, service, userId); 9231 } 9232 9233 @Override setPermittedAccessibilityServices(ComponentName who, List packageList)9234 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 9235 if (!mHasFeature) { 9236 return false; 9237 } 9238 Preconditions.checkNotNull(who, "ComponentName is null"); 9239 9240 if (packageList != null) { 9241 int userId = UserHandle.getCallingUserId(); 9242 List<AccessibilityServiceInfo> enabledServices = null; 9243 long id = mInjector.binderClearCallingIdentity(); 9244 try { 9245 UserInfo user = getUserInfo(userId); 9246 if (user.isManagedProfile()) { 9247 userId = user.profileGroupId; 9248 } 9249 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 9250 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 9251 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 9252 } finally { 9253 mInjector.binderRestoreCallingIdentity(id); 9254 } 9255 9256 if (enabledServices != null) { 9257 List<String> enabledPackages = new ArrayList<String>(); 9258 for (AccessibilityServiceInfo service : enabledServices) { 9259 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 9260 } 9261 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 9262 userId)) { 9263 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 9264 + "because it contains already enabled accesibility services."); 9265 return false; 9266 } 9267 } 9268 } 9269 9270 synchronized (getLockObject()) { 9271 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9272 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9273 admin.permittedAccessiblityServices = packageList; 9274 saveSettingsLocked(UserHandle.getCallingUserId()); 9275 } 9276 final String[] packageArray = 9277 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null; 9278 DevicePolicyEventLogger 9279 .createEvent(DevicePolicyEnums.SET_PERMITTED_ACCESSIBILITY_SERVICES) 9280 .setAdmin(who) 9281 .setStrings(packageArray) 9282 .write(); 9283 return true; 9284 } 9285 9286 @Override getPermittedAccessibilityServices(ComponentName who)9287 public List getPermittedAccessibilityServices(ComponentName who) { 9288 if (!mHasFeature) { 9289 return null; 9290 } 9291 Preconditions.checkNotNull(who, "ComponentName is null"); 9292 9293 synchronized (getLockObject()) { 9294 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9295 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9296 return admin.permittedAccessiblityServices; 9297 } 9298 } 9299 9300 @Override getPermittedAccessibilityServicesForUser(int userId)9301 public List getPermittedAccessibilityServicesForUser(int userId) { 9302 if (!mHasFeature) { 9303 return null; 9304 } 9305 enforceManageUsers(); 9306 synchronized (getLockObject()) { 9307 List<String> result = null; 9308 // If we have multiple profiles we return the intersection of the 9309 // permitted lists. This can happen in cases where we have a device 9310 // and profile owner. 9311 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 9312 for (int profileId : profileIds) { 9313 // Just loop though all admins, only device or profiles 9314 // owners can have permitted lists set. 9315 DevicePolicyData policy = getUserDataUnchecked(profileId); 9316 final int N = policy.mAdminList.size(); 9317 for (int j = 0; j < N; j++) { 9318 ActiveAdmin admin = policy.mAdminList.get(j); 9319 List<String> fromAdmin = admin.permittedAccessiblityServices; 9320 if (fromAdmin != null) { 9321 if (result == null) { 9322 result = new ArrayList<>(fromAdmin); 9323 } else { 9324 result.retainAll(fromAdmin); 9325 } 9326 } 9327 } 9328 } 9329 9330 // If we have a permitted list add all system accessibility services. 9331 if (result != null) { 9332 long id = mInjector.binderClearCallingIdentity(); 9333 try { 9334 UserInfo user = getUserInfo(userId); 9335 if (user.isManagedProfile()) { 9336 userId = user.profileGroupId; 9337 } 9338 AccessibilityManager accessibilityManager = 9339 getAccessibilityManagerForUser(userId); 9340 List<AccessibilityServiceInfo> installedServices = 9341 accessibilityManager.getInstalledAccessibilityServiceList(); 9342 9343 if (installedServices != null) { 9344 for (AccessibilityServiceInfo service : installedServices) { 9345 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 9346 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 9347 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9348 result.add(serviceInfo.packageName); 9349 } 9350 } 9351 } 9352 } finally { 9353 mInjector.binderRestoreCallingIdentity(id); 9354 } 9355 } 9356 9357 return result; 9358 } 9359 } 9360 9361 @Override isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, int userHandle)9362 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 9363 int userHandle) { 9364 if (!mHasFeature) { 9365 return true; 9366 } 9367 Preconditions.checkNotNull(who, "ComponentName is null"); 9368 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 9369 if (!isCallerWithSystemUid()){ 9370 throw new SecurityException( 9371 "Only the system can query if an accessibility service is disabled by admin"); 9372 } 9373 synchronized (getLockObject()) { 9374 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 9375 if (admin == null) { 9376 return false; 9377 } 9378 if (admin.permittedAccessiblityServices == null) { 9379 return true; 9380 } 9381 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 9382 admin.permittedAccessiblityServices, userHandle); 9383 } 9384 } 9385 checkCallerIsCurrentUserOrProfile()9386 private boolean checkCallerIsCurrentUserOrProfile() { 9387 final int callingUserId = UserHandle.getCallingUserId(); 9388 final long token = mInjector.binderClearCallingIdentity(); 9389 try { 9390 UserInfo currentUser; 9391 UserInfo callingUser = getUserInfo(callingUserId); 9392 try { 9393 currentUser = mInjector.getIActivityManager().getCurrentUser(); 9394 } catch (RemoteException e) { 9395 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 9396 return false; 9397 } 9398 9399 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 9400 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 9401 + "of a user that isn't the foreground user."); 9402 return false; 9403 } 9404 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 9405 Slog.e(LOG_TAG, "Cannot set permitted input methods " 9406 + "of a user that isn't the foreground user."); 9407 return false; 9408 } 9409 } finally { 9410 mInjector.binderRestoreCallingIdentity(token); 9411 } 9412 return true; 9413 } 9414 9415 @Override setPermittedInputMethods(ComponentName who, List packageList)9416 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 9417 if (!mHasFeature) { 9418 return false; 9419 } 9420 Preconditions.checkNotNull(who, "ComponentName is null"); 9421 9422 // TODO When InputMethodManager supports per user calls remove this restriction. 9423 if (!InputMethodSystemProperty.PER_PROFILE_IME_ENABLED 9424 && !checkCallerIsCurrentUserOrProfile()) { 9425 return false; 9426 } 9427 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9428 if (packageList != null) { 9429 List<InputMethodInfo> enabledImes = InputMethodManagerInternal.get() 9430 .getEnabledInputMethodListAsUser(callingUserId); 9431 if (enabledImes != null) { 9432 List<String> enabledPackages = new ArrayList<String>(); 9433 for (InputMethodInfo ime : enabledImes) { 9434 enabledPackages.add(ime.getPackageName()); 9435 } 9436 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 9437 callingUserId)) { 9438 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 9439 + "because it contains already enabled input method."); 9440 return false; 9441 } 9442 } 9443 } 9444 9445 synchronized (getLockObject()) { 9446 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9447 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9448 admin.permittedInputMethods = packageList; 9449 saveSettingsLocked(callingUserId); 9450 } 9451 final String[] packageArray = 9452 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null; 9453 DevicePolicyEventLogger 9454 .createEvent(DevicePolicyEnums.SET_PERMITTED_INPUT_METHODS) 9455 .setAdmin(who) 9456 .setStrings(packageArray) 9457 .write(); 9458 return true; 9459 } 9460 9461 @Override getPermittedInputMethods(ComponentName who)9462 public List getPermittedInputMethods(ComponentName who) { 9463 if (!mHasFeature) { 9464 return null; 9465 } 9466 Preconditions.checkNotNull(who, "ComponentName is null"); 9467 9468 synchronized (getLockObject()) { 9469 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9470 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9471 return admin.permittedInputMethods; 9472 } 9473 } 9474 9475 @Override getPermittedInputMethodsForCurrentUser()9476 public List getPermittedInputMethodsForCurrentUser() { 9477 enforceManageUsers(); 9478 9479 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9480 synchronized (getLockObject()) { 9481 List<String> result = null; 9482 // If we have multiple profiles we return the intersection of the 9483 // permitted lists. This can happen in cases where we have a device 9484 // and profile owner. 9485 int[] profileIds = InputMethodSystemProperty.PER_PROFILE_IME_ENABLED 9486 ? new int[]{callingUserId} 9487 : mUserManager.getProfileIdsWithDisabled(callingUserId); 9488 for (int profileId : profileIds) { 9489 // Just loop though all admins, only device or profiles 9490 // owners can have permitted lists set. 9491 DevicePolicyData policy = getUserDataUnchecked(profileId); 9492 final int N = policy.mAdminList.size(); 9493 for (int j = 0; j < N; j++) { 9494 ActiveAdmin admin = policy.mAdminList.get(j); 9495 List<String> fromAdmin = admin.permittedInputMethods; 9496 if (fromAdmin != null) { 9497 if (result == null) { 9498 result = new ArrayList<String>(fromAdmin); 9499 } else { 9500 result.retainAll(fromAdmin); 9501 } 9502 } 9503 } 9504 } 9505 9506 // If we have a permitted list add all system input methods. 9507 if (result != null) { 9508 List<InputMethodInfo> imes = 9509 InputMethodManagerInternal.get().getInputMethodListAsUser(callingUserId); 9510 if (imes != null) { 9511 for (InputMethodInfo ime : imes) { 9512 ServiceInfo serviceInfo = ime.getServiceInfo(); 9513 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 9514 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9515 result.add(serviceInfo.packageName); 9516 } 9517 } 9518 } 9519 } 9520 return result; 9521 } 9522 } 9523 9524 @Override isInputMethodPermittedByAdmin(ComponentName who, String packageName, int userHandle)9525 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 9526 int userHandle) { 9527 if (!mHasFeature) { 9528 return true; 9529 } 9530 Preconditions.checkNotNull(who, "ComponentName is null"); 9531 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 9532 if (!isCallerWithSystemUid()) { 9533 throw new SecurityException( 9534 "Only the system can query if an input method is disabled by admin"); 9535 } 9536 synchronized (getLockObject()) { 9537 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 9538 if (admin == null) { 9539 return false; 9540 } 9541 if (admin.permittedInputMethods == null) { 9542 return true; 9543 } 9544 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 9545 admin.permittedInputMethods, userHandle); 9546 } 9547 } 9548 9549 @Override setPermittedCrossProfileNotificationListeners( ComponentName who, List<String> packageList)9550 public boolean setPermittedCrossProfileNotificationListeners( 9551 ComponentName who, List<String> packageList) { 9552 if (!mHasFeature) { 9553 return false; 9554 } 9555 Preconditions.checkNotNull(who, "ComponentName is null"); 9556 9557 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9558 if (!isManagedProfile(callingUserId)) { 9559 return false; 9560 } 9561 9562 synchronized (getLockObject()) { 9563 ActiveAdmin admin = getActiveAdminForCallerLocked( 9564 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9565 admin.permittedNotificationListeners = packageList; 9566 saveSettingsLocked(callingUserId); 9567 } 9568 return true; 9569 } 9570 9571 @Override getPermittedCrossProfileNotificationListeners(ComponentName who)9572 public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) { 9573 if (!mHasFeature) { 9574 return null; 9575 } 9576 Preconditions.checkNotNull(who, "ComponentName is null"); 9577 9578 synchronized (getLockObject()) { 9579 ActiveAdmin admin = getActiveAdminForCallerLocked( 9580 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9581 return admin.permittedNotificationListeners; 9582 } 9583 } 9584 9585 @Override isNotificationListenerServicePermitted(String packageName, int userId)9586 public boolean isNotificationListenerServicePermitted(String packageName, int userId) { 9587 if (!mHasFeature) { 9588 return true; 9589 } 9590 9591 Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty"); 9592 if (!isCallerWithSystemUid()) { 9593 throw new SecurityException( 9594 "Only the system can query if a notification listener service is permitted"); 9595 } 9596 synchronized (getLockObject()) { 9597 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 9598 if (profileOwner == null || profileOwner.permittedNotificationListeners == null) { 9599 return true; 9600 } 9601 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName), 9602 profileOwner.permittedNotificationListeners, userId); 9603 9604 } 9605 } 9606 maybeSendAdminEnabledBroadcastLocked(int userHandle)9607 private void maybeSendAdminEnabledBroadcastLocked(int userHandle) { 9608 DevicePolicyData policyData = getUserData(userHandle); 9609 if (policyData.mAdminBroadcastPending) { 9610 // Send the initialization data to profile owner and delete the data 9611 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 9612 boolean clearInitBundle = true; 9613 if (admin != null) { 9614 PersistableBundle initBundle = policyData.mInitBundle; 9615 clearInitBundle = sendAdminCommandLocked(admin, 9616 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 9617 initBundle == null ? null : new Bundle(initBundle), 9618 null /* result receiver */, 9619 true /* send in foreground */); 9620 } 9621 if (clearInitBundle) { 9622 // If there's no admin or we've successfully called the admin, clear the init bundle 9623 // otherwise, keep it around 9624 policyData.mInitBundle = null; 9625 policyData.mAdminBroadcastPending = false; 9626 saveSettingsLocked(userHandle); 9627 } 9628 } 9629 } 9630 9631 @Override createAndManageUser(ComponentName admin, String name, ComponentName profileOwner, PersistableBundle adminExtras, int flags)9632 public UserHandle createAndManageUser(ComponentName admin, String name, 9633 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 9634 Preconditions.checkNotNull(admin, "admin is null"); 9635 Preconditions.checkNotNull(profileOwner, "profileOwner is null"); 9636 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 9637 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 9638 + admin + " are not in the same package"); 9639 } 9640 // Only allow the system user to use this method 9641 if (!mInjector.binderGetCallingUserHandle().isSystem()) { 9642 throw new SecurityException("createAndManageUser was called from non-system user"); 9643 } 9644 final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0; 9645 final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0 9646 && UserManager.isDeviceInDemoMode(mContext); 9647 final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0; 9648 final int targetSdkVersion; 9649 9650 // Create user. 9651 UserHandle user = null; 9652 synchronized (getLockObject()) { 9653 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9654 9655 final int callingUid = mInjector.binderGetCallingUid(); 9656 final long id = mInjector.binderClearCallingIdentity(); 9657 try { 9658 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion( 9659 callingUid); 9660 9661 // Return detail error code for checks inside 9662 // UserManagerService.createUserInternalUnchecked. 9663 DeviceStorageMonitorInternal deviceStorageMonitorInternal = 9664 LocalServices.getService(DeviceStorageMonitorInternal.class); 9665 if (deviceStorageMonitorInternal.isMemoryLow()) { 9666 if (targetSdkVersion >= Build.VERSION_CODES.P) { 9667 throw new ServiceSpecificException( 9668 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage"); 9669 } else { 9670 return null; 9671 } 9672 } 9673 if (!mUserManager.canAddMoreUsers()) { 9674 if (targetSdkVersion >= Build.VERSION_CODES.P) { 9675 throw new ServiceSpecificException( 9676 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached"); 9677 } else { 9678 return null; 9679 } 9680 } 9681 9682 int userInfoFlags = 0; 9683 if (ephemeral) { 9684 userInfoFlags |= UserInfo.FLAG_EPHEMERAL; 9685 } 9686 if (demo) { 9687 userInfoFlags |= UserInfo.FLAG_DEMO; 9688 } 9689 String[] disallowedPackages = null; 9690 if (!leaveAllSystemAppsEnabled) { 9691 disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin, 9692 UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray( 9693 new String[0]); 9694 } 9695 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 9696 userInfoFlags, disallowedPackages); 9697 if (userInfo != null) { 9698 user = userInfo.getUserHandle(); 9699 } 9700 } finally { 9701 mInjector.binderRestoreCallingIdentity(id); 9702 } 9703 } 9704 if (user == null) { 9705 if (targetSdkVersion >= Build.VERSION_CODES.P) { 9706 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN, 9707 "failed to create user"); 9708 } else { 9709 return null; 9710 } 9711 } 9712 9713 final int userHandle = user.getIdentifier(); 9714 final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED) 9715 .putExtra(Intent.EXTRA_USER_HANDLE, userHandle) 9716 .putExtra( 9717 DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED, 9718 leaveAllSystemAppsEnabled) 9719 .setPackage(getManagedProvisioningPackage(mContext)) 9720 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9721 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM); 9722 9723 final long id = mInjector.binderClearCallingIdentity(); 9724 try { 9725 final String adminPkg = admin.getPackageName(); 9726 try { 9727 // Install the profile owner if not present. 9728 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) { 9729 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle, 9730 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 9731 PackageManager.INSTALL_REASON_POLICY, null); 9732 } 9733 } catch (RemoteException e) { 9734 // Does not happen, same process 9735 } 9736 9737 // Set admin. 9738 setActiveAdmin(profileOwner, true, userHandle); 9739 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier()); 9740 setProfileOwner(profileOwner, ownerName, userHandle); 9741 9742 synchronized (getLockObject()) { 9743 DevicePolicyData policyData = getUserData(userHandle); 9744 policyData.mInitBundle = adminExtras; 9745 policyData.mAdminBroadcastPending = true; 9746 saveSettingsLocked(userHandle); 9747 } 9748 9749 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 9750 Settings.Secure.putIntForUser(mContext.getContentResolver(), 9751 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 9752 } 9753 9754 return user; 9755 } catch (Throwable re) { 9756 mUserManager.removeUser(userHandle); 9757 if (targetSdkVersion >= Build.VERSION_CODES.P) { 9758 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN, 9759 re.getMessage()); 9760 } else { 9761 return null; 9762 } 9763 } finally { 9764 mInjector.binderRestoreCallingIdentity(id); 9765 } 9766 } 9767 9768 @Override removeUser(ComponentName who, UserHandle userHandle)9769 public boolean removeUser(ComponentName who, UserHandle userHandle) { 9770 Preconditions.checkNotNull(who, "ComponentName is null"); 9771 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 9772 enforceDeviceOwner(who); 9773 9774 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9775 final long id = mInjector.binderClearCallingIdentity(); 9776 try { 9777 String restriction = isManagedProfile(userHandle.getIdentifier()) 9778 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 9779 : UserManager.DISALLOW_REMOVE_USER; 9780 if (isAdminAffectedByRestriction(who, restriction, callingUserId)) { 9781 Log.w(LOG_TAG, "The device owner cannot remove a user because " 9782 + restriction + " is enabled, and was not set by the device owner"); 9783 return false; 9784 } 9785 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 9786 } finally { 9787 mInjector.binderRestoreCallingIdentity(id); 9788 } 9789 } 9790 isAdminAffectedByRestriction( ComponentName admin, String userRestriction, int userId)9791 private boolean isAdminAffectedByRestriction( 9792 ComponentName admin, String userRestriction, int userId) { 9793 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 9794 case UserManager.RESTRICTION_NOT_SET: 9795 return false; 9796 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 9797 return !isDeviceOwner(admin, userId); 9798 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 9799 return !isProfileOwner(admin, userId); 9800 default: 9801 return true; 9802 } 9803 } 9804 9805 @Override switchUser(ComponentName who, UserHandle userHandle)9806 public boolean switchUser(ComponentName who, UserHandle userHandle) { 9807 Preconditions.checkNotNull(who, "ComponentName is null"); 9808 9809 synchronized (getLockObject()) { 9810 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9811 9812 long id = mInjector.binderClearCallingIdentity(); 9813 try { 9814 int userId = UserHandle.USER_SYSTEM; 9815 if (userHandle != null) { 9816 userId = userHandle.getIdentifier(); 9817 } 9818 return mInjector.getIActivityManager().switchUser(userId); 9819 } catch (RemoteException e) { 9820 Log.e(LOG_TAG, "Couldn't switch user", e); 9821 return false; 9822 } finally { 9823 mInjector.binderRestoreCallingIdentity(id); 9824 } 9825 } 9826 } 9827 9828 @Override startUserInBackground(ComponentName who, UserHandle userHandle)9829 public int startUserInBackground(ComponentName who, UserHandle userHandle) { 9830 Preconditions.checkNotNull(who, "ComponentName is null"); 9831 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 9832 enforceDeviceOwner(who); 9833 9834 final int userId = userHandle.getIdentifier(); 9835 if (isManagedProfile(userId)) { 9836 Log.w(LOG_TAG, "Managed profile cannot be started in background"); 9837 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9838 } 9839 9840 final long id = mInjector.binderClearCallingIdentity(); 9841 try { 9842 if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) { 9843 Log.w(LOG_TAG, "Cannot start more users in background"); 9844 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS; 9845 } 9846 9847 if (mInjector.getIActivityManager().startUserInBackground(userId)) { 9848 return UserManager.USER_OPERATION_SUCCESS; 9849 } else { 9850 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9851 } 9852 } catch (RemoteException e) { 9853 // Same process, should not happen. 9854 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9855 } finally { 9856 mInjector.binderRestoreCallingIdentity(id); 9857 } 9858 } 9859 9860 @Override stopUser(ComponentName who, UserHandle userHandle)9861 public int stopUser(ComponentName who, UserHandle userHandle) { 9862 Preconditions.checkNotNull(who, "ComponentName is null"); 9863 Preconditions.checkNotNull(userHandle, "UserHandle is null"); 9864 enforceDeviceOwner(who); 9865 9866 final int userId = userHandle.getIdentifier(); 9867 if (isManagedProfile(userId)) { 9868 Log.w(LOG_TAG, "Managed profile cannot be stopped"); 9869 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9870 } 9871 9872 return stopUserUnchecked(userId); 9873 } 9874 9875 @Override logoutUser(ComponentName who)9876 public int logoutUser(ComponentName who) { 9877 Preconditions.checkNotNull(who, "ComponentName is null"); 9878 9879 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9880 synchronized (getLockObject()) { 9881 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9882 if (!isUserAffiliatedWithDeviceLocked(callingUserId)) { 9883 throw new SecurityException("Admin " + who + 9884 " is neither the device owner or affiliated user's profile owner."); 9885 } 9886 } 9887 9888 if (isManagedProfile(callingUserId)) { 9889 Log.w(LOG_TAG, "Managed profile cannot be logout"); 9890 return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE; 9891 } 9892 9893 final long id = mInjector.binderClearCallingIdentity(); 9894 try { 9895 if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) { 9896 Log.w(LOG_TAG, "Failed to switch to primary user"); 9897 // This should never happen as target user is UserHandle.USER_SYSTEM 9898 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9899 } 9900 } catch (RemoteException e) { 9901 // Same process, should not happen. 9902 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9903 } finally { 9904 mInjector.binderRestoreCallingIdentity(id); 9905 } 9906 9907 return stopUserUnchecked(callingUserId); 9908 } 9909 stopUserUnchecked(int userId)9910 private int stopUserUnchecked(int userId) { 9911 final long id = mInjector.binderClearCallingIdentity(); 9912 try { 9913 switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) { 9914 case ActivityManager.USER_OP_SUCCESS: 9915 return UserManager.USER_OPERATION_SUCCESS; 9916 case ActivityManager.USER_OP_IS_CURRENT: 9917 return UserManager.USER_OPERATION_ERROR_CURRENT_USER; 9918 default: 9919 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9920 } 9921 } catch (RemoteException e) { 9922 // Same process, should not happen. 9923 return UserManager.USER_OPERATION_ERROR_UNKNOWN; 9924 } finally { 9925 mInjector.binderRestoreCallingIdentity(id); 9926 } 9927 } 9928 9929 @Override getSecondaryUsers(ComponentName who)9930 public List<UserHandle> getSecondaryUsers(ComponentName who) { 9931 Preconditions.checkNotNull(who, "ComponentName is null"); 9932 enforceDeviceOwner(who); 9933 9934 final long id = mInjector.binderClearCallingIdentity(); 9935 try { 9936 final List<UserInfo> userInfos = mInjector.getUserManager().getUsers(true 9937 /*excludeDying*/); 9938 final List<UserHandle> userHandles = new ArrayList<>(); 9939 for (UserInfo userInfo : userInfos) { 9940 UserHandle userHandle = userInfo.getUserHandle(); 9941 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) { 9942 userHandles.add(userInfo.getUserHandle()); 9943 } 9944 } 9945 return userHandles; 9946 } finally { 9947 mInjector.binderRestoreCallingIdentity(id); 9948 } 9949 } 9950 9951 @Override isEphemeralUser(ComponentName who)9952 public boolean isEphemeralUser(ComponentName who) { 9953 Preconditions.checkNotNull(who, "ComponentName is null"); 9954 enforceProfileOrDeviceOwner(who); 9955 9956 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9957 final long id = mInjector.binderClearCallingIdentity(); 9958 try { 9959 return mInjector.getUserManager().isUserEphemeral(callingUserId); 9960 } finally { 9961 mInjector.binderRestoreCallingIdentity(id); 9962 } 9963 } 9964 9965 @Override getApplicationRestrictions(ComponentName who, String callerPackage, String packageName)9966 public Bundle getApplicationRestrictions(ComponentName who, String callerPackage, 9967 String packageName) { 9968 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9969 DELEGATION_APP_RESTRICTIONS); 9970 9971 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 9972 final long id = mInjector.binderClearCallingIdentity(); 9973 try { 9974 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 9975 // if no restrictions were saved, mUserManager.getApplicationRestrictions 9976 // returns null, but DPM method should return an empty Bundle as per JavaDoc 9977 return bundle != null ? bundle : Bundle.EMPTY; 9978 } finally { 9979 mInjector.binderRestoreCallingIdentity(id); 9980 } 9981 } 9982 9983 @Override setPackagesSuspended(ComponentName who, String callerPackage, String[] packageNames, boolean suspended)9984 public String[] setPackagesSuspended(ComponentName who, String callerPackage, 9985 String[] packageNames, boolean suspended) { 9986 int callingUserId = UserHandle.getCallingUserId(); 9987 String[] result = null; 9988 synchronized (getLockObject()) { 9989 // Ensure the caller is a DO/PO or a package access delegate. 9990 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9991 DELEGATION_PACKAGE_ACCESS); 9992 9993 long id = mInjector.binderClearCallingIdentity(); 9994 try { 9995 result = mIPackageManager 9996 .setPackagesSuspendedAsUser(packageNames, suspended, 9997 null, null, null, PLATFORM_PACKAGE_NAME, callingUserId); 9998 } catch (RemoteException re) { 9999 // Shouldn't happen. 10000 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 10001 } finally { 10002 mInjector.binderRestoreCallingIdentity(id); 10003 } 10004 } 10005 final boolean isDelegate = (who == null); 10006 DevicePolicyEventLogger 10007 .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED) 10008 .setAdmin(callerPackage) 10009 .setBoolean(isDelegate) 10010 .setStrings(packageNames) 10011 .write(); 10012 if (result != null) { 10013 return result; 10014 } 10015 return packageNames; 10016 } 10017 10018 @Override isPackageSuspended(ComponentName who, String callerPackage, String packageName)10019 public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) { 10020 int callingUserId = UserHandle.getCallingUserId(); 10021 synchronized (getLockObject()) { 10022 // Ensure the caller is a DO/PO or a package access delegate. 10023 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10024 DELEGATION_PACKAGE_ACCESS); 10025 10026 long id = mInjector.binderClearCallingIdentity(); 10027 try { 10028 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId); 10029 } catch (RemoteException re) { 10030 // Shouldn't happen. 10031 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 10032 } finally { 10033 mInjector.binderRestoreCallingIdentity(id); 10034 } 10035 return false; 10036 } 10037 } 10038 10039 @Override setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner)10040 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) { 10041 Preconditions.checkNotNull(who, "ComponentName is null"); 10042 if (!UserRestrictionsUtils.isValidRestriction(key)) { 10043 return; 10044 } 10045 10046 final int userHandle = mInjector.userHandleGetCallingUserId(); 10047 synchronized (getLockObject()) { 10048 final ActiveAdmin activeAdmin = 10049 getActiveAdminForCallerLocked(who, 10050 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10051 final boolean isDeviceOwner = isDeviceOwner(who, userHandle); 10052 if (isDeviceOwner) { 10053 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 10054 throw new SecurityException("Device owner cannot set user restriction " + key); 10055 } 10056 } else { // profile owner 10057 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) { 10058 throw new SecurityException("Profile owner cannot set user restriction " + key); 10059 } 10060 } 10061 10062 // Save the restriction to ActiveAdmin. 10063 final Bundle restrictions = activeAdmin.ensureUserRestrictions(); 10064 if (enabledFromThisOwner) { 10065 restrictions.putBoolean(key, true); 10066 } else { 10067 restrictions.remove(key); 10068 } 10069 saveUserRestrictionsLocked(userHandle); 10070 } 10071 final int eventId = enabledFromThisOwner 10072 ? DevicePolicyEnums.ADD_USER_RESTRICTION 10073 : DevicePolicyEnums.REMOVE_USER_RESTRICTION; 10074 DevicePolicyEventLogger 10075 .createEvent(eventId) 10076 .setAdmin(who) 10077 .setStrings(key) 10078 .write(); 10079 if (SecurityLog.isLoggingEnabled()) { 10080 final int eventTag = enabledFromThisOwner 10081 ? SecurityLog.TAG_USER_RESTRICTION_ADDED 10082 : SecurityLog.TAG_USER_RESTRICTION_REMOVED; 10083 SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key); 10084 } 10085 } 10086 saveUserRestrictionsLocked(int userId)10087 private void saveUserRestrictionsLocked(int userId) { 10088 saveSettingsLocked(userId); 10089 pushUserRestrictions(userId); 10090 sendChangedNotification(userId); 10091 } 10092 pushUserRestrictions(int userId)10093 private void pushUserRestrictions(int userId) { 10094 synchronized (getLockObject()) { 10095 final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId); 10096 final Bundle userRestrictions; 10097 // Whether device owner enforces camera restriction. 10098 boolean disallowCameraGlobally = false; 10099 10100 if (isDeviceOwner) { 10101 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10102 if (deviceOwner == null) { 10103 return; // Shouldn't happen. 10104 } 10105 userRestrictions = deviceOwner.userRestrictions; 10106 // DO can disable camera globally. 10107 disallowCameraGlobally = deviceOwner.disableCamera; 10108 } else { 10109 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 10110 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null; 10111 } 10112 10113 // Whether any admin enforces camera restriction. 10114 final int cameraRestrictionScope = 10115 getCameraRestrictionScopeLocked(userId, disallowCameraGlobally); 10116 10117 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions, 10118 isDeviceOwner, cameraRestrictionScope); 10119 } 10120 } 10121 10122 /** 10123 * Get the scope of camera restriction for a given user if any. 10124 */ getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally)10125 private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) { 10126 if (disallowCameraGlobally) { 10127 return UserManagerInternal.CAMERA_DISABLED_GLOBALLY; 10128 } else if (getCameraDisabled( 10129 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) { 10130 return UserManagerInternal.CAMERA_DISABLED_LOCALLY; 10131 } 10132 return UserManagerInternal.CAMERA_NOT_DISABLED; 10133 } 10134 10135 @Override getUserRestrictions(ComponentName who)10136 public Bundle getUserRestrictions(ComponentName who) { 10137 if (!mHasFeature) { 10138 return null; 10139 } 10140 Preconditions.checkNotNull(who, "ComponentName is null"); 10141 synchronized (getLockObject()) { 10142 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who, 10143 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10144 return activeAdmin.userRestrictions; 10145 } 10146 } 10147 10148 @Override setApplicationHidden(ComponentName who, String callerPackage, String packageName, boolean hidden)10149 public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName, 10150 boolean hidden) { 10151 int callingUserId = UserHandle.getCallingUserId(); 10152 boolean result = false; 10153 synchronized (getLockObject()) { 10154 // Ensure the caller is a DO/PO or a package access delegate. 10155 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10156 DELEGATION_PACKAGE_ACCESS); 10157 10158 long id = mInjector.binderClearCallingIdentity(); 10159 try { 10160 result = mIPackageManager 10161 .setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId); 10162 } catch (RemoteException re) { 10163 // shouldn't happen 10164 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 10165 } finally { 10166 mInjector.binderRestoreCallingIdentity(id); 10167 } 10168 } 10169 final boolean isDelegate = (who == null); 10170 DevicePolicyEventLogger 10171 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN) 10172 .setAdmin(callerPackage) 10173 .setBoolean(isDelegate) 10174 .setStrings(packageName, hidden ? "hidden" : "not_hidden") 10175 .write(); 10176 return result; 10177 } 10178 10179 @Override isApplicationHidden(ComponentName who, String callerPackage, String packageName)10180 public boolean isApplicationHidden(ComponentName who, String callerPackage, 10181 String packageName) { 10182 int callingUserId = UserHandle.getCallingUserId(); 10183 synchronized (getLockObject()) { 10184 // Ensure the caller is a DO/PO or a package access delegate. 10185 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10186 DELEGATION_PACKAGE_ACCESS); 10187 10188 long id = mInjector.binderClearCallingIdentity(); 10189 try { 10190 return mIPackageManager.getApplicationHiddenSettingAsUser( 10191 packageName, callingUserId); 10192 } catch (RemoteException re) { 10193 // shouldn't happen 10194 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 10195 } finally { 10196 mInjector.binderRestoreCallingIdentity(id); 10197 } 10198 return false; 10199 } 10200 } 10201 10202 @Override enableSystemApp(ComponentName who, String callerPackage, String packageName)10203 public void enableSystemApp(ComponentName who, String callerPackage, String packageName) { 10204 synchronized (getLockObject()) { 10205 // Ensure the caller is a DO/PO or an enable system app delegate. 10206 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10207 DELEGATION_ENABLE_SYSTEM_APP); 10208 10209 final boolean isDemo = isCurrentUserDemo(); 10210 10211 int userId = UserHandle.getCallingUserId(); 10212 long id = mInjector.binderClearCallingIdentity(); 10213 10214 try { 10215 if (VERBOSE_LOG) { 10216 Slog.v(LOG_TAG, "installing " + packageName + " for " 10217 + userId); 10218 } 10219 10220 int parentUserId = getProfileParentId(userId); 10221 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) { 10222 throw new IllegalArgumentException("Only system apps can be enabled this way."); 10223 } 10224 10225 // Install the app. 10226 mIPackageManager.installExistingPackageAsUser(packageName, userId, 10227 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 10228 PackageManager.INSTALL_REASON_POLICY, null); 10229 if (isDemo) { 10230 // Ensure the app is also ENABLED for demo users. 10231 mIPackageManager.setApplicationEnabledSetting(packageName, 10232 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 10233 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 10234 } 10235 } catch (RemoteException re) { 10236 // shouldn't happen 10237 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 10238 } finally { 10239 mInjector.binderRestoreCallingIdentity(id); 10240 } 10241 } 10242 final boolean isDelegate = (who == null); 10243 DevicePolicyEventLogger 10244 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP) 10245 .setAdmin(callerPackage) 10246 .setBoolean(isDelegate) 10247 .setStrings(packageName) 10248 .write(); 10249 } 10250 10251 @Override enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent)10252 public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) { 10253 int numberOfAppsInstalled = 0; 10254 synchronized (getLockObject()) { 10255 // Ensure the caller is a DO/PO or an enable system app delegate. 10256 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10257 DELEGATION_ENABLE_SYSTEM_APP); 10258 10259 int userId = UserHandle.getCallingUserId(); 10260 long id = mInjector.binderClearCallingIdentity(); 10261 10262 try { 10263 int parentUserId = getProfileParentId(userId); 10264 List<ResolveInfo> activitiesToEnable = mIPackageManager 10265 .queryIntentActivities(intent, 10266 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10267 PackageManager.MATCH_DIRECT_BOOT_AWARE 10268 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 10269 parentUserId) 10270 .getList(); 10271 10272 if (VERBOSE_LOG) { 10273 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 10274 } 10275 if (activitiesToEnable != null) { 10276 for (ResolveInfo info : activitiesToEnable) { 10277 if (info.activityInfo != null) { 10278 String packageName = info.activityInfo.packageName; 10279 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 10280 numberOfAppsInstalled++; 10281 mIPackageManager.installExistingPackageAsUser(packageName, userId, 10282 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 10283 PackageManager.INSTALL_REASON_POLICY, null); 10284 } else { 10285 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 10286 + " system app"); 10287 } 10288 } 10289 } 10290 } 10291 } catch (RemoteException e) { 10292 // shouldn't happen 10293 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 10294 return 0; 10295 } finally { 10296 mInjector.binderRestoreCallingIdentity(id); 10297 } 10298 } 10299 final boolean isDelegate = (who == null); 10300 DevicePolicyEventLogger 10301 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP_WITH_INTENT) 10302 .setAdmin(callerPackage) 10303 .setBoolean(isDelegate) 10304 .setStrings(intent.getAction()) 10305 .write(); 10306 return numberOfAppsInstalled; 10307 } 10308 isSystemApp(IPackageManager pm, String packageName, int userId)10309 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 10310 throws RemoteException { 10311 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 10312 userId); 10313 if (appInfo == null) { 10314 throw new IllegalArgumentException("The application " + packageName + 10315 " is not present on this device"); 10316 } 10317 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10318 } 10319 10320 @Override installExistingPackage(ComponentName who, String callerPackage, String packageName)10321 public boolean installExistingPackage(ComponentName who, String callerPackage, 10322 String packageName) { 10323 boolean result; 10324 synchronized (getLockObject()) { 10325 // Ensure the caller is a PO or an install existing package delegate 10326 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10327 DELEGATION_INSTALL_EXISTING_PACKAGE); 10328 final int callingUserId = mInjector.userHandleGetCallingUserId(); 10329 if (!isUserAffiliatedWithDeviceLocked(callingUserId)) { 10330 throw new SecurityException("Admin " + who + 10331 " is neither the device owner or affiliated user's profile owner."); 10332 } 10333 10334 final long id = mInjector.binderClearCallingIdentity(); 10335 try { 10336 if (VERBOSE_LOG) { 10337 Slog.v(LOG_TAG, "installing " + packageName + " for " 10338 + callingUserId); 10339 } 10340 10341 // Install the package. 10342 result = mIPackageManager.installExistingPackageAsUser(packageName, callingUserId, 10343 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 10344 PackageManager.INSTALL_REASON_POLICY, null) 10345 == PackageManager.INSTALL_SUCCEEDED; 10346 } catch (RemoteException re) { 10347 // shouldn't happen 10348 return false; 10349 } finally { 10350 mInjector.binderRestoreCallingIdentity(id); 10351 } 10352 } 10353 if (result) { 10354 final boolean isDelegate = (who == null); 10355 DevicePolicyEventLogger 10356 .createEvent(DevicePolicyEnums.INSTALL_EXISTING_PACKAGE) 10357 .setAdmin(callerPackage) 10358 .setBoolean(isDelegate) 10359 .setStrings(packageName) 10360 .write(); 10361 } 10362 return result; 10363 } 10364 10365 @Override setAccountManagementDisabled(ComponentName who, String accountType, boolean disabled)10366 public void setAccountManagementDisabled(ComponentName who, String accountType, 10367 boolean disabled) { 10368 if (!mHasFeature) { 10369 return; 10370 } 10371 Preconditions.checkNotNull(who, "ComponentName is null"); 10372 synchronized (getLockObject()) { 10373 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 10374 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10375 if (disabled) { 10376 ap.accountTypesWithManagementDisabled.add(accountType); 10377 } else { 10378 ap.accountTypesWithManagementDisabled.remove(accountType); 10379 } 10380 saveSettingsLocked(UserHandle.getCallingUserId()); 10381 } 10382 } 10383 10384 @Override getAccountTypesWithManagementDisabled()10385 public String[] getAccountTypesWithManagementDisabled() { 10386 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 10387 } 10388 10389 @Override getAccountTypesWithManagementDisabledAsUser(int userId)10390 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 10391 enforceFullCrossUsersPermission(userId); 10392 if (!mHasFeature) { 10393 return null; 10394 } 10395 synchronized (getLockObject()) { 10396 DevicePolicyData policy = getUserData(userId); 10397 final int N = policy.mAdminList.size(); 10398 ArraySet<String> resultSet = new ArraySet<>(); 10399 for (int i = 0; i < N; i++) { 10400 ActiveAdmin admin = policy.mAdminList.get(i); 10401 resultSet.addAll(admin.accountTypesWithManagementDisabled); 10402 } 10403 return resultSet.toArray(new String[resultSet.size()]); 10404 } 10405 } 10406 10407 @Override setUninstallBlocked(ComponentName who, String callerPackage, String packageName, boolean uninstallBlocked)10408 public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName, 10409 boolean uninstallBlocked) { 10410 final int userId = UserHandle.getCallingUserId(); 10411 synchronized (getLockObject()) { 10412 // Ensure the caller is a DO/PO or a block uninstall delegate 10413 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 10414 DELEGATION_BLOCK_UNINSTALL); 10415 10416 long id = mInjector.binderClearCallingIdentity(); 10417 try { 10418 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 10419 } catch (RemoteException re) { 10420 // Shouldn't happen. 10421 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 10422 } finally { 10423 mInjector.binderRestoreCallingIdentity(id); 10424 } 10425 } 10426 final boolean isDelegate = (who == null); 10427 DevicePolicyEventLogger 10428 .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED) 10429 .setAdmin(callerPackage) 10430 .setBoolean(isDelegate) 10431 .setStrings(packageName) 10432 .write(); 10433 } 10434 10435 @Override isUninstallBlocked(ComponentName who, String packageName)10436 public boolean isUninstallBlocked(ComponentName who, String packageName) { 10437 // This function should return true if and only if the package is blocked by 10438 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 10439 // when the package is a system app, or when it is an active device admin. 10440 final int userId = UserHandle.getCallingUserId(); 10441 10442 synchronized (getLockObject()) { 10443 if (who != null) { 10444 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10445 } 10446 10447 long id = mInjector.binderClearCallingIdentity(); 10448 try { 10449 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 10450 } catch (RemoteException re) { 10451 // Shouldn't happen. 10452 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 10453 } finally { 10454 mInjector.binderRestoreCallingIdentity(id); 10455 } 10456 } 10457 return false; 10458 } 10459 10460 @Override setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled)10461 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 10462 if (!mHasFeature) { 10463 return; 10464 } 10465 Preconditions.checkNotNull(who, "ComponentName is null"); 10466 synchronized (getLockObject()) { 10467 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10468 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10469 if (admin.disableCallerId != disabled) { 10470 admin.disableCallerId = disabled; 10471 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 10472 } 10473 } 10474 DevicePolicyEventLogger 10475 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALLER_ID_DISABLED) 10476 .setAdmin(who) 10477 .setBoolean(disabled) 10478 .write(); 10479 } 10480 10481 @Override getCrossProfileCallerIdDisabled(ComponentName who)10482 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 10483 if (!mHasFeature) { 10484 return false; 10485 } 10486 Preconditions.checkNotNull(who, "ComponentName is null"); 10487 synchronized (getLockObject()) { 10488 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10489 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10490 return admin.disableCallerId; 10491 } 10492 } 10493 10494 @Override getCrossProfileCallerIdDisabledForUser(int userId)10495 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 10496 enforceCrossUsersPermission(userId); 10497 synchronized (getLockObject()) { 10498 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 10499 return (admin != null) ? admin.disableCallerId : false; 10500 } 10501 } 10502 10503 @Override setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled)10504 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 10505 if (!mHasFeature) { 10506 return; 10507 } 10508 Preconditions.checkNotNull(who, "ComponentName is null"); 10509 synchronized (getLockObject()) { 10510 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10511 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10512 if (admin.disableContactsSearch != disabled) { 10513 admin.disableContactsSearch = disabled; 10514 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 10515 } 10516 } 10517 DevicePolicyEventLogger 10518 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED) 10519 .setAdmin(who) 10520 .setBoolean(disabled) 10521 .write(); 10522 } 10523 10524 @Override getCrossProfileContactsSearchDisabled(ComponentName who)10525 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 10526 if (!mHasFeature) { 10527 return false; 10528 } 10529 Preconditions.checkNotNull(who, "ComponentName is null"); 10530 synchronized (getLockObject()) { 10531 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10532 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10533 return admin.disableContactsSearch; 10534 } 10535 } 10536 10537 @Override getCrossProfileContactsSearchDisabledForUser(int userId)10538 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 10539 enforceCrossUsersPermission(userId); 10540 synchronized (getLockObject()) { 10541 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 10542 return (admin != null) ? admin.disableContactsSearch : false; 10543 } 10544 } 10545 10546 @Override startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent)10547 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 10548 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 10549 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 10550 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 10551 final int callingUserId = UserHandle.getCallingUserId(); 10552 10553 final long ident = mInjector.binderClearCallingIdentity(); 10554 try { 10555 synchronized (getLockObject()) { 10556 final int managedUserId = getManagedUserId(callingUserId); 10557 if (managedUserId < 0) { 10558 return; 10559 } 10560 if (isCrossProfileQuickContactDisabled(managedUserId)) { 10561 if (VERBOSE_LOG) { 10562 Log.v(LOG_TAG, 10563 "Cross-profile contacts access disabled for user " + managedUserId); 10564 } 10565 return; 10566 } 10567 ContactsInternal.startQuickContactWithErrorToastForUser( 10568 mContext, intent, new UserHandle(managedUserId)); 10569 } 10570 } finally { 10571 mInjector.binderRestoreCallingIdentity(ident); 10572 } 10573 } 10574 10575 /** 10576 * @return true if cross-profile QuickContact is disabled 10577 */ isCrossProfileQuickContactDisabled(int userId)10578 private boolean isCrossProfileQuickContactDisabled(int userId) { 10579 return getCrossProfileCallerIdDisabledForUser(userId) 10580 && getCrossProfileContactsSearchDisabledForUser(userId); 10581 } 10582 10583 /** 10584 * @return the user ID of the managed user that is linked to the current user, if any. 10585 * Otherwise -1. 10586 */ getManagedUserId(int callingUserId)10587 public int getManagedUserId(int callingUserId) { 10588 if (VERBOSE_LOG) { 10589 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 10590 } 10591 10592 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 10593 if (ui.id == callingUserId || !ui.isManagedProfile()) { 10594 continue; // Caller user self, or not a managed profile. Skip. 10595 } 10596 if (VERBOSE_LOG) { 10597 Log.v(LOG_TAG, "Managed user=" + ui.id); 10598 } 10599 return ui.id; 10600 } 10601 if (VERBOSE_LOG) { 10602 Log.v(LOG_TAG, "Managed user not found."); 10603 } 10604 return -1; 10605 } 10606 10607 @Override setBluetoothContactSharingDisabled(ComponentName who, boolean disabled)10608 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 10609 if (!mHasFeature) { 10610 return; 10611 } 10612 Preconditions.checkNotNull(who, "ComponentName is null"); 10613 synchronized (getLockObject()) { 10614 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10615 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10616 if (admin.disableBluetoothContactSharing != disabled) { 10617 admin.disableBluetoothContactSharing = disabled; 10618 saveSettingsLocked(UserHandle.getCallingUserId()); 10619 } 10620 } 10621 DevicePolicyEventLogger 10622 .createEvent(DevicePolicyEnums.SET_BLUETOOTH_CONTACT_SHARING_DISABLED) 10623 .setAdmin(who) 10624 .setBoolean(disabled) 10625 .write(); 10626 } 10627 10628 @Override getBluetoothContactSharingDisabled(ComponentName who)10629 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 10630 if (!mHasFeature) { 10631 return false; 10632 } 10633 Preconditions.checkNotNull(who, "ComponentName is null"); 10634 synchronized (getLockObject()) { 10635 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 10636 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10637 return admin.disableBluetoothContactSharing; 10638 } 10639 } 10640 10641 @Override getBluetoothContactSharingDisabledForUser(int userId)10642 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 10643 // TODO: Should there be a check to make sure this relationship is 10644 // within a profile group? 10645 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 10646 synchronized (getLockObject()) { 10647 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 10648 return (admin != null) ? admin.disableBluetoothContactSharing : false; 10649 } 10650 } 10651 10652 @Override setLockTaskPackages(ComponentName who, String[] packages)10653 public void setLockTaskPackages(ComponentName who, String[] packages) 10654 throws SecurityException { 10655 Preconditions.checkNotNull(who, "ComponentName is null"); 10656 Preconditions.checkNotNull(packages, "packages is null"); 10657 10658 synchronized (getLockObject()) { 10659 enforceCanCallLockTaskLocked(who); 10660 final int userHandle = mInjector.userHandleGetCallingUserId(); 10661 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 10662 } 10663 } 10664 setLockTaskPackagesLocked(int userHandle, List<String> packages)10665 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 10666 DevicePolicyData policy = getUserData(userHandle); 10667 policy.mLockTaskPackages = packages; 10668 10669 // Store the settings persistently. 10670 saveSettingsLocked(userHandle); 10671 updateLockTaskPackagesLocked(packages, userHandle); 10672 } 10673 10674 @Override getLockTaskPackages(ComponentName who)10675 public String[] getLockTaskPackages(ComponentName who) { 10676 Preconditions.checkNotNull(who, "ComponentName is null"); 10677 10678 final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 10679 synchronized (getLockObject()) { 10680 enforceCanCallLockTaskLocked(who); 10681 final List<String> packages = getUserData(userHandle).mLockTaskPackages; 10682 return packages.toArray(new String[packages.size()]); 10683 } 10684 } 10685 10686 @Override isLockTaskPermitted(String pkg)10687 public boolean isLockTaskPermitted(String pkg) { 10688 final int userHandle = mInjector.userHandleGetCallingUserId(); 10689 synchronized (getLockObject()) { 10690 return getUserData(userHandle).mLockTaskPackages.contains(pkg); 10691 } 10692 } 10693 10694 @Override setLockTaskFeatures(ComponentName who, int flags)10695 public void setLockTaskFeatures(ComponentName who, int flags) { 10696 Preconditions.checkNotNull(who, "ComponentName is null"); 10697 10698 // Throw if Overview is used without Home. 10699 boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0; 10700 boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0; 10701 Preconditions.checkArgument(hasHome || !hasOverview, 10702 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME"); 10703 boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0; 10704 Preconditions.checkArgument(hasHome || !hasNotification, 10705 "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME"); 10706 10707 final int userHandle = mInjector.userHandleGetCallingUserId(); 10708 synchronized (getLockObject()) { 10709 enforceCanCallLockTaskLocked(who); 10710 setLockTaskFeaturesLocked(userHandle, flags); 10711 } 10712 } 10713 setLockTaskFeaturesLocked(int userHandle, int flags)10714 private void setLockTaskFeaturesLocked(int userHandle, int flags) { 10715 DevicePolicyData policy = getUserData(userHandle); 10716 policy.mLockTaskFeatures = flags; 10717 saveSettingsLocked(userHandle); 10718 updateLockTaskFeaturesLocked(flags, userHandle); 10719 } 10720 10721 @Override getLockTaskFeatures(ComponentName who)10722 public int getLockTaskFeatures(ComponentName who) { 10723 Preconditions.checkNotNull(who, "ComponentName is null"); 10724 final int userHandle = mInjector.userHandleGetCallingUserId(); 10725 synchronized (getLockObject()) { 10726 enforceCanCallLockTaskLocked(who); 10727 return getUserData(userHandle).mLockTaskFeatures; 10728 } 10729 } 10730 maybeClearLockTaskPolicyLocked()10731 private void maybeClearLockTaskPolicyLocked() { 10732 final long ident = mInjector.binderClearCallingIdentity(); 10733 try { 10734 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 10735 for (int i = userInfos.size() - 1; i >= 0; i--) { 10736 int userId = userInfos.get(i).id; 10737 if (canUserUseLockTaskLocked(userId)) { 10738 continue; 10739 } 10740 10741 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages; 10742 if (!lockTaskPackages.isEmpty()) { 10743 Slog.d(LOG_TAG, 10744 "User id " + userId + " not affiliated. Clearing lock task packages"); 10745 setLockTaskPackagesLocked(userId, Collections.<String>emptyList()); 10746 } 10747 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures; 10748 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){ 10749 Slog.d(LOG_TAG, 10750 "User id " + userId + " not affiliated. Clearing lock task features"); 10751 setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE); 10752 } 10753 } 10754 } finally { 10755 mInjector.binderRestoreCallingIdentity(ident); 10756 } 10757 } 10758 10759 @Override notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle)10760 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 10761 if (!isCallerWithSystemUid()) { 10762 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 10763 } 10764 synchronized (getLockObject()) { 10765 final DevicePolicyData policy = getUserData(userHandle); 10766 10767 if (policy.mStatusBarDisabled) { 10768 // Status bar is managed by LockTaskController during LockTask, so we cancel this 10769 // policy when LockTask starts, and reapply it when LockTask ends 10770 setStatusBarDisabledInternal(!isEnabled, userHandle); 10771 } 10772 10773 Bundle adminExtras = new Bundle(); 10774 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 10775 for (ActiveAdmin admin : policy.mAdminList) { 10776 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 10777 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 10778 if (ownsDevice || ownsProfile) { 10779 if (isEnabled) { 10780 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 10781 adminExtras, null); 10782 } else { 10783 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 10784 } 10785 DevicePolicyEventLogger 10786 .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED) 10787 .setAdmin(admin.info.getPackageName()) 10788 .setBoolean(isEnabled) 10789 .setStrings(pkg) 10790 .write(); 10791 } 10792 } 10793 } 10794 } 10795 10796 @Override setGlobalSetting(ComponentName who, String setting, String value)10797 public void setGlobalSetting(ComponentName who, String setting, String value) { 10798 Preconditions.checkNotNull(who, "ComponentName is null"); 10799 10800 synchronized (getLockObject()) { 10801 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10802 10803 // Some settings are no supported any more. However we do not want to throw a 10804 // SecurityException to avoid breaking apps. 10805 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 10806 Log.i(LOG_TAG, "Global setting no longer supported: " + setting); 10807 return; 10808 } 10809 10810 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting) 10811 && !UserManager.isDeviceInDemoMode(mContext)) { 10812 throw new SecurityException(String.format( 10813 "Permission denial: device owners cannot update %1$s", setting)); 10814 } 10815 10816 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 10817 // ignore if it contradicts an existing policy 10818 long timeMs = getMaximumTimeToLock( 10819 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 10820 if (timeMs > 0 && timeMs < Long.MAX_VALUE) { 10821 return; 10822 } 10823 } 10824 10825 long id = mInjector.binderClearCallingIdentity(); 10826 try { 10827 mInjector.settingsGlobalPutString(setting, value); 10828 } finally { 10829 mInjector.binderRestoreCallingIdentity(id); 10830 } 10831 } 10832 } 10833 10834 @Override setSystemSetting(ComponentName who, String setting, String value)10835 public void setSystemSetting(ComponentName who, String setting, String value) { 10836 Preconditions.checkNotNull(who, "ComponentName is null"); 10837 Preconditions.checkStringNotEmpty(setting, "String setting is null or empty"); 10838 10839 synchronized (getLockObject()) { 10840 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10841 10842 if (!SYSTEM_SETTINGS_WHITELIST.contains(setting)) { 10843 throw new SecurityException(String.format( 10844 "Permission denial: device owners cannot update %1$s", setting)); 10845 } 10846 10847 final int callingUserId = mInjector.userHandleGetCallingUserId(); 10848 10849 mInjector.binderWithCleanCallingIdentity(() -> 10850 mInjector.settingsSystemPutStringForUser(setting, value, callingUserId)); 10851 } 10852 } 10853 10854 @Override setTime(ComponentName who, long millis)10855 public boolean setTime(ComponentName who, long millis) { 10856 Preconditions.checkNotNull(who, "ComponentName is null in setTime"); 10857 enforceDeviceOwner(who); 10858 // Don't allow set time when auto time is on. 10859 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) { 10860 return false; 10861 } 10862 mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis)); 10863 return true; 10864 } 10865 10866 @Override setTimeZone(ComponentName who, String timeZone)10867 public boolean setTimeZone(ComponentName who, String timeZone) { 10868 Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone"); 10869 enforceDeviceOwner(who); 10870 // Don't allow set timezone when auto timezone is on. 10871 if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) { 10872 return false; 10873 } 10874 mInjector.binderWithCleanCallingIdentity(() -> 10875 mInjector.getAlarmManager().setTimeZone(timeZone)); 10876 return true; 10877 } 10878 10879 @Override setSecureSetting(ComponentName who, String setting, String value)10880 public void setSecureSetting(ComponentName who, String setting, String value) { 10881 Preconditions.checkNotNull(who, "ComponentName is null"); 10882 int callingUserId = mInjector.userHandleGetCallingUserId(); 10883 10884 synchronized (getLockObject()) { 10885 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10886 10887 if (isDeviceOwner(who, callingUserId)) { 10888 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting) 10889 && !isCurrentUserDemo()) { 10890 throw new SecurityException(String.format( 10891 "Permission denial: Device owners cannot update %1$s", setting)); 10892 } 10893 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) { 10894 throw new SecurityException(String.format( 10895 "Permission denial: Profile owners cannot update %1$s", setting)); 10896 } 10897 if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) { 10898 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) { 10899 throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS 10900 + " is deprecated. Please use one of the user restrictions " 10901 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or " 10902 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY + " instead."); 10903 } 10904 if (!mUserManager.isManagedProfile(callingUserId)) { 10905 Slog.e(LOG_TAG, "Ignoring setSecureSetting request for " 10906 + setting + ". User restriction " 10907 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or " 10908 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY 10909 + " should be used instead."); 10910 } else { 10911 try { 10912 setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 10913 (Integer.parseInt(value) == 0) ? true : false); 10914 DevicePolicyEventLogger 10915 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING) 10916 .setAdmin(who) 10917 .setStrings(setting, value) 10918 .write(); 10919 } catch (NumberFormatException exc) { 10920 Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting); 10921 } 10922 } 10923 return; 10924 } 10925 long id = mInjector.binderClearCallingIdentity(); 10926 try { 10927 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) { 10928 final String currentValue = mInjector.settingsSecureGetStringForUser( 10929 Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId); 10930 if (!TextUtils.equals(currentValue, value)) { 10931 // Tell the content observer that the next change will be due to the owner 10932 // changing the value. There is a small race condition here that we cannot 10933 // avoid: Change notifications are sent asynchronously, so it is possible 10934 // that there are prior notifications queued up before the one we are about 10935 // to trigger. This is a corner case that will have no impact in practice. 10936 mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId); 10937 } 10938 getUserData(callingUserId).mCurrentInputMethodSet = true; 10939 saveSettingsLocked(callingUserId); 10940 } 10941 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 10942 } finally { 10943 mInjector.binderRestoreCallingIdentity(id); 10944 } 10945 } 10946 DevicePolicyEventLogger 10947 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING) 10948 .setAdmin(who) 10949 .setStrings(setting, value) 10950 .write(); 10951 } 10952 10953 @Override setMasterVolumeMuted(ComponentName who, boolean on)10954 public void setMasterVolumeMuted(ComponentName who, boolean on) { 10955 Preconditions.checkNotNull(who, "ComponentName is null"); 10956 synchronized (getLockObject()) { 10957 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10958 setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on); 10959 DevicePolicyEventLogger 10960 .createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED) 10961 .setAdmin(who) 10962 .setBoolean(on) 10963 .write(); 10964 } 10965 } 10966 10967 @Override isMasterVolumeMuted(ComponentName who)10968 public boolean isMasterVolumeMuted(ComponentName who) { 10969 Preconditions.checkNotNull(who, "ComponentName is null"); 10970 synchronized (getLockObject()) { 10971 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10972 10973 AudioManager audioManager = 10974 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 10975 return audioManager.isMasterMute(); 10976 } 10977 } 10978 10979 @Override setUserIcon(ComponentName who, Bitmap icon)10980 public void setUserIcon(ComponentName who, Bitmap icon) { 10981 synchronized (getLockObject()) { 10982 Preconditions.checkNotNull(who, "ComponentName is null"); 10983 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10984 10985 int userId = UserHandle.getCallingUserId(); 10986 long id = mInjector.binderClearCallingIdentity(); 10987 try { 10988 mUserManagerInternal.setUserIcon(userId, icon); 10989 } finally { 10990 mInjector.binderRestoreCallingIdentity(id); 10991 } 10992 } 10993 DevicePolicyEventLogger 10994 .createEvent(DevicePolicyEnums.SET_USER_ICON) 10995 .setAdmin(who) 10996 .write(); 10997 } 10998 10999 @Override setKeyguardDisabled(ComponentName who, boolean disabled)11000 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 11001 Preconditions.checkNotNull(who, "ComponentName is null"); 11002 final int userId = mInjector.userHandleGetCallingUserId(); 11003 synchronized (getLockObject()) { 11004 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11005 if (!isUserAffiliatedWithDeviceLocked(userId)) { 11006 throw new SecurityException("Admin " + who + 11007 " is neither the device owner or affiliated user's profile owner."); 11008 } 11009 } 11010 if (isManagedProfile(userId)) { 11011 throw new SecurityException("Managed profile cannot disable keyguard"); 11012 } 11013 11014 long ident = mInjector.binderClearCallingIdentity(); 11015 try { 11016 // disallow disabling the keyguard if a password is currently set 11017 if (disabled && mLockPatternUtils.isSecure(userId)) { 11018 return false; 11019 } 11020 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 11021 if (disabled) { 11022 mInjector 11023 .getIWindowManager() 11024 .dismissKeyguard(null /* callback */, null /* message */); 11025 } 11026 DevicePolicyEventLogger 11027 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED) 11028 .setAdmin(who) 11029 .setBoolean(disabled) 11030 .write(); 11031 } catch (RemoteException e) { 11032 // Same process, does not happen. 11033 } finally { 11034 mInjector.binderRestoreCallingIdentity(ident); 11035 } 11036 return true; 11037 } 11038 11039 @Override setStatusBarDisabled(ComponentName who, boolean disabled)11040 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 11041 int userId = UserHandle.getCallingUserId(); 11042 synchronized (getLockObject()) { 11043 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 11044 if (!isUserAffiliatedWithDeviceLocked(userId)) { 11045 throw new SecurityException("Admin " + who + 11046 " is neither the device owner or affiliated user's profile owner."); 11047 } 11048 if (isManagedProfile(userId)) { 11049 throw new SecurityException("Managed profile cannot disable status bar"); 11050 } 11051 DevicePolicyData policy = getUserData(userId); 11052 if (policy.mStatusBarDisabled != disabled) { 11053 boolean isLockTaskMode = false; 11054 try { 11055 isLockTaskMode = mInjector.getIActivityTaskManager().getLockTaskModeState() 11056 != LOCK_TASK_MODE_NONE; 11057 } catch (RemoteException e) { 11058 Slog.e(LOG_TAG, "Failed to get LockTask mode"); 11059 } 11060 if (!isLockTaskMode) { 11061 if (!setStatusBarDisabledInternal(disabled, userId)) { 11062 return false; 11063 } 11064 } 11065 policy.mStatusBarDisabled = disabled; 11066 saveSettingsLocked(userId); 11067 } 11068 } 11069 DevicePolicyEventLogger 11070 .createEvent(DevicePolicyEnums.SET_STATUS_BAR_DISABLED) 11071 .setAdmin(who) 11072 .setBoolean(disabled) 11073 .write(); 11074 return true; 11075 } 11076 setStatusBarDisabledInternal(boolean disabled, int userId)11077 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 11078 long ident = mInjector.binderClearCallingIdentity(); 11079 try { 11080 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 11081 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 11082 if (statusBarService != null) { 11083 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 11084 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 11085 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 11086 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 11087 return true; 11088 } 11089 } catch (RemoteException e) { 11090 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 11091 } finally { 11092 mInjector.binderRestoreCallingIdentity(ident); 11093 } 11094 return false; 11095 } 11096 11097 /** 11098 * We need to update the internal state of whether a user has completed setup or a 11099 * device has paired once. After that, we ignore any changes that reset the 11100 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 11101 * as we don't trust any apps that might try to reset them. 11102 * <p> 11103 * Unfortunately, we don't know which user's setup state was changed, so we write all of 11104 * them. 11105 */ updateUserSetupCompleteAndPaired()11106 void updateUserSetupCompleteAndPaired() { 11107 List<UserInfo> users = mUserManager.getUsers(true); 11108 final int N = users.size(); 11109 for (int i = 0; i < N; i++) { 11110 int userHandle = users.get(i).id; 11111 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 11112 userHandle) != 0) { 11113 DevicePolicyData policy = getUserData(userHandle); 11114 if (!policy.mUserSetupComplete) { 11115 policy.mUserSetupComplete = true; 11116 synchronized (getLockObject()) { 11117 saveSettingsLocked(userHandle); 11118 } 11119 } 11120 } 11121 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 11122 userHandle) != 0) { 11123 DevicePolicyData policy = getUserData(userHandle); 11124 if (!policy.mPaired) { 11125 policy.mPaired = true; 11126 synchronized (getLockObject()) { 11127 saveSettingsLocked(userHandle); 11128 } 11129 } 11130 } 11131 } 11132 } 11133 11134 private class SetupContentObserver extends ContentObserver { 11135 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 11136 Settings.Secure.USER_SETUP_COMPLETE); 11137 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 11138 Settings.Global.DEVICE_PROVISIONED); 11139 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 11140 private final Uri mDefaultImeChanged = Settings.Secure.getUriFor( 11141 Settings.Secure.DEFAULT_INPUT_METHOD); 11142 11143 @GuardedBy("getLockObject()") 11144 private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>(); 11145 SetupContentObserver(Handler handler)11146 public SetupContentObserver(Handler handler) { 11147 super(handler); 11148 } 11149 register()11150 void register() { 11151 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 11152 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 11153 if (mIsWatch) { 11154 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 11155 } 11156 mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL); 11157 } 11158 11159 @GuardedBy("getLockObject()") addPendingChangeByOwnerLocked(int userId)11160 private void addPendingChangeByOwnerLocked(int userId) { 11161 mUserIdsWithPendingChangesByOwner.add(userId); 11162 } 11163 11164 @Override onChange(boolean selfChange, Uri uri, int userId)11165 public void onChange(boolean selfChange, Uri uri, int userId) { 11166 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 11167 updateUserSetupCompleteAndPaired(); 11168 } else if (mDeviceProvisioned.equals(uri)) { 11169 synchronized (getLockObject()) { 11170 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 11171 // is delayed until device is marked as provisioned. 11172 setDeviceOwnerSystemPropertyLocked(); 11173 } 11174 } else if (mDefaultImeChanged.equals(uri)) { 11175 synchronized (getLockObject()) { 11176 if (mUserIdsWithPendingChangesByOwner.contains(userId)) { 11177 // This change notification was triggered by the owner changing the current 11178 // IME. Ignore it. 11179 mUserIdsWithPendingChangesByOwner.remove(userId); 11180 } else { 11181 // This change notification was triggered by the user manually changing the 11182 // current IME. 11183 getUserData(userId).mCurrentInputMethodSet = false; 11184 saveSettingsLocked(userId); 11185 } 11186 } 11187 } 11188 } 11189 } 11190 11191 private class DevicePolicyConstantsObserver extends ContentObserver { 11192 final Uri mConstantsUri = 11193 Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS); 11194 DevicePolicyConstantsObserver(Handler handler)11195 DevicePolicyConstantsObserver(Handler handler) { 11196 super(handler); 11197 } 11198 register()11199 void register() { 11200 mInjector.registerContentObserver( 11201 mConstantsUri, /* notifyForDescendents= */ false, this, UserHandle.USER_ALL); 11202 } 11203 11204 @Override onChange(boolean selfChange, Uri uri, int userId)11205 public void onChange(boolean selfChange, Uri uri, int userId) { 11206 mConstants = loadConstants(); 11207 } 11208 } 11209 11210 @VisibleForTesting 11211 final class LocalService extends DevicePolicyManagerInternal { 11212 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 11213 11214 @Override getCrossProfileWidgetProviders(int profileId)11215 public List<String> getCrossProfileWidgetProviders(int profileId) { 11216 synchronized (getLockObject()) { 11217 if (mOwners == null) { 11218 return Collections.emptyList(); 11219 } 11220 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 11221 if (ownerComponent == null) { 11222 return Collections.emptyList(); 11223 } 11224 11225 DevicePolicyData policy = getUserDataUnchecked(profileId); 11226 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 11227 11228 if (admin == null || admin.crossProfileWidgetProviders == null 11229 || admin.crossProfileWidgetProviders.isEmpty()) { 11230 return Collections.emptyList(); 11231 } 11232 11233 return admin.crossProfileWidgetProviders; 11234 } 11235 } 11236 11237 @Override addOnCrossProfileWidgetProvidersChangeListener( OnCrossProfileWidgetProvidersChangeListener listener)11238 public void addOnCrossProfileWidgetProvidersChangeListener( 11239 OnCrossProfileWidgetProvidersChangeListener listener) { 11240 synchronized (getLockObject()) { 11241 if (mWidgetProviderListeners == null) { 11242 mWidgetProviderListeners = new ArrayList<>(); 11243 } 11244 if (!mWidgetProviderListeners.contains(listener)) { 11245 mWidgetProviderListeners.add(listener); 11246 } 11247 } 11248 } 11249 11250 @Override isActiveAdminWithPolicy(int uid, int reqPolicy)11251 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 11252 synchronized (getLockObject()) { 11253 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 11254 } 11255 } 11256 notifyCrossProfileProvidersChanged(int userId, List<String> packages)11257 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 11258 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 11259 synchronized (getLockObject()) { 11260 listeners = new ArrayList<>(mWidgetProviderListeners); 11261 } 11262 final int listenerCount = listeners.size(); 11263 for (int i = 0; i < listenerCount; i++) { 11264 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 11265 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 11266 } 11267 } 11268 11269 @Override createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin)11270 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 11271 // This method is called from AM with its lock held, so don't take the DPMS lock. 11272 // b/29242568 11273 11274 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 11275 if (profileOwner != null) { 11276 return DevicePolicyManagerService.this 11277 .createShowAdminSupportIntent(profileOwner, userId); 11278 } 11279 11280 final Pair<Integer, ComponentName> deviceOwner = 11281 mOwners.getDeviceOwnerUserIdAndComponent(); 11282 if (deviceOwner != null && deviceOwner.first == userId) { 11283 return DevicePolicyManagerService.this 11284 .createShowAdminSupportIntent(deviceOwner.second, userId); 11285 } 11286 11287 // We're not specifying the device admin because there isn't one. 11288 if (useDefaultIfNoAdmin) { 11289 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 11290 } 11291 return null; 11292 } 11293 11294 @Override createUserRestrictionSupportIntent(int userId, String userRestriction)11295 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 11296 final long ident = mInjector.binderClearCallingIdentity(); 11297 try { 11298 final List<UserManager.EnforcingUser> sources = mUserManager 11299 .getUserRestrictionSources(userRestriction, UserHandle.of(userId)); 11300 if (sources == null || sources.isEmpty()) { 11301 // The restriction is not enforced. 11302 return null; 11303 } else if (sources.size() > 1) { 11304 // In this case, we'll show an admin support dialog that does not 11305 // specify the admin. 11306 // TODO(b/128928355): if this restriction is enforced by multiple DPCs, return 11307 // the admin for the calling user. 11308 return DevicePolicyManagerService.this.createShowAdminSupportIntent( 11309 null, userId); 11310 } 11311 final UserManager.EnforcingUser enforcingUser = sources.get(0); 11312 final int sourceType = enforcingUser.getUserRestrictionSource(); 11313 final int enforcingUserId = enforcingUser.getUserHandle().getIdentifier(); 11314 if (sourceType == UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) { 11315 // Restriction was enforced by PO 11316 final ComponentName profileOwner = mOwners.getProfileOwnerComponent( 11317 enforcingUserId); 11318 if (profileOwner != null) { 11319 return DevicePolicyManagerService.this.createShowAdminSupportIntent( 11320 profileOwner, enforcingUserId); 11321 } 11322 } else if (sourceType == UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) { 11323 // Restriction was enforced by DO 11324 final Pair<Integer, ComponentName> deviceOwner = 11325 mOwners.getDeviceOwnerUserIdAndComponent(); 11326 if (deviceOwner != null) { 11327 return DevicePolicyManagerService.this.createShowAdminSupportIntent( 11328 deviceOwner.second, deviceOwner.first); 11329 } 11330 } else if (sourceType == UserManager.RESTRICTION_SOURCE_SYSTEM) { 11331 /* 11332 * In this case, the user restriction is enforced by the system. 11333 * So we won't show an admin support intent, even if it is also 11334 * enforced by a profile/device owner. 11335 */ 11336 return null; 11337 } 11338 } finally { 11339 mInjector.binderRestoreCallingIdentity(ident); 11340 } 11341 return null; 11342 } 11343 11344 @Override isUserAffiliatedWithDevice(int userId)11345 public boolean isUserAffiliatedWithDevice(int userId) { 11346 return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId); 11347 } 11348 11349 @Override canSilentlyInstallPackage(String callerPackage, int callerUid)11350 public boolean canSilentlyInstallPackage(String callerPackage, int callerUid) { 11351 if (callerPackage == null) { 11352 return false; 11353 } 11354 if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid)) 11355 && isActiveAdminWithPolicy(callerUid, 11356 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER)) { 11357 // device owner or a profile owner affiliated with the device owner 11358 return true; 11359 } 11360 return false; 11361 } 11362 11363 @Override reportSeparateProfileChallengeChanged(@serIdInt int userId)11364 public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) { 11365 final long ident = mInjector.binderClearCallingIdentity(); 11366 try { 11367 synchronized (getLockObject()) { 11368 updateMaximumTimeToLockLocked(userId); 11369 updatePasswordQualityCacheForUserGroup(userId); 11370 } 11371 } finally { 11372 mInjector.binderRestoreCallingIdentity(ident); 11373 } 11374 DevicePolicyEventLogger 11375 .createEvent(DevicePolicyEnums.SEPARATE_PROFILE_CHALLENGE_CHANGED) 11376 .setBoolean(isSeparateProfileChallengeEnabled(userId)) 11377 .write(); 11378 } 11379 11380 @Override canUserHaveUntrustedCredentialReset(@serIdInt int userId)11381 public boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) { 11382 return DevicePolicyManagerService.this.canUserHaveUntrustedCredentialReset(userId); 11383 } 11384 11385 @Override getPrintingDisabledReasonForUser(@serIdInt int userId)11386 public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) { 11387 synchronized (getLockObject()) { 11388 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING, 11389 UserHandle.of(userId))) { 11390 Log.e(LOG_TAG, "printing is enabled"); 11391 return null; 11392 } 11393 String ownerPackage = mOwners.getProfileOwnerPackage(userId); 11394 if (ownerPackage == null) { 11395 ownerPackage = mOwners.getDeviceOwnerPackageName(); 11396 } 11397 PackageManager pm = mInjector.getPackageManager(); 11398 PackageInfo packageInfo; 11399 try { 11400 packageInfo = pm.getPackageInfo(ownerPackage, 0); 11401 } catch (NameNotFoundException e) { 11402 Log.e(LOG_TAG, "getPackageInfo error", e); 11403 return null; 11404 } 11405 if (packageInfo == null) { 11406 Log.e(LOG_TAG, "packageInfo is inexplicably null"); 11407 return null; 11408 } 11409 ApplicationInfo appInfo = packageInfo.applicationInfo; 11410 if (appInfo == null) { 11411 Log.e(LOG_TAG, "appInfo is inexplicably null"); 11412 return null; 11413 } 11414 CharSequence appLabel = pm.getApplicationLabel(appInfo); 11415 if (appLabel == null) { 11416 Log.e(LOG_TAG, "appLabel is inexplicably null"); 11417 return null; 11418 } 11419 return ((Context) ActivityThread.currentActivityThread().getSystemUiContext()) 11420 .getResources().getString(R.string.printing_disabled_by, appLabel); 11421 } 11422 } 11423 11424 @Override getDevicePolicyCache()11425 protected DevicePolicyCache getDevicePolicyCache() { 11426 return mPolicyCache; 11427 } 11428 } 11429 createShowAdminSupportIntent(ComponentName admin, int userId)11430 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) { 11431 // This method is called with AMS lock held, so don't take DPMS lock 11432 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 11433 intent.putExtra(Intent.EXTRA_USER_ID, userId); 11434 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin); 11435 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 11436 return intent; 11437 } 11438 11439 @Override createAdminSupportIntent(String restriction)11440 public Intent createAdminSupportIntent(String restriction) { 11441 Preconditions.checkNotNull(restriction); 11442 final int uid = mInjector.binderGetCallingUid(); 11443 final int userId = UserHandle.getUserId(uid); 11444 Intent intent = null; 11445 if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) || 11446 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) { 11447 synchronized (getLockObject()) { 11448 final DevicePolicyData policy = getUserData(userId); 11449 final int N = policy.mAdminList.size(); 11450 for (int i = 0; i < N; i++) { 11451 final ActiveAdmin admin = policy.mAdminList.get(i); 11452 if ((admin.disableCamera && 11453 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) || 11454 (admin.disableScreenCapture && DevicePolicyManager 11455 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) { 11456 intent = createShowAdminSupportIntent(admin.info.getComponent(), userId); 11457 break; 11458 } 11459 } 11460 // For the camera, a device owner on a different user can disable it globally, 11461 // so we need an additional check. 11462 if (intent == null 11463 && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) { 11464 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 11465 if (admin != null && admin.disableCamera) { 11466 intent = createShowAdminSupportIntent(admin.info.getComponent(), 11467 mOwners.getDeviceOwnerUserId()); 11468 } 11469 } 11470 } 11471 } else { 11472 // if valid, |restriction| can only be a user restriction 11473 intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction); 11474 } 11475 if (intent != null) { 11476 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction); 11477 } 11478 return intent; 11479 } 11480 11481 /** 11482 * Returns true if specified admin is allowed to limit passwords and has a 11483 * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality} 11484 */ isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality)11485 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 11486 if (admin.minimumPasswordMetrics.quality < minPasswordQuality) { 11487 return false; 11488 } 11489 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 11490 } 11491 11492 @Override setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy)11493 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 11494 if (policy != null) { 11495 // throws exception if policy type is invalid 11496 policy.validateType(); 11497 // throws exception if freeze period is invalid 11498 policy.validateFreezePeriods(); 11499 Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 11500 // throws exception if freeze period is incompatible with previous freeze period record 11501 policy.validateAgainstPreviousFreezePeriod(record.first, record.second, 11502 LocalDate.now()); 11503 } 11504 synchronized (getLockObject()) { 11505 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 11506 if (policy == null) { 11507 mOwners.clearSystemUpdatePolicy(); 11508 } else { 11509 mOwners.setSystemUpdatePolicy(policy); 11510 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false); 11511 } 11512 mOwners.writeDeviceOwner(); 11513 } 11514 mContext.sendBroadcastAsUser( 11515 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 11516 UserHandle.SYSTEM); 11517 DevicePolicyEventLogger 11518 .createEvent(DevicePolicyEnums.SET_SYSTEM_UPDATE_POLICY) 11519 .setAdmin(who) 11520 .setInt(policy != null ? policy.getPolicyType() : 0) 11521 .write(); 11522 } 11523 11524 @Override getSystemUpdatePolicy()11525 public SystemUpdatePolicy getSystemUpdatePolicy() { 11526 synchronized (getLockObject()) { 11527 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 11528 if (policy != null && !policy.isValid()) { 11529 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 11530 return null; 11531 } 11532 return policy; 11533 } 11534 } 11535 withinRange(Pair<LocalDate, LocalDate> range, LocalDate date)11536 private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) { 11537 return (!date.isBefore(range.first) && !date.isAfter(range.second)); 11538 } 11539 11540 /** 11541 * keeps track of the last continuous period when the system is under OTA freeze. 11542 * 11543 * DPMS keeps track of the previous dates during which OTA was freezed as a result of an 11544 * system update policy with freeze periods in effect. This is needed to make robust 11545 * validation on new system update polices, for example to prevent the OTA from being 11546 * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period 11547 * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting 11548 * a new freeze period after a few days. 11549 * 11550 * @param saveIfChanged whether to persist the result on disk if freeze period record is 11551 * updated. This should only be set to {@code false} if there is a guaranteed 11552 * mOwners.writeDeviceOwner() later in the control flow to reduce the number of 11553 * disk writes. Otherwise you risk inconsistent on-disk state. 11554 * 11555 * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod 11556 */ updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged)11557 private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) { 11558 Slog.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord"); 11559 synchronized (getLockObject()) { 11560 final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 11561 if (policy == null) { 11562 return; 11563 } 11564 final LocalDate now = LocalDate.now(); 11565 final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now); 11566 if (currentPeriod == null) { 11567 return; 11568 } 11569 final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord(); 11570 final LocalDate start = record.first; 11571 final LocalDate end = record.second; 11572 final boolean changed; 11573 if (end == null || start == null) { 11574 // Start a new period if there is none at the moment 11575 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 11576 } else if (now.equals(end.plusDays(1))) { 11577 // Extend the existing period 11578 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 11579 } else if (now.isAfter(end.plusDays(1))) { 11580 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) { 11581 // The device might be off for some period. If the past freeze record 11582 // is within range of the current freeze period, assume the device was off 11583 // during the period [end, now] and extend the freeze record to [start, now]. 11584 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now); 11585 } else { 11586 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 11587 } 11588 } else if (now.isBefore(start)) { 11589 // Systm clock was adjusted backwards, restart record 11590 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now); 11591 } else /* start <= now <= end */ { 11592 changed = false; 11593 } 11594 if (changed && saveIfChanged) { 11595 mOwners.writeDeviceOwner(); 11596 } 11597 } 11598 } 11599 11600 @Override clearSystemUpdatePolicyFreezePeriodRecord()11601 public void clearSystemUpdatePolicyFreezePeriodRecord() { 11602 enforceShell("clearSystemUpdatePolicyFreezePeriodRecord"); 11603 synchronized (getLockObject()) { 11604 // Print out current record to help diagnosed CTS failures 11605 Slog.i(LOG_TAG, "Clear freeze period record: " 11606 + mOwners.getSystemUpdateFreezePeriodRecordAsString()); 11607 if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) { 11608 mOwners.writeDeviceOwner(); 11609 } 11610 } 11611 } 11612 11613 /** 11614 * Checks if the caller of the method is the device owner app. 11615 * 11616 * @param callerUid UID of the caller. 11617 * @return true if the caller is the device owner app 11618 */ 11619 @VisibleForTesting isCallerDeviceOwner(int callerUid)11620 boolean isCallerDeviceOwner(int callerUid) { 11621 synchronized (getLockObject()) { 11622 if (!mOwners.hasDeviceOwner()) { 11623 return false; 11624 } 11625 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 11626 return false; 11627 } 11628 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 11629 .getPackageName(); 11630 try { 11631 String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid); 11632 for (String pkg : pkgs) { 11633 if (deviceOwnerPackageName.equals(pkg)) { 11634 return true; 11635 } 11636 } 11637 } catch (RemoteException e) { 11638 return false; 11639 } 11640 } 11641 return false; 11642 } 11643 11644 @Override notifyPendingSystemUpdate(@ullable SystemUpdateInfo info)11645 public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) { 11646 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 11647 "Only the system update service can broadcast update information"); 11648 11649 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 11650 Slog.w(LOG_TAG, "Only the system update service in the system user " + 11651 "can broadcast update information."); 11652 return; 11653 } 11654 11655 if (!mOwners.saveSystemUpdateInfo(info)) { 11656 // Pending system update hasn't changed, don't send duplicate notification. 11657 return; 11658 } 11659 11660 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE) 11661 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 11662 info == null ? -1 : info.getReceivedTime()); 11663 11664 final long ident = mInjector.binderClearCallingIdentity(); 11665 try { 11666 synchronized (getLockObject()) { 11667 // Broadcast to device owner first if there is one. 11668 if (mOwners.hasDeviceOwner()) { 11669 final UserHandle deviceOwnerUser = 11670 UserHandle.of(mOwners.getDeviceOwnerUserId()); 11671 intent.setComponent(mOwners.getDeviceOwnerComponent()); 11672 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 11673 } 11674 } 11675 // Get running users. 11676 final int runningUserIds[]; 11677 try { 11678 runningUserIds = mInjector.getIActivityManager().getRunningUserIds(); 11679 } catch (RemoteException e) { 11680 // Shouldn't happen. 11681 Log.e(LOG_TAG, "Could not retrieve the list of running users", e); 11682 return; 11683 } 11684 // Send broadcasts to corresponding profile owners if any. 11685 for (final int userId : runningUserIds) { 11686 synchronized (getLockObject()) { 11687 final ComponentName profileOwnerPackage = 11688 mOwners.getProfileOwnerComponent(userId); 11689 if (profileOwnerPackage != null) { 11690 intent.setComponent(profileOwnerPackage); 11691 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 11692 } 11693 } 11694 } 11695 } finally { 11696 mInjector.binderRestoreCallingIdentity(ident); 11697 } 11698 } 11699 11700 @Override getPendingSystemUpdate(ComponentName admin)11701 public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) { 11702 Preconditions.checkNotNull(admin, "ComponentName is null"); 11703 enforceProfileOrDeviceOwner(admin); 11704 11705 return mOwners.getSystemUpdateInfo(); 11706 } 11707 11708 @Override setPermissionPolicy(ComponentName admin, String callerPackage, int policy)11709 public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) 11710 throws RemoteException { 11711 int userId = UserHandle.getCallingUserId(); 11712 synchronized (getLockObject()) { 11713 // Ensure the caller is a DO/PO or a permission grant state delegate. 11714 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 11715 DELEGATION_PERMISSION_GRANT); 11716 DevicePolicyData userPolicy = getUserData(userId); 11717 if (userPolicy.mPermissionPolicy != policy) { 11718 userPolicy.mPermissionPolicy = policy; 11719 saveSettingsLocked(userId); 11720 } 11721 } 11722 final boolean isDelegate = (admin == null); 11723 DevicePolicyEventLogger 11724 .createEvent(DevicePolicyEnums.SET_PERMISSION_POLICY) 11725 .setAdmin(callerPackage) 11726 .setInt(policy) 11727 .setBoolean(isDelegate) 11728 .write(); 11729 } 11730 11731 @Override getPermissionPolicy(ComponentName admin)11732 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 11733 int userId = UserHandle.getCallingUserId(); 11734 synchronized (getLockObject()) { 11735 DevicePolicyData userPolicy = getUserData(userId); 11736 return userPolicy.mPermissionPolicy; 11737 } 11738 } 11739 11740 @Override setPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission, int grantState, RemoteCallback callback)11741 public void setPermissionGrantState(ComponentName admin, String callerPackage, 11742 String packageName, String permission, int grantState, RemoteCallback callback) 11743 throws RemoteException { 11744 Preconditions.checkNotNull(callback); 11745 11746 UserHandle user = mInjector.binderGetCallingUserHandle(); 11747 synchronized (getLockObject()) { 11748 // Ensure the caller is a DO/PO or a permission grant state delegate. 11749 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 11750 DELEGATION_PERMISSION_GRANT); 11751 long ident = mInjector.binderClearCallingIdentity(); 11752 try { 11753 boolean isPostQAdmin = getTargetSdk(callerPackage, user.getIdentifier()) 11754 >= android.os.Build.VERSION_CODES.Q; 11755 if (!isPostQAdmin) { 11756 // Legacy admins assume that they cannot control pre-M apps 11757 if (getTargetSdk(packageName, user.getIdentifier()) 11758 < android.os.Build.VERSION_CODES.M) { 11759 callback.sendResult(null); 11760 return; 11761 } 11762 } 11763 try { 11764 if (!isRuntimePermission(permission)) { 11765 callback.sendResult(null); 11766 return; 11767 } 11768 } catch (NameNotFoundException e) { 11769 throw new RemoteException( 11770 "Cannot check if " + permission + "is a runtime permission", e, false, 11771 true); 11772 } 11773 11774 if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 11775 || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED 11776 || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) { 11777 mInjector.getPermissionControllerManager(user) 11778 .setRuntimePermissionGrantStateByDeviceAdmin(callerPackage, 11779 packageName, permission, grantState, mContext.getMainExecutor(), 11780 (permissionWasSet) -> { 11781 if (isPostQAdmin && !permissionWasSet) { 11782 callback.sendResult(null); 11783 return; 11784 } 11785 11786 final boolean isDelegate = (admin == null); 11787 DevicePolicyEventLogger 11788 .createEvent(DevicePolicyEnums 11789 .SET_PERMISSION_GRANT_STATE) 11790 .setAdmin(callerPackage) 11791 .setStrings(permission) 11792 .setInt(grantState) 11793 .setBoolean(isDelegate) 11794 .write(); 11795 11796 callback.sendResult(Bundle.EMPTY); 11797 }); 11798 } 11799 } catch (SecurityException e) { 11800 Slog.e(LOG_TAG, "Could not set permission grant state", e); 11801 11802 callback.sendResult(null); 11803 } finally { 11804 mInjector.binderRestoreCallingIdentity(ident); 11805 } 11806 } 11807 } 11808 11809 @Override getPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission)11810 public int getPermissionGrantState(ComponentName admin, String callerPackage, 11811 String packageName, String permission) throws RemoteException { 11812 PackageManager packageManager = mInjector.getPackageManager(); 11813 11814 UserHandle user = mInjector.binderGetCallingUserHandle(); 11815 if (!isCallerWithSystemUid()) { 11816 // Ensure the caller is a DO/PO or a permission grant state delegate. 11817 enforceCanManageScope(admin, callerPackage, 11818 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT); 11819 } 11820 synchronized (getLockObject()) { 11821 long ident = mInjector.binderClearCallingIdentity(); 11822 try { 11823 int granted; 11824 if (getTargetSdk(callerPackage, user.getIdentifier()) 11825 < android.os.Build.VERSION_CODES.Q) { 11826 // The per-Q behavior was to not check the app-ops state. 11827 granted = mIPackageManager.checkPermission(permission, packageName, 11828 user.getIdentifier()); 11829 } else { 11830 try { 11831 int uid = packageManager.getPackageUidAsUser(packageName, 11832 user.getIdentifier()); 11833 if (PermissionChecker.checkPermissionForPreflight(mContext, permission, 11834 PermissionChecker.PID_UNKNOWN, uid, packageName) 11835 != PermissionChecker.PERMISSION_GRANTED) { 11836 granted = PackageManager.PERMISSION_DENIED; 11837 } else { 11838 granted = PackageManager.PERMISSION_GRANTED; 11839 } 11840 } catch (NameNotFoundException e) { 11841 throw new RemoteException( 11842 "Cannot check if " + permission + "is a runtime permission", e, 11843 false, true); 11844 } 11845 } 11846 int permFlags = packageManager.getPermissionFlags(permission, packageName, user); 11847 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 11848 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 11849 // Not controlled by policy 11850 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 11851 } else { 11852 // Policy controlled so return result based on permission grant state 11853 return granted == PackageManager.PERMISSION_GRANTED 11854 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 11855 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 11856 } 11857 } finally { 11858 mInjector.binderRestoreCallingIdentity(ident); 11859 } 11860 } 11861 } 11862 isPackageInstalledForUser(String packageName, int userHandle)11863 boolean isPackageInstalledForUser(String packageName, int userHandle) { 11864 try { 11865 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 11866 userHandle); 11867 return (pi != null) && (pi.applicationInfo.flags != 0); 11868 } catch (RemoteException re) { 11869 throw new RuntimeException("Package manager has died", re); 11870 } 11871 } 11872 isRuntimePermission(String permissionName)11873 public boolean isRuntimePermission(String permissionName) throws NameNotFoundException { 11874 final PackageManager packageManager = mInjector.getPackageManager(); 11875 PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0); 11876 return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 11877 == PermissionInfo.PROTECTION_DANGEROUS; 11878 } 11879 11880 @Override isProvisioningAllowed(String action, String packageName)11881 public boolean isProvisioningAllowed(String action, String packageName) { 11882 Preconditions.checkNotNull(packageName); 11883 11884 final int callingUid = mInjector.binderGetCallingUid(); 11885 final long ident = mInjector.binderClearCallingIdentity(); 11886 try { 11887 final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser( 11888 packageName, UserHandle.getUserId(callingUid)); 11889 Preconditions.checkArgument(callingUid == uidForPackage, 11890 "Caller uid doesn't match the one for the provided package."); 11891 } catch (NameNotFoundException e) { 11892 throw new IllegalArgumentException("Invalid package provided " + packageName, e); 11893 } finally { 11894 mInjector.binderRestoreCallingIdentity(ident); 11895 } 11896 11897 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK; 11898 } 11899 11900 @Override checkProvisioningPreCondition(String action, String packageName)11901 public int checkProvisioningPreCondition(String action, String packageName) { 11902 Preconditions.checkNotNull(packageName); 11903 enforceCanManageProfileAndDeviceOwners(); 11904 return checkProvisioningPreConditionSkipPermission(action, packageName); 11905 } 11906 checkProvisioningPreConditionSkipPermission(String action, String packageName)11907 private int checkProvisioningPreConditionSkipPermission(String action, String packageName) { 11908 if (!mHasFeature) { 11909 return CODE_DEVICE_ADMIN_NOT_SUPPORTED; 11910 } 11911 11912 final int callingUserId = mInjector.userHandleGetCallingUserId(); 11913 if (action != null) { 11914 switch (action) { 11915 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 11916 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 11917 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 11918 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 11919 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER: 11920 return checkManagedUserProvisioningPreCondition(callingUserId); 11921 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE: 11922 return checkManagedShareableDeviceProvisioningPreCondition(callingUserId); 11923 } 11924 } 11925 throw new IllegalArgumentException("Unknown provisioning action " + action); 11926 } 11927 11928 /** 11929 * The device owner can only be set before the setup phase of the primary user has completed, 11930 * except for adb command if no accounts or additional users are present on the device. 11931 */ checkDeviceOwnerProvisioningPreConditionLocked(@ullable ComponentName owner, int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb)11932 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 11933 int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) { 11934 if (mOwners.hasDeviceOwner()) { 11935 return CODE_HAS_DEVICE_OWNER; 11936 } 11937 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 11938 return CODE_USER_HAS_PROFILE_OWNER; 11939 } 11940 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 11941 return CODE_USER_NOT_RUNNING; 11942 } 11943 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 11944 return CODE_HAS_PAIRED; 11945 } 11946 if (isAdb) { 11947 // if shell command runs after user setup completed check device status. Otherwise, OK. 11948 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 11949 if (!mInjector.userManagerIsSplitSystemUser()) { 11950 if (mUserManager.getUserCount() > 1) { 11951 return CODE_NONSYSTEM_USER_EXISTS; 11952 } 11953 if (hasIncompatibleAccountsOrNonAdb) { 11954 return CODE_ACCOUNTS_NOT_EMPTY; 11955 } 11956 } else { 11957 // STOPSHIP Do proper check in split user mode 11958 } 11959 } 11960 return CODE_OK; 11961 } else { 11962 if (!mInjector.userManagerIsSplitSystemUser()) { 11963 // In non-split user mode, DO has to be user 0 11964 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 11965 return CODE_NOT_SYSTEM_USER; 11966 } 11967 // In non-split user mode, only provision DO before setup wizard completes 11968 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 11969 return CODE_USER_SETUP_COMPLETED; 11970 } 11971 } else { 11972 // STOPSHIP Do proper check in split user mode 11973 } 11974 return CODE_OK; 11975 } 11976 } 11977 checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId)11978 private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) { 11979 synchronized (getLockObject()) { 11980 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb. 11981 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 11982 deviceOwnerUserId, /* isAdb= */ false, 11983 /* hasIncompatibleAccountsOrNonAdb=*/ true); 11984 } 11985 } 11986 checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId)11987 private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) { 11988 if (!hasFeatureManagedUsers()) { 11989 return CODE_MANAGED_USERS_NOT_SUPPORTED; 11990 } 11991 if (callingUserId == UserHandle.USER_SYSTEM 11992 && mInjector.userManagerIsSplitSystemUser()) { 11993 // Managed-profiles cannot be setup on the system user. 11994 return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 11995 } 11996 if (getProfileOwner(callingUserId) != null) { 11997 // Managed user cannot have a managed profile. 11998 return CODE_USER_HAS_PROFILE_OWNER; 11999 } 12000 12001 final long ident = mInjector.binderClearCallingIdentity(); 12002 try { 12003 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 12004 final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId); 12005 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, 12006 callingUserHandle)) { 12007 // An admin can initiate provisioning if it has set the restriction. 12008 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 12009 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) { 12010 return CODE_ADD_MANAGED_PROFILE_DISALLOWED; 12011 } 12012 } 12013 boolean canRemoveProfile = true; 12014 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 12015 callingUserHandle)) { 12016 // We can remove a profile if the admin itself has set the restriction. 12017 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 12018 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 12019 callingUserId)) { 12020 canRemoveProfile = false; 12021 } 12022 } 12023 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) { 12024 return CODE_CANNOT_ADD_MANAGED_PROFILE; 12025 } 12026 } finally { 12027 mInjector.binderRestoreCallingIdentity(ident); 12028 } 12029 return CODE_OK; 12030 } 12031 getOwnerComponent(String packageName, int userId)12032 private ComponentName getOwnerComponent(String packageName, int userId) { 12033 if (isDeviceOwnerPackage(packageName, userId)) { 12034 return mOwners.getDeviceOwnerComponent(); 12035 } 12036 if (isProfileOwnerPackage(packageName, userId)) { 12037 return mOwners.getProfileOwnerComponent(userId); 12038 } 12039 return null; 12040 } 12041 12042 /** 12043 * Return device owner or profile owner set on a given user. 12044 */ getOwnerComponent(int userId)12045 private @Nullable ComponentName getOwnerComponent(int userId) { 12046 synchronized (getLockObject()) { 12047 if (mOwners.getDeviceOwnerUserId() == userId) { 12048 return mOwners.getDeviceOwnerComponent(); 12049 } 12050 if (mOwners.hasProfileOwner(userId)) { 12051 return mOwners.getProfileOwnerComponent(userId); 12052 } 12053 } 12054 return null; 12055 } 12056 checkManagedUserProvisioningPreCondition(int callingUserId)12057 private int checkManagedUserProvisioningPreCondition(int callingUserId) { 12058 if (!hasFeatureManagedUsers()) { 12059 return CODE_MANAGED_USERS_NOT_SUPPORTED; 12060 } 12061 if (!mInjector.userManagerIsSplitSystemUser()) { 12062 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems. 12063 return CODE_NOT_SYSTEM_USER_SPLIT; 12064 } 12065 if (callingUserId == UserHandle.USER_SYSTEM) { 12066 // System user cannot be a managed user. 12067 return CODE_SYSTEM_USER; 12068 } 12069 if (hasUserSetupCompleted(callingUserId)) { 12070 return CODE_USER_SETUP_COMPLETED; 12071 } 12072 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 12073 return CODE_HAS_PAIRED; 12074 } 12075 return CODE_OK; 12076 } 12077 checkManagedShareableDeviceProvisioningPreCondition(int callingUserId)12078 private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) { 12079 if (!mInjector.userManagerIsSplitSystemUser()) { 12080 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems. 12081 return CODE_NOT_SYSTEM_USER_SPLIT; 12082 } 12083 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 12084 } 12085 hasFeatureManagedUsers()12086 private boolean hasFeatureManagedUsers() { 12087 try { 12088 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 12089 } catch (RemoteException e) { 12090 return false; 12091 } 12092 } 12093 12094 @Override getWifiMacAddress(ComponentName admin)12095 public String getWifiMacAddress(ComponentName admin) { 12096 // Make sure caller has DO. 12097 enforceDeviceOwner(admin); 12098 12099 final long ident = mInjector.binderClearCallingIdentity(); 12100 try { 12101 String[] macAddresses = mInjector.getWifiManager().getFactoryMacAddresses(); 12102 if (macAddresses == null) { 12103 return null; 12104 } 12105 DevicePolicyEventLogger 12106 .createEvent(DevicePolicyEnums.GET_WIFI_MAC_ADDRESS) 12107 .setAdmin(admin) 12108 .write(); 12109 return macAddresses.length > 0 ? macAddresses[0] : null; 12110 } finally { 12111 mInjector.binderRestoreCallingIdentity(ident); 12112 } 12113 } 12114 12115 /** 12116 * Returns the target sdk version number that the given packageName was built for 12117 * in the given user. 12118 */ getTargetSdk(String packageName, int userId)12119 private int getTargetSdk(String packageName, int userId) { 12120 final ApplicationInfo ai; 12121 try { 12122 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 12123 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion; 12124 return targetSdkVersion; 12125 } catch (RemoteException e) { 12126 // Shouldn't happen 12127 return 0; 12128 } 12129 } 12130 12131 @Override isManagedProfile(ComponentName admin)12132 public boolean isManagedProfile(ComponentName admin) { 12133 enforceProfileOrDeviceOwner(admin); 12134 return isManagedProfile(mInjector.userHandleGetCallingUserId()); 12135 } 12136 12137 @Override isSystemOnlyUser(ComponentName admin)12138 public boolean isSystemOnlyUser(ComponentName admin) { 12139 enforceDeviceOwner(admin); 12140 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12141 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM; 12142 } 12143 12144 @Override reboot(ComponentName admin)12145 public void reboot(ComponentName admin) { 12146 Preconditions.checkNotNull(admin); 12147 // Make sure caller has DO. 12148 enforceDeviceOwner(admin); 12149 long ident = mInjector.binderClearCallingIdentity(); 12150 try { 12151 // Make sure there are no ongoing calls on the device. 12152 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 12153 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 12154 } 12155 DevicePolicyEventLogger 12156 .createEvent(DevicePolicyEnums.REBOOT) 12157 .setAdmin(admin) 12158 .write(); 12159 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 12160 } finally { 12161 mInjector.binderRestoreCallingIdentity(ident); 12162 } 12163 } 12164 12165 @Override setShortSupportMessage(@onNull ComponentName who, CharSequence message)12166 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 12167 if (!mHasFeature) { 12168 return; 12169 } 12170 Preconditions.checkNotNull(who, "ComponentName is null"); 12171 final int userHandle = mInjector.userHandleGetCallingUserId(); 12172 synchronized (getLockObject()) { 12173 ActiveAdmin admin = getActiveAdminForUidLocked(who, 12174 mInjector.binderGetCallingUid()); 12175 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 12176 admin.shortSupportMessage = message; 12177 saveSettingsLocked(userHandle); 12178 } 12179 } 12180 DevicePolicyEventLogger 12181 .createEvent(DevicePolicyEnums.SET_SHORT_SUPPORT_MESSAGE) 12182 .setAdmin(who) 12183 .write(); 12184 } 12185 12186 @Override getShortSupportMessage(@onNull ComponentName who)12187 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 12188 if (!mHasFeature) { 12189 return null; 12190 } 12191 Preconditions.checkNotNull(who, "ComponentName is null"); 12192 synchronized (getLockObject()) { 12193 ActiveAdmin admin = getActiveAdminForUidLocked(who, 12194 mInjector.binderGetCallingUid()); 12195 return admin.shortSupportMessage; 12196 } 12197 } 12198 12199 @Override setLongSupportMessage(@onNull ComponentName who, CharSequence message)12200 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 12201 if (!mHasFeature) { 12202 return; 12203 } 12204 Preconditions.checkNotNull(who, "ComponentName is null"); 12205 final int userHandle = mInjector.userHandleGetCallingUserId(); 12206 synchronized (getLockObject()) { 12207 ActiveAdmin admin = getActiveAdminForUidLocked(who, 12208 mInjector.binderGetCallingUid()); 12209 if (!TextUtils.equals(admin.longSupportMessage, message)) { 12210 admin.longSupportMessage = message; 12211 saveSettingsLocked(userHandle); 12212 } 12213 } 12214 DevicePolicyEventLogger 12215 .createEvent(DevicePolicyEnums.SET_LONG_SUPPORT_MESSAGE) 12216 .setAdmin(who) 12217 .write(); 12218 } 12219 12220 @Override getLongSupportMessage(@onNull ComponentName who)12221 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 12222 if (!mHasFeature) { 12223 return null; 12224 } 12225 Preconditions.checkNotNull(who, "ComponentName is null"); 12226 synchronized (getLockObject()) { 12227 ActiveAdmin admin = getActiveAdminForUidLocked(who, 12228 mInjector.binderGetCallingUid()); 12229 return admin.longSupportMessage; 12230 } 12231 } 12232 12233 @Override getShortSupportMessageForUser(@onNull ComponentName who, int userHandle)12234 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 12235 if (!mHasFeature) { 12236 return null; 12237 } 12238 Preconditions.checkNotNull(who, "ComponentName is null"); 12239 if (!isCallerWithSystemUid()) { 12240 throw new SecurityException("Only the system can query support message for user"); 12241 } 12242 synchronized (getLockObject()) { 12243 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 12244 if (admin != null) { 12245 return admin.shortSupportMessage; 12246 } 12247 } 12248 return null; 12249 } 12250 12251 @Override getLongSupportMessageForUser(@onNull ComponentName who, int userHandle)12252 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 12253 if (!mHasFeature) { 12254 return null; 12255 } 12256 Preconditions.checkNotNull(who, "ComponentName is null"); 12257 if (!isCallerWithSystemUid()) { 12258 throw new SecurityException("Only the system can query support message for user"); 12259 } 12260 synchronized (getLockObject()) { 12261 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 12262 if (admin != null) { 12263 return admin.longSupportMessage; 12264 } 12265 } 12266 return null; 12267 } 12268 12269 @Override setOrganizationColor(@onNull ComponentName who, int color)12270 public void setOrganizationColor(@NonNull ComponentName who, int color) { 12271 if (!mHasFeature) { 12272 return; 12273 } 12274 Preconditions.checkNotNull(who, "ComponentName is null"); 12275 final int userHandle = mInjector.userHandleGetCallingUserId(); 12276 enforceManagedProfile(userHandle, "set organization color"); 12277 synchronized (getLockObject()) { 12278 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 12279 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12280 admin.organizationColor = color; 12281 saveSettingsLocked(userHandle); 12282 } 12283 DevicePolicyEventLogger 12284 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_COLOR) 12285 .setAdmin(who) 12286 .write(); 12287 } 12288 12289 @Override setOrganizationColorForUser(int color, int userId)12290 public void setOrganizationColorForUser(int color, int userId) { 12291 if (!mHasFeature) { 12292 return; 12293 } 12294 enforceFullCrossUsersPermission(userId); 12295 enforceManageUsers(); 12296 enforceManagedProfile(userId, "set organization color"); 12297 synchronized (getLockObject()) { 12298 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 12299 admin.organizationColor = color; 12300 saveSettingsLocked(userId); 12301 } 12302 } 12303 12304 @Override getOrganizationColor(@onNull ComponentName who)12305 public int getOrganizationColor(@NonNull ComponentName who) { 12306 if (!mHasFeature) { 12307 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 12308 } 12309 Preconditions.checkNotNull(who, "ComponentName is null"); 12310 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color"); 12311 synchronized (getLockObject()) { 12312 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 12313 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12314 return admin.organizationColor; 12315 } 12316 } 12317 12318 @Override getOrganizationColorForUser(int userHandle)12319 public int getOrganizationColorForUser(int userHandle) { 12320 if (!mHasFeature) { 12321 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 12322 } 12323 enforceFullCrossUsersPermission(userHandle); 12324 enforceManagedProfile(userHandle, "get organization color"); 12325 synchronized (getLockObject()) { 12326 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 12327 return (profileOwner != null) 12328 ? profileOwner.organizationColor 12329 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 12330 } 12331 } 12332 12333 @Override setOrganizationName(@onNull ComponentName who, CharSequence text)12334 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 12335 if (!mHasFeature) { 12336 return; 12337 } 12338 Preconditions.checkNotNull(who, "ComponentName is null"); 12339 final int userHandle = mInjector.userHandleGetCallingUserId(); 12340 12341 synchronized (getLockObject()) { 12342 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 12343 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12344 if (!TextUtils.equals(admin.organizationName, text)) { 12345 admin.organizationName = (text == null || text.length() == 0) 12346 ? null : text.toString(); 12347 saveSettingsLocked(userHandle); 12348 } 12349 } 12350 } 12351 12352 @Override getOrganizationName(@onNull ComponentName who)12353 public CharSequence getOrganizationName(@NonNull ComponentName who) { 12354 if (!mHasFeature) { 12355 return null; 12356 } 12357 Preconditions.checkNotNull(who, "ComponentName is null"); 12358 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name"); 12359 synchronized (getLockObject()) { 12360 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 12361 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12362 return admin.organizationName; 12363 } 12364 } 12365 12366 @Override getDeviceOwnerOrganizationName()12367 public CharSequence getDeviceOwnerOrganizationName() { 12368 if (!mHasFeature) { 12369 return null; 12370 } 12371 enforceDeviceOwnerOrManageUsers(); 12372 synchronized (getLockObject()) { 12373 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 12374 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 12375 } 12376 } 12377 12378 @Override getOrganizationNameForUser(int userHandle)12379 public CharSequence getOrganizationNameForUser(int userHandle) { 12380 if (!mHasFeature) { 12381 return null; 12382 } 12383 enforceFullCrossUsersPermission(userHandle); 12384 enforceManagedProfile(userHandle, "get organization name"); 12385 synchronized (getLockObject()) { 12386 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 12387 return (profileOwner != null) 12388 ? profileOwner.organizationName 12389 : null; 12390 } 12391 } 12392 12393 @Override setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames)12394 public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) { 12395 Preconditions.checkNotNull(who); 12396 Preconditions.checkNotNull(packageNames); 12397 12398 if (!mHasFeature) { 12399 return packageNames; 12400 } 12401 synchronized (getLockObject()) { 12402 final ActiveAdmin admin = getActiveAdminForCallerLocked(who, 12403 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12404 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12405 final long identity = mInjector.binderClearCallingIdentity(); 12406 try { 12407 final List<String> excludedPkgs 12408 = removeInvalidPkgsForMeteredDataRestriction(callingUserId, packageNames); 12409 admin.meteredDisabledPackages = packageNames; 12410 pushMeteredDisabledPackagesLocked(callingUserId); 12411 saveSettingsLocked(callingUserId); 12412 return excludedPkgs; 12413 } finally { 12414 mInjector.binderRestoreCallingIdentity(identity); 12415 } 12416 } 12417 } 12418 removeInvalidPkgsForMeteredDataRestriction( int userId, List<String> pkgNames)12419 private List<String> removeInvalidPkgsForMeteredDataRestriction( 12420 int userId, List<String> pkgNames) { 12421 final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId); 12422 final List<String> excludedPkgs = new ArrayList<>(); 12423 for (int i = pkgNames.size() - 1; i >= 0; --i) { 12424 final String pkgName = pkgNames.get(i); 12425 // If the package is an active admin, don't restrict it. 12426 if (activeAdmins.contains(pkgName)) { 12427 excludedPkgs.add(pkgName); 12428 continue; 12429 } 12430 // If the package doesn't exist, don't restrict it. 12431 try { 12432 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) { 12433 excludedPkgs.add(pkgName); 12434 } 12435 } catch (RemoteException e) { 12436 // Should not happen 12437 } 12438 } 12439 pkgNames.removeAll(excludedPkgs); 12440 return excludedPkgs; 12441 } 12442 12443 @Override getMeteredDataDisabledPackages(ComponentName who)12444 public List<String> getMeteredDataDisabledPackages(ComponentName who) { 12445 Preconditions.checkNotNull(who); 12446 12447 if (!mHasFeature) { 12448 return new ArrayList<>(); 12449 } 12450 synchronized (getLockObject()) { 12451 final ActiveAdmin admin = getActiveAdminForCallerLocked(who, 12452 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12453 return admin.meteredDisabledPackages == null 12454 ? new ArrayList<>() : admin.meteredDisabledPackages; 12455 } 12456 } 12457 12458 @Override isMeteredDataDisabledPackageForUser(ComponentName who, String packageName, int userId)12459 public boolean isMeteredDataDisabledPackageForUser(ComponentName who, 12460 String packageName, int userId) { 12461 Preconditions.checkNotNull(who); 12462 12463 if (!mHasFeature) { 12464 return false; 12465 } 12466 if (!isCallerWithSystemUid()) { 12467 throw new SecurityException( 12468 "Only the system can query restricted pkgs for a specific user"); 12469 } 12470 synchronized (getLockObject()) { 12471 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 12472 if (admin != null && admin.meteredDisabledPackages != null) { 12473 return admin.meteredDisabledPackages.contains(packageName); 12474 } 12475 } 12476 return false; 12477 } 12478 hasGrantProfileOwnerDevcieIdAccessPermission()12479 private boolean hasGrantProfileOwnerDevcieIdAccessPermission() { 12480 return mContext.checkCallingPermission( 12481 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS) 12482 == PackageManager.PERMISSION_GRANTED; 12483 } 12484 12485 @Override grantDeviceIdsAccessToProfileOwner(ComponentName who, int userId)12486 public void grantDeviceIdsAccessToProfileOwner(ComponentName who, int userId) { 12487 // As the caller is the system, it must specify the component name of the profile owner 12488 // as a sanity / safety check. 12489 Preconditions.checkNotNull(who); 12490 12491 if (!mHasFeature) { 12492 return; 12493 } 12494 12495 // Only privileged system apps can grant the Profile Owner access to Device IDs. 12496 if (!(isCallerWithSystemUid() || isAdb() 12497 || hasGrantProfileOwnerDevcieIdAccessPermission())) { 12498 throw new SecurityException( 12499 "Only the system can grant Device IDs access for a profile owner."); 12500 } 12501 12502 if (isAdb() && hasIncompatibleAccountsOrNonAdbNoLock(userId, who)) { 12503 throw new SecurityException( 12504 "Can only be called from ADB if the device has no accounts."); 12505 } 12506 12507 // Grant access under lock. 12508 synchronized (getLockObject()) { 12509 // Sanity check: Make sure that the user has a profile owner and that the specified 12510 // component is the profile owner of that user. 12511 if (!isProfileOwner(who, userId)) { 12512 throw new IllegalArgumentException(String.format( 12513 "Component %s is not a Profile Owner of user %d", 12514 who.flattenToString(), userId)); 12515 } 12516 12517 Slog.i(LOG_TAG, String.format("Granting Device ID access to %s, for user %d", 12518 who.flattenToString(), userId)); 12519 12520 // setProfileOwnerCanAccessDeviceIds will trigger writing of the profile owner 12521 // data, no need to do it manually. 12522 mOwners.setProfileOwnerCanAccessDeviceIds(userId); 12523 } 12524 } 12525 pushMeteredDisabledPackagesLocked(int userId)12526 private void pushMeteredDisabledPackagesLocked(int userId) { 12527 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages( 12528 getMeteredDisabledPackagesLocked(userId), userId); 12529 } 12530 getMeteredDisabledPackagesLocked(int userId)12531 private Set<String> getMeteredDisabledPackagesLocked(int userId) { 12532 final ComponentName who = getOwnerComponent(userId); 12533 final Set<String> restrictedPkgs = new ArraySet<>(); 12534 if (who != null) { 12535 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId); 12536 if (admin != null && admin.meteredDisabledPackages != null) { 12537 restrictedPkgs.addAll(admin.meteredDisabledPackages); 12538 } 12539 } 12540 return restrictedPkgs; 12541 } 12542 12543 @Override setAffiliationIds(ComponentName admin, List<String> ids)12544 public void setAffiliationIds(ComponentName admin, List<String> ids) { 12545 if (!mHasFeature) { 12546 return; 12547 } 12548 if (ids == null) { 12549 throw new IllegalArgumentException("ids must not be null"); 12550 } 12551 for (String id : ids) { 12552 if (TextUtils.isEmpty(id)) { 12553 throw new IllegalArgumentException("ids must not contain empty string"); 12554 } 12555 } 12556 12557 final Set<String> affiliationIds = new ArraySet<>(ids); 12558 final int callingUserId = mInjector.userHandleGetCallingUserId(); 12559 synchronized (getLockObject()) { 12560 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12561 getUserData(callingUserId).mAffiliationIds = affiliationIds; 12562 saveSettingsLocked(callingUserId); 12563 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 12564 // Affiliation ids specified by the device owner are additionally stored in 12565 // UserHandle.USER_SYSTEM's DevicePolicyData. 12566 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 12567 saveSettingsLocked(UserHandle.USER_SYSTEM); 12568 } 12569 12570 // Affiliation status for any user, not just the calling user, might have changed. 12571 // The device owner user will still be affiliated after changing its affiliation ids, 12572 // but as a result of that other users might become affiliated or un-affiliated. 12573 maybePauseDeviceWideLoggingLocked(); 12574 maybeResumeDeviceWideLoggingLocked(); 12575 maybeClearLockTaskPolicyLocked(); 12576 } 12577 } 12578 12579 @Override getAffiliationIds(ComponentName admin)12580 public List<String> getAffiliationIds(ComponentName admin) { 12581 if (!mHasFeature) { 12582 return Collections.emptyList(); 12583 } 12584 12585 Preconditions.checkNotNull(admin); 12586 synchronized (getLockObject()) { 12587 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 12588 return new ArrayList<String>( 12589 getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds); 12590 } 12591 } 12592 12593 @Override isAffiliatedUser()12594 public boolean isAffiliatedUser() { 12595 if (!mHasFeature) { 12596 return false; 12597 } 12598 12599 synchronized (getLockObject()) { 12600 return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId()); 12601 } 12602 } 12603 isUserAffiliatedWithDeviceLocked(int userId)12604 private boolean isUserAffiliatedWithDeviceLocked(int userId) { 12605 if (!mOwners.hasDeviceOwner()) { 12606 return false; 12607 } 12608 if (userId == mOwners.getDeviceOwnerUserId()) { 12609 // The user that the DO is installed on is always affiliated with the device. 12610 return true; 12611 } 12612 if (userId == UserHandle.USER_SYSTEM) { 12613 // The system user is always affiliated in a DO device, even if the DO is set on a 12614 // different user. This could be the case if the DO is set in the primary user 12615 // of a split user device. 12616 return true; 12617 } 12618 12619 final ComponentName profileOwner = getProfileOwner(userId); 12620 if (profileOwner == null) { 12621 return false; 12622 } 12623 12624 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 12625 final Set<String> deviceAffiliationIds = 12626 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 12627 for (String id : userAffiliationIds) { 12628 if (deviceAffiliationIds.contains(id)) { 12629 return true; 12630 } 12631 } 12632 return false; 12633 } 12634 areAllUsersAffiliatedWithDeviceLocked()12635 private boolean areAllUsersAffiliatedWithDeviceLocked() { 12636 final long ident = mInjector.binderClearCallingIdentity(); 12637 try { 12638 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 12639 for (int i = 0; i < userInfos.size(); i++) { 12640 int userId = userInfos.get(i).id; 12641 if (!isUserAffiliatedWithDeviceLocked(userId)) { 12642 Slog.d(LOG_TAG, "User id " + userId + " not affiliated."); 12643 return false; 12644 } 12645 } 12646 } finally { 12647 mInjector.binderRestoreCallingIdentity(ident); 12648 } 12649 12650 return true; 12651 } 12652 12653 @Override setSecurityLoggingEnabled(ComponentName admin, boolean enabled)12654 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) { 12655 if (!mHasFeature) { 12656 return; 12657 } 12658 Preconditions.checkNotNull(admin); 12659 12660 synchronized (getLockObject()) { 12661 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12662 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 12663 return; 12664 } 12665 mInjector.securityLogSetLoggingEnabledProperty(enabled); 12666 if (enabled) { 12667 mSecurityLogMonitor.start(); 12668 maybePauseDeviceWideLoggingLocked(); 12669 } else { 12670 mSecurityLogMonitor.stop(); 12671 } 12672 } 12673 DevicePolicyEventLogger 12674 .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED) 12675 .setAdmin(admin) 12676 .setBoolean(enabled) 12677 .write(); 12678 } 12679 12680 @Override isSecurityLoggingEnabled(ComponentName admin)12681 public boolean isSecurityLoggingEnabled(ComponentName admin) { 12682 if (!mHasFeature) { 12683 return false; 12684 } 12685 12686 synchronized (getLockObject()) { 12687 if (!isCallerWithSystemUid()) { 12688 Preconditions.checkNotNull(admin); 12689 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 12690 } 12691 return mInjector.securityLogGetLoggingEnabledProperty(); 12692 } 12693 } 12694 recordSecurityLogRetrievalTime()12695 private void recordSecurityLogRetrievalTime() { 12696 synchronized (getLockObject()) { 12697 final long currentTime = System.currentTimeMillis(); 12698 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 12699 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 12700 policyData.mLastSecurityLogRetrievalTime = currentTime; 12701 saveSettingsLocked(UserHandle.USER_SYSTEM); 12702 } 12703 } 12704 } 12705 12706 @Override retrievePreRebootSecurityLogs(ComponentName admin)12707 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) { 12708 if (!mHasFeature) { 12709 return null; 12710 } 12711 12712 Preconditions.checkNotNull(admin); 12713 ensureDeviceOwnerAndAllUsersAffiliated(admin); 12714 12715 DevicePolicyEventLogger 12716 .createEvent(DevicePolicyEnums.RETRIEVE_PRE_REBOOT_SECURITY_LOGS) 12717 .setAdmin(admin) 12718 .write(); 12719 12720 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs) 12721 || !mInjector.securityLogGetLoggingEnabledProperty()) { 12722 return null; 12723 } 12724 12725 recordSecurityLogRetrievalTime(); 12726 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 12727 try { 12728 SecurityLog.readPreviousEvents(output); 12729 return new ParceledListSlice<SecurityEvent>(output); 12730 } catch (IOException e) { 12731 Slog.w(LOG_TAG, "Fail to read previous events" , e); 12732 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 12733 } 12734 } 12735 12736 @Override retrieveSecurityLogs(ComponentName admin)12737 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) { 12738 if (!mHasFeature) { 12739 return null; 12740 } 12741 12742 Preconditions.checkNotNull(admin); 12743 ensureDeviceOwnerAndAllUsersAffiliated(admin); 12744 12745 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 12746 return null; 12747 } 12748 12749 recordSecurityLogRetrievalTime(); 12750 12751 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 12752 DevicePolicyEventLogger 12753 .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS) 12754 .setAdmin(admin) 12755 .write(); 12756 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 12757 } 12758 12759 @Override forceSecurityLogs()12760 public long forceSecurityLogs() { 12761 enforceShell("forceSecurityLogs"); 12762 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 12763 throw new IllegalStateException("logging is not available"); 12764 } 12765 return mSecurityLogMonitor.forceLogs(); 12766 } 12767 enforceCanManageDeviceAdmin()12768 private void enforceCanManageDeviceAdmin() { 12769 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS, 12770 null); 12771 } 12772 enforceCanManageProfileAndDeviceOwners()12773 private void enforceCanManageProfileAndDeviceOwners() { 12774 mContext.enforceCallingOrSelfPermission( 12775 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 12776 } 12777 enforceCallerSystemUserHandle()12778 private void enforceCallerSystemUserHandle() { 12779 final int callingUid = mInjector.binderGetCallingUid(); 12780 final int userId = UserHandle.getUserId(callingUid); 12781 if (userId != UserHandle.USER_SYSTEM) { 12782 throw new SecurityException("Caller has to be in user 0"); 12783 } 12784 } 12785 12786 @Override isUninstallInQueue(final String packageName)12787 public boolean isUninstallInQueue(final String packageName) { 12788 enforceCanManageDeviceAdmin(); 12789 final int userId = mInjector.userHandleGetCallingUserId(); 12790 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 12791 synchronized (getLockObject()) { 12792 return mPackagesToRemove.contains(packageUserPair); 12793 } 12794 } 12795 12796 @Override uninstallPackageWithActiveAdmins(final String packageName)12797 public void uninstallPackageWithActiveAdmins(final String packageName) { 12798 enforceCanManageDeviceAdmin(); 12799 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 12800 12801 final int userId = mInjector.userHandleGetCallingUserId(); 12802 12803 enforceUserUnlocked(userId); 12804 12805 final ComponentName profileOwner = getProfileOwner(userId); 12806 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 12807 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 12808 } 12809 12810 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 12811 if (getDeviceOwnerUserId() == userId && deviceOwner != null 12812 && packageName.equals(deviceOwner.getPackageName())) { 12813 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 12814 } 12815 12816 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 12817 synchronized (getLockObject()) { 12818 mPackagesToRemove.add(packageUserPair); 12819 } 12820 12821 // All active admins on the user. 12822 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 12823 12824 // Active admins in the target package. 12825 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 12826 if (allActiveAdmins != null) { 12827 for (ComponentName activeAdmin : allActiveAdmins) { 12828 if (packageName.equals(activeAdmin.getPackageName())) { 12829 packageActiveAdmins.add(activeAdmin); 12830 removeActiveAdmin(activeAdmin, userId); 12831 } 12832 } 12833 } 12834 if (packageActiveAdmins.size() == 0) { 12835 startUninstallIntent(packageName, userId); 12836 } else { 12837 mHandler.postDelayed(new Runnable() { 12838 @Override 12839 public void run() { 12840 for (ComponentName activeAdmin : packageActiveAdmins) { 12841 removeAdminArtifacts(activeAdmin, userId); 12842 } 12843 startUninstallIntent(packageName, userId); 12844 } 12845 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 12846 } 12847 } 12848 12849 @Override isDeviceProvisioned()12850 public boolean isDeviceProvisioned() { 12851 enforceManageUsers(); 12852 synchronized (getLockObject()) { 12853 return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete; 12854 } 12855 } 12856 isCurrentUserDemo()12857 private boolean isCurrentUserDemo() { 12858 if (UserManager.isDeviceInDemoMode(mContext)) { 12859 final int userId = mInjector.userHandleGetCallingUserId(); 12860 final long callingIdentity = mInjector.binderClearCallingIdentity(); 12861 try { 12862 return mUserManager.getUserInfo(userId).isDemo(); 12863 } finally { 12864 mInjector.binderRestoreCallingIdentity(callingIdentity); 12865 } 12866 } 12867 return false; 12868 } 12869 removePackageIfRequired(final String packageName, final int userId)12870 private void removePackageIfRequired(final String packageName, final int userId) { 12871 if (!packageHasActiveAdmins(packageName, userId)) { 12872 // Will not do anything if uninstall was not requested or was already started. 12873 startUninstallIntent(packageName, userId); 12874 } 12875 } 12876 startUninstallIntent(final String packageName, final int userId)12877 private void startUninstallIntent(final String packageName, final int userId) { 12878 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 12879 synchronized (getLockObject()) { 12880 if (!mPackagesToRemove.contains(packageUserPair)) { 12881 // Do nothing if uninstall was not requested or was already started. 12882 return; 12883 } 12884 mPackagesToRemove.remove(packageUserPair); 12885 } 12886 try { 12887 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) { 12888 // Package does not exist. Nothing to do. 12889 return; 12890 } 12891 } catch (RemoteException re) { 12892 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info"); 12893 } 12894 12895 try { // force stop the package before uninstalling 12896 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 12897 } catch (RemoteException re) { 12898 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 12899 } 12900 final Uri packageURI = Uri.parse("package:" + packageName); 12901 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 12902 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 12903 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 12904 } 12905 12906 /** 12907 * Removes the admin from the policy. Ideally called after the admin's 12908 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 12909 * 12910 * @param adminReceiver The admin to remove 12911 * @param userHandle The user for which this admin has to be removed. 12912 */ removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle)12913 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 12914 synchronized (getLockObject()) { 12915 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 12916 if (admin == null) { 12917 return; 12918 } 12919 final DevicePolicyData policy = getUserData(userHandle); 12920 final boolean doProxyCleanup = admin.info.usesPolicy( 12921 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 12922 policy.mAdminList.remove(admin); 12923 policy.mAdminMap.remove(adminReceiver); 12924 validatePasswordOwnerLocked(policy); 12925 if (doProxyCleanup) { 12926 resetGlobalProxyLocked(policy); 12927 } 12928 pushActiveAdminPackagesLocked(userHandle); 12929 pushMeteredDisabledPackagesLocked(userHandle); 12930 saveSettingsLocked(userHandle); 12931 updateMaximumTimeToLockLocked(userHandle); 12932 policy.mRemovingAdmins.remove(adminReceiver); 12933 12934 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 12935 } 12936 // The removed admin might have disabled camera, so update user 12937 // restrictions. 12938 pushUserRestrictions(userHandle); 12939 } 12940 12941 @Override setDeviceProvisioningConfigApplied()12942 public void setDeviceProvisioningConfigApplied() { 12943 enforceManageUsers(); 12944 synchronized (getLockObject()) { 12945 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 12946 policy.mDeviceProvisioningConfigApplied = true; 12947 saveSettingsLocked(UserHandle.USER_SYSTEM); 12948 } 12949 } 12950 12951 @Override isDeviceProvisioningConfigApplied()12952 public boolean isDeviceProvisioningConfigApplied() { 12953 enforceManageUsers(); 12954 synchronized (getLockObject()) { 12955 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 12956 return policy.mDeviceProvisioningConfigApplied; 12957 } 12958 } 12959 12960 /** 12961 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 12962 * 12963 * It's added for testing only. Please use this API carefully if it's used by other system app 12964 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 12965 * apps. 12966 */ 12967 @Override forceUpdateUserSetupComplete()12968 public void forceUpdateUserSetupComplete() { 12969 enforceCanManageProfileAndDeviceOwners(); 12970 enforceCallerSystemUserHandle(); 12971 // no effect if it's called from user build 12972 if (!mInjector.isBuildDebuggable()) { 12973 return; 12974 } 12975 final int userId = UserHandle.USER_SYSTEM; 12976 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 12977 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 12978 DevicePolicyData policy = getUserData(userId); 12979 policy.mUserSetupComplete = isUserCompleted; 12980 synchronized (getLockObject()) { 12981 saveSettingsLocked(userId); 12982 } 12983 } 12984 12985 @Override setBackupServiceEnabled(ComponentName admin, boolean enabled)12986 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 12987 if (!mHasFeature) { 12988 return; 12989 } 12990 Preconditions.checkNotNull(admin); 12991 enforceProfileOrDeviceOwner(admin); 12992 int userId = mInjector.userHandleGetCallingUserId(); 12993 toggleBackupServiceActive(userId, enabled); 12994 } 12995 12996 @Override isBackupServiceEnabled(ComponentName admin)12997 public boolean isBackupServiceEnabled(ComponentName admin) { 12998 Preconditions.checkNotNull(admin); 12999 if (!mHasFeature) { 13000 return true; 13001 } 13002 13003 enforceProfileOrDeviceOwner(admin); 13004 synchronized (getLockObject()) { 13005 try { 13006 IBackupManager ibm = mInjector.getIBackupManager(); 13007 return ibm != null && ibm.isBackupServiceActive( 13008 mInjector.userHandleGetCallingUserId()); 13009 } catch (RemoteException e) { 13010 throw new IllegalStateException("Failed requesting backup service state.", e); 13011 } 13012 } 13013 } 13014 13015 @Override bindDeviceAdminServiceAsUser( @onNull ComponentName admin, @NonNull IApplicationThread caller, @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId)13016 public boolean bindDeviceAdminServiceAsUser( 13017 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 13018 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 13019 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 13020 if (!mHasFeature) { 13021 return false; 13022 } 13023 Preconditions.checkNotNull(admin); 13024 Preconditions.checkNotNull(caller); 13025 Preconditions.checkNotNull(serviceIntent); 13026 Preconditions.checkArgument( 13027 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 13028 "Service intent must be explicit (with a package name or component): " 13029 + serviceIntent); 13030 Preconditions.checkNotNull(connection); 13031 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 13032 "target user id must be different from the calling user id"); 13033 13034 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 13035 throw new SecurityException("Not allowed to bind to target user id"); 13036 } 13037 13038 final String targetPackage; 13039 synchronized (getLockObject()) { 13040 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 13041 } 13042 13043 final long callingIdentity = mInjector.binderClearCallingIdentity(); 13044 try { 13045 // Validate and sanitize the incoming service intent. 13046 final Intent sanitizedIntent = 13047 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 13048 if (sanitizedIntent == null) { 13049 // Fail, cannot lookup the target service. 13050 return false; 13051 } 13052 // Ask ActivityManager to bind it. Notice that we are binding the service with the 13053 // caller app instead of DevicePolicyManagerService. 13054 return mInjector.getIActivityManager().bindService( 13055 caller, activtiyToken, serviceIntent, 13056 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 13057 connection, flags, mContext.getOpPackageName(), 13058 targetUserId) != 0; 13059 } catch (RemoteException ex) { 13060 // Same process, should not happen. 13061 } finally { 13062 mInjector.binderRestoreCallingIdentity(callingIdentity); 13063 } 13064 13065 // Failed to bind. 13066 return false; 13067 } 13068 13069 @Override getBindDeviceAdminTargetUsers(@onNull ComponentName admin)13070 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 13071 if (!mHasFeature) { 13072 return Collections.emptyList(); 13073 } 13074 Preconditions.checkNotNull(admin); 13075 13076 synchronized (getLockObject()) { 13077 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 13078 13079 final int callingUserId = mInjector.userHandleGetCallingUserId(); 13080 final long callingIdentity = mInjector.binderClearCallingIdentity(); 13081 try { 13082 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 13083 if (!isDeviceOwner(admin, callingUserId)) { 13084 // Profile owners can only bind to the device owner. 13085 if (canUserBindToDeviceOwnerLocked(callingUserId)) { 13086 targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId())); 13087 } 13088 } else { 13089 // Caller is the device owner: Look for profile owners that it can bind to. 13090 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 13091 for (int i = 0; i < userInfos.size(); i++) { 13092 final int userId = userInfos.get(i).id; 13093 if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) { 13094 targetUsers.add(UserHandle.of(userId)); 13095 } 13096 } 13097 } 13098 13099 return targetUsers; 13100 } finally { 13101 mInjector.binderRestoreCallingIdentity(callingIdentity); 13102 } 13103 } 13104 } 13105 canUserBindToDeviceOwnerLocked(int userId)13106 private boolean canUserBindToDeviceOwnerLocked(int userId) { 13107 // There has to be a device owner, under another user id. 13108 if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) { 13109 return false; 13110 } 13111 13112 // The user must have a profile owner that belongs to the same package as the device owner. 13113 if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals( 13114 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) { 13115 return false; 13116 } 13117 13118 // The user must be affiliated. 13119 return isUserAffiliatedWithDeviceLocked(userId); 13120 } 13121 13122 /** 13123 * Return true if a given user has any accounts that'll prevent installing a device or profile 13124 * owner {@code owner}. 13125 * - If the user has no accounts, then return false. 13126 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 13127 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 13128 * ..._DISALLOWED, return true. 13129 * - Otherwise return false. 13130 * 13131 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used 13132 * when the caller is not ADB. 13133 * 13134 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 13135 */ hasIncompatibleAccountsOrNonAdbNoLock( int userId, @Nullable ComponentName owner)13136 private boolean hasIncompatibleAccountsOrNonAdbNoLock( 13137 int userId, @Nullable ComponentName owner) { 13138 if (!isAdb()) { 13139 return true; 13140 } 13141 wtfIfInLock(); 13142 13143 final long token = mInjector.binderClearCallingIdentity(); 13144 try { 13145 final AccountManager am = AccountManager.get(mContext); 13146 final Account accounts[] = am.getAccountsAsUser(userId); 13147 if (accounts.length == 0) { 13148 return false; 13149 } 13150 synchronized (getLockObject()) { 13151 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 13152 Log.w(LOG_TAG, 13153 "Non test-only owner can't be installed with existing accounts."); 13154 return true; 13155 } 13156 } 13157 13158 final String[] feature_allow = 13159 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 13160 final String[] feature_disallow = 13161 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 13162 13163 boolean compatible = true; 13164 for (Account account : accounts) { 13165 if (hasAccountFeatures(am, account, feature_disallow)) { 13166 Log.e(LOG_TAG, account + " has " + feature_disallow[0]); 13167 compatible = false; 13168 break; 13169 } 13170 if (!hasAccountFeatures(am, account, feature_allow)) { 13171 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]); 13172 compatible = false; 13173 break; 13174 } 13175 } 13176 if (compatible) { 13177 Log.w(LOG_TAG, "All accounts are compatible"); 13178 } else { 13179 Log.e(LOG_TAG, "Found incompatible accounts"); 13180 } 13181 return !compatible; 13182 } finally { 13183 mInjector.binderRestoreCallingIdentity(token); 13184 } 13185 } 13186 hasAccountFeatures(AccountManager am, Account account, String[] features)13187 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 13188 try { 13189 return am.hasFeatures(account, features, null, null).getResult(); 13190 } catch (Exception e) { 13191 Log.w(LOG_TAG, "Failed to get account feature", e); 13192 return false; 13193 } 13194 } 13195 isAdb()13196 private boolean isAdb() { 13197 final int callingUid = mInjector.binderGetCallingUid(); 13198 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 13199 } 13200 13201 @Override setNetworkLoggingEnabled(@ullable ComponentName admin, @NonNull String packageName, boolean enabled)13202 public void setNetworkLoggingEnabled(@Nullable ComponentName admin, 13203 @NonNull String packageName, boolean enabled) { 13204 if (!mHasFeature) { 13205 return; 13206 } 13207 synchronized (getLockObject()) { 13208 enforceCanManageScope(admin, packageName, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 13209 DELEGATION_NETWORK_LOGGING); 13210 13211 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 13212 // already in the requested state 13213 return; 13214 } 13215 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 13216 deviceOwner.isNetworkLoggingEnabled = enabled; 13217 if (!enabled) { 13218 deviceOwner.numNetworkLoggingNotifications = 0; 13219 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 13220 } 13221 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 13222 13223 setNetworkLoggingActiveInternal(enabled); 13224 13225 final boolean isDelegate = (admin == null); 13226 DevicePolicyEventLogger 13227 .createEvent(DevicePolicyEnums.SET_NETWORK_LOGGING_ENABLED) 13228 .setAdmin(packageName) 13229 .setBoolean(isDelegate) 13230 .setInt(enabled ? 1 : 0) 13231 .write(); 13232 } 13233 } 13234 setNetworkLoggingActiveInternal(boolean active)13235 private void setNetworkLoggingActiveInternal(boolean active) { 13236 synchronized (getLockObject()) { 13237 final long callingIdentity = mInjector.binderClearCallingIdentity(); 13238 try { 13239 if (active) { 13240 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal()); 13241 if (!mNetworkLogger.startNetworkLogging()) { 13242 mNetworkLogger = null; 13243 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging" 13244 + " service not being available yet."); 13245 } 13246 maybePauseDeviceWideLoggingLocked(); 13247 sendNetworkLoggingNotificationLocked(); 13248 } else { 13249 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 13250 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 13251 + " service not being available yet."); 13252 } 13253 mNetworkLogger = null; 13254 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING); 13255 } 13256 } finally { 13257 mInjector.binderRestoreCallingIdentity(callingIdentity); 13258 } 13259 } 13260 } 13261 13262 @Override forceNetworkLogs()13263 public long forceNetworkLogs() { 13264 enforceShell("forceNetworkLogs"); 13265 synchronized (getLockObject()) { 13266 if (!isNetworkLoggingEnabledInternalLocked()) { 13267 throw new IllegalStateException("logging is not available"); 13268 } 13269 if (mNetworkLogger != null) { 13270 final long ident = mInjector.binderClearCallingIdentity(); 13271 try { 13272 return mNetworkLogger.forceBatchFinalization(); 13273 } finally { 13274 mInjector.binderRestoreCallingIdentity(ident); 13275 } 13276 } 13277 return 0; 13278 } 13279 } 13280 13281 /** Pauses security and network logging if there are unaffiliated users on the device */ 13282 @GuardedBy("getLockObject()") maybePauseDeviceWideLoggingLocked()13283 private void maybePauseDeviceWideLoggingLocked() { 13284 if (!areAllUsersAffiliatedWithDeviceLocked()) { 13285 Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be " 13286 + "paused if enabled."); 13287 mSecurityLogMonitor.pause(); 13288 if (mNetworkLogger != null) { 13289 mNetworkLogger.pause(); 13290 } 13291 } 13292 } 13293 13294 /** Resumes security and network logging (if they are enabled) if all users are affiliated */ 13295 @GuardedBy("getLockObject()") maybeResumeDeviceWideLoggingLocked()13296 private void maybeResumeDeviceWideLoggingLocked() { 13297 if (areAllUsersAffiliatedWithDeviceLocked()) { 13298 final long ident = mInjector.binderClearCallingIdentity(); 13299 try { 13300 mSecurityLogMonitor.resume(); 13301 if (mNetworkLogger != null) { 13302 mNetworkLogger.resume(); 13303 } 13304 } finally { 13305 mInjector.binderRestoreCallingIdentity(ident); 13306 } 13307 } 13308 } 13309 13310 /** Deletes any security and network logs that might have been collected so far */ 13311 @GuardedBy("getLockObject()") discardDeviceWideLogsLocked()13312 private void discardDeviceWideLogsLocked() { 13313 mSecurityLogMonitor.discardLogs(); 13314 if (mNetworkLogger != null) { 13315 mNetworkLogger.discardLogs(); 13316 } 13317 // TODO: We should discard pre-boot security logs here too, as otherwise those 13318 // logs (which might contain data from the user just removed) will be 13319 // available after next boot. 13320 } 13321 13322 @Override isNetworkLoggingEnabled(@ullable ComponentName admin, @NonNull String packageName)13323 public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin, 13324 @NonNull String packageName) { 13325 if (!mHasFeature) { 13326 return false; 13327 } 13328 synchronized (getLockObject()) { 13329 enforceCanManageScopeOrCheckPermission(admin, packageName, 13330 DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, DELEGATION_NETWORK_LOGGING, 13331 android.Manifest.permission.MANAGE_USERS); 13332 return isNetworkLoggingEnabledInternalLocked(); 13333 } 13334 } 13335 isNetworkLoggingEnabledInternalLocked()13336 private boolean isNetworkLoggingEnabledInternalLocked() { 13337 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 13338 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled; 13339 } 13340 13341 /* 13342 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 13343 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 13344 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 13345 * 13346 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 13347 */ 13348 @Override retrieveNetworkLogs(@ullable ComponentName admin, @NonNull String packageName, long batchToken)13349 public List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin, 13350 @NonNull String packageName, long batchToken) { 13351 if (!mHasFeature) { 13352 return null; 13353 } 13354 enforceCanManageScope(admin, packageName, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 13355 DELEGATION_NETWORK_LOGGING); 13356 ensureAllUsersAffiliated(); 13357 13358 synchronized (getLockObject()) { 13359 if (mNetworkLogger == null 13360 || !isNetworkLoggingEnabledInternalLocked()) { 13361 return null; 13362 } 13363 final boolean isDelegate = (admin == null); 13364 DevicePolicyEventLogger 13365 .createEvent(DevicePolicyEnums.RETRIEVE_NETWORK_LOGS) 13366 .setAdmin(packageName) 13367 .setBoolean(isDelegate) 13368 .write(); 13369 13370 final long currentTime = System.currentTimeMillis(); 13371 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 13372 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 13373 policyData.mLastNetworkLogsRetrievalTime = currentTime; 13374 saveSettingsLocked(UserHandle.USER_SYSTEM); 13375 } 13376 return mNetworkLogger.retrieveLogs(batchToken); 13377 } 13378 } 13379 sendNetworkLoggingNotificationLocked()13380 private void sendNetworkLoggingNotificationLocked() { 13381 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 13382 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 13383 return; 13384 } 13385 if (deviceOwner.numNetworkLoggingNotifications >= 13386 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 13387 return; 13388 } 13389 final long now = System.currentTimeMillis(); 13390 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 13391 return; 13392 } 13393 deviceOwner.numNetworkLoggingNotifications++; 13394 if (deviceOwner.numNetworkLoggingNotifications 13395 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 13396 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 13397 } else { 13398 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 13399 } 13400 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 13401 intent.setPackage("com.android.systemui"); 13402 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0, 13403 UserHandle.CURRENT); 13404 Notification notification = 13405 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 13406 .setSmallIcon(R.drawable.ic_info_outline) 13407 .setContentTitle(mContext.getString(R.string.network_logging_notification_title)) 13408 .setContentText(mContext.getString(R.string.network_logging_notification_text)) 13409 .setTicker(mContext.getString(R.string.network_logging_notification_title)) 13410 .setShowWhen(true) 13411 .setContentIntent(pendingIntent) 13412 .setStyle(new Notification.BigTextStyle() 13413 .bigText(mContext.getString(R.string.network_logging_notification_text))) 13414 .build(); 13415 mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification); 13416 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 13417 } 13418 13419 /** 13420 * Return the package name of owner in a given user. 13421 */ getOwnerPackageNameForUserLocked(int userId)13422 private String getOwnerPackageNameForUserLocked(int userId) { 13423 return mOwners.getDeviceOwnerUserId() == userId 13424 ? mOwners.getDeviceOwnerPackageName() 13425 : mOwners.getProfileOwnerPackage(userId); 13426 } 13427 13428 /** 13429 * @param rawIntent Original service intent specified by caller. It must be explicit. 13430 * @param expectedPackageName The expected package name of the resolved service. 13431 * @return Intent that have component explicitly set. {@code null} if no service is resolved 13432 * with the given intent. 13433 * @throws SecurityException if the intent is resolved to an invalid service. 13434 */ createCrossUserServiceIntent( @onNull Intent rawIntent, @NonNull String expectedPackageName, @UserIdInt int targetUserId)13435 private Intent createCrossUserServiceIntent( 13436 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 13437 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 13438 ResolveInfo info = mIPackageManager.resolveService( 13439 rawIntent, 13440 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 13441 0, // flags 13442 targetUserId); 13443 if (info == null || info.serviceInfo == null) { 13444 Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent 13445 + " or user " + targetUserId + " is not running"); 13446 return null; 13447 } 13448 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 13449 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 13450 } 13451 // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release. 13452 if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) { 13453 throw new SecurityException( 13454 "Service must be protected by BIND_DEVICE_ADMIN permission"); 13455 } 13456 // It is the system server to bind the service, it would be extremely dangerous if it 13457 // can be exploited to bind any service. Set the component explicitly to make sure we 13458 // do not bind anything accidentally. 13459 rawIntent.setComponent(info.serviceInfo.getComponentName()); 13460 return rawIntent; 13461 } 13462 13463 @Override getLastSecurityLogRetrievalTime()13464 public long getLastSecurityLogRetrievalTime() { 13465 enforceDeviceOwnerOrManageUsers(); 13466 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 13467 } 13468 13469 @Override getLastBugReportRequestTime()13470 public long getLastBugReportRequestTime() { 13471 enforceDeviceOwnerOrManageUsers(); 13472 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 13473 } 13474 13475 @Override getLastNetworkLogRetrievalTime()13476 public long getLastNetworkLogRetrievalTime() { 13477 enforceDeviceOwnerOrManageUsers(); 13478 return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime; 13479 } 13480 13481 @Override setResetPasswordToken(ComponentName admin, byte[] token)13482 public boolean setResetPasswordToken(ComponentName admin, byte[] token) { 13483 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 13484 return false; 13485 } 13486 if (token == null || token.length < 32) { 13487 throw new IllegalArgumentException("token must be at least 32-byte long"); 13488 } 13489 synchronized (getLockObject()) { 13490 final int userHandle = mInjector.userHandleGetCallingUserId(); 13491 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 13492 13493 DevicePolicyData policy = getUserData(userHandle); 13494 long ident = mInjector.binderClearCallingIdentity(); 13495 try { 13496 if (policy.mPasswordTokenHandle != 0) { 13497 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle); 13498 } 13499 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, 13500 userHandle, /*EscrowTokenStateChangeCallback*/ null); 13501 saveSettingsLocked(userHandle); 13502 return policy.mPasswordTokenHandle != 0; 13503 } finally { 13504 mInjector.binderRestoreCallingIdentity(ident); 13505 } 13506 } 13507 } 13508 13509 @Override clearResetPasswordToken(ComponentName admin)13510 public boolean clearResetPasswordToken(ComponentName admin) { 13511 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 13512 return false; 13513 } 13514 synchronized (getLockObject()) { 13515 final int userHandle = mInjector.userHandleGetCallingUserId(); 13516 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 13517 13518 DevicePolicyData policy = getUserData(userHandle); 13519 if (policy.mPasswordTokenHandle != 0) { 13520 long ident = mInjector.binderClearCallingIdentity(); 13521 try { 13522 boolean result = mLockPatternUtils.removeEscrowToken( 13523 policy.mPasswordTokenHandle, userHandle); 13524 policy.mPasswordTokenHandle = 0; 13525 saveSettingsLocked(userHandle); 13526 return result; 13527 } finally { 13528 mInjector.binderRestoreCallingIdentity(ident); 13529 } 13530 } 13531 } 13532 return false; 13533 } 13534 13535 @Override isResetPasswordTokenActive(ComponentName admin)13536 public boolean isResetPasswordTokenActive(ComponentName admin) { 13537 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 13538 return false; 13539 } 13540 synchronized (getLockObject()) { 13541 final int userHandle = mInjector.userHandleGetCallingUserId(); 13542 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 13543 13544 DevicePolicyData policy = getUserData(userHandle); 13545 if (policy.mPasswordTokenHandle != 0) { 13546 long ident = mInjector.binderClearCallingIdentity(); 13547 try { 13548 return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle, 13549 userHandle); 13550 } finally { 13551 mInjector.binderRestoreCallingIdentity(ident); 13552 } 13553 } 13554 } 13555 return false; 13556 } 13557 13558 @Override resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, int flags)13559 public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, 13560 int flags) { 13561 if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) { 13562 return false; 13563 } 13564 Preconditions.checkNotNull(token); 13565 synchronized (getLockObject()) { 13566 final int userHandle = mInjector.userHandleGetCallingUserId(); 13567 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 13568 13569 DevicePolicyData policy = getUserData(userHandle); 13570 if (policy.mPasswordTokenHandle != 0) { 13571 final String password = passwordOrNull != null ? passwordOrNull : ""; 13572 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token, 13573 flags, mInjector.binderGetCallingUid(), userHandle); 13574 } else { 13575 Slog.w(LOG_TAG, "No saved token handle"); 13576 } 13577 } 13578 return false; 13579 } 13580 13581 @Override isCurrentInputMethodSetByOwner()13582 public boolean isCurrentInputMethodSetByOwner() { 13583 enforceProfileOwnerOrSystemUser(); 13584 return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet; 13585 } 13586 13587 @Override getOwnerInstalledCaCerts(@onNull UserHandle user)13588 public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) { 13589 final int userId = user.getIdentifier(); 13590 enforceProfileOwnerOrFullCrossUsersPermission(userId); 13591 synchronized (getLockObject()) { 13592 return new StringParceledListSlice( 13593 new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts)); 13594 } 13595 } 13596 13597 @Override clearApplicationUserData(ComponentName admin, String packageName, IPackageDataObserver callback)13598 public void clearApplicationUserData(ComponentName admin, String packageName, 13599 IPackageDataObserver callback) { 13600 Preconditions.checkNotNull(admin, "ComponentName is null"); 13601 Preconditions.checkNotNull(packageName, "packageName is null"); 13602 Preconditions.checkNotNull(callback, "callback is null"); 13603 enforceProfileOrDeviceOwner(admin); 13604 final int userId = UserHandle.getCallingUserId(); 13605 13606 long ident = mInjector.binderClearCallingIdentity(); 13607 try { 13608 ActivityManager.getService().clearApplicationUserData(packageName, false, callback, 13609 userId); 13610 } catch(RemoteException re) { 13611 // Same process, should not happen. 13612 } catch (SecurityException se) { 13613 // This can happen e.g. for device admin packages, do not throw out the exception, 13614 // because callers have no means to know beforehand for which packages this might 13615 // happen. If so, we send back that removal failed. 13616 Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName, 13617 se); 13618 try { 13619 callback.onRemoveCompleted(packageName, false); 13620 } catch (RemoteException re) { 13621 // Caller is no longer available, ignore 13622 } 13623 } finally { 13624 mInjector.binderRestoreCallingIdentity(ident); 13625 } 13626 } 13627 13628 @Override setLogoutEnabled(ComponentName admin, boolean enabled)13629 public void setLogoutEnabled(ComponentName admin, boolean enabled) { 13630 if (!mHasFeature) { 13631 return; 13632 } 13633 Preconditions.checkNotNull(admin); 13634 13635 synchronized (getLockObject()) { 13636 ActiveAdmin deviceOwner = 13637 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 13638 13639 if (deviceOwner.isLogoutEnabled == enabled) { 13640 // already in the requested state 13641 return; 13642 } 13643 deviceOwner.isLogoutEnabled = enabled; 13644 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 13645 } 13646 } 13647 13648 @Override isLogoutEnabled()13649 public boolean isLogoutEnabled() { 13650 if (!mHasFeature) { 13651 return false; 13652 } 13653 synchronized (getLockObject()) { 13654 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 13655 return (deviceOwner != null) && deviceOwner.isLogoutEnabled; 13656 } 13657 } 13658 13659 @Override getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)13660 public List<String> getDisallowedSystemApps(ComponentName admin, int userId, 13661 String provisioningAction) throws RemoteException { 13662 enforceCanManageProfileAndDeviceOwners(); 13663 return new ArrayList<>( 13664 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction)); 13665 } 13666 13667 @Override transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)13668 public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target, 13669 @Nullable PersistableBundle bundle) { 13670 if (!mHasFeature) { 13671 return; 13672 } 13673 13674 Preconditions.checkNotNull(admin, "Admin cannot be null."); 13675 Preconditions.checkNotNull(target, "Target cannot be null."); 13676 13677 enforceProfileOrDeviceOwner(admin); 13678 13679 if (admin.equals(target)) { 13680 throw new IllegalArgumentException("Provided administrator and target are " 13681 + "the same object."); 13682 } 13683 13684 if (admin.getPackageName().equals(target.getPackageName())) { 13685 throw new IllegalArgumentException("Provided administrator and target have " 13686 + "the same package name."); 13687 } 13688 13689 final int callingUserId = mInjector.userHandleGetCallingUserId(); 13690 final DevicePolicyData policy = getUserData(callingUserId); 13691 final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId, 13692 /* throwForMissingPermission= */ true); 13693 checkActiveAdminPrecondition(target, incomingDeviceInfo, policy); 13694 if (!incomingDeviceInfo.supportsTransferOwnership()) { 13695 throw new IllegalArgumentException("Provided target does not support " 13696 + "ownership transfer."); 13697 } 13698 13699 final long id = mInjector.binderClearCallingIdentity(); 13700 String ownerType = null; 13701 try { 13702 synchronized (getLockObject()) { 13703 /* 13704 * We must ensure the whole process is atomic to prevent the device from ending up 13705 * in an invalid state (e.g. no active admin). This could happen if the device 13706 * is rebooted or work mode is turned off mid-transfer. 13707 * In order to guarantee atomicity, we: 13708 * 13709 * 1. Save an atomic journal file describing the transfer process 13710 * 2. Perform the transfer itself 13711 * 3. Delete the journal file 13712 * 13713 * That way if the journal file exists on device boot, we know that the transfer 13714 * must be reverted back to the original administrator. This logic is implemented in 13715 * revertTransferOwnershipIfNecessaryLocked. 13716 * */ 13717 if (bundle == null) { 13718 bundle = new PersistableBundle(); 13719 } 13720 if (isProfileOwner(admin, callingUserId)) { 13721 ownerType = ADMIN_TYPE_PROFILE_OWNER; 13722 prepareTransfer(admin, target, bundle, callingUserId, 13723 ADMIN_TYPE_PROFILE_OWNER); 13724 transferProfileOwnershipLocked(admin, target, callingUserId); 13725 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 13726 getTransferOwnershipAdminExtras(bundle), callingUserId); 13727 postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId); 13728 if (isUserAffiliatedWithDeviceLocked(callingUserId)) { 13729 notifyAffiliatedProfileTransferOwnershipComplete(callingUserId); 13730 } 13731 } else if (isDeviceOwner(admin, callingUserId)) { 13732 ownerType = ADMIN_TYPE_DEVICE_OWNER; 13733 prepareTransfer(admin, target, bundle, callingUserId, 13734 ADMIN_TYPE_DEVICE_OWNER); 13735 transferDeviceOwnershipLocked(admin, target, callingUserId); 13736 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE, 13737 getTransferOwnershipAdminExtras(bundle)); 13738 postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId); 13739 } 13740 } 13741 } finally { 13742 mInjector.binderRestoreCallingIdentity(id); 13743 } 13744 DevicePolicyEventLogger 13745 .createEvent(DevicePolicyEnums.TRANSFER_OWNERSHIP) 13746 .setAdmin(admin) 13747 .setStrings(target.getPackageName(), ownerType) 13748 .write(); 13749 } 13750 prepareTransfer(ComponentName admin, ComponentName target, PersistableBundle bundle, int callingUserId, String adminType)13751 private void prepareTransfer(ComponentName admin, ComponentName target, 13752 PersistableBundle bundle, int callingUserId, String adminType) { 13753 saveTransferOwnershipBundleLocked(bundle, callingUserId); 13754 mTransferOwnershipMetadataManager.saveMetadataFile( 13755 new TransferOwnershipMetadataManager.Metadata(admin, target, 13756 callingUserId, adminType)); 13757 } 13758 postTransfer(String broadcast, int callingUserId)13759 private void postTransfer(String broadcast, int callingUserId) { 13760 deleteTransferOwnershipMetadataFileLocked(); 13761 sendOwnerChangedBroadcast(broadcast, callingUserId); 13762 } 13763 notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId)13764 private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) { 13765 final Bundle extras = new Bundle(); 13766 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId)); 13767 sendDeviceOwnerCommand( 13768 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras); 13769 } 13770 13771 /** 13772 * Transfers the profile owner for user with id profileOwnerUserId from admin to target. 13773 */ transferProfileOwnershipLocked(ComponentName admin, ComponentName target, int profileOwnerUserId)13774 private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target, 13775 int profileOwnerUserId) { 13776 transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId); 13777 mOwners.transferProfileOwner(target, profileOwnerUserId); 13778 Slog.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId); 13779 mOwners.writeProfileOwner(profileOwnerUserId); 13780 mDeviceAdminServiceController.startServiceForOwner( 13781 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner"); 13782 } 13783 13784 /** 13785 * Transfers the device owner for user with id userId from admin to target. 13786 */ transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId)13787 private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) { 13788 transferActiveAdminUncheckedLocked(target, admin, userId); 13789 mOwners.transferDeviceOwnership(target); 13790 Slog.i(LOG_TAG, "Device owner set: " + target + " on user " + userId); 13791 mOwners.writeDeviceOwner(); 13792 mDeviceAdminServiceController.startServiceForOwner( 13793 target.getPackageName(), userId, "transfer-device-owner"); 13794 } 13795 getTransferOwnershipAdminExtras(PersistableBundle bundle)13796 private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) { 13797 Bundle extras = new Bundle(); 13798 if (bundle != null) { 13799 extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle); 13800 } 13801 return extras; 13802 } 13803 13804 @Override setStartUserSessionMessage( ComponentName admin, CharSequence startUserSessionMessage)13805 public void setStartUserSessionMessage( 13806 ComponentName admin, CharSequence startUserSessionMessage) { 13807 if (!mHasFeature) { 13808 return; 13809 } 13810 Preconditions.checkNotNull(admin); 13811 13812 final String startUserSessionMessageString = 13813 startUserSessionMessage != null ? startUserSessionMessage.toString() : null; 13814 13815 synchronized (getLockObject()) { 13816 final ActiveAdmin deviceOwner = 13817 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 13818 13819 if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) { 13820 return; 13821 } 13822 deviceOwner.startUserSessionMessage = startUserSessionMessageString; 13823 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 13824 } 13825 13826 mInjector.getActivityManagerInternal() 13827 .setSwitchingFromSystemUserMessage(startUserSessionMessageString); 13828 } 13829 13830 @Override setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage)13831 public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) { 13832 if (!mHasFeature) { 13833 return; 13834 } 13835 Preconditions.checkNotNull(admin); 13836 13837 final String endUserSessionMessageString = 13838 endUserSessionMessage != null ? endUserSessionMessage.toString() : null; 13839 13840 synchronized (getLockObject()) { 13841 final ActiveAdmin deviceOwner = 13842 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 13843 13844 if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) { 13845 return; 13846 } 13847 deviceOwner.endUserSessionMessage = endUserSessionMessageString; 13848 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 13849 } 13850 13851 mInjector.getActivityManagerInternal() 13852 .setSwitchingToSystemUserMessage(endUserSessionMessageString); 13853 } 13854 13855 @Override getStartUserSessionMessage(ComponentName admin)13856 public String getStartUserSessionMessage(ComponentName admin) { 13857 if (!mHasFeature) { 13858 return null; 13859 } 13860 Preconditions.checkNotNull(admin); 13861 13862 synchronized (getLockObject()) { 13863 final ActiveAdmin deviceOwner = 13864 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 13865 return deviceOwner.startUserSessionMessage; 13866 } 13867 } 13868 13869 @Override getEndUserSessionMessage(ComponentName admin)13870 public String getEndUserSessionMessage(ComponentName admin) { 13871 if (!mHasFeature) { 13872 return null; 13873 } 13874 Preconditions.checkNotNull(admin); 13875 13876 synchronized (getLockObject()) { 13877 final ActiveAdmin deviceOwner = 13878 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 13879 return deviceOwner.endUserSessionMessage; 13880 } 13881 } 13882 deleteTransferOwnershipMetadataFileLocked()13883 private void deleteTransferOwnershipMetadataFileLocked() { 13884 mTransferOwnershipMetadataManager.deleteMetadataFile(); 13885 } 13886 13887 @Override 13888 @Nullable getTransferOwnershipBundle()13889 public PersistableBundle getTransferOwnershipBundle() { 13890 synchronized (getLockObject()) { 13891 final int callingUserId = mInjector.userHandleGetCallingUserId(); 13892 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 13893 final File bundleFile = new File( 13894 mInjector.environmentGetUserSystemDirectory(callingUserId), 13895 TRANSFER_OWNERSHIP_PARAMETERS_XML); 13896 if (!bundleFile.exists()) { 13897 return null; 13898 } 13899 try (FileInputStream stream = new FileInputStream(bundleFile)) { 13900 XmlPullParser parser = Xml.newPullParser(); 13901 parser.setInput(stream, null); 13902 parser.next(); 13903 return PersistableBundle.restoreFromXml(parser); 13904 } catch (IOException | XmlPullParserException | IllegalArgumentException e) { 13905 Slog.e(LOG_TAG, "Caught exception while trying to load the " 13906 + "owner transfer parameters from file " + bundleFile, e); 13907 return null; 13908 } 13909 } 13910 } 13911 13912 @Override addOverrideApn(@onNull ComponentName who, @NonNull ApnSetting apnSetting)13913 public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) { 13914 if (!mHasFeature || !mHasTelephonyFeature) { 13915 return -1; 13916 } 13917 Preconditions.checkNotNull(who, "ComponentName is null in addOverrideApn"); 13918 Preconditions.checkNotNull(apnSetting, "ApnSetting is null in addOverrideApn"); 13919 enforceDeviceOwner(who); 13920 13921 int operatedId = -1; 13922 Uri resultUri; 13923 final long id = mInjector.binderClearCallingIdentity(); 13924 try { 13925 resultUri = mContext.getContentResolver().insert(DPC_URI, apnSetting.toContentValues()); 13926 } finally { 13927 mInjector.binderRestoreCallingIdentity(id); 13928 } 13929 if (resultUri != null) { 13930 try { 13931 operatedId = Integer.parseInt(resultUri.getLastPathSegment()); 13932 } catch (NumberFormatException e) { 13933 Slog.e(LOG_TAG, "Failed to parse inserted override APN id.", e); 13934 } 13935 } 13936 13937 return operatedId; 13938 } 13939 13940 @Override updateOverrideApn(@onNull ComponentName who, int apnId, @NonNull ApnSetting apnSetting)13941 public boolean updateOverrideApn(@NonNull ComponentName who, int apnId, 13942 @NonNull ApnSetting apnSetting) { 13943 if (!mHasFeature || !mHasTelephonyFeature) { 13944 return false; 13945 } 13946 Preconditions.checkNotNull(who, "ComponentName is null in updateOverrideApn"); 13947 Preconditions.checkNotNull(apnSetting, "ApnSetting is null in updateOverrideApn"); 13948 enforceDeviceOwner(who); 13949 13950 if (apnId < 0) { 13951 return false; 13952 } 13953 final long id = mInjector.binderClearCallingIdentity(); 13954 try { 13955 return mContext.getContentResolver().update( 13956 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), 13957 apnSetting.toContentValues(), null, null) > 0; 13958 } finally { 13959 mInjector.binderRestoreCallingIdentity(id); 13960 } 13961 } 13962 13963 @Override removeOverrideApn(@onNull ComponentName who, int apnId)13964 public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) { 13965 if (!mHasFeature || !mHasTelephonyFeature) { 13966 return false; 13967 } 13968 Preconditions.checkNotNull(who, "ComponentName is null in removeOverrideApn"); 13969 enforceDeviceOwner(who); 13970 13971 return removeOverrideApnUnchecked(apnId); 13972 } 13973 removeOverrideApnUnchecked(int apnId)13974 private boolean removeOverrideApnUnchecked(int apnId) { 13975 if(apnId < 0) { 13976 return false; 13977 } 13978 int numDeleted = 0; 13979 final long id = mInjector.binderClearCallingIdentity(); 13980 try { 13981 numDeleted = mContext.getContentResolver().delete( 13982 Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null); 13983 } finally { 13984 mInjector.binderRestoreCallingIdentity(id); 13985 } 13986 return numDeleted > 0; 13987 } 13988 13989 @Override getOverrideApns(@onNull ComponentName who)13990 public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) { 13991 if (!mHasFeature || !mHasTelephonyFeature) { 13992 return Collections.emptyList(); 13993 } 13994 Preconditions.checkNotNull(who, "ComponentName is null in getOverrideApns"); 13995 enforceDeviceOwner(who); 13996 13997 return getOverrideApnsUnchecked(); 13998 } 13999 getOverrideApnsUnchecked()14000 private List<ApnSetting> getOverrideApnsUnchecked() { 14001 final Cursor cursor; 14002 final long id = mInjector.binderClearCallingIdentity(); 14003 try { 14004 cursor = mContext.getContentResolver().query(DPC_URI, null, null, null, null); 14005 } finally { 14006 mInjector.binderRestoreCallingIdentity(id); 14007 } 14008 14009 if (cursor == null) { 14010 return Collections.emptyList(); 14011 } 14012 try { 14013 List<ApnSetting> apnList = new ArrayList<ApnSetting>(); 14014 cursor.moveToPosition(-1); 14015 while (cursor.moveToNext()) { 14016 ApnSetting apn = ApnSetting.makeApnSetting(cursor); 14017 apnList.add(apn); 14018 } 14019 return apnList; 14020 } finally { 14021 cursor.close(); 14022 } 14023 } 14024 14025 @Override setOverrideApnsEnabled(@onNull ComponentName who, boolean enabled)14026 public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) { 14027 if (!mHasFeature || !mHasTelephonyFeature) { 14028 return; 14029 } 14030 Preconditions.checkNotNull(who, "ComponentName is null in setOverrideApnEnabled"); 14031 enforceDeviceOwner(who); 14032 14033 setOverrideApnsEnabledUnchecked(enabled); 14034 } 14035 setOverrideApnsEnabledUnchecked(boolean enabled)14036 private void setOverrideApnsEnabledUnchecked(boolean enabled) { 14037 ContentValues value = new ContentValues(); 14038 value.put(ENFORCE_KEY, enabled); 14039 final long id = mInjector.binderClearCallingIdentity(); 14040 try { 14041 mContext.getContentResolver().update( 14042 ENFORCE_MANAGED_URI, value, null, null); 14043 } finally { 14044 mInjector.binderRestoreCallingIdentity(id); 14045 } 14046 } 14047 14048 @Override isOverrideApnEnabled(@onNull ComponentName who)14049 public boolean isOverrideApnEnabled(@NonNull ComponentName who) { 14050 if (!mHasFeature || !mHasTelephonyFeature) { 14051 return false; 14052 } 14053 Preconditions.checkNotNull(who, "ComponentName is null in isOverrideApnEnabled"); 14054 enforceDeviceOwner(who); 14055 14056 Cursor enforceCursor; 14057 final long id = mInjector.binderClearCallingIdentity(); 14058 try { 14059 enforceCursor = mContext.getContentResolver().query( 14060 ENFORCE_MANAGED_URI, null, null, null, null); 14061 } finally { 14062 mInjector.binderRestoreCallingIdentity(id); 14063 } 14064 14065 if (enforceCursor == null) { 14066 return false; 14067 } 14068 try { 14069 if (enforceCursor.moveToFirst()) { 14070 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1; 14071 } 14072 } catch (IllegalArgumentException e) { 14073 Slog.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain " 14074 + "correct info.", e); 14075 } finally { 14076 enforceCursor.close(); 14077 } 14078 return false; 14079 } 14080 14081 @VisibleForTesting saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId)14082 void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) { 14083 final File parametersFile = new File( 14084 mInjector.environmentGetUserSystemDirectory(userId), 14085 TRANSFER_OWNERSHIP_PARAMETERS_XML); 14086 final AtomicFile atomicFile = new AtomicFile(parametersFile); 14087 FileOutputStream stream = null; 14088 try { 14089 stream = atomicFile.startWrite(); 14090 final XmlSerializer serializer = new FastXmlSerializer(); 14091 serializer.setOutput(stream, StandardCharsets.UTF_8.name()); 14092 serializer.startDocument(null, true); 14093 serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 14094 bundle.saveToXml(serializer); 14095 serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE); 14096 serializer.endDocument(); 14097 atomicFile.finishWrite(stream); 14098 } catch (IOException | XmlPullParserException e) { 14099 Slog.e(LOG_TAG, "Caught exception while trying to save the " 14100 + "owner transfer parameters to file " + parametersFile, e); 14101 parametersFile.delete(); 14102 atomicFile.failWrite(stream); 14103 } 14104 } 14105 deleteTransferOwnershipBundleLocked(int userId)14106 void deleteTransferOwnershipBundleLocked(int userId) { 14107 final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId), 14108 TRANSFER_OWNERSHIP_PARAMETERS_XML); 14109 parametersFile.delete(); 14110 } 14111 maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent, PasswordMetrics metrics)14112 private void maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent, 14113 PasswordMetrics metrics) { 14114 if (SecurityLog.isLoggingEnabled()) { 14115 final int affectedUserId = parent ? getProfileParentId(userId) : userId; 14116 SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(), 14117 userId, affectedUserId, metrics.length, metrics.quality, metrics.letters, 14118 metrics.nonLetter, metrics.numeric, metrics.upperCase, metrics.lowerCase, 14119 metrics.symbols); 14120 } 14121 } 14122 getManagedProvisioningPackage(Context context)14123 private static String getManagedProvisioningPackage(Context context) { 14124 return context.getResources().getString(R.string.config_managed_provisioning_package); 14125 } 14126 putPrivateDnsSettings(@ullable String mode, @Nullable String host)14127 private void putPrivateDnsSettings(@Nullable String mode, @Nullable String host) { 14128 // Set Private DNS settings using system permissions, as apps cannot write 14129 // to global settings. 14130 long origId = mInjector.binderClearCallingIdentity(); 14131 try { 14132 mInjector.settingsGlobalPutString(PRIVATE_DNS_MODE, mode); 14133 mInjector.settingsGlobalPutString(PRIVATE_DNS_SPECIFIER, host); 14134 } finally { 14135 mInjector.binderRestoreCallingIdentity(origId); 14136 } 14137 } 14138 14139 @Override setGlobalPrivateDns(@onNull ComponentName who, int mode, String privateDnsHost)14140 public int setGlobalPrivateDns(@NonNull ComponentName who, int mode, String privateDnsHost) { 14141 if (!mHasFeature) { 14142 return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING; 14143 } 14144 14145 Preconditions.checkNotNull(who, "ComponentName is null"); 14146 enforceDeviceOwner(who); 14147 14148 final int returnCode; 14149 14150 switch (mode) { 14151 case PRIVATE_DNS_MODE_OPPORTUNISTIC: 14152 if (!TextUtils.isEmpty(privateDnsHost)) { 14153 throw new IllegalArgumentException( 14154 "Host provided for opportunistic mode, but is not needed."); 14155 } 14156 putPrivateDnsSettings(ConnectivityManager.PRIVATE_DNS_MODE_OPPORTUNISTIC, null); 14157 return PRIVATE_DNS_SET_NO_ERROR; 14158 case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME: 14159 if (TextUtils.isEmpty(privateDnsHost) 14160 || !NetworkUtils.isWeaklyValidatedHostname(privateDnsHost)) { 14161 throw new IllegalArgumentException( 14162 String.format("Provided hostname %s is not valid", privateDnsHost)); 14163 } 14164 14165 // Connectivity check will have been performed in the DevicePolicyManager before 14166 // the call here. 14167 putPrivateDnsSettings( 14168 ConnectivityManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, 14169 privateDnsHost); 14170 return PRIVATE_DNS_SET_NO_ERROR; 14171 default: 14172 throw new IllegalArgumentException( 14173 String.format("Provided mode, %d, is not a valid mode.", mode)); 14174 } 14175 } 14176 14177 @Override getGlobalPrivateDnsMode(@onNull ComponentName who)14178 public int getGlobalPrivateDnsMode(@NonNull ComponentName who) { 14179 if (!mHasFeature) { 14180 return PRIVATE_DNS_MODE_UNKNOWN; 14181 } 14182 14183 Preconditions.checkNotNull(who, "ComponentName is null"); 14184 enforceDeviceOwner(who); 14185 String currentMode = mInjector.settingsGlobalGetString(PRIVATE_DNS_MODE); 14186 if (currentMode == null) { 14187 currentMode = ConnectivityManager.PRIVATE_DNS_DEFAULT_MODE_FALLBACK; 14188 } 14189 switch (currentMode) { 14190 case ConnectivityManager.PRIVATE_DNS_MODE_OFF: 14191 return PRIVATE_DNS_MODE_OFF; 14192 case ConnectivityManager.PRIVATE_DNS_MODE_OPPORTUNISTIC: 14193 return PRIVATE_DNS_MODE_OPPORTUNISTIC; 14194 case ConnectivityManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME: 14195 return PRIVATE_DNS_MODE_PROVIDER_HOSTNAME; 14196 } 14197 14198 return PRIVATE_DNS_MODE_UNKNOWN; 14199 } 14200 14201 @Override getGlobalPrivateDnsHost(@onNull ComponentName who)14202 public String getGlobalPrivateDnsHost(@NonNull ComponentName who) { 14203 if (!mHasFeature) { 14204 return null; 14205 } 14206 14207 Preconditions.checkNotNull(who, "ComponentName is null"); 14208 enforceDeviceOwner(who); 14209 14210 return mInjector.settingsGlobalGetString(PRIVATE_DNS_SPECIFIER); 14211 } 14212 14213 @Override installUpdateFromFile(ComponentName admin, ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback)14214 public void installUpdateFromFile(ComponentName admin, 14215 ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback) { 14216 DevicePolicyEventLogger 14217 .createEvent(DevicePolicyEnums.INSTALL_SYSTEM_UPDATE) 14218 .setAdmin(admin) 14219 .setBoolean(isDeviceAB()) 14220 .write(); 14221 enforceDeviceOwner(admin); 14222 final long id = mInjector.binderClearCallingIdentity(); 14223 try { 14224 UpdateInstaller updateInstaller; 14225 if (isDeviceAB()) { 14226 updateInstaller = new AbUpdateInstaller( 14227 mContext, updateFileDescriptor, callback, mInjector, mConstants); 14228 } else { 14229 updateInstaller = new NonAbUpdateInstaller( 14230 mContext, updateFileDescriptor, callback, mInjector, mConstants); 14231 } 14232 updateInstaller.startInstallUpdate(); 14233 } finally { 14234 mInjector.binderRestoreCallingIdentity(id); 14235 } 14236 } 14237 isDeviceAB()14238 private boolean isDeviceAB() { 14239 return "true".equalsIgnoreCase(android.os.SystemProperties 14240 .get(AB_DEVICE_KEY, "")); 14241 } 14242 14243 @Override setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames)14244 public void setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames) { 14245 if (!mHasFeature) { 14246 return; 14247 } 14248 Preconditions.checkNotNull(who, "ComponentName is null"); 14249 14250 synchronized (getLockObject()) { 14251 final ActiveAdmin admin = getActiveAdminForCallerLocked( 14252 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 14253 admin.mCrossProfileCalendarPackages = packageNames; 14254 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 14255 } 14256 DevicePolicyEventLogger 14257 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALENDAR_PACKAGES) 14258 .setAdmin(who) 14259 .setStrings(packageNames == null ? null 14260 : packageNames.toArray(new String[packageNames.size()])) 14261 .write(); 14262 } 14263 14264 @Override getCrossProfileCalendarPackages(ComponentName who)14265 public List<String> getCrossProfileCalendarPackages(ComponentName who) { 14266 if (!mHasFeature) { 14267 return Collections.emptyList(); 14268 } 14269 Preconditions.checkNotNull(who, "ComponentName is null"); 14270 14271 synchronized (getLockObject()) { 14272 final ActiveAdmin admin = getActiveAdminForCallerLocked( 14273 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 14274 return admin.mCrossProfileCalendarPackages; 14275 } 14276 } 14277 14278 @Override isPackageAllowedToAccessCalendarForUser(String packageName, int userHandle)14279 public boolean isPackageAllowedToAccessCalendarForUser(String packageName, 14280 int userHandle) { 14281 if (!mHasFeature) { 14282 return false; 14283 } 14284 Preconditions.checkStringNotEmpty(packageName, "Package name is null or empty"); 14285 14286 enforceCrossUsersPermission(userHandle); 14287 synchronized (getLockObject()) { 14288 if (mInjector.settingsSecureGetIntForUser( 14289 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userHandle) == 0) { 14290 return false; 14291 } 14292 final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 14293 if (admin != null) { 14294 if (admin.mCrossProfileCalendarPackages == null) { 14295 return true; 14296 } 14297 return admin.mCrossProfileCalendarPackages.contains(packageName); 14298 } 14299 } 14300 return false; 14301 } 14302 14303 @Override getCrossProfileCalendarPackagesForUser(int userHandle)14304 public List<String> getCrossProfileCalendarPackagesForUser(int userHandle) { 14305 if (!mHasFeature) { 14306 return Collections.emptyList(); 14307 } 14308 enforceCrossUsersPermission(userHandle); 14309 synchronized (getLockObject()) { 14310 final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 14311 if (admin != null) { 14312 return admin.mCrossProfileCalendarPackages; 14313 } 14314 } 14315 return Collections.emptyList(); 14316 } 14317 14318 @Override isManagedKiosk()14319 public boolean isManagedKiosk() { 14320 if (!mHasFeature) { 14321 return false; 14322 } 14323 enforceManageUsers(); 14324 long id = mInjector.binderClearCallingIdentity(); 14325 try { 14326 return isManagedKioskInternal(); 14327 } catch (RemoteException e) { 14328 throw new IllegalStateException(e); 14329 } finally { 14330 mInjector.binderRestoreCallingIdentity(id); 14331 } 14332 } 14333 14334 @Override isUnattendedManagedKiosk()14335 public boolean isUnattendedManagedKiosk() { 14336 if (!mHasFeature) { 14337 return false; 14338 } 14339 enforceManageUsers(); 14340 long id = mInjector.binderClearCallingIdentity(); 14341 try { 14342 return isManagedKioskInternal() 14343 && getPowerManagerInternal().wasDeviceIdleFor(UNATTENDED_MANAGED_KIOSK_MS); 14344 } catch (RemoteException e) { 14345 throw new IllegalStateException(e); 14346 } finally { 14347 mInjector.binderRestoreCallingIdentity(id); 14348 } 14349 } 14350 14351 /** 14352 * Returns whether the device is currently being used as a publicly-accessible dedicated device. 14353 * Assumes that feature checks and permission checks have already been performed, and that the 14354 * calling identity has been cleared. 14355 */ isManagedKioskInternal()14356 private boolean isManagedKioskInternal() throws RemoteException { 14357 return mOwners.hasDeviceOwner() 14358 && mInjector.getIActivityManager().getLockTaskModeState() 14359 == ActivityManager.LOCK_TASK_MODE_LOCKED 14360 && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO) 14361 && !deviceHasKeyguard() 14362 && !inEphemeralUserSession(); 14363 } 14364 isLockTaskFeatureEnabled(int lockTaskFeature)14365 private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException { 14366 int lockTaskFeatures = 14367 getUserData(mInjector.getIActivityManager().getCurrentUser().id).mLockTaskFeatures; 14368 return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature; 14369 } 14370 deviceHasKeyguard()14371 private boolean deviceHasKeyguard() { 14372 for (UserInfo userInfo : mUserManager.getUsers()) { 14373 if (mLockPatternUtils.isSecure(userInfo.id)) { 14374 return true; 14375 } 14376 } 14377 return false; 14378 } 14379 inEphemeralUserSession()14380 private boolean inEphemeralUserSession() { 14381 for (UserInfo userInfo : mUserManager.getUsers()) { 14382 if (mInjector.getUserManager().isUserEphemeral(userInfo.id)) { 14383 return true; 14384 } 14385 } 14386 return false; 14387 } 14388 getPowerManagerInternal()14389 private PowerManagerInternal getPowerManagerInternal() { 14390 return mInjector.getPowerManagerInternal(); 14391 } 14392 14393 @Override startViewCalendarEventInManagedProfile(String packageName, long eventId, long start, long end, boolean allDay, int flags)14394 public boolean startViewCalendarEventInManagedProfile(String packageName, long eventId, 14395 long start, long end, boolean allDay, int flags) { 14396 if (!mHasFeature) { 14397 return false; 14398 } 14399 Preconditions.checkStringNotEmpty(packageName, "Package name is empty"); 14400 14401 final int callingUid = mInjector.binderGetCallingUid(); 14402 final int callingUserId = mInjector.userHandleGetCallingUserId(); 14403 if (!isCallingFromPackage(packageName, callingUid)) { 14404 throw new SecurityException("Input package name doesn't align with actual " 14405 + "calling package."); 14406 } 14407 final long identity = mInjector.binderClearCallingIdentity(); 14408 try { 14409 final int workProfileUserId = getManagedUserId(callingUserId); 14410 if (workProfileUserId < 0) { 14411 return false; 14412 } 14413 if (!isPackageAllowedToAccessCalendarForUser(packageName, workProfileUserId)) { 14414 Log.d(LOG_TAG, String.format("Package %s is not allowed to access cross-profile" 14415 + "calendar APIs", packageName)); 14416 return false; 14417 } 14418 final Intent intent = new Intent( 14419 CalendarContract.ACTION_VIEW_MANAGED_PROFILE_CALENDAR_EVENT); 14420 intent.setPackage(packageName); 14421 intent.putExtra(CalendarContract.EXTRA_EVENT_ID, eventId); 14422 intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start); 14423 intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end); 14424 intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay); 14425 intent.setFlags(flags); 14426 try { 14427 mContext.startActivityAsUser(intent, UserHandle.of(workProfileUserId)); 14428 } catch (ActivityNotFoundException e) { 14429 Log.e(LOG_TAG, "View event activity not found", e); 14430 return false; 14431 } 14432 } finally { 14433 mInjector.binderRestoreCallingIdentity(identity); 14434 } 14435 return true; 14436 } 14437 isCallingFromPackage(String packageName, int callingUid)14438 private boolean isCallingFromPackage(String packageName, int callingUid) { 14439 try { 14440 final int packageUid = mInjector.getPackageManager().getPackageUidAsUser( 14441 packageName, UserHandle.getUserId(callingUid)); 14442 return packageUid == callingUid; 14443 } catch (NameNotFoundException e) { 14444 Log.d(LOG_TAG, "Calling package not found", e); 14445 return false; 14446 } 14447 } 14448 loadConstants()14449 private DevicePolicyConstants loadConstants() { 14450 return DevicePolicyConstants.loadFromString( 14451 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS)); 14452 } 14453 } 14454