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