1 /* 2 * Copyright (C) 2020 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 com.android.server.devicepolicy.DevicePolicyManagerService.DEFAULT_KEEP_PROFILES_RUNNING_FLAG; 20 21 import android.annotation.NonNull; 22 import android.annotation.Nullable; 23 import android.annotation.UserIdInt; 24 import android.app.admin.DeviceAdminInfo; 25 import android.app.admin.DevicePolicyManager; 26 import android.content.ComponentName; 27 import android.os.FileUtils; 28 import android.os.PersistableBundle; 29 import android.os.UserHandle; 30 import android.util.ArrayMap; 31 import android.util.ArraySet; 32 import android.util.DebugUtils; 33 import android.util.IndentingPrintWriter; 34 import android.util.Xml; 35 36 import com.android.internal.util.JournaledFile; 37 import com.android.internal.util.XmlUtils; 38 import com.android.modules.utils.TypedXmlPullParser; 39 import com.android.modules.utils.TypedXmlSerializer; 40 import com.android.server.utils.Slogf; 41 42 import org.xmlpull.v1.XmlPullParser; 43 import org.xmlpull.v1.XmlPullParserException; 44 45 import java.io.File; 46 import java.io.FileInputStream; 47 import java.io.FileNotFoundException; 48 import java.io.FileOutputStream; 49 import java.io.IOException; 50 import java.util.ArrayList; 51 import java.util.List; 52 import java.util.Set; 53 import java.util.function.Function; 54 55 class DevicePolicyData { 56 private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate"; 57 private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component"; 58 private static final String TAG_LOCK_TASK_FEATURES = "lock-task-features"; 59 private static final String TAG_STATUS_BAR = "statusbar"; 60 private static final String TAG_APPS_SUSPENDED = "apps-suspended"; 61 private static final String TAG_SECONDARY_LOCK_SCREEN = "secondary-lock-screen"; 62 private static final String TAG_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 63 "do-not-ask-credentials-on-boot"; 64 private static final String TAG_AFFILIATION_ID = "affiliation-id"; 65 private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval"; 66 private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request"; 67 private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval"; 68 private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending"; 69 private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set"; 70 private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert"; 71 private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle"; 72 private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token"; 73 private static final String TAG_PROTECTED_PACKAGES = "protected-packages"; 74 private static final String TAG_BYPASS_ROLE_QUALIFICATIONS = "bypass-role-qualifications"; 75 private static final String TAG_KEEP_PROFILES_RUNNING = "keep-profiles-running"; 76 private static final String ATTR_VALUE = "value"; 77 private static final String ATTR_ALIAS = "alias"; 78 private static final String ATTR_ID = "id"; 79 private static final String ATTR_PERMISSION_PROVIDER = "permission-provider"; 80 private static final String ATTR_NAME = "name"; 81 private static final String ATTR_DISABLED = "disabled"; 82 private static final String ATTR_SETUP_COMPLETE = "setup-complete"; 83 private static final String ATTR_PROVISIONING_STATE = "provisioning-state"; 84 private static final String ATTR_PERMISSION_POLICY = "permission-policy"; 85 private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED = 86 "device-provisioning-config-applied"; 87 private static final String ATTR_DEVICE_PAIRED = "device-paired"; 88 private static final String ATTR_NEW_USER_DISCLAIMER = "new-user-disclaimer"; 89 90 // Values of ATTR_NEW_USER_DISCLAIMER 91 static final String NEW_USER_DISCLAIMER_ACKNOWLEDGED = "acked"; 92 static final String NEW_USER_DISCLAIMER_NOT_NEEDED = "not_needed"; 93 static final String NEW_USER_DISCLAIMER_NEEDED = "needed"; 94 95 private static final String ATTR_FACTORY_RESET_FLAGS = "factory-reset-flags"; 96 private static final String ATTR_FACTORY_RESET_REASON = "factory-reset-reason"; 97 98 // NOTE: must be public because of DebugUtils.flagsToString() 99 public static final int FACTORY_RESET_FLAG_ON_BOOT = 1; 100 public static final int FACTORY_RESET_FLAG_WIPE_EXTERNAL_STORAGE = 2; 101 public static final int FACTORY_RESET_FLAG_WIPE_EUICC = 4; 102 public static final int FACTORY_RESET_FLAG_WIPE_FACTORY_RESET_PROTECTION = 8; 103 104 private static final String TAG = DevicePolicyManagerService.LOG_TAG; 105 private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE 106 107 int mFailedPasswordAttempts = 0; 108 boolean mPasswordValidAtLastCheckpoint = true; 109 110 final @UserIdInt int mUserId; 111 int mPasswordOwner = -1; 112 long mLastMaximumTimeToLock = -1; 113 boolean mUserSetupComplete = false; 114 boolean mBypassDevicePolicyManagementRoleQualifications = false; 115 String mCurrentRoleHolder; 116 boolean mPaired = false; 117 int mUserProvisioningState; 118 int mPermissionPolicy; 119 120 int mFactoryResetFlags; 121 String mFactoryResetReason; 122 123 boolean mDeviceProvisioningConfigApplied = false; 124 125 final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>(); 126 final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>(); 127 final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>(); 128 129 // Some DevicePolicyManager APIs can be called by (1) a DPC or (2) an app with permissions that 130 // isn't a DPC. For the latter, the caller won't have to provide a ComponentName and won't be 131 // mapped to an ActiveAdmin. This permission-based admin should be used to persist policies 132 // set by the permission-based caller. This admin should not be added to mAdminMap or mAdminList 133 // since a lot of methods in DPMS assume the ActiveAdmins here have a valid ComponentName. 134 // Instead, use variants of DPMS active admin getters to include the permission-based admin. 135 ActiveAdmin mPermissionBasedAdmin; 136 137 // Create or get the permission-based admin. The permission-based admin will not have a 138 // DeviceAdminInfo or ComponentName. createOrGetPermissionBasedAdmin(int userId)139 ActiveAdmin createOrGetPermissionBasedAdmin(int userId) { 140 if (mPermissionBasedAdmin == null) { 141 mPermissionBasedAdmin = new ActiveAdmin(userId, /* permissionBased= */ true); 142 } 143 return mPermissionBasedAdmin; 144 } 145 146 // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead. 147 final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>(); 148 149 // This is the list of component allowed to start lock task mode. 150 List<String> mLockTaskPackages = new ArrayList<>(); 151 152 /** @deprecated moved to {@link ActiveAdmin#protectedPackages}. */ 153 @Deprecated 154 @Nullable 155 List<String> mUserControlDisabledPackages; 156 157 // Bitfield of feature flags to be enabled during LockTask mode. 158 // We default on the power button menu, in order to be consistent with pre-P behaviour. 159 int mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS; 160 161 boolean mStatusBarDisabled = false; 162 163 ComponentName mRestrictionsProvider; 164 165 // Map of delegate package to delegation scopes 166 final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>(); 167 168 boolean mDoNotAskCredentialsOnBoot = false; 169 170 Set<String> mAffiliationIds = new ArraySet<>(); 171 172 long mLastSecurityLogRetrievalTime = -1; 173 174 long mLastBugReportRequestTime = -1; 175 176 long mLastNetworkLogsRetrievalTime = -1; 177 178 boolean mCurrentInputMethodSet = false; 179 180 boolean mSecondaryLockscreenEnabled = false; 181 182 // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead. 183 Set<String> mOwnerInstalledCaCerts = new ArraySet<>(); 184 185 // Used for initialization of users created by createAndManageUser. 186 boolean mAdminBroadcastPending = false; 187 PersistableBundle mInitBundle = null; 188 189 long mPasswordTokenHandle = 0; 190 191 // Whether user's apps are suspended. This flag should only be written AFTER all the needed 192 // apps were suspended or unsuspended. 193 boolean mAppsSuspended = false; 194 195 // Whether it's necessary to show a disclaimer (that the device is managed) after the user 196 // starts. 197 String mNewUserDisclaimer = NEW_USER_DISCLAIMER_NOT_NEEDED; 198 199 /** 200 * Effective state of the feature flag. It is updated to the current configuration value 201 * during boot and doesn't change value after than unless overridden by test code. 202 */ 203 boolean mEffectiveKeepProfilesRunning = DEFAULT_KEEP_PROFILES_RUNNING_FLAG; 204 DevicePolicyData(@serIdInt int userId)205 DevicePolicyData(@UserIdInt int userId) { 206 mUserId = userId; 207 } 208 209 /** 210 * Serializes DevicePolicyData object as XML. 211 */ store(DevicePolicyData policyData, JournaledFile file)212 static boolean store(DevicePolicyData policyData, JournaledFile file) { 213 FileOutputStream stream = null; 214 File chooseForWrite = null; 215 try { 216 chooseForWrite = file.chooseForWrite(); 217 if (VERBOSE_LOG) { 218 Slogf.v(TAG, "Storing data for user %d on %s ", policyData.mUserId, chooseForWrite); 219 } 220 stream = new FileOutputStream(chooseForWrite, false); 221 TypedXmlSerializer out = Xml.resolveSerializer(stream); 222 out.startDocument(null, true); 223 224 out.startTag(null, "policies"); 225 if (policyData.mRestrictionsProvider != null) { 226 out.attribute(null, ATTR_PERMISSION_PROVIDER, 227 policyData.mRestrictionsProvider.flattenToString()); 228 } 229 if (policyData.mUserSetupComplete) { 230 if (VERBOSE_LOG) Slogf.v(TAG, "setting %s to true", ATTR_SETUP_COMPLETE); 231 out.attributeBoolean(null, ATTR_SETUP_COMPLETE, true); 232 } 233 if (policyData.mPaired) { 234 out.attributeBoolean(null, ATTR_DEVICE_PAIRED, true); 235 } 236 if (policyData.mDeviceProvisioningConfigApplied) { 237 out.attributeBoolean(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED, true); 238 } 239 if (policyData.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) { 240 out.attributeInt(null, ATTR_PROVISIONING_STATE, policyData.mUserProvisioningState); 241 } 242 if (policyData.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) { 243 out.attributeInt(null, ATTR_PERMISSION_POLICY, policyData.mPermissionPolicy); 244 } 245 if (NEW_USER_DISCLAIMER_NEEDED.equals(policyData.mNewUserDisclaimer)) { 246 out.attribute(null, ATTR_NEW_USER_DISCLAIMER, policyData.mNewUserDisclaimer); 247 } 248 249 if (policyData.mFactoryResetFlags != 0) { 250 if (VERBOSE_LOG) { 251 Slogf.v(TAG, "Storing factory reset flags for user %d: %s", policyData.mUserId, 252 factoryResetFlagsToString(policyData.mFactoryResetFlags)); 253 } 254 out.attributeInt(null, ATTR_FACTORY_RESET_FLAGS, policyData.mFactoryResetFlags); 255 } 256 if (policyData.mFactoryResetReason != null) { 257 out.attribute(null, ATTR_FACTORY_RESET_REASON, policyData.mFactoryResetReason); 258 } 259 260 // Serialize delegations. 261 for (int i = 0; i < policyData.mDelegationMap.size(); ++i) { 262 final String delegatePackage = policyData.mDelegationMap.keyAt(i); 263 final List<String> scopes = policyData.mDelegationMap.valueAt(i); 264 265 // Every "delegation" tag serializes the information of one delegate-scope pair. 266 for (String scope : scopes) { 267 out.startTag(null, "delegation"); 268 out.attribute(null, "delegatePackage", delegatePackage); 269 out.attribute(null, "scope", scope); 270 out.endTag(null, "delegation"); 271 } 272 } 273 274 final int n = policyData.mAdminList.size(); 275 for (int i = 0; i < n; i++) { 276 ActiveAdmin ap = policyData.mAdminList.get(i); 277 if (ap != null) { 278 out.startTag(null, "admin"); 279 out.attribute(null, "name", ap.info.getComponent().flattenToString()); 280 ap.writeToXml(out); 281 out.endTag(null, "admin"); 282 } 283 } 284 285 if (policyData.mPermissionBasedAdmin != null) { 286 out.startTag(null, "permission-based-admin"); 287 policyData.mPermissionBasedAdmin.writeToXml(out); 288 out.endTag(null, "permission-based-admin"); 289 } 290 291 if (policyData.mPasswordOwner >= 0) { 292 out.startTag(null, "password-owner"); 293 out.attributeInt(null, "value", policyData.mPasswordOwner); 294 out.endTag(null, "password-owner"); 295 } 296 297 if (policyData.mFailedPasswordAttempts != 0) { 298 out.startTag(null, "failed-password-attempts"); 299 out.attributeInt(null, "value", policyData.mFailedPasswordAttempts); 300 out.endTag(null, "failed-password-attempts"); 301 } 302 303 for (int i = 0; i < policyData.mAcceptedCaCertificates.size(); i++) { 304 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 305 out.attribute(null, ATTR_NAME, policyData.mAcceptedCaCertificates.valueAt(i)); 306 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 307 } 308 309 for (int i = 0; i < policyData.mLockTaskPackages.size(); i++) { 310 String component = policyData.mLockTaskPackages.get(i); 311 out.startTag(null, TAG_LOCK_TASK_COMPONENTS); 312 out.attribute(null, "name", component); 313 out.endTag(null, TAG_LOCK_TASK_COMPONENTS); 314 } 315 316 if (policyData.mLockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) { 317 out.startTag(null, TAG_LOCK_TASK_FEATURES); 318 out.attributeInt(null, ATTR_VALUE, policyData.mLockTaskFeatures); 319 out.endTag(null, TAG_LOCK_TASK_FEATURES); 320 } 321 322 if (policyData.mSecondaryLockscreenEnabled) { 323 out.startTag(null, TAG_SECONDARY_LOCK_SCREEN); 324 out.attributeBoolean(null, ATTR_VALUE, true); 325 out.endTag(null, TAG_SECONDARY_LOCK_SCREEN); 326 } 327 328 if (policyData.mStatusBarDisabled) { 329 out.startTag(null, TAG_STATUS_BAR); 330 out.attributeBoolean(null, ATTR_DISABLED, policyData.mStatusBarDisabled); 331 out.endTag(null, TAG_STATUS_BAR); 332 } 333 334 if (policyData.mDoNotAskCredentialsOnBoot) { 335 out.startTag(null, TAG_DO_NOT_ASK_CREDENTIALS_ON_BOOT); 336 out.endTag(null, TAG_DO_NOT_ASK_CREDENTIALS_ON_BOOT); 337 } 338 339 for (String id : policyData.mAffiliationIds) { 340 out.startTag(null, TAG_AFFILIATION_ID); 341 out.attribute(null, ATTR_ID, id); 342 out.endTag(null, TAG_AFFILIATION_ID); 343 } 344 345 if (policyData.mLastSecurityLogRetrievalTime >= 0) { 346 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 347 out.attributeLong(null, ATTR_VALUE, policyData.mLastSecurityLogRetrievalTime); 348 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 349 } 350 351 if (policyData.mLastBugReportRequestTime >= 0) { 352 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST); 353 out.attributeLong(null, ATTR_VALUE, policyData.mLastBugReportRequestTime); 354 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST); 355 } 356 357 if (policyData.mLastNetworkLogsRetrievalTime >= 0) { 358 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 359 out.attributeLong(null, ATTR_VALUE, policyData.mLastNetworkLogsRetrievalTime); 360 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 361 } 362 363 if (policyData.mAdminBroadcastPending) { 364 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING); 365 out.attributeBoolean(null, ATTR_VALUE, policyData.mAdminBroadcastPending); 366 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING); 367 } 368 369 if (policyData.mInitBundle != null) { 370 out.startTag(null, TAG_INITIALIZATION_BUNDLE); 371 policyData.mInitBundle.saveToXml(out); 372 out.endTag(null, TAG_INITIALIZATION_BUNDLE); 373 } 374 375 if (policyData.mPasswordTokenHandle != 0) { 376 out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE); 377 out.attributeLong(null, ATTR_VALUE, policyData.mPasswordTokenHandle); 378 out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE); 379 } 380 381 if (policyData.mCurrentInputMethodSet) { 382 out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET); 383 out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET); 384 } 385 386 for (final String cert : policyData.mOwnerInstalledCaCerts) { 387 out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT); 388 out.attribute(null, ATTR_ALIAS, cert); 389 out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT); 390 } 391 392 if (policyData.mAppsSuspended) { 393 out.startTag(null, TAG_APPS_SUSPENDED); 394 out.attributeBoolean(null, ATTR_VALUE, policyData.mAppsSuspended); 395 out.endTag(null, TAG_APPS_SUSPENDED); 396 } 397 398 if (policyData.mBypassDevicePolicyManagementRoleQualifications) { 399 out.startTag(null, TAG_BYPASS_ROLE_QUALIFICATIONS); 400 out.attribute(null, ATTR_VALUE, policyData.mCurrentRoleHolder); 401 out.endTag(null, TAG_BYPASS_ROLE_QUALIFICATIONS); 402 } 403 404 if (policyData.mEffectiveKeepProfilesRunning != DEFAULT_KEEP_PROFILES_RUNNING_FLAG) { 405 out.startTag(null, TAG_KEEP_PROFILES_RUNNING); 406 out.attributeBoolean(null, ATTR_VALUE, policyData.mEffectiveKeepProfilesRunning); 407 out.endTag(null, TAG_KEEP_PROFILES_RUNNING); 408 } 409 410 out.endTag(null, "policies"); 411 412 out.endDocument(); 413 stream.flush(); 414 FileUtils.sync(stream); 415 stream.close(); 416 file.commit(); 417 return true; 418 } catch (XmlPullParserException | IOException e) { 419 Slogf.w(TAG, e, "failed writing file %s", chooseForWrite); 420 try { 421 if (stream != null) { 422 stream.close(); 423 } 424 } catch (IOException ex) { 425 // Ignore 426 } 427 file.rollback(); 428 return false; 429 } 430 } 431 432 /** 433 * @param adminInfoSupplier function that queries DeviceAdminInfo from PackageManager 434 * @param ownerComponent device or profile owner component if any. 435 */ load(DevicePolicyData policy, JournaledFile journaledFile, Function<ComponentName, DeviceAdminInfo> adminInfoSupplier, ComponentName ownerComponent)436 static void load(DevicePolicyData policy, JournaledFile journaledFile, 437 Function<ComponentName, DeviceAdminInfo> adminInfoSupplier, 438 ComponentName ownerComponent) { 439 FileInputStream stream = null; 440 File file = journaledFile.chooseForRead(); 441 if (VERBOSE_LOG) Slogf.v(TAG, "Loading data for user %d from %s", policy.mUserId, file); 442 boolean needsRewrite = false; 443 try { 444 stream = new FileInputStream(file); 445 TypedXmlPullParser parser = Xml.resolvePullParser(stream); 446 447 int type; 448 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 449 && type != XmlPullParser.START_TAG) { 450 } 451 String tag = parser.getName(); 452 if (!"policies".equals(tag)) { 453 throw new XmlPullParserException( 454 "Settings do not start with policies tag: found " + tag); 455 } 456 457 // Extract the permission provider component name if available 458 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER); 459 if (permissionProvider != null) { 460 policy.mRestrictionsProvider = 461 ComponentName.unflattenFromString(permissionProvider); 462 } 463 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE); 464 if (Boolean.toString(true).equals(userSetupComplete)) { 465 if (VERBOSE_LOG) Slogf.v(TAG, "setting mUserSetupComplete to true"); 466 policy.mUserSetupComplete = true; 467 } 468 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED); 469 if (Boolean.toString(true).equals(paired)) { 470 policy.mPaired = true; 471 } 472 String deviceProvisioningConfigApplied = parser.getAttributeValue(null, 473 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED); 474 if (Boolean.toString(true).equals(deviceProvisioningConfigApplied)) { 475 policy.mDeviceProvisioningConfigApplied = true; 476 } 477 int provisioningState = parser.getAttributeInt(null, ATTR_PROVISIONING_STATE, -1); 478 if (provisioningState != -1) { 479 policy.mUserProvisioningState = provisioningState; 480 } 481 int permissionPolicy = parser.getAttributeInt(null, ATTR_PERMISSION_POLICY, -1); 482 if (permissionPolicy != -1) { 483 policy.mPermissionPolicy = permissionPolicy; 484 } 485 policy.mNewUserDisclaimer = parser.getAttributeValue(null, ATTR_NEW_USER_DISCLAIMER); 486 487 policy.mFactoryResetFlags = parser.getAttributeInt(null, ATTR_FACTORY_RESET_FLAGS, 0); 488 if (VERBOSE_LOG) { 489 Slogf.v(TAG, "Restored factory reset flags for user %d: %s", policy.mUserId, 490 factoryResetFlagsToString(policy.mFactoryResetFlags)); 491 } 492 policy.mFactoryResetReason = parser.getAttributeValue(null, ATTR_FACTORY_RESET_REASON); 493 494 int outerDepth = parser.getDepth(); 495 policy.mLockTaskPackages.clear(); 496 policy.mAdminList.clear(); 497 policy.mAdminMap.clear(); 498 policy.mPermissionBasedAdmin = null; 499 policy.mAffiliationIds.clear(); 500 policy.mOwnerInstalledCaCerts.clear(); 501 policy.mUserControlDisabledPackages = null; 502 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 503 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 504 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 505 continue; 506 } 507 tag = parser.getName(); 508 if ("admin".equals(tag)) { 509 String name = parser.getAttributeValue(null, "name"); 510 try { 511 DeviceAdminInfo dai = adminInfoSupplier.apply( 512 ComponentName.unflattenFromString(name)); 513 514 if (dai != null) { 515 // b/123415062: If DA, overwrite with the stored policies that were 516 // agreed by the user to prevent apps from sneaking additional policies 517 // into updates. 518 boolean overwritePolicies = !dai.getComponent().equals(ownerComponent); 519 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false); 520 ap.readFromXml(parser, overwritePolicies); 521 policy.mAdminMap.put(ap.info.getComponent(), ap); 522 } 523 } catch (RuntimeException e) { 524 Slogf.w(TAG, e, "Failed loading admin %s", name); 525 } 526 } else if ("permission-based-admin".equals(tag)) { 527 ActiveAdmin ap = new ActiveAdmin(policy.mUserId, /* permissionBased= */ true); 528 ap.readFromXml(parser, /* overwritePolicies= */ false); 529 policy.mPermissionBasedAdmin = ap; 530 } else if ("delegation".equals(tag)) { 531 // Parse delegation info. 532 final String delegatePackage = parser.getAttributeValue(null, 533 "delegatePackage"); 534 final String scope = parser.getAttributeValue(null, "scope"); 535 536 // Get a reference to the scopes list for the delegatePackage. 537 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 538 // Or make a new list if none was found. 539 if (scopes == null) { 540 scopes = new ArrayList<>(); 541 policy.mDelegationMap.put(delegatePackage, scopes); 542 } 543 // Add the new scope to the list of delegatePackage if it's not already there. 544 if (!scopes.contains(scope)) { 545 scopes.add(scope); 546 } 547 } else if ("failed-password-attempts".equals(tag)) { 548 policy.mFailedPasswordAttempts = parser.getAttributeInt(null, "value"); 549 } else if ("password-owner".equals(tag)) { 550 policy.mPasswordOwner = parser.getAttributeInt(null, "value"); 551 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) { 552 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME)); 553 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) { 554 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name")); 555 } else if (TAG_LOCK_TASK_FEATURES.equals(tag)) { 556 policy.mLockTaskFeatures = parser.getAttributeInt(null, ATTR_VALUE); 557 } else if (TAG_SECONDARY_LOCK_SCREEN.equals(tag)) { 558 policy.mSecondaryLockscreenEnabled = 559 parser.getAttributeBoolean(null, ATTR_VALUE, false); 560 } else if (TAG_STATUS_BAR.equals(tag)) { 561 policy.mStatusBarDisabled = 562 parser.getAttributeBoolean(null, ATTR_DISABLED, false); 563 } else if (TAG_DO_NOT_ASK_CREDENTIALS_ON_BOOT.equals(tag)) { 564 policy.mDoNotAskCredentialsOnBoot = true; 565 } else if (TAG_AFFILIATION_ID.equals(tag)) { 566 policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID)); 567 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) { 568 policy.mLastSecurityLogRetrievalTime = 569 parser.getAttributeLong(null, ATTR_VALUE); 570 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) { 571 policy.mLastBugReportRequestTime = 572 parser.getAttributeLong(null, ATTR_VALUE); 573 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) { 574 policy.mLastNetworkLogsRetrievalTime = 575 parser.getAttributeLong(null, ATTR_VALUE); 576 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) { 577 String pending = parser.getAttributeValue(null, ATTR_VALUE); 578 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending); 579 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) { 580 policy.mInitBundle = PersistableBundle.restoreFromXml(parser); 581 } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) { 582 policy.mPasswordTokenHandle = parser.getAttributeLong(null, ATTR_VALUE); 583 } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) { 584 policy.mCurrentInputMethodSet = true; 585 } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) { 586 policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS)); 587 } else if (TAG_APPS_SUSPENDED.equals(tag)) { 588 policy.mAppsSuspended = 589 parser.getAttributeBoolean(null, ATTR_VALUE, false); 590 } else if (TAG_BYPASS_ROLE_QUALIFICATIONS.equals(tag)) { 591 policy.mBypassDevicePolicyManagementRoleQualifications = true; 592 policy.mCurrentRoleHolder = parser.getAttributeValue(null, ATTR_VALUE); 593 } else if (TAG_KEEP_PROFILES_RUNNING.equals(tag)) { 594 policy.mEffectiveKeepProfilesRunning = parser.getAttributeBoolean( 595 null, ATTR_VALUE, DEFAULT_KEEP_PROFILES_RUNNING_FLAG); 596 // Deprecated tags below 597 } else if (TAG_PROTECTED_PACKAGES.equals(tag)) { 598 if (policy.mUserControlDisabledPackages == null) { 599 policy.mUserControlDisabledPackages = new ArrayList<>(); 600 } 601 policy.mUserControlDisabledPackages.add( 602 parser.getAttributeValue(null, ATTR_NAME)); 603 } else { 604 Slogf.w(TAG, "Unknown tag: %s", tag); 605 XmlUtils.skipCurrentTag(parser); 606 } 607 } 608 } catch (FileNotFoundException e) { 609 // Don't be noisy, this is normal if we haven't defined any policies. 610 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException 611 | IndexOutOfBoundsException e) { 612 Slogf.w(TAG, e, "failed parsing %s", file); 613 } 614 try { 615 if (stream != null) { 616 stream.close(); 617 } 618 } catch (IOException e) { 619 // Ignore 620 } 621 622 // Generate a list of admins from the admin map 623 policy.mAdminList.addAll(policy.mAdminMap.values()); 624 } 625 validatePasswordOwner()626 void validatePasswordOwner() { 627 if (mPasswordOwner >= 0) { 628 boolean haveOwner = false; 629 for (int i = mAdminList.size() - 1; i >= 0; i--) { 630 if (mAdminList.get(i).getUid() == mPasswordOwner) { 631 haveOwner = true; 632 break; 633 } 634 } 635 if (!haveOwner) { 636 Slogf.w(TAG, "Previous password owner %s no longer active; disabling", 637 mPasswordOwner); 638 mPasswordOwner = -1; 639 } 640 } 641 } 642 setDelayedFactoryReset(@onNull String reason, boolean wipeExtRequested, boolean wipeEuicc, boolean wipeResetProtectionData)643 void setDelayedFactoryReset(@NonNull String reason, boolean wipeExtRequested, boolean wipeEuicc, 644 boolean wipeResetProtectionData) { 645 mFactoryResetReason = reason; 646 647 mFactoryResetFlags = FACTORY_RESET_FLAG_ON_BOOT; 648 if (wipeExtRequested) { 649 mFactoryResetFlags |= FACTORY_RESET_FLAG_WIPE_EXTERNAL_STORAGE; 650 } 651 if (wipeEuicc) { 652 mFactoryResetFlags |= FACTORY_RESET_FLAG_WIPE_EUICC; 653 } 654 if (wipeResetProtectionData) { 655 mFactoryResetFlags |= FACTORY_RESET_FLAG_WIPE_FACTORY_RESET_PROTECTION; 656 } 657 } 658 isNewUserDisclaimerAcknowledged()659 boolean isNewUserDisclaimerAcknowledged() { 660 if (mNewUserDisclaimer == null) { 661 if (mUserId == UserHandle.USER_SYSTEM) { 662 return true; 663 } 664 Slogf.w(TAG, "isNewUserDisclaimerAcknowledged(%d): mNewUserDisclaimer is null", 665 mUserId); 666 return false; 667 } 668 switch (mNewUserDisclaimer) { 669 case NEW_USER_DISCLAIMER_ACKNOWLEDGED: 670 case NEW_USER_DISCLAIMER_NOT_NEEDED: 671 return true; 672 case NEW_USER_DISCLAIMER_NEEDED: 673 return false; 674 default: 675 Slogf.w(TAG, "isNewUserDisclaimerAcknowledged(%d): invalid value %d", mUserId, 676 mNewUserDisclaimer); 677 return false; 678 } 679 } 680 dump(IndentingPrintWriter pw)681 void dump(IndentingPrintWriter pw) { 682 pw.println(); 683 pw.println("Enabled Device Admins (User " + mUserId + ", provisioningState: " 684 + mUserProvisioningState + "):"); 685 final int n = mAdminList.size(); 686 for (int i = 0; i < n; i++) { 687 ActiveAdmin ap = mAdminList.get(i); 688 if (ap != null) { 689 pw.increaseIndent(); 690 pw.print(ap.info.getComponent().flattenToShortString()); 691 pw.println(":"); 692 pw.increaseIndent(); 693 ap.dump(pw); 694 pw.decreaseIndent(); 695 pw.decreaseIndent(); 696 } 697 } 698 if (!mRemovingAdmins.isEmpty()) { 699 pw.increaseIndent(); 700 pw.println("Removing Device Admins (User " + mUserId + "): " + mRemovingAdmins); 701 pw.decreaseIndent(); 702 } 703 pw.println(); 704 pw.increaseIndent(); 705 pw.print("mPasswordOwner="); pw.println(mPasswordOwner); 706 pw.print("mPasswordTokenHandle="); pw.println(Long.toHexString(mPasswordTokenHandle)); 707 pw.print("mAppsSuspended="); pw.println(mAppsSuspended); 708 pw.print("mUserSetupComplete="); pw.println(mUserSetupComplete); 709 pw.print("mAffiliationIds="); pw.println(mAffiliationIds); 710 pw.print("mNewUserDisclaimer="); pw.println(mNewUserDisclaimer); 711 if (mFactoryResetFlags != 0) { 712 pw.print("mFactoryResetFlags="); pw.print(mFactoryResetFlags); 713 pw.print(" ("); 714 pw.print(factoryResetFlagsToString(mFactoryResetFlags)); 715 pw.println(')'); 716 } 717 if (mFactoryResetReason != null) { 718 pw.print("mFactoryResetReason="); pw.println(mFactoryResetReason); 719 } 720 if (mDelegationMap.size() != 0) { 721 pw.println("mDelegationMap="); 722 pw.increaseIndent(); 723 for (int i = 0; i < mDelegationMap.size(); i++) { 724 List<String> delegationScopes = mDelegationMap.valueAt(i); 725 pw.println(mDelegationMap.keyAt(i) + "[size=" + delegationScopes.size() 726 + "]"); 727 pw.increaseIndent(); 728 for (int j = 0; j < delegationScopes.size(); j++) { 729 pw.println(j + ": " + delegationScopes.get(j)); 730 } 731 pw.decreaseIndent(); 732 } 733 pw.decreaseIndent(); 734 } 735 pw.decreaseIndent(); 736 } 737 factoryResetFlagsToString(int flags)738 static String factoryResetFlagsToString(int flags) { 739 return DebugUtils.flagsToString(DevicePolicyData.class, "FACTORY_RESET_FLAG_", flags); 740 } 741 } 742