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