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